blob: ad0e2e3843caeede4f1a670fa46155c3dcc48f86 [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,
1159 (char*)from_data + how_many);
1160 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 Stinner56c161a2011-10-06 02:47:11 +02001257 assert(ch <= to_maxchar);
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001258#else
1259 if (ch > to_maxchar)
1260 return -1;
1261#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
3863#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +02003864static int unicode_as_unicode_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003865#endif
3866
3867
3868Py_UNICODE *
3869PyUnicode_AsUnicodeAndSize(PyObject *unicode, Py_ssize_t *size)
3870{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003871 const unsigned char *one_byte;
3872#if SIZEOF_WCHAR_T == 4
3873 const Py_UCS2 *two_bytes;
3874#else
3875 const Py_UCS4 *four_bytes;
3876 const Py_UCS4 *ucs4_end;
3877 Py_ssize_t num_surrogates;
3878#endif
3879 wchar_t *w;
3880 wchar_t *wchar_end;
3881
3882 if (!PyUnicode_Check(unicode)) {
3883 PyErr_BadArgument();
3884 return NULL;
3885 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003886 if (_PyUnicode_WSTR(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003887 /* Non-ASCII compact unicode object */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003888 assert(_PyUnicode_KIND(unicode) != 0);
3889 assert(PyUnicode_IS_READY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003890
3891#ifdef Py_DEBUG
3892 ++unicode_as_unicode_calls;
3893#endif
3894
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003895 if (PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003896#if SIZEOF_WCHAR_T == 2
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003897 four_bytes = PyUnicode_4BYTE_DATA(unicode);
3898 ucs4_end = four_bytes + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003899 num_surrogates = 0;
3900
3901 for (; four_bytes < ucs4_end; ++four_bytes) {
3902 if (*four_bytes > 0xFFFF)
3903 ++num_surrogates;
3904 }
3905
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003906 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(
3907 sizeof(wchar_t) * (_PyUnicode_LENGTH(unicode) + 1 + num_surrogates));
3908 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003909 PyErr_NoMemory();
3910 return NULL;
3911 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003912 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode) + num_surrogates;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003913
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003914 w = _PyUnicode_WSTR(unicode);
3915 wchar_end = w + _PyUnicode_WSTR_LENGTH(unicode);
3916 four_bytes = PyUnicode_4BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003917 for (; four_bytes < ucs4_end; ++four_bytes, ++w) {
3918 if (*four_bytes > 0xFFFF) {
Victor Stinner8faf8212011-12-08 22:14:11 +01003919 assert(*four_bytes <= MAX_UNICODE);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003920 /* encode surrogate pair in this case */
Victor Stinner551ac952011-11-29 22:58:13 +01003921 *w++ = Py_UNICODE_HIGH_SURROGATE(*four_bytes);
3922 *w = Py_UNICODE_LOW_SURROGATE(*four_bytes);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003923 }
3924 else
3925 *w = *four_bytes;
3926
3927 if (w > wchar_end) {
3928 assert(0 && "Miscalculated string end");
3929 }
3930 }
3931 *w = 0;
3932#else
3933 /* sizeof(wchar_t) == 4 */
3934 Py_FatalError("Impossible unicode object state, wstr and str "
3935 "should share memory already.");
3936 return NULL;
3937#endif
3938 }
3939 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003940 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(sizeof(wchar_t) *
3941 (_PyUnicode_LENGTH(unicode) + 1));
3942 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003943 PyErr_NoMemory();
3944 return NULL;
3945 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003946 if (!PyUnicode_IS_COMPACT_ASCII(unicode))
3947 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode);
3948 w = _PyUnicode_WSTR(unicode);
3949 wchar_end = w + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003950
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003951 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND) {
3952 one_byte = PyUnicode_1BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003953 for (; w < wchar_end; ++one_byte, ++w)
3954 *w = *one_byte;
3955 /* null-terminate the wstr */
3956 *w = 0;
3957 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003958 else if (PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003959#if SIZEOF_WCHAR_T == 4
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003960 two_bytes = PyUnicode_2BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003961 for (; w < wchar_end; ++two_bytes, ++w)
3962 *w = *two_bytes;
3963 /* null-terminate the wstr */
3964 *w = 0;
3965#else
3966 /* sizeof(wchar_t) == 2 */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003967 PyObject_FREE(_PyUnicode_WSTR(unicode));
3968 _PyUnicode_WSTR(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003969 Py_FatalError("Impossible unicode object state, wstr "
3970 "and str should share memory already.");
3971 return NULL;
3972#endif
3973 }
3974 else {
3975 assert(0 && "This should never happen.");
3976 }
3977 }
3978 }
3979 if (size != NULL)
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003980 *size = PyUnicode_WSTR_LENGTH(unicode);
3981 return _PyUnicode_WSTR(unicode);
Martin v. Löwis5b222132007-06-10 09:51:05 +00003982}
3983
Alexander Belopolsky40018472011-02-26 01:02:56 +00003984Py_UNICODE *
3985PyUnicode_AsUnicode(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003986{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003987 return PyUnicode_AsUnicodeAndSize(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003988}
3989
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003990
Alexander Belopolsky40018472011-02-26 01:02:56 +00003991Py_ssize_t
3992PyUnicode_GetSize(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003993{
3994 if (!PyUnicode_Check(unicode)) {
3995 PyErr_BadArgument();
3996 goto onError;
3997 }
3998 return PyUnicode_GET_SIZE(unicode);
3999
Benjamin Peterson29060642009-01-31 22:14:21 +00004000 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00004001 return -1;
4002}
4003
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004004Py_ssize_t
4005PyUnicode_GetLength(PyObject *unicode)
4006{
Victor Stinner5a706cf2011-10-02 00:36:53 +02004007 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004008 PyErr_BadArgument();
4009 return -1;
4010 }
4011
4012 return PyUnicode_GET_LENGTH(unicode);
4013}
4014
4015Py_UCS4
4016PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
4017{
Victor Stinner2fe5ced2011-10-02 00:25:40 +02004018 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
4019 PyErr_BadArgument();
4020 return (Py_UCS4)-1;
4021 }
Victor Stinnerc4b49542011-12-11 22:44:26 +01004022 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinner2fe5ced2011-10-02 00:25:40 +02004023 PyErr_SetString(PyExc_IndexError, "string index out of range");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004024 return (Py_UCS4)-1;
4025 }
4026 return PyUnicode_READ_CHAR(unicode, index);
4027}
4028
4029int
4030PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 ch)
4031{
4032 if (!PyUnicode_Check(unicode) || !PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02004033 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004034 return -1;
4035 }
Victor Stinner488fa492011-12-12 00:01:39 +01004036 assert(PyUnicode_IS_READY(unicode));
Victor Stinnerc4b49542011-12-11 22:44:26 +01004037 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02004038 PyErr_SetString(PyExc_IndexError, "string index out of range");
4039 return -1;
4040 }
Victor Stinner488fa492011-12-12 00:01:39 +01004041 if (unicode_check_modifiable(unicode))
Victor Stinnercd9950f2011-10-02 00:34:53 +02004042 return -1;
Victor Stinnerc9590ad2012-03-04 01:34:37 +01004043 if (ch > PyUnicode_MAX_CHAR_VALUE(unicode)) {
4044 PyErr_SetString(PyExc_ValueError, "character out of range");
4045 return -1;
4046 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004047 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
4048 index, ch);
4049 return 0;
4050}
4051
Alexander Belopolsky40018472011-02-26 01:02:56 +00004052const char *
4053PyUnicode_GetDefaultEncoding(void)
Fred Drakee4315f52000-05-09 19:53:39 +00004054{
Victor Stinner42cb4622010-09-01 19:39:01 +00004055 return "utf-8";
Fred Drakee4315f52000-05-09 19:53:39 +00004056}
4057
Victor Stinner554f3f02010-06-16 23:33:54 +00004058/* create or adjust a UnicodeDecodeError */
4059static void
4060make_decode_exception(PyObject **exceptionObject,
4061 const char *encoding,
4062 const char *input, Py_ssize_t length,
4063 Py_ssize_t startpos, Py_ssize_t endpos,
4064 const char *reason)
4065{
4066 if (*exceptionObject == NULL) {
4067 *exceptionObject = PyUnicodeDecodeError_Create(
4068 encoding, input, length, startpos, endpos, reason);
4069 }
4070 else {
4071 if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
4072 goto onError;
4073 if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
4074 goto onError;
4075 if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
4076 goto onError;
4077 }
4078 return;
4079
4080onError:
4081 Py_DECREF(*exceptionObject);
4082 *exceptionObject = NULL;
4083}
4084
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004085/* error handling callback helper:
4086 build arguments, call the callback and check the arguments,
Fred Drakedb390c12005-10-28 14:39:47 +00004087 if no exception occurred, copy the replacement to the output
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004088 and adjust various state variables.
4089 return 0 on success, -1 on error
4090*/
4091
Alexander Belopolsky40018472011-02-26 01:02:56 +00004092static int
4093unicode_decode_call_errorhandler(const char *errors, PyObject **errorHandler,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004094 const char *encoding, const char *reason,
4095 const char **input, const char **inend, Py_ssize_t *startinpos,
4096 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004097 PyObject **output, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004098{
Benjamin Peterson142957c2008-07-04 19:55:29 +00004099 static char *argparse = "O!n;decoding error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004100
4101 PyObject *restuple = NULL;
4102 PyObject *repunicode = NULL;
Victor Stinner596a6c42011-11-09 00:02:18 +01004103 Py_ssize_t outsize;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004104 Py_ssize_t insize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004105 Py_ssize_t requiredsize;
4106 Py_ssize_t newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004107 PyObject *inputobj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004108 int res = -1;
4109
Victor Stinner596a6c42011-11-09 00:02:18 +01004110 if (_PyUnicode_KIND(*output) != PyUnicode_WCHAR_KIND)
4111 outsize = PyUnicode_GET_LENGTH(*output);
4112 else
4113 outsize = _PyUnicode_WSTR_LENGTH(*output);
4114
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004115 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004116 *errorHandler = PyCodec_LookupError(errors);
4117 if (*errorHandler == NULL)
4118 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004119 }
4120
Victor Stinner554f3f02010-06-16 23:33:54 +00004121 make_decode_exception(exceptionObject,
4122 encoding,
4123 *input, *inend - *input,
4124 *startinpos, *endinpos,
4125 reason);
4126 if (*exceptionObject == NULL)
4127 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004128
4129 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
4130 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004131 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004132 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00004133 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00004134 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004135 }
4136 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00004137 goto onError;
Benjamin Petersonbac79492012-01-14 13:34:47 -05004138 if (PyUnicode_READY(repunicode) == -1)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004139 goto onError;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004140
4141 /* Copy back the bytes variables, which might have been modified by the
4142 callback */
4143 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4144 if (!inputobj)
4145 goto onError;
Christian Heimes72b710a2008-05-26 13:28:38 +00004146 if (!PyBytes_Check(inputobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004147 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
Walter Dörwalde78178e2007-07-30 13:31:40 +00004148 }
Christian Heimes72b710a2008-05-26 13:28:38 +00004149 *input = PyBytes_AS_STRING(inputobj);
4150 insize = PyBytes_GET_SIZE(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004151 *inend = *input + insize;
Walter Dörwald36f938f2007-08-10 10:11:43 +00004152 /* we can DECREF safely, as the exception has another reference,
4153 so the object won't go away. */
4154 Py_DECREF(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004155
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004156 if (newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004157 newpos = insize+newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004158 if (newpos<0 || newpos>insize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004159 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
4160 goto onError;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004161 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004162
Victor Stinner596a6c42011-11-09 00:02:18 +01004163 if (_PyUnicode_KIND(*output) != PyUnicode_WCHAR_KIND) {
4164 /* need more space? (at least enough for what we
4165 have+the replacement+the rest of the string (starting
4166 at the new input position), so we won't have to check space
4167 when there are no errors in the rest of the string) */
4168 Py_ssize_t replen = PyUnicode_GET_LENGTH(repunicode);
4169 requiredsize = *outpos + replen + insize-newpos;
4170 if (requiredsize > outsize) {
4171 if (requiredsize<2*outsize)
4172 requiredsize = 2*outsize;
4173 if (unicode_resize(output, requiredsize) < 0)
4174 goto onError;
4175 }
Victor Stinner1b487b42012-05-03 12:29:04 +02004176 if (unicode_widen(output, *outpos,
4177 PyUnicode_MAX_CHAR_VALUE(repunicode)) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004178 goto onError;
Victor Stinnerd3f08822012-05-29 12:57:52 +02004179 _PyUnicode_FastCopyCharacters(*output, *outpos, repunicode, 0, replen);
Victor Stinner596a6c42011-11-09 00:02:18 +01004180 *outpos += replen;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004181 }
Victor Stinner596a6c42011-11-09 00:02:18 +01004182 else {
4183 wchar_t *repwstr;
4184 Py_ssize_t repwlen;
4185 repwstr = PyUnicode_AsUnicodeAndSize(repunicode, &repwlen);
4186 if (repwstr == NULL)
4187 goto onError;
4188 /* need more space? (at least enough for what we
4189 have+the replacement+the rest of the string (starting
4190 at the new input position), so we won't have to check space
4191 when there are no errors in the rest of the string) */
4192 requiredsize = *outpos + repwlen + insize-newpos;
4193 if (requiredsize > outsize) {
4194 if (requiredsize < 2*outsize)
4195 requiredsize = 2*outsize;
4196 if (unicode_resize(output, requiredsize) < 0)
4197 goto onError;
4198 }
4199 wcsncpy(_PyUnicode_WSTR(*output) + *outpos, repwstr, repwlen);
4200 *outpos += repwlen;
4201 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004202 *endinpos = newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004203 *inptr = *input + newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004204
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004205 /* we made it! */
4206 res = 0;
4207
Benjamin Peterson29060642009-01-31 22:14:21 +00004208 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004209 Py_XDECREF(restuple);
4210 return res;
4211}
4212
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004213/* --- UTF-7 Codec -------------------------------------------------------- */
4214
Antoine Pitrou244651a2009-05-04 18:56:13 +00004215/* See RFC2152 for details. We encode conservatively and decode liberally. */
4216
4217/* Three simple macros defining base-64. */
4218
4219/* Is c a base-64 character? */
4220
4221#define IS_BASE64(c) \
4222 (((c) >= 'A' && (c) <= 'Z') || \
4223 ((c) >= 'a' && (c) <= 'z') || \
4224 ((c) >= '0' && (c) <= '9') || \
4225 (c) == '+' || (c) == '/')
4226
4227/* given that c is a base-64 character, what is its base-64 value? */
4228
4229#define FROM_BASE64(c) \
4230 (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' : \
4231 ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 : \
4232 ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 : \
4233 (c) == '+' ? 62 : 63)
4234
4235/* What is the base-64 character of the bottom 6 bits of n? */
4236
4237#define TO_BASE64(n) \
4238 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
4239
4240/* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
4241 * decoded as itself. We are permissive on decoding; the only ASCII
4242 * byte not decoding to itself is the + which begins a base64
4243 * string. */
4244
4245#define DECODE_DIRECT(c) \
4246 ((c) <= 127 && (c) != '+')
4247
4248/* The UTF-7 encoder treats ASCII characters differently according to
4249 * whether they are Set D, Set O, Whitespace, or special (i.e. none of
4250 * the above). See RFC2152. This array identifies these different
4251 * sets:
4252 * 0 : "Set D"
4253 * alphanumeric and '(),-./:?
4254 * 1 : "Set O"
4255 * !"#$%&*;<=>@[]^_`{|}
4256 * 2 : "whitespace"
4257 * ht nl cr sp
4258 * 3 : special (must be base64 encoded)
4259 * everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
4260 */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004261
Tim Petersced69f82003-09-16 20:30:58 +00004262static
Antoine Pitrou244651a2009-05-04 18:56:13 +00004263char utf7_category[128] = {
4264/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
4265 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
4266/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
4267 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
4268/* sp ! " # $ % & ' ( ) * + , - . / */
4269 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
4270/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
4271 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
4272/* @ A B C D E F G H I J K L M N O */
4273 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4274/* P Q R S T U V W X Y Z [ \ ] ^ _ */
4275 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
4276/* ` a b c d e f g h i j k l m n o */
4277 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4278/* p q r s t u v w x y z { | } ~ del */
4279 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004280};
4281
Antoine Pitrou244651a2009-05-04 18:56:13 +00004282/* ENCODE_DIRECT: this character should be encoded as itself. The
4283 * answer depends on whether we are encoding set O as itself, and also
4284 * on whether we are encoding whitespace as itself. RFC2152 makes it
4285 * clear that the answers to these questions vary between
4286 * applications, so this code needs to be flexible. */
Marc-André Lemburge115ec82005-10-19 22:33:31 +00004287
Antoine Pitrou244651a2009-05-04 18:56:13 +00004288#define ENCODE_DIRECT(c, directO, directWS) \
4289 ((c) < 128 && (c) > 0 && \
4290 ((utf7_category[(c)] == 0) || \
4291 (directWS && (utf7_category[(c)] == 2)) || \
4292 (directO && (utf7_category[(c)] == 1))))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004293
Alexander Belopolsky40018472011-02-26 01:02:56 +00004294PyObject *
4295PyUnicode_DecodeUTF7(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004296 Py_ssize_t size,
4297 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004298{
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004299 return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
4300}
4301
Antoine Pitrou244651a2009-05-04 18:56:13 +00004302/* The decoder. The only state we preserve is our read position,
4303 * i.e. how many characters we have consumed. So if we end in the
4304 * middle of a shift sequence we have to back off the read position
4305 * and the output to the beginning of the sequence, otherwise we lose
4306 * all the shift state (seen bits, number of bits seen, high
4307 * surrogate). */
4308
Alexander Belopolsky40018472011-02-26 01:02:56 +00004309PyObject *
4310PyUnicode_DecodeUTF7Stateful(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004311 Py_ssize_t size,
4312 const char *errors,
4313 Py_ssize_t *consumed)
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004314{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004315 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004316 Py_ssize_t startinpos;
4317 Py_ssize_t endinpos;
4318 Py_ssize_t outpos;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004319 const char *e;
Victor Stinner7931d9a2011-11-04 00:22:48 +01004320 PyObject *unicode;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004321 const char *errmsg = "";
4322 int inShift = 0;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004323 Py_ssize_t shiftOutStart;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004324 unsigned int base64bits = 0;
4325 unsigned long base64buffer = 0;
Victor Stinner24729f32011-11-10 20:31:37 +01004326 Py_UCS4 surrogate = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004327 PyObject *errorHandler = NULL;
4328 PyObject *exc = NULL;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004329
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004330 /* Start off assuming it's all ASCII. Widen later as necessary. */
4331 unicode = PyUnicode_New(size, 127);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004332 if (!unicode)
4333 return NULL;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004334 if (size == 0) {
4335 if (consumed)
4336 *consumed = 0;
Victor Stinner7931d9a2011-11-04 00:22:48 +01004337 return unicode;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004338 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004339
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004340 shiftOutStart = outpos = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004341 e = s + size;
4342
4343 while (s < e) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004344 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00004345 restart:
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00004346 ch = (unsigned char) *s;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004347
Antoine Pitrou244651a2009-05-04 18:56:13 +00004348 if (inShift) { /* in a base-64 section */
4349 if (IS_BASE64(ch)) { /* consume a base-64 character */
4350 base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
4351 base64bits += 6;
4352 s++;
4353 if (base64bits >= 16) {
4354 /* we have enough bits for a UTF-16 value */
Victor Stinner24729f32011-11-10 20:31:37 +01004355 Py_UCS4 outCh = (Py_UCS4)(base64buffer >> (base64bits-16));
Antoine Pitrou244651a2009-05-04 18:56:13 +00004356 base64bits -= 16;
4357 base64buffer &= (1 << base64bits) - 1; /* clear high bits */
4358 if (surrogate) {
4359 /* expecting a second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004360 if (Py_UNICODE_IS_LOW_SURROGATE(outCh)) {
4361 Py_UCS4 ch2 = Py_UNICODE_JOIN_SURROGATES(surrogate, outCh);
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004362 if (unicode_putchar(&unicode, &outpos, ch2) < 0)
4363 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004364 surrogate = 0;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01004365 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004366 }
4367 else {
Antoine Pitrou78edf752011-11-15 01:44:16 +01004368 if (unicode_putchar(&unicode, &outpos, surrogate) < 0)
4369 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004370 surrogate = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004371 }
4372 }
Victor Stinner551ac952011-11-29 22:58:13 +01004373 if (Py_UNICODE_IS_HIGH_SURROGATE(outCh)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004374 /* first surrogate */
4375 surrogate = outCh;
4376 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004377 else {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004378 if (unicode_putchar(&unicode, &outpos, outCh) < 0)
4379 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004380 }
4381 }
4382 }
4383 else { /* now leaving a base-64 section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004384 inShift = 0;
4385 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004386 if (surrogate) {
Antoine Pitrou78edf752011-11-15 01:44:16 +01004387 if (unicode_putchar(&unicode, &outpos, surrogate) < 0)
4388 goto onError;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01004389 surrogate = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004390 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004391 if (base64bits > 0) { /* left-over bits */
4392 if (base64bits >= 6) {
4393 /* We've seen at least one base-64 character */
4394 errmsg = "partial character in shift sequence";
4395 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004396 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004397 else {
4398 /* Some bits remain; they should be zero */
4399 if (base64buffer != 0) {
4400 errmsg = "non-zero padding bits in shift sequence";
4401 goto utf7Error;
4402 }
4403 }
4404 }
4405 if (ch != '-') {
4406 /* '-' is absorbed; other terminating
4407 characters are preserved */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004408 if (unicode_putchar(&unicode, &outpos, ch) < 0)
4409 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004410 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004411 }
4412 }
4413 else if ( ch == '+' ) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004414 startinpos = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004415 s++; /* consume '+' */
4416 if (s < e && *s == '-') { /* '+-' encodes '+' */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004417 s++;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004418 if (unicode_putchar(&unicode, &outpos, '+') < 0)
4419 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004420 }
4421 else { /* begin base64-encoded section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004422 inShift = 1;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004423 shiftOutStart = outpos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004424 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004425 }
4426 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004427 else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004428 if (unicode_putchar(&unicode, &outpos, ch) < 0)
4429 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004430 s++;
4431 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004432 else {
4433 startinpos = s-starts;
4434 s++;
4435 errmsg = "unexpected special character";
4436 goto utf7Error;
4437 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004438 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004439utf7Error:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004440 endinpos = s-starts;
4441 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00004442 errors, &errorHandler,
4443 "utf7", errmsg,
4444 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004445 &unicode, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00004446 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004447 }
4448
Antoine Pitrou244651a2009-05-04 18:56:13 +00004449 /* end of string */
4450
4451 if (inShift && !consumed) { /* in shift sequence, no more to follow */
4452 /* if we're in an inconsistent state, that's an error */
4453 if (surrogate ||
4454 (base64bits >= 6) ||
4455 (base64bits > 0 && base64buffer != 0)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004456 endinpos = size;
4457 if (unicode_decode_call_errorhandler(
4458 errors, &errorHandler,
4459 "utf7", "unterminated shift sequence",
4460 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004461 &unicode, &outpos))
Antoine Pitrou244651a2009-05-04 18:56:13 +00004462 goto onError;
4463 if (s < e)
4464 goto restart;
4465 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004466 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004467
4468 /* return state */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004469 if (consumed) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004470 if (inShift) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004471 outpos = shiftOutStart; /* back off output */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004472 *consumed = startinpos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004473 }
4474 else {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004475 *consumed = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004476 }
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004477 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004478
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004479 if (unicode_resize(&unicode, outpos) < 0)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004480 goto onError;
4481
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004482 Py_XDECREF(errorHandler);
4483 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01004484 return unicode_result(unicode);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004485
Benjamin Peterson29060642009-01-31 22:14:21 +00004486 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004487 Py_XDECREF(errorHandler);
4488 Py_XDECREF(exc);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004489 Py_DECREF(unicode);
4490 return NULL;
4491}
4492
4493
Alexander Belopolsky40018472011-02-26 01:02:56 +00004494PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004495_PyUnicode_EncodeUTF7(PyObject *str,
4496 int base64SetO,
4497 int base64WhiteSpace,
4498 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004499{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004500 int kind;
4501 void *data;
4502 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004503 PyObject *v;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004504 Py_ssize_t allocated;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004505 int inShift = 0;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004506 Py_ssize_t i;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004507 unsigned int base64bits = 0;
4508 unsigned long base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004509 char * out;
4510 char * start;
4511
Benjamin Petersonbac79492012-01-14 13:34:47 -05004512 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004513 return NULL;
4514 kind = PyUnicode_KIND(str);
4515 data = PyUnicode_DATA(str);
4516 len = PyUnicode_GET_LENGTH(str);
4517
4518 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004519 return PyBytes_FromStringAndSize(NULL, 0);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004520
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004521 /* It might be possible to tighten this worst case */
4522 allocated = 8 * len;
4523 if (allocated / 8 != len)
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004524 return PyErr_NoMemory();
4525
Antoine Pitrou244651a2009-05-04 18:56:13 +00004526 v = PyBytes_FromStringAndSize(NULL, allocated);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004527 if (v == NULL)
4528 return NULL;
4529
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004530 start = out = PyBytes_AS_STRING(v);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004531 for (i = 0; i < len; ++i) {
Victor Stinner0e368262011-11-10 20:12:49 +01004532 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004533
Antoine Pitrou244651a2009-05-04 18:56:13 +00004534 if (inShift) {
4535 if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4536 /* shifting out */
4537 if (base64bits) { /* output remaining bits */
4538 *out++ = TO_BASE64(base64buffer << (6-base64bits));
4539 base64buffer = 0;
4540 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004541 }
4542 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004543 /* Characters not in the BASE64 set implicitly unshift the sequence
4544 so no '-' is required, except if the character is itself a '-' */
4545 if (IS_BASE64(ch) || ch == '-') {
4546 *out++ = '-';
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004547 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004548 *out++ = (char) ch;
4549 }
4550 else {
4551 goto encode_char;
Tim Petersced69f82003-09-16 20:30:58 +00004552 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004553 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004554 else { /* not in a shift sequence */
4555 if (ch == '+') {
4556 *out++ = '+';
4557 *out++ = '-';
4558 }
4559 else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4560 *out++ = (char) ch;
4561 }
4562 else {
4563 *out++ = '+';
4564 inShift = 1;
4565 goto encode_char;
4566 }
4567 }
4568 continue;
4569encode_char:
Antoine Pitrou244651a2009-05-04 18:56:13 +00004570 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01004571 assert(ch <= MAX_UNICODE);
Victor Stinner0d3721d2011-11-22 03:27:53 +01004572
Antoine Pitrou244651a2009-05-04 18:56:13 +00004573 /* code first surrogate */
4574 base64bits += 16;
4575 base64buffer = (base64buffer << 16) | 0xd800 | ((ch-0x10000) >> 10);
4576 while (base64bits >= 6) {
4577 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4578 base64bits -= 6;
4579 }
4580 /* prepare second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004581 ch = Py_UNICODE_LOW_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004582 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004583 base64bits += 16;
4584 base64buffer = (base64buffer << 16) | ch;
4585 while (base64bits >= 6) {
4586 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4587 base64bits -= 6;
4588 }
Hye-Shik Chang1bc09b72004-01-03 19:35:43 +00004589 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004590 if (base64bits)
4591 *out++= TO_BASE64(base64buffer << (6-base64bits) );
4592 if (inShift)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004593 *out++ = '-';
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004594 if (_PyBytes_Resize(&v, out - start) < 0)
4595 return NULL;
4596 return v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004597}
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004598PyObject *
4599PyUnicode_EncodeUTF7(const Py_UNICODE *s,
4600 Py_ssize_t size,
4601 int base64SetO,
4602 int base64WhiteSpace,
4603 const char *errors)
4604{
4605 PyObject *result;
4606 PyObject *tmp = PyUnicode_FromUnicode(s, size);
4607 if (tmp == NULL)
4608 return NULL;
Victor Stinner0e368262011-11-10 20:12:49 +01004609 result = _PyUnicode_EncodeUTF7(tmp, base64SetO,
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004610 base64WhiteSpace, errors);
4611 Py_DECREF(tmp);
4612 return result;
4613}
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004614
Antoine Pitrou244651a2009-05-04 18:56:13 +00004615#undef IS_BASE64
4616#undef FROM_BASE64
4617#undef TO_BASE64
4618#undef DECODE_DIRECT
4619#undef ENCODE_DIRECT
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004620
Guido van Rossumd57fd912000-03-10 22:53:23 +00004621/* --- UTF-8 Codec -------------------------------------------------------- */
4622
Alexander Belopolsky40018472011-02-26 01:02:56 +00004623PyObject *
4624PyUnicode_DecodeUTF8(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004625 Py_ssize_t size,
4626 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004627{
Walter Dörwald69652032004-09-07 20:24:22 +00004628 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
4629}
4630
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004631#include "stringlib/asciilib.h"
4632#include "stringlib/codecs.h"
4633#include "stringlib/undef.h"
4634
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004635#include "stringlib/ucs1lib.h"
4636#include "stringlib/codecs.h"
4637#include "stringlib/undef.h"
4638
4639#include "stringlib/ucs2lib.h"
4640#include "stringlib/codecs.h"
4641#include "stringlib/undef.h"
4642
4643#include "stringlib/ucs4lib.h"
4644#include "stringlib/codecs.h"
4645#include "stringlib/undef.h"
4646
Antoine Pitrouab868312009-01-10 15:40:25 +00004647/* Mask to check or force alignment of a pointer to C 'long' boundaries */
4648#define LONG_PTR_MASK (size_t) (SIZEOF_LONG - 1)
4649
4650/* Mask to quickly check whether a C 'long' contains a
4651 non-ASCII, UTF8-encoded char. */
4652#if (SIZEOF_LONG == 8)
4653# define ASCII_CHAR_MASK 0x8080808080808080L
4654#elif (SIZEOF_LONG == 4)
4655# define ASCII_CHAR_MASK 0x80808080L
4656#else
4657# error C 'long' size should be either 4 or 8!
4658#endif
4659
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004660static Py_ssize_t
4661ascii_decode(const char *start, const char *end, Py_UCS1 *dest)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004662{
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004663 const char *p = start;
4664 const char *aligned_end = (const char *) ((size_t) end & ~LONG_PTR_MASK);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004665
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004666#if SIZEOF_LONG <= SIZEOF_VOID_P
4667 assert(!((size_t) dest & LONG_PTR_MASK));
4668 if (!((size_t) p & LONG_PTR_MASK)) {
4669 /* Fast path, see in STRINGLIB(utf8_decode) for
4670 an explanation. */
4671 /* Help register allocation */
4672 register const char *_p = p;
4673 register Py_UCS1 * q = dest;
4674 while (_p < aligned_end) {
4675 unsigned long value = *(const unsigned long *) _p;
4676 if (value & ASCII_CHAR_MASK)
Benjamin Peterson29060642009-01-31 22:14:21 +00004677 break;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004678 *((unsigned long *)q) = value;
4679 _p += SIZEOF_LONG;
4680 q += SIZEOF_LONG;
Benjamin Peterson14339b62009-01-31 16:36:08 +00004681 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004682 p = _p;
4683 while (p < end) {
4684 if ((unsigned char)*p & 0x80)
4685 break;
4686 *q++ = *p++;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004687 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004688 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004689 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004690#endif
4691 while (p < end) {
4692 /* Fast path, see in STRINGLIB(utf8_decode) in stringlib/codecs.h
4693 for an explanation. */
4694 if (!((size_t) p & LONG_PTR_MASK)) {
4695 /* Help register allocation */
4696 register const char *_p = p;
4697 while (_p < aligned_end) {
4698 unsigned long value = *(unsigned long *) _p;
4699 if (value & ASCII_CHAR_MASK)
4700 break;
4701 _p += SIZEOF_LONG;
4702 }
4703 p = _p;
4704 if (_p == end)
4705 break;
4706 }
4707 if ((unsigned char)*p & 0x80)
4708 break;
4709 ++p;
4710 }
4711 memcpy(dest, start, p - start);
4712 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004713}
Antoine Pitrouab868312009-01-10 15:40:25 +00004714
Victor Stinner785938e2011-12-11 20:09:03 +01004715PyObject *
4716PyUnicode_DecodeUTF8Stateful(const char *s,
4717 Py_ssize_t size,
4718 const char *errors,
4719 Py_ssize_t *consumed)
4720{
Victor Stinner785938e2011-12-11 20:09:03 +01004721 PyObject *unicode;
Victor Stinner785938e2011-12-11 20:09:03 +01004722 const char *starts = s;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004723 const char *end = s + size;
4724 Py_ssize_t outpos;
4725
4726 Py_ssize_t startinpos;
4727 Py_ssize_t endinpos;
4728 const char *errmsg = "";
4729 PyObject *errorHandler = NULL;
4730 PyObject *exc = NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01004731
4732 if (size == 0) {
4733 if (consumed)
4734 *consumed = 0;
Victor Stinner382955f2011-12-11 21:44:00 +01004735 Py_INCREF(unicode_empty);
4736 return unicode_empty;
Victor Stinner785938e2011-12-11 20:09:03 +01004737 }
4738
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004739 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
4740 if (size == 1 && (unsigned char)s[0] < 128) {
Victor Stinner785938e2011-12-11 20:09:03 +01004741 if (consumed)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004742 *consumed = 1;
4743 return get_latin1_char((unsigned char)s[0]);
Victor Stinner785938e2011-12-11 20:09:03 +01004744 }
4745
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004746 unicode = PyUnicode_New(size, 127);
Victor Stinner785938e2011-12-11 20:09:03 +01004747 if (!unicode)
4748 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01004749
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004750 outpos = ascii_decode(s, end, PyUnicode_1BYTE_DATA(unicode));
4751 s += outpos;
4752 while (s < end) {
4753 Py_UCS4 ch;
4754 int kind = PyUnicode_KIND(unicode);
4755 if (kind == PyUnicode_1BYTE_KIND) {
4756 if (PyUnicode_IS_ASCII(unicode))
4757 ch = asciilib_utf8_decode(&s, end,
4758 PyUnicode_1BYTE_DATA(unicode), &outpos);
4759 else
4760 ch = ucs1lib_utf8_decode(&s, end,
4761 PyUnicode_1BYTE_DATA(unicode), &outpos);
4762 } else if (kind == PyUnicode_2BYTE_KIND) {
4763 ch = ucs2lib_utf8_decode(&s, end,
4764 PyUnicode_2BYTE_DATA(unicode), &outpos);
4765 } else {
4766 assert(kind == PyUnicode_4BYTE_KIND);
4767 ch = ucs4lib_utf8_decode(&s, end,
4768 PyUnicode_4BYTE_DATA(unicode), &outpos);
4769 }
4770
4771 switch (ch) {
4772 case 0:
4773 if (s == end || consumed)
4774 goto End;
4775 errmsg = "unexpected end of data";
4776 startinpos = s - starts;
4777 endinpos = startinpos + 1;
4778 while (endinpos < size && (starts[endinpos] & 0xC0) == 0x80)
4779 endinpos++;
4780 break;
4781 case 1:
4782 errmsg = "invalid start byte";
4783 startinpos = s - starts;
4784 endinpos = startinpos + 1;
4785 break;
4786 case 2:
4787 errmsg = "invalid continuation byte";
4788 startinpos = s - starts;
4789 endinpos = startinpos + 1;
4790 while (endinpos < size && (starts[endinpos] & 0xC0) == 0x80)
4791 endinpos++;
4792 break;
4793 default:
4794 if (unicode_putchar(&unicode, &outpos, ch) < 0)
4795 goto onError;
4796 continue;
4797 }
4798
4799 if (unicode_decode_call_errorhandler(
4800 errors, &errorHandler,
4801 "utf-8", errmsg,
4802 &starts, &end, &startinpos, &endinpos, &exc, &s,
4803 &unicode, &outpos))
4804 goto onError;
Victor Stinner785938e2011-12-11 20:09:03 +01004805 }
4806
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004807End:
4808 if (unicode_resize(&unicode, outpos) < 0)
4809 goto onError;
4810
4811 if (consumed)
4812 *consumed = s - starts;
4813
4814 Py_XDECREF(errorHandler);
4815 Py_XDECREF(exc);
4816 assert(_PyUnicode_CheckConsistency(unicode, 1));
4817 return unicode;
4818
4819onError:
4820 Py_XDECREF(errorHandler);
4821 Py_XDECREF(exc);
4822 Py_XDECREF(unicode);
4823 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01004824}
4825
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004826#ifdef __APPLE__
4827
4828/* Simplified UTF-8 decoder using surrogateescape error handler,
4829 used to decode the command line arguments on Mac OS X. */
4830
4831wchar_t*
4832_Py_DecodeUTF8_surrogateescape(const char *s, Py_ssize_t size)
4833{
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004834 const char *e;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004835 wchar_t *unicode;
4836 Py_ssize_t outpos;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004837
4838 /* Note: size will always be longer than the resulting Unicode
4839 character count */
4840 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < (size + 1)) {
4841 PyErr_NoMemory();
4842 return NULL;
4843 }
4844 unicode = PyMem_Malloc((size + 1) * sizeof(wchar_t));
4845 if (!unicode)
4846 return NULL;
4847
4848 /* Unpack UTF-8 encoded data */
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004849 e = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004850 outpos = 0;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004851 while (s < e) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004852 Py_UCS4 ch;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004853#if SIZEOF_WCHAR_T == 4
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004854 ch = ucs4lib_utf8_decode(&s, e, (Py_UCS4 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004855#else
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004856 ch = ucs2lib_utf8_decode(&s, e, (Py_UCS2 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004857#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004858 if (ch > 0xFF) {
4859#if SIZEOF_WCHAR_T == 4
4860 assert(0);
4861#else
4862 assert(Py_UNICODE_IS_SURROGATE(ch));
4863 /* compute and append the two surrogates: */
4864 unicode[outpos++] = (wchar_t)Py_UNICODE_HIGH_SURROGATE(ch);
4865 unicode[outpos++] = (wchar_t)Py_UNICODE_LOW_SURROGATE(ch);
4866#endif
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004867 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004868 else {
4869 if (!ch && s == e)
4870 break;
4871 /* surrogateescape */
4872 unicode[outpos++] = 0xDC00 + (unsigned char)*s++;
4873 }
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004874 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004875 unicode[outpos] = L'\0';
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004876 return unicode;
4877}
4878
4879#endif /* __APPLE__ */
Antoine Pitrouab868312009-01-10 15:40:25 +00004880
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004881/* Primary internal function which creates utf8 encoded bytes objects.
4882
4883 Allocation strategy: if the string is short, convert into a stack buffer
Tim Peters602f7402002-04-27 18:03:26 +00004884 and allocate exactly as much space needed at the end. Else allocate the
4885 maximum possible needed (4 result bytes per Unicode character), and return
4886 the excess memory at the end.
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004887*/
Tim Peters7e3d9612002-04-21 03:26:37 +00004888PyObject *
Victor Stinner7931d9a2011-11-04 00:22:48 +01004889_PyUnicode_AsUTF8String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004890{
Victor Stinner6099a032011-12-18 14:22:26 +01004891 enum PyUnicode_Kind kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004892 void *data;
4893 Py_ssize_t size;
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00004894
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004895 if (!PyUnicode_Check(unicode)) {
4896 PyErr_BadArgument();
4897 return NULL;
4898 }
4899
4900 if (PyUnicode_READY(unicode) == -1)
4901 return NULL;
4902
Victor Stinnere90fe6a2011-10-01 16:48:13 +02004903 if (PyUnicode_UTF8(unicode))
4904 return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode),
4905 PyUnicode_UTF8_LENGTH(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004906
4907 kind = PyUnicode_KIND(unicode);
4908 data = PyUnicode_DATA(unicode);
4909 size = PyUnicode_GET_LENGTH(unicode);
4910
Benjamin Petersonead6b532011-12-20 17:23:42 -06004911 switch (kind) {
Victor Stinner6099a032011-12-18 14:22:26 +01004912 default:
4913 assert(0);
4914 case PyUnicode_1BYTE_KIND:
4915 /* the string cannot be ASCII, or PyUnicode_UTF8() would be set */
4916 assert(!PyUnicode_IS_ASCII(unicode));
4917 return ucs1lib_utf8_encoder(unicode, data, size, errors);
4918 case PyUnicode_2BYTE_KIND:
4919 return ucs2lib_utf8_encoder(unicode, data, size, errors);
4920 case PyUnicode_4BYTE_KIND:
4921 return ucs4lib_utf8_encoder(unicode, data, size, errors);
Tim Peters602f7402002-04-27 18:03:26 +00004922 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004923}
4924
Alexander Belopolsky40018472011-02-26 01:02:56 +00004925PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004926PyUnicode_EncodeUTF8(const Py_UNICODE *s,
4927 Py_ssize_t size,
4928 const char *errors)
4929{
4930 PyObject *v, *unicode;
4931
4932 unicode = PyUnicode_FromUnicode(s, size);
4933 if (unicode == NULL)
4934 return NULL;
4935 v = _PyUnicode_AsUTF8String(unicode, errors);
4936 Py_DECREF(unicode);
4937 return v;
4938}
4939
4940PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00004941PyUnicode_AsUTF8String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004942{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004943 return _PyUnicode_AsUTF8String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004944}
4945
Walter Dörwald41980ca2007-08-16 21:55:45 +00004946/* --- UTF-32 Codec ------------------------------------------------------- */
4947
4948PyObject *
4949PyUnicode_DecodeUTF32(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004950 Py_ssize_t size,
4951 const char *errors,
4952 int *byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004953{
4954 return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
4955}
4956
4957PyObject *
4958PyUnicode_DecodeUTF32Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004959 Py_ssize_t size,
4960 const char *errors,
4961 int *byteorder,
4962 Py_ssize_t *consumed)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004963{
4964 const char *starts = s;
4965 Py_ssize_t startinpos;
4966 Py_ssize_t endinpos;
4967 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01004968 PyObject *unicode;
Mark Dickinson7db923c2010-06-12 09:10:14 +00004969 const unsigned char *q, *e;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004970 int bo = 0; /* assume native ordering by default */
4971 const char *errmsg = "";
Walter Dörwald41980ca2007-08-16 21:55:45 +00004972 /* Offsets from q for retrieving bytes in the right order. */
4973#ifdef BYTEORDER_IS_LITTLE_ENDIAN
4974 int iorder[] = {0, 1, 2, 3};
4975#else
4976 int iorder[] = {3, 2, 1, 0};
4977#endif
4978 PyObject *errorHandler = NULL;
4979 PyObject *exc = NULL;
Victor Stinner313a1202010-06-11 23:56:51 +00004980
Walter Dörwald41980ca2007-08-16 21:55:45 +00004981 q = (unsigned char *)s;
4982 e = q + size;
4983
4984 if (byteorder)
4985 bo = *byteorder;
4986
4987 /* Check for BOM marks (U+FEFF) in the input and adjust current
4988 byte order setting accordingly. In native mode, the leading BOM
4989 mark is skipped, in all other modes, it is copied to the output
4990 stream as-is (giving a ZWNBSP character). */
4991 if (bo == 0) {
4992 if (size >= 4) {
4993 const Py_UCS4 bom = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
Benjamin Peterson29060642009-01-31 22:14:21 +00004994 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00004995#ifdef BYTEORDER_IS_LITTLE_ENDIAN
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#else
Benjamin Peterson29060642009-01-31 22:14:21 +00005005 if (bom == 0x0000FEFF) {
5006 q += 4;
5007 bo = 1;
5008 }
5009 else if (bom == 0xFFFE0000) {
5010 q += 4;
5011 bo = -1;
5012 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00005013#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00005014 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00005015 }
5016
5017 if (bo == -1) {
5018 /* force LE */
5019 iorder[0] = 0;
5020 iorder[1] = 1;
5021 iorder[2] = 2;
5022 iorder[3] = 3;
5023 }
5024 else if (bo == 1) {
5025 /* force BE */
5026 iorder[0] = 3;
5027 iorder[1] = 2;
5028 iorder[2] = 1;
5029 iorder[3] = 0;
5030 }
5031
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005032 /* This might be one to much, because of a BOM */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005033 unicode = PyUnicode_New((size+3)/4, 127);
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005034 if (!unicode)
5035 return NULL;
5036 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01005037 return unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005038 outpos = 0;
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005039
Walter Dörwald41980ca2007-08-16 21:55:45 +00005040 while (q < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005041 Py_UCS4 ch;
5042 /* remaining bytes at the end? (size should be divisible by 4) */
5043 if (e-q<4) {
5044 if (consumed)
5045 break;
5046 errmsg = "truncated data";
5047 startinpos = ((const char *)q)-starts;
5048 endinpos = ((const char *)e)-starts;
5049 goto utf32Error;
5050 /* The remaining input chars are ignored if the callback
5051 chooses to skip the input */
5052 }
5053 ch = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
5054 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00005055
Benjamin Peterson29060642009-01-31 22:14:21 +00005056 if (ch >= 0x110000)
5057 {
5058 errmsg = "codepoint not in range(0x110000)";
5059 startinpos = ((const char *)q)-starts;
5060 endinpos = startinpos+4;
5061 goto utf32Error;
5062 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005063 if (unicode_putchar(&unicode, &outpos, ch) < 0)
5064 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005065 q += 4;
5066 continue;
5067 utf32Error:
Benjamin Peterson29060642009-01-31 22:14:21 +00005068 if (unicode_decode_call_errorhandler(
5069 errors, &errorHandler,
5070 "utf32", errmsg,
5071 &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005072 &unicode, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00005073 goto onError;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005074 }
5075
5076 if (byteorder)
5077 *byteorder = bo;
5078
5079 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005080 *consumed = (const char *)q-starts;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005081
5082 /* Adjust length */
Victor Stinner16e6a802011-12-12 13:24:15 +01005083 if (unicode_resize(&unicode, outpos) < 0)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005084 goto onError;
5085
5086 Py_XDECREF(errorHandler);
5087 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01005088 return unicode_result(unicode);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005089
Benjamin Peterson29060642009-01-31 22:14:21 +00005090 onError:
Walter Dörwald41980ca2007-08-16 21:55:45 +00005091 Py_DECREF(unicode);
5092 Py_XDECREF(errorHandler);
5093 Py_XDECREF(exc);
5094 return NULL;
5095}
5096
5097PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005098_PyUnicode_EncodeUTF32(PyObject *str,
5099 const char *errors,
5100 int byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005101{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005102 int kind;
5103 void *data;
5104 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005105 PyObject *v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005106 unsigned char *p;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005107 Py_ssize_t nsize, bytesize, i;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005108 /* Offsets from p for storing byte pairs in the right order. */
5109#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5110 int iorder[] = {0, 1, 2, 3};
5111#else
5112 int iorder[] = {3, 2, 1, 0};
5113#endif
5114
Benjamin Peterson29060642009-01-31 22:14:21 +00005115#define STORECHAR(CH) \
5116 do { \
5117 p[iorder[3]] = ((CH) >> 24) & 0xff; \
5118 p[iorder[2]] = ((CH) >> 16) & 0xff; \
5119 p[iorder[1]] = ((CH) >> 8) & 0xff; \
5120 p[iorder[0]] = (CH) & 0xff; \
5121 p += 4; \
Walter Dörwald41980ca2007-08-16 21:55:45 +00005122 } while(0)
5123
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005124 if (!PyUnicode_Check(str)) {
5125 PyErr_BadArgument();
5126 return NULL;
5127 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005128 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005129 return NULL;
5130 kind = PyUnicode_KIND(str);
5131 data = PyUnicode_DATA(str);
5132 len = PyUnicode_GET_LENGTH(str);
5133
5134 nsize = len + (byteorder == 0);
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005135 bytesize = nsize * 4;
5136 if (bytesize / 4 != nsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005137 return PyErr_NoMemory();
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005138 v = PyBytes_FromStringAndSize(NULL, bytesize);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005139 if (v == NULL)
5140 return NULL;
5141
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005142 p = (unsigned char *)PyBytes_AS_STRING(v);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005143 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005144 STORECHAR(0xFEFF);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005145 if (len == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005146 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005147
5148 if (byteorder == -1) {
5149 /* force LE */
5150 iorder[0] = 0;
5151 iorder[1] = 1;
5152 iorder[2] = 2;
5153 iorder[3] = 3;
5154 }
5155 else if (byteorder == 1) {
5156 /* force BE */
5157 iorder[0] = 3;
5158 iorder[1] = 2;
5159 iorder[2] = 1;
5160 iorder[3] = 0;
5161 }
5162
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005163 for (i = 0; i < len; i++)
5164 STORECHAR(PyUnicode_READ(kind, data, i));
Guido van Rossum98297ee2007-11-06 21:34:58 +00005165
5166 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005167 return v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005168#undef STORECHAR
5169}
5170
Alexander Belopolsky40018472011-02-26 01:02:56 +00005171PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005172PyUnicode_EncodeUTF32(const Py_UNICODE *s,
5173 Py_ssize_t size,
5174 const char *errors,
5175 int byteorder)
5176{
5177 PyObject *result;
5178 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5179 if (tmp == NULL)
5180 return NULL;
5181 result = _PyUnicode_EncodeUTF32(tmp, errors, byteorder);
5182 Py_DECREF(tmp);
5183 return result;
5184}
5185
5186PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005187PyUnicode_AsUTF32String(PyObject *unicode)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005188{
Victor Stinnerb960b342011-11-20 19:12:52 +01005189 return _PyUnicode_EncodeUTF32(unicode, NULL, 0);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005190}
5191
Guido van Rossumd57fd912000-03-10 22:53:23 +00005192/* --- UTF-16 Codec ------------------------------------------------------- */
5193
Tim Peters772747b2001-08-09 22:21:55 +00005194PyObject *
5195PyUnicode_DecodeUTF16(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005196 Py_ssize_t size,
5197 const char *errors,
5198 int *byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005199{
Walter Dörwald69652032004-09-07 20:24:22 +00005200 return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
5201}
5202
5203PyObject *
5204PyUnicode_DecodeUTF16Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005205 Py_ssize_t size,
5206 const char *errors,
5207 int *byteorder,
5208 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00005209{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005210 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005211 Py_ssize_t startinpos;
5212 Py_ssize_t endinpos;
5213 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01005214 PyObject *unicode;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005215 const unsigned char *q, *e;
Tim Peters772747b2001-08-09 22:21:55 +00005216 int bo = 0; /* assume native ordering by default */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005217 int native_ordering;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00005218 const char *errmsg = "";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005219 PyObject *errorHandler = NULL;
5220 PyObject *exc = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005221
Tim Peters772747b2001-08-09 22:21:55 +00005222 q = (unsigned char *)s;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005223 e = q + size;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005224
5225 if (byteorder)
Tim Peters772747b2001-08-09 22:21:55 +00005226 bo = *byteorder;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005227
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005228 /* Check for BOM marks (U+FEFF) in the input and adjust current
5229 byte order setting accordingly. In native mode, the leading BOM
5230 mark is skipped, in all other modes, it is copied to the output
5231 stream as-is (giving a ZWNBSP character). */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005232 if (bo == 0 && size >= 2) {
5233 const Py_UCS4 bom = (q[1] << 8) | q[0];
5234 if (bom == 0xFEFF) {
5235 q += 2;
5236 bo = -1;
Benjamin Peterson29060642009-01-31 22:14:21 +00005237 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005238 else if (bom == 0xFFFE) {
5239 q += 2;
5240 bo = 1;
5241 }
5242 if (byteorder)
5243 *byteorder = bo;
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005244 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005245
Antoine Pitrou63065d72012-05-15 23:48:04 +02005246 if (q == e) {
5247 if (consumed)
5248 *consumed = size;
5249 Py_INCREF(unicode_empty);
5250 return unicode_empty;
Tim Peters772747b2001-08-09 22:21:55 +00005251 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005252
Antoine Pitrouab868312009-01-10 15:40:25 +00005253#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Antoine Pitrou63065d72012-05-15 23:48:04 +02005254 native_ordering = bo <= 0;
Antoine Pitrouab868312009-01-10 15:40:25 +00005255#else
Antoine Pitrou63065d72012-05-15 23:48:04 +02005256 native_ordering = bo >= 0;
Antoine Pitrouab868312009-01-10 15:40:25 +00005257#endif
Tim Peters772747b2001-08-09 22:21:55 +00005258
Antoine Pitrou63065d72012-05-15 23:48:04 +02005259 /* Note: size will always be longer than the resulting Unicode
5260 character count */
5261 unicode = PyUnicode_New((e - q + 1) / 2, 127);
5262 if (!unicode)
5263 return NULL;
5264
5265 outpos = 0;
5266 while (1) {
5267 Py_UCS4 ch = 0;
5268 if (e - q >= 2) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005269 int kind = PyUnicode_KIND(unicode);
Antoine Pitrou63065d72012-05-15 23:48:04 +02005270 if (kind == PyUnicode_1BYTE_KIND) {
5271 if (PyUnicode_IS_ASCII(unicode))
5272 ch = asciilib_utf16_decode(&q, e,
5273 PyUnicode_1BYTE_DATA(unicode), &outpos,
5274 native_ordering);
5275 else
5276 ch = ucs1lib_utf16_decode(&q, e,
5277 PyUnicode_1BYTE_DATA(unicode), &outpos,
5278 native_ordering);
5279 } else if (kind == PyUnicode_2BYTE_KIND) {
5280 ch = ucs2lib_utf16_decode(&q, e,
5281 PyUnicode_2BYTE_DATA(unicode), &outpos,
5282 native_ordering);
5283 } else {
5284 assert(kind == PyUnicode_4BYTE_KIND);
5285 ch = ucs4lib_utf16_decode(&q, e,
5286 PyUnicode_4BYTE_DATA(unicode), &outpos,
5287 native_ordering);
Antoine Pitrouab868312009-01-10 15:40:25 +00005288 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005289 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005290
Antoine Pitrou63065d72012-05-15 23:48:04 +02005291 switch (ch)
5292 {
5293 case 0:
5294 /* remaining byte at the end? (size should be even) */
5295 if (q == e || consumed)
5296 goto End;
5297 errmsg = "truncated data";
5298 startinpos = ((const char *)q) - starts;
5299 endinpos = ((const char *)e) - starts;
5300 break;
5301 /* The remaining input chars are ignored if the callback
5302 chooses to skip the input */
5303 case 1:
5304 errmsg = "unexpected end of data";
5305 startinpos = ((const char *)q) - 2 - starts;
5306 endinpos = ((const char *)e) - starts;
5307 break;
5308 case 2:
5309 errmsg = "illegal encoding";
5310 startinpos = ((const char *)q) - 2 - starts;
5311 endinpos = startinpos + 2;
5312 break;
5313 case 3:
5314 errmsg = "illegal UTF-16 surrogate";
5315 startinpos = ((const char *)q) - 4 - starts;
5316 endinpos = startinpos + 2;
5317 break;
5318 default:
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005319 if (unicode_putchar(&unicode, &outpos, ch) < 0)
5320 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005321 continue;
5322 }
5323
Benjamin Peterson29060642009-01-31 22:14:21 +00005324 if (unicode_decode_call_errorhandler(
Antoine Pitrouab868312009-01-10 15:40:25 +00005325 errors,
5326 &errorHandler,
5327 "utf16", errmsg,
5328 &starts,
5329 (const char **)&e,
5330 &startinpos,
5331 &endinpos,
5332 &exc,
5333 (const char **)&q,
5334 &unicode,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005335 &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00005336 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005337 }
5338
Antoine Pitrou63065d72012-05-15 23:48:04 +02005339End:
Walter Dörwald69652032004-09-07 20:24:22 +00005340 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005341 *consumed = (const char *)q-starts;
Walter Dörwald69652032004-09-07 20:24:22 +00005342
Guido van Rossumd57fd912000-03-10 22:53:23 +00005343 /* Adjust length */
Victor Stinner16e6a802011-12-12 13:24:15 +01005344 if (unicode_resize(&unicode, outpos) < 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005345 goto onError;
5346
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005347 Py_XDECREF(errorHandler);
5348 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01005349 return unicode_result(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005350
Benjamin Peterson29060642009-01-31 22:14:21 +00005351 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00005352 Py_DECREF(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005353 Py_XDECREF(errorHandler);
5354 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005355 return NULL;
5356}
5357
Tim Peters772747b2001-08-09 22:21:55 +00005358PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005359_PyUnicode_EncodeUTF16(PyObject *str,
5360 const char *errors,
5361 int byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005362{
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005363 enum PyUnicode_Kind kind;
5364 const void *data;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005365 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005366 PyObject *v;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005367 unsigned short *out;
5368 Py_ssize_t bytesize;
5369 Py_ssize_t pairs;
5370#ifdef WORDS_BIGENDIAN
5371 int native_ordering = byteorder >= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005372#else
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005373 int native_ordering = byteorder <= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005374#endif
5375
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005376 if (!PyUnicode_Check(str)) {
5377 PyErr_BadArgument();
5378 return NULL;
5379 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005380 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005381 return NULL;
5382 kind = PyUnicode_KIND(str);
5383 data = PyUnicode_DATA(str);
5384 len = PyUnicode_GET_LENGTH(str);
Victor Stinner0e368262011-11-10 20:12:49 +01005385
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005386 pairs = 0;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005387 if (kind == PyUnicode_4BYTE_KIND) {
5388 const Py_UCS4 *in = (const Py_UCS4 *)data;
5389 const Py_UCS4 *end = in + len;
5390 while (in < end)
5391 if (*in++ >= 0x10000)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005392 pairs++;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005393 }
5394 if (len > PY_SSIZE_T_MAX / 2 - pairs - (byteorder == 0))
Benjamin Peterson29060642009-01-31 22:14:21 +00005395 return PyErr_NoMemory();
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005396 bytesize = (len + pairs + (byteorder == 0)) * 2;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005397 v = PyBytes_FromStringAndSize(NULL, bytesize);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005398 if (v == NULL)
5399 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005400
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005401 /* output buffer is 2-bytes aligned */
5402 assert(((Py_uintptr_t)PyBytes_AS_STRING(v) & 1) == 0);
5403 out = (unsigned short *)PyBytes_AS_STRING(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005404 if (byteorder == 0)
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005405 *out++ = 0xFEFF;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005406 if (len == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005407 goto done;
Tim Peters772747b2001-08-09 22:21:55 +00005408
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005409 switch (kind) {
5410 case PyUnicode_1BYTE_KIND: {
5411 ucs1lib_utf16_encode(out, (const Py_UCS1 *)data, len, native_ordering);
5412 break;
Tim Peters772747b2001-08-09 22:21:55 +00005413 }
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005414 case PyUnicode_2BYTE_KIND: {
5415 ucs2lib_utf16_encode(out, (const Py_UCS2 *)data, len, native_ordering);
5416 break;
Tim Peters772747b2001-08-09 22:21:55 +00005417 }
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005418 case PyUnicode_4BYTE_KIND: {
5419 ucs4lib_utf16_encode(out, (const Py_UCS4 *)data, len, native_ordering);
5420 break;
5421 }
5422 default:
5423 assert(0);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005424 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005425
5426 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005427 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005428}
5429
Alexander Belopolsky40018472011-02-26 01:02:56 +00005430PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005431PyUnicode_EncodeUTF16(const Py_UNICODE *s,
5432 Py_ssize_t size,
5433 const char *errors,
5434 int byteorder)
5435{
5436 PyObject *result;
5437 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5438 if (tmp == NULL)
5439 return NULL;
5440 result = _PyUnicode_EncodeUTF16(tmp, errors, byteorder);
5441 Py_DECREF(tmp);
5442 return result;
5443}
5444
5445PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005446PyUnicode_AsUTF16String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005447{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005448 return _PyUnicode_EncodeUTF16(unicode, NULL, 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005449}
5450
5451/* --- Unicode Escape Codec ----------------------------------------------- */
5452
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005453/* Helper function for PyUnicode_DecodeUnicodeEscape, determines
5454 if all the escapes in the string make it still a valid ASCII string.
5455 Returns -1 if any escapes were found which cause the string to
5456 pop out of ASCII range. Otherwise returns the length of the
5457 required buffer to hold the string.
5458 */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02005459static Py_ssize_t
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005460length_of_escaped_ascii_string(const char *s, Py_ssize_t size)
5461{
5462 const unsigned char *p = (const unsigned char *)s;
5463 const unsigned char *end = p + size;
5464 Py_ssize_t length = 0;
5465
5466 if (size < 0)
5467 return -1;
5468
5469 for (; p < end; ++p) {
5470 if (*p > 127) {
5471 /* Non-ASCII */
5472 return -1;
5473 }
5474 else if (*p != '\\') {
5475 /* Normal character */
5476 ++length;
5477 }
5478 else {
5479 /* Backslash-escape, check next char */
5480 ++p;
5481 /* Escape sequence reaches till end of string or
5482 non-ASCII follow-up. */
5483 if (p >= end || *p > 127)
5484 return -1;
5485 switch (*p) {
5486 case '\n':
5487 /* backslash + \n result in zero characters */
5488 break;
5489 case '\\': case '\'': case '\"':
5490 case 'b': case 'f': case 't':
5491 case 'n': case 'r': case 'v': case 'a':
5492 ++length;
5493 break;
5494 case '0': case '1': case '2': case '3':
5495 case '4': case '5': case '6': case '7':
5496 case 'x': case 'u': case 'U': case 'N':
5497 /* these do not guarantee ASCII characters */
5498 return -1;
5499 default:
5500 /* count the backslash + the other character */
5501 length += 2;
5502 }
5503 }
5504 }
5505 return length;
5506}
5507
Fredrik Lundh06d12682001-01-24 07:59:11 +00005508static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
Marc-André Lemburg0f774e32000-06-28 16:43:35 +00005509
Alexander Belopolsky40018472011-02-26 01:02:56 +00005510PyObject *
5511PyUnicode_DecodeUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005512 Py_ssize_t size,
Victor Stinnerc17f5402011-09-29 00:16:58 +02005513 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005514{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005515 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005516 Py_ssize_t startinpos;
5517 Py_ssize_t endinpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005518 int j;
Victor Stinner7931d9a2011-11-04 00:22:48 +01005519 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005520 const char *end;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005521 char* message;
5522 Py_UCS4 chr = 0xffffffff; /* in case 'getcode' messes up */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005523 PyObject *errorHandler = NULL;
5524 PyObject *exc = NULL;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005525 Py_ssize_t len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005526 Py_ssize_t i;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005527
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005528 len = length_of_escaped_ascii_string(s, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005529
5530 /* After length_of_escaped_ascii_string() there are two alternatives,
5531 either the string is pure ASCII with named escapes like \n, etc.
5532 and we determined it's exact size (common case)
5533 or it contains \x, \u, ... escape sequences. then we create a
5534 legacy wchar string and resize it at the end of this function. */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005535 if (len >= 0) {
5536 v = PyUnicode_New(len, 127);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005537 if (!v)
5538 goto onError;
5539 assert(PyUnicode_KIND(v) == PyUnicode_1BYTE_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005540 }
5541 else {
5542 /* Escaped strings will always be longer than the resulting
5543 Unicode string, so we start with size here and then reduce the
5544 length after conversion to the true value.
5545 (but if the error callback returns a long replacement string
5546 we'll have to allocate more space) */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005547 v = PyUnicode_New(size, 127);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005548 if (!v)
5549 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005550 len = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005551 }
5552
Guido van Rossumd57fd912000-03-10 22:53:23 +00005553 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01005554 return v;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005555 i = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005556 end = s + size;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005557
Guido van Rossumd57fd912000-03-10 22:53:23 +00005558 while (s < end) {
5559 unsigned char c;
Victor Stinner24729f32011-11-10 20:31:37 +01005560 Py_UCS4 x;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005561 int digits;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005562
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005563 /* The only case in which i == ascii_length is a backslash
5564 followed by a newline. */
5565 assert(i <= len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005566
Guido van Rossumd57fd912000-03-10 22:53:23 +00005567 /* Non-escape characters are interpreted as Unicode ordinals */
5568 if (*s != '\\') {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005569 if (unicode_putchar(&v, &i, (unsigned char) *s++) < 0)
5570 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005571 continue;
5572 }
5573
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005574 startinpos = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005575 /* \ - Escapes */
5576 s++;
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005577 c = *s++;
5578 if (s > end)
5579 c = '\0'; /* Invalid after \ */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005580
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005581 /* The only case in which i == ascii_length is a backslash
5582 followed by a newline. */
5583 assert(i < len || (i == len && c == '\n'));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005584
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005585 switch (c) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005586
Benjamin Peterson29060642009-01-31 22:14:21 +00005587 /* \x escapes */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005588#define WRITECHAR(ch) \
5589 do { \
5590 if (unicode_putchar(&v, &i, ch) < 0) \
5591 goto onError; \
5592 }while(0)
5593
Guido van Rossumd57fd912000-03-10 22:53:23 +00005594 case '\n': break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005595 case '\\': WRITECHAR('\\'); break;
5596 case '\'': WRITECHAR('\''); break;
5597 case '\"': WRITECHAR('\"'); break;
5598 case 'b': WRITECHAR('\b'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005599 /* FF */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005600 case 'f': WRITECHAR('\014'); break;
5601 case 't': WRITECHAR('\t'); break;
5602 case 'n': WRITECHAR('\n'); break;
5603 case 'r': WRITECHAR('\r'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005604 /* VT */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005605 case 'v': WRITECHAR('\013'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005606 /* BEL, not classic C */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005607 case 'a': WRITECHAR('\007'); break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005608
Benjamin Peterson29060642009-01-31 22:14:21 +00005609 /* \OOO (octal) escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005610 case '0': case '1': case '2': case '3':
5611 case '4': case '5': case '6': case '7':
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005612 x = s[-1] - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005613 if (s < end && '0' <= *s && *s <= '7') {
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005614 x = (x<<3) + *s++ - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005615 if (s < end && '0' <= *s && *s <= '7')
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005616 x = (x<<3) + *s++ - '0';
Guido van Rossumd57fd912000-03-10 22:53:23 +00005617 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005618 WRITECHAR(x);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005619 break;
5620
Benjamin Peterson29060642009-01-31 22:14:21 +00005621 /* hex escapes */
5622 /* \xXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005623 case 'x':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005624 digits = 2;
5625 message = "truncated \\xXX escape";
5626 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005627
Benjamin Peterson29060642009-01-31 22:14:21 +00005628 /* \uXXXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005629 case 'u':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005630 digits = 4;
5631 message = "truncated \\uXXXX escape";
5632 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005633
Benjamin Peterson29060642009-01-31 22:14:21 +00005634 /* \UXXXXXXXX */
Fredrik Lundhdf846752000-09-03 11:29:49 +00005635 case 'U':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005636 digits = 8;
5637 message = "truncated \\UXXXXXXXX escape";
5638 hexescape:
5639 chr = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005640 if (s+digits>end) {
5641 endinpos = size;
5642 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005643 errors, &errorHandler,
5644 "unicodeescape", "end of string in escape sequence",
5645 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005646 &v, &i))
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005647 goto onError;
5648 goto nextByte;
5649 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005650 for (j = 0; j < digits; ++j) {
5651 c = (unsigned char) s[j];
David Malcolm96960882010-11-05 17:23:41 +00005652 if (!Py_ISXDIGIT(c)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005653 endinpos = (s+j+1)-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005654 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005655 errors, &errorHandler,
5656 "unicodeescape", message,
5657 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005658 &v, &i))
Fredrik Lundhdf846752000-09-03 11:29:49 +00005659 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005660 len = PyUnicode_GET_LENGTH(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005661 goto nextByte;
Fredrik Lundhdf846752000-09-03 11:29:49 +00005662 }
5663 chr = (chr<<4) & ~0xF;
5664 if (c >= '0' && c <= '9')
5665 chr += c - '0';
5666 else if (c >= 'a' && c <= 'f')
5667 chr += 10 + c - 'a';
5668 else
5669 chr += 10 + c - 'A';
5670 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005671 s += j;
Jeremy Hylton504de6b2003-10-06 05:08:26 +00005672 if (chr == 0xffffffff && PyErr_Occurred())
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005673 /* _decoding_error will have already written into the
5674 target buffer. */
5675 break;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005676 store:
Fredrik Lundhdf846752000-09-03 11:29:49 +00005677 /* when we get here, chr is a 32-bit unicode character */
Victor Stinner8faf8212011-12-08 22:14:11 +01005678 if (chr <= MAX_UNICODE) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005679 WRITECHAR(chr);
Fredrik Lundhdf846752000-09-03 11:29:49 +00005680 } else {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005681 endinpos = s-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005682 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005683 errors, &errorHandler,
5684 "unicodeescape", "illegal Unicode character",
5685 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005686 &v, &i))
Fredrik Lundhdf846752000-09-03 11:29:49 +00005687 goto onError;
5688 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00005689 break;
5690
Benjamin Peterson29060642009-01-31 22:14:21 +00005691 /* \N{name} */
Fredrik Lundhccc74732001-02-18 22:13:49 +00005692 case 'N':
5693 message = "malformed \\N character escape";
5694 if (ucnhash_CAPI == NULL) {
5695 /* load the unicode data module */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005696 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
5697 PyUnicodeData_CAPSULE_NAME, 1);
Fredrik Lundhccc74732001-02-18 22:13:49 +00005698 if (ucnhash_CAPI == NULL)
5699 goto ucnhashError;
5700 }
5701 if (*s == '{') {
5702 const char *start = s+1;
5703 /* look for the closing brace */
5704 while (*s != '}' && s < end)
5705 s++;
5706 if (s > start && s < end && *s == '}') {
5707 /* found a name. look it up in the unicode database */
5708 message = "unknown Unicode character name";
5709 s++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005710 if (ucnhash_CAPI->getcode(NULL, start, (int)(s-start-1),
Ezio Melotti931b8aa2011-10-21 21:57:36 +03005711 &chr, 0))
Fredrik Lundhccc74732001-02-18 22:13:49 +00005712 goto store;
5713 }
5714 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005715 endinpos = s-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005716 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005717 errors, &errorHandler,
5718 "unicodeescape", message,
5719 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005720 &v, &i))
Fredrik Lundhccc74732001-02-18 22:13:49 +00005721 goto onError;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005722 break;
5723
5724 default:
Walter Dörwald8c077222002-03-25 11:16:18 +00005725 if (s > end) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005726 message = "\\ at end of string";
5727 s--;
5728 endinpos = s-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005729 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005730 errors, &errorHandler,
5731 "unicodeescape", message,
5732 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005733 &v, &i))
Walter Dörwald8c077222002-03-25 11:16:18 +00005734 goto onError;
5735 }
5736 else {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005737 WRITECHAR('\\');
5738 WRITECHAR(s[-1]);
Walter Dörwald8c077222002-03-25 11:16:18 +00005739 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00005740 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005741 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005742 nextByte:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005743 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005744 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005745#undef WRITECHAR
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005746
Victor Stinner16e6a802011-12-12 13:24:15 +01005747 if (unicode_resize(&v, i) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005748 goto onError;
Walter Dörwaldd4ade082003-08-15 15:00:26 +00005749 Py_XDECREF(errorHandler);
5750 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01005751 return unicode_result(v);
Walter Dörwald8c077222002-03-25 11:16:18 +00005752
Benjamin Peterson29060642009-01-31 22:14:21 +00005753 ucnhashError:
Fredrik Lundh06d12682001-01-24 07:59:11 +00005754 PyErr_SetString(
5755 PyExc_UnicodeError,
5756 "\\N escapes not supported (can't load unicodedata module)"
5757 );
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00005758 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005759 Py_XDECREF(errorHandler);
5760 Py_XDECREF(exc);
Fredrik Lundhf6056062001-01-20 11:15:25 +00005761 return NULL;
5762
Benjamin Peterson29060642009-01-31 22:14:21 +00005763 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00005764 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005765 Py_XDECREF(errorHandler);
5766 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005767 return NULL;
5768}
5769
5770/* Return a Unicode-Escape string version of the Unicode object.
5771
5772 If quotes is true, the string is enclosed in u"" or u'' quotes as
5773 appropriate.
5774
5775*/
5776
Alexander Belopolsky40018472011-02-26 01:02:56 +00005777PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005778PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005779{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005780 Py_ssize_t i, len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005781 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005782 char *p;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005783 int kind;
5784 void *data;
5785 Py_ssize_t expandsize = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005786
Thomas Wouters89f507f2006-12-13 04:49:30 +00005787 /* Initial allocation is based on the longest-possible unichr
5788 escape.
5789
5790 In wide (UTF-32) builds '\U00xxxxxx' is 10 chars per source
5791 unichr, so in this case it's the longest unichr escape. In
5792 narrow (UTF-16) builds this is five chars per source unichr
5793 since there are two unichrs in the surrogate pair, so in narrow
5794 (UTF-16) builds it's not the longest unichr escape.
5795
5796 In wide or narrow builds '\uxxxx' is 6 chars per source unichr,
5797 so in the narrow (UTF-16) build case it's the longest unichr
5798 escape.
5799 */
5800
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005801 if (!PyUnicode_Check(unicode)) {
5802 PyErr_BadArgument();
5803 return NULL;
5804 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005805 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005806 return NULL;
5807 len = PyUnicode_GET_LENGTH(unicode);
5808 kind = PyUnicode_KIND(unicode);
5809 data = PyUnicode_DATA(unicode);
Benjamin Petersonead6b532011-12-20 17:23:42 -06005810 switch (kind) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005811 case PyUnicode_1BYTE_KIND: expandsize = 4; break;
5812 case PyUnicode_2BYTE_KIND: expandsize = 6; break;
5813 case PyUnicode_4BYTE_KIND: expandsize = 10; break;
5814 }
5815
5816 if (len == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005817 return PyBytes_FromStringAndSize(NULL, 0);
5818
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005819 if (len > (PY_SSIZE_T_MAX - 2 - 1) / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005820 return PyErr_NoMemory();
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005821
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005822 repr = PyBytes_FromStringAndSize(NULL,
Benjamin Peterson29060642009-01-31 22:14:21 +00005823 2
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005824 + expandsize*len
Benjamin Peterson29060642009-01-31 22:14:21 +00005825 + 1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005826 if (repr == NULL)
5827 return NULL;
5828
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005829 p = PyBytes_AS_STRING(repr);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005830
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005831 for (i = 0; i < len; i++) {
Victor Stinner3326cb62011-11-10 20:15:25 +01005832 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005833
Walter Dörwald79e913e2007-05-12 11:08:06 +00005834 /* Escape backslashes */
5835 if (ch == '\\') {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005836 *p++ = '\\';
5837 *p++ = (char) ch;
Walter Dörwald79e913e2007-05-12 11:08:06 +00005838 continue;
Tim Petersced69f82003-09-16 20:30:58 +00005839 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005840
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005841 /* Map 21-bit characters to '\U00xxxxxx' */
5842 else if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01005843 assert(ch <= MAX_UNICODE);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005844 *p++ = '\\';
5845 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005846 *p++ = Py_hexdigits[(ch >> 28) & 0x0000000F];
5847 *p++ = Py_hexdigits[(ch >> 24) & 0x0000000F];
5848 *p++ = Py_hexdigits[(ch >> 20) & 0x0000000F];
5849 *p++ = Py_hexdigits[(ch >> 16) & 0x0000000F];
5850 *p++ = Py_hexdigits[(ch >> 12) & 0x0000000F];
5851 *p++ = Py_hexdigits[(ch >> 8) & 0x0000000F];
5852 *p++ = Py_hexdigits[(ch >> 4) & 0x0000000F];
5853 *p++ = Py_hexdigits[ch & 0x0000000F];
Benjamin Peterson29060642009-01-31 22:14:21 +00005854 continue;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005855 }
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005856
Guido van Rossumd57fd912000-03-10 22:53:23 +00005857 /* Map 16-bit characters to '\uxxxx' */
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005858 if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005859 *p++ = '\\';
5860 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005861 *p++ = Py_hexdigits[(ch >> 12) & 0x000F];
5862 *p++ = Py_hexdigits[(ch >> 8) & 0x000F];
5863 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
5864 *p++ = Py_hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00005865 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005866
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005867 /* Map special whitespace to '\t', \n', '\r' */
5868 else if (ch == '\t') {
5869 *p++ = '\\';
5870 *p++ = 't';
5871 }
5872 else if (ch == '\n') {
5873 *p++ = '\\';
5874 *p++ = 'n';
5875 }
5876 else if (ch == '\r') {
5877 *p++ = '\\';
5878 *p++ = 'r';
5879 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005880
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005881 /* Map non-printable US ASCII to '\xhh' */
Marc-André Lemburg11326de2001-11-28 12:56:20 +00005882 else if (ch < ' ' || ch >= 0x7F) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005883 *p++ = '\\';
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005884 *p++ = 'x';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005885 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
5886 *p++ = Py_hexdigits[ch & 0x000F];
Tim Petersced69f82003-09-16 20:30:58 +00005887 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005888
Guido van Rossumd57fd912000-03-10 22:53:23 +00005889 /* Copy everything else as-is */
5890 else
5891 *p++ = (char) ch;
5892 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005893
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005894 assert(p - PyBytes_AS_STRING(repr) > 0);
5895 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0)
5896 return NULL;
5897 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005898}
5899
Alexander Belopolsky40018472011-02-26 01:02:56 +00005900PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005901PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
5902 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005903{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005904 PyObject *result;
5905 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5906 if (tmp == NULL)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005907 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005908 result = PyUnicode_AsUnicodeEscapeString(tmp);
5909 Py_DECREF(tmp);
5910 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005911}
5912
5913/* --- Raw Unicode Escape Codec ------------------------------------------- */
5914
Alexander Belopolsky40018472011-02-26 01:02:56 +00005915PyObject *
5916PyUnicode_DecodeRawUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005917 Py_ssize_t size,
5918 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005919{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005920 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005921 Py_ssize_t startinpos;
5922 Py_ssize_t endinpos;
5923 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01005924 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005925 const char *end;
5926 const char *bs;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005927 PyObject *errorHandler = NULL;
5928 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00005929
Guido van Rossumd57fd912000-03-10 22:53:23 +00005930 /* Escaped strings will always be longer than the resulting
5931 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005932 length after conversion to the true value. (But decoding error
5933 handler might have to resize the string) */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005934 v = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005935 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005936 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005937 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01005938 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005939 outpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005940 end = s + size;
5941 while (s < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005942 unsigned char c;
5943 Py_UCS4 x;
5944 int i;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00005945 int count;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005946
Benjamin Peterson29060642009-01-31 22:14:21 +00005947 /* Non-escape characters are interpreted as Unicode ordinals */
5948 if (*s != '\\') {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005949 if (unicode_putchar(&v, &outpos, (unsigned char)*s++) < 0)
5950 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005951 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00005952 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005953 startinpos = s-starts;
5954
5955 /* \u-escapes are only interpreted iff the number of leading
5956 backslashes if odd */
5957 bs = s;
5958 for (;s < end;) {
5959 if (*s != '\\')
5960 break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005961 if (unicode_putchar(&v, &outpos, (unsigned char)*s++) < 0)
5962 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005963 }
5964 if (((s - bs) & 1) == 0 ||
5965 s >= end ||
5966 (*s != 'u' && *s != 'U')) {
5967 continue;
5968 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005969 outpos--;
Benjamin Peterson29060642009-01-31 22:14:21 +00005970 count = *s=='u' ? 4 : 8;
5971 s++;
5972
5973 /* \uXXXX with 4 hex digits, \Uxxxxxxxx with 8 */
Benjamin Peterson29060642009-01-31 22:14:21 +00005974 for (x = 0, i = 0; i < count; ++i, ++s) {
5975 c = (unsigned char)*s;
David Malcolm96960882010-11-05 17:23:41 +00005976 if (!Py_ISXDIGIT(c)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005977 endinpos = s-starts;
5978 if (unicode_decode_call_errorhandler(
5979 errors, &errorHandler,
5980 "rawunicodeescape", "truncated \\uXXXX",
5981 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005982 &v, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00005983 goto onError;
5984 goto nextByte;
5985 }
5986 x = (x<<4) & ~0xF;
5987 if (c >= '0' && c <= '9')
5988 x += c - '0';
5989 else if (c >= 'a' && c <= 'f')
5990 x += 10 + c - 'a';
5991 else
5992 x += 10 + c - 'A';
5993 }
Victor Stinner8faf8212011-12-08 22:14:11 +01005994 if (x <= MAX_UNICODE) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005995 if (unicode_putchar(&v, &outpos, x) < 0)
5996 goto onError;
Christian Heimesfe337bf2008-03-23 21:54:12 +00005997 } else {
5998 endinpos = s-starts;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00005999 if (unicode_decode_call_errorhandler(
6000 errors, &errorHandler,
6001 "rawunicodeescape", "\\Uxxxxxxxx out of range",
Benjamin Peterson29060642009-01-31 22:14:21 +00006002 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006003 &v, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00006004 goto onError;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006005 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006006 nextByte:
6007 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006008 }
Victor Stinner16e6a802011-12-12 13:24:15 +01006009 if (unicode_resize(&v, outpos) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006010 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006011 Py_XDECREF(errorHandler);
6012 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006013 return unicode_result(v);
Tim Petersced69f82003-09-16 20:30:58 +00006014
Benjamin Peterson29060642009-01-31 22:14:21 +00006015 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00006016 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006017 Py_XDECREF(errorHandler);
6018 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006019 return NULL;
6020}
6021
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006022
Alexander Belopolsky40018472011-02-26 01:02:56 +00006023PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006024PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006025{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006026 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006027 char *p;
6028 char *q;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006029 Py_ssize_t expandsize, pos;
6030 int kind;
6031 void *data;
6032 Py_ssize_t len;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006033
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006034 if (!PyUnicode_Check(unicode)) {
6035 PyErr_BadArgument();
6036 return NULL;
6037 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05006038 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006039 return NULL;
6040 kind = PyUnicode_KIND(unicode);
6041 data = PyUnicode_DATA(unicode);
6042 len = PyUnicode_GET_LENGTH(unicode);
Benjamin Peterson1518e872011-11-23 10:44:52 -06006043 /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6
6044 bytes, and 1 byte characters 4. */
6045 expandsize = kind * 2 + 2;
Victor Stinner0e368262011-11-10 20:12:49 +01006046
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006047 if (len > PY_SSIZE_T_MAX / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00006048 return PyErr_NoMemory();
Benjamin Peterson14339b62009-01-31 16:36:08 +00006049
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006050 repr = PyBytes_FromStringAndSize(NULL, expandsize * len);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006051 if (repr == NULL)
6052 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006053 if (len == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006054 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006055
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006056 p = q = PyBytes_AS_STRING(repr);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006057 for (pos = 0; pos < len; pos++) {
6058 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Benjamin Peterson29060642009-01-31 22:14:21 +00006059 /* Map 32-bit characters to '\Uxxxxxxxx' */
6060 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01006061 assert(ch <= MAX_UNICODE);
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006062 *p++ = '\\';
6063 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006064 *p++ = Py_hexdigits[(ch >> 28) & 0xf];
6065 *p++ = Py_hexdigits[(ch >> 24) & 0xf];
6066 *p++ = Py_hexdigits[(ch >> 20) & 0xf];
6067 *p++ = Py_hexdigits[(ch >> 16) & 0xf];
6068 *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];
Tim Petersced69f82003-09-16 20:30:58 +00006072 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006073 /* Map 16-bit characters to '\uxxxx' */
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006074 else if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006075 *p++ = '\\';
6076 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006077 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6078 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6079 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6080 *p++ = Py_hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006081 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006082 /* Copy everything else as-is */
6083 else
Guido van Rossumd57fd912000-03-10 22:53:23 +00006084 *p++ = (char) ch;
6085 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00006086
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006087 assert(p > q);
6088 if (_PyBytes_Resize(&repr, p - q) < 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006089 return NULL;
6090 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006091}
6092
Alexander Belopolsky40018472011-02-26 01:02:56 +00006093PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006094PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
6095 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006096{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006097 PyObject *result;
6098 PyObject *tmp = PyUnicode_FromUnicode(s, size);
6099 if (tmp == NULL)
Walter Dörwald711005d2007-05-12 12:03:26 +00006100 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006101 result = PyUnicode_AsRawUnicodeEscapeString(tmp);
6102 Py_DECREF(tmp);
6103 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006104}
6105
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006106/* --- Unicode Internal Codec ------------------------------------------- */
6107
Alexander Belopolsky40018472011-02-26 01:02:56 +00006108PyObject *
6109_PyUnicode_DecodeUnicodeInternal(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006110 Py_ssize_t size,
6111 const char *errors)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006112{
6113 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006114 Py_ssize_t startinpos;
6115 Py_ssize_t endinpos;
6116 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01006117 PyObject *v;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006118 const char *end;
6119 const char *reason;
6120 PyObject *errorHandler = NULL;
6121 PyObject *exc = NULL;
6122
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006123 if (PyErr_WarnEx(PyExc_DeprecationWarning,
Ezio Melotti11060a42011-11-16 09:39:10 +02006124 "unicode_internal codec has been deprecated",
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006125 1))
6126 return NULL;
6127
Thomas Wouters89f507f2006-12-13 04:49:30 +00006128 /* XXX overflow detection missing */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006129 v = PyUnicode_New((size+Py_UNICODE_SIZE-1)/ Py_UNICODE_SIZE, 127);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006130 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006131 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006132 if (PyUnicode_GET_LENGTH(v) == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01006133 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006134 outpos = 0;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006135 end = s + size;
6136
6137 while (s < end) {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006138 Py_UNICODE uch;
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006139 Py_UCS4 ch;
6140 /* We copy the raw representation one byte at a time because the
6141 pointer may be unaligned (see test_codeccallbacks). */
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006142 ((char *) &uch)[0] = s[0];
6143 ((char *) &uch)[1] = s[1];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006144#ifdef Py_UNICODE_WIDE
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006145 ((char *) &uch)[2] = s[2];
6146 ((char *) &uch)[3] = s[3];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006147#endif
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006148 ch = uch;
6149
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006150 /* We have to sanity check the raw data, otherwise doom looms for
6151 some malformed UCS-4 data. */
6152 if (
Benjamin Peterson29060642009-01-31 22:14:21 +00006153#ifdef Py_UNICODE_WIDE
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006154 ch > 0x10ffff ||
Benjamin Peterson29060642009-01-31 22:14:21 +00006155#endif
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006156 end-s < Py_UNICODE_SIZE
6157 )
Benjamin Peterson29060642009-01-31 22:14:21 +00006158 {
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006159 startinpos = s - starts;
6160 if (end-s < Py_UNICODE_SIZE) {
6161 endinpos = end-starts;
6162 reason = "truncated input";
6163 }
6164 else {
6165 endinpos = s - starts + Py_UNICODE_SIZE;
6166 reason = "illegal code point (> 0x10FFFF)";
6167 }
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006168 if (unicode_decode_call_errorhandler(
6169 errors, &errorHandler,
6170 "unicode_internal", reason,
Walter Dörwalde78178e2007-07-30 13:31:40 +00006171 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006172 &v, &outpos))
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006173 goto onError;
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006174 continue;
6175 }
6176
6177 s += Py_UNICODE_SIZE;
6178#ifndef Py_UNICODE_WIDE
Victor Stinner551ac952011-11-29 22:58:13 +01006179 if (Py_UNICODE_IS_HIGH_SURROGATE(ch) && s < end)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006180 {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006181 Py_UNICODE uch2;
6182 ((char *) &uch2)[0] = s[0];
6183 ((char *) &uch2)[1] = s[1];
Victor Stinner551ac952011-11-29 22:58:13 +01006184 if (Py_UNICODE_IS_LOW_SURROGATE(uch2))
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006185 {
Victor Stinner551ac952011-11-29 22:58:13 +01006186 ch = Py_UNICODE_JOIN_SURROGATES(uch, uch2);
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006187 s += Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006188 }
6189 }
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006190#endif
6191
6192 if (unicode_putchar(&v, &outpos, ch) < 0)
6193 goto onError;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006194 }
6195
Victor Stinner16e6a802011-12-12 13:24:15 +01006196 if (unicode_resize(&v, outpos) < 0)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006197 goto onError;
6198 Py_XDECREF(errorHandler);
6199 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006200 return unicode_result(v);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006201
Benjamin Peterson29060642009-01-31 22:14:21 +00006202 onError:
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006203 Py_XDECREF(v);
6204 Py_XDECREF(errorHandler);
6205 Py_XDECREF(exc);
6206 return NULL;
6207}
6208
Guido van Rossumd57fd912000-03-10 22:53:23 +00006209/* --- Latin-1 Codec ------------------------------------------------------ */
6210
Alexander Belopolsky40018472011-02-26 01:02:56 +00006211PyObject *
6212PyUnicode_DecodeLatin1(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006213 Py_ssize_t size,
6214 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006215{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006216 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Victor Stinnere57b1c02011-09-28 22:20:48 +02006217 return _PyUnicode_FromUCS1((unsigned char*)s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006218}
6219
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006220/* create or adjust a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006221static void
6222make_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006223 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006224 PyObject *unicode,
6225 Py_ssize_t startpos, Py_ssize_t endpos,
6226 const char *reason)
6227{
6228 if (*exceptionObject == NULL) {
6229 *exceptionObject = PyObject_CallFunction(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006230 PyExc_UnicodeEncodeError, "sOnns",
Martin v. Löwis9e816682011-11-02 12:45:42 +01006231 encoding, unicode, startpos, endpos, reason);
6232 }
6233 else {
6234 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
6235 goto onError;
6236 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
6237 goto onError;
6238 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
6239 goto onError;
6240 return;
6241 onError:
6242 Py_DECREF(*exceptionObject);
6243 *exceptionObject = NULL;
6244 }
6245}
6246
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006247/* raises a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006248static void
6249raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006250 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006251 PyObject *unicode,
6252 Py_ssize_t startpos, Py_ssize_t endpos,
6253 const char *reason)
6254{
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006255 make_encode_exception(exceptionObject,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006256 encoding, unicode, startpos, endpos, reason);
6257 if (*exceptionObject != NULL)
6258 PyCodec_StrictErrors(*exceptionObject);
6259}
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006260
6261/* error handling callback helper:
6262 build arguments, call the callback and check the arguments,
6263 put the result into newpos and return the replacement string, which
6264 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006265static PyObject *
6266unicode_encode_call_errorhandler(const char *errors,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006267 PyObject **errorHandler,
6268 const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006269 PyObject *unicode, PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006270 Py_ssize_t startpos, Py_ssize_t endpos,
6271 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006272{
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006273 static char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006274 Py_ssize_t len;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006275 PyObject *restuple;
6276 PyObject *resunicode;
6277
6278 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006279 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006280 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006281 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006282 }
6283
Benjamin Petersonbac79492012-01-14 13:34:47 -05006284 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006285 return NULL;
6286 len = PyUnicode_GET_LENGTH(unicode);
6287
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006288 make_encode_exception(exceptionObject,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006289 encoding, unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006290 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006291 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006292
6293 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00006294 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006295 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006296 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006297 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006298 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00006299 Py_DECREF(restuple);
6300 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006301 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006302 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00006303 &resunicode, newpos)) {
6304 Py_DECREF(restuple);
6305 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006306 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006307 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
6308 PyErr_SetString(PyExc_TypeError, &argparse[3]);
6309 Py_DECREF(restuple);
6310 return NULL;
6311 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006312 if (*newpos<0)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006313 *newpos = len + *newpos;
6314 if (*newpos<0 || *newpos>len) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006315 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
6316 Py_DECREF(restuple);
6317 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00006318 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006319 Py_INCREF(resunicode);
6320 Py_DECREF(restuple);
6321 return resunicode;
6322}
6323
Alexander Belopolsky40018472011-02-26 01:02:56 +00006324static PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006325unicode_encode_ucs1(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006326 const char *errors,
Victor Stinnerfcd96532011-11-04 00:28:50 +01006327 unsigned int limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006328{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006329 /* input state */
6330 Py_ssize_t pos=0, size;
6331 int kind;
6332 void *data;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006333 /* output object */
6334 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006335 /* pointer into the output */
6336 char *str;
6337 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00006338 Py_ssize_t ressize;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006339 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
6340 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006341 PyObject *errorHandler = NULL;
6342 PyObject *exc = NULL;
6343 /* the following variable is used for caching string comparisons
6344 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
6345 int known_errorHandler = -1;
6346
Benjamin Petersonbac79492012-01-14 13:34:47 -05006347 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006348 return NULL;
6349 size = PyUnicode_GET_LENGTH(unicode);
6350 kind = PyUnicode_KIND(unicode);
6351 data = PyUnicode_DATA(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006352 /* allocate enough for a simple encoding without
6353 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00006354 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00006355 return PyBytes_FromStringAndSize(NULL, 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006356 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006357 if (res == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00006358 return NULL;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006359 str = PyBytes_AS_STRING(res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006360 ressize = size;
6361
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006362 while (pos < size) {
6363 Py_UCS4 c = PyUnicode_READ(kind, data, pos);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006364
Benjamin Peterson29060642009-01-31 22:14:21 +00006365 /* can we encode this? */
6366 if (c<limit) {
6367 /* no overflow check, because we know that the space is enough */
6368 *str++ = (char)c;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006369 ++pos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006370 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006371 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006372 Py_ssize_t requiredsize;
6373 PyObject *repunicode;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006374 Py_ssize_t repsize, newpos, respos, i;
Benjamin Peterson29060642009-01-31 22:14:21 +00006375 /* startpos for collecting unencodable chars */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006376 Py_ssize_t collstart = pos;
6377 Py_ssize_t collend = pos;
Benjamin Peterson29060642009-01-31 22:14:21 +00006378 /* find all unecodable characters */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006379 while ((collend < size) && (PyUnicode_READ(kind, data, collend)>=limit))
Benjamin Peterson29060642009-01-31 22:14:21 +00006380 ++collend;
6381 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
6382 if (known_errorHandler==-1) {
6383 if ((errors==NULL) || (!strcmp(errors, "strict")))
6384 known_errorHandler = 1;
6385 else if (!strcmp(errors, "replace"))
6386 known_errorHandler = 2;
6387 else if (!strcmp(errors, "ignore"))
6388 known_errorHandler = 3;
6389 else if (!strcmp(errors, "xmlcharrefreplace"))
6390 known_errorHandler = 4;
6391 else
6392 known_errorHandler = 0;
6393 }
6394 switch (known_errorHandler) {
6395 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006396 raise_encode_exception(&exc, encoding, unicode, collstart, collend, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006397 goto onError;
6398 case 2: /* replace */
6399 while (collstart++<collend)
6400 *str++ = '?'; /* fall through */
6401 case 3: /* ignore */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006402 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006403 break;
6404 case 4: /* xmlcharrefreplace */
6405 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006406 /* determine replacement size */
6407 for (i = collstart, repsize = 0; i < collend; ++i) {
6408 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
6409 if (ch < 10)
Benjamin Peterson29060642009-01-31 22:14:21 +00006410 repsize += 2+1+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006411 else if (ch < 100)
Benjamin Peterson29060642009-01-31 22:14:21 +00006412 repsize += 2+2+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006413 else if (ch < 1000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006414 repsize += 2+3+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006415 else if (ch < 10000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006416 repsize += 2+4+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006417 else if (ch < 100000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006418 repsize += 2+5+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006419 else if (ch < 1000000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006420 repsize += 2+6+1;
Victor Stinner0d3721d2011-11-22 03:27:53 +01006421 else {
Victor Stinner8faf8212011-12-08 22:14:11 +01006422 assert(ch <= MAX_UNICODE);
Benjamin Peterson29060642009-01-31 22:14:21 +00006423 repsize += 2+7+1;
Victor Stinner0d3721d2011-11-22 03:27:53 +01006424 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006425 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006426 requiredsize = respos+repsize+(size-collend);
Benjamin Peterson29060642009-01-31 22:14:21 +00006427 if (requiredsize > ressize) {
6428 if (requiredsize<2*ressize)
6429 requiredsize = 2*ressize;
6430 if (_PyBytes_Resize(&res, requiredsize))
6431 goto onError;
6432 str = PyBytes_AS_STRING(res) + respos;
6433 ressize = requiredsize;
6434 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006435 /* generate replacement */
6436 for (i = collstart; i < collend; ++i) {
6437 str += sprintf(str, "&#%d;", PyUnicode_READ(kind, data, i));
Benjamin Peterson29060642009-01-31 22:14:21 +00006438 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006439 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006440 break;
6441 default:
6442 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006443 encoding, reason, unicode, &exc,
6444 collstart, collend, &newpos);
6445 if (repunicode == NULL || (PyUnicode_Check(repunicode) &&
Benjamin Petersonbac79492012-01-14 13:34:47 -05006446 PyUnicode_READY(repunicode) == -1))
Benjamin Peterson29060642009-01-31 22:14:21 +00006447 goto onError;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006448 if (PyBytes_Check(repunicode)) {
6449 /* Directly copy bytes result to output. */
6450 repsize = PyBytes_Size(repunicode);
6451 if (repsize > 1) {
6452 /* Make room for all additional bytes. */
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006453 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006454 if (_PyBytes_Resize(&res, ressize+repsize-1)) {
6455 Py_DECREF(repunicode);
6456 goto onError;
6457 }
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006458 str = PyBytes_AS_STRING(res) + respos;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006459 ressize += repsize-1;
6460 }
6461 memcpy(str, PyBytes_AsString(repunicode), repsize);
6462 str += repsize;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006463 pos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006464 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006465 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006466 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006467 /* need more space? (at least enough for what we
6468 have+the replacement+the rest of the string, so
6469 we won't have to check space for encodable characters) */
6470 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006471 repsize = PyUnicode_GET_LENGTH(repunicode);
6472 requiredsize = respos+repsize+(size-collend);
Benjamin Peterson29060642009-01-31 22:14:21 +00006473 if (requiredsize > ressize) {
6474 if (requiredsize<2*ressize)
6475 requiredsize = 2*ressize;
6476 if (_PyBytes_Resize(&res, requiredsize)) {
6477 Py_DECREF(repunicode);
6478 goto onError;
6479 }
6480 str = PyBytes_AS_STRING(res) + respos;
6481 ressize = requiredsize;
6482 }
6483 /* check if there is anything unencodable in the replacement
6484 and copy it to the output */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006485 for (i = 0; repsize-->0; ++i, ++str) {
6486 c = PyUnicode_READ_CHAR(repunicode, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00006487 if (c >= limit) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006488 raise_encode_exception(&exc, encoding, unicode,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006489 pos, pos+1, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006490 Py_DECREF(repunicode);
6491 goto onError;
6492 }
6493 *str = (char)c;
6494 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006495 pos = newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006496 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006497 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00006498 }
6499 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006500 /* Resize if we allocated to much */
6501 size = str - PyBytes_AS_STRING(res);
6502 if (size < ressize) { /* If this falls res will be NULL */
Alexandre Vassalottibad1b922008-12-27 09:49:09 +00006503 assert(size >= 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006504 if (_PyBytes_Resize(&res, size) < 0)
6505 goto onError;
6506 }
6507
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006508 Py_XDECREF(errorHandler);
6509 Py_XDECREF(exc);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006510 return res;
6511
6512 onError:
6513 Py_XDECREF(res);
6514 Py_XDECREF(errorHandler);
6515 Py_XDECREF(exc);
6516 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006517}
6518
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006519/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006520PyObject *
6521PyUnicode_EncodeLatin1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006522 Py_ssize_t size,
6523 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006524{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006525 PyObject *result;
6526 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6527 if (unicode == NULL)
6528 return NULL;
6529 result = unicode_encode_ucs1(unicode, errors, 256);
6530 Py_DECREF(unicode);
6531 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006532}
6533
Alexander Belopolsky40018472011-02-26 01:02:56 +00006534PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006535_PyUnicode_AsLatin1String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006536{
6537 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006538 PyErr_BadArgument();
6539 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006540 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006541 if (PyUnicode_READY(unicode) == -1)
6542 return NULL;
6543 /* Fast path: if it is a one-byte string, construct
6544 bytes object directly. */
6545 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND)
6546 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6547 PyUnicode_GET_LENGTH(unicode));
6548 /* Non-Latin-1 characters present. Defer to above function to
6549 raise the exception. */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006550 return unicode_encode_ucs1(unicode, errors, 256);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006551}
6552
6553PyObject*
6554PyUnicode_AsLatin1String(PyObject *unicode)
6555{
6556 return _PyUnicode_AsLatin1String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006557}
6558
6559/* --- 7-bit ASCII Codec -------------------------------------------------- */
6560
Alexander Belopolsky40018472011-02-26 01:02:56 +00006561PyObject *
6562PyUnicode_DecodeASCII(const char *s,
6563 Py_ssize_t size,
6564 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006565{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006566 const char *starts = s;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006567 PyObject *unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006568 int kind;
6569 void *data;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006570 Py_ssize_t startinpos;
6571 Py_ssize_t endinpos;
6572 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006573 const char *e;
6574 PyObject *errorHandler = NULL;
6575 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006576
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006577 if (size == 0) {
6578 Py_INCREF(unicode_empty);
6579 return unicode_empty;
6580 }
6581
Guido van Rossumd57fd912000-03-10 22:53:23 +00006582 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Victor Stinner702c7342011-10-05 13:50:52 +02006583 if (size == 1 && (unsigned char)s[0] < 128)
6584 return get_latin1_char((unsigned char)s[0]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006585
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006586 unicode = PyUnicode_New(size, 127);
6587 if (unicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006588 goto onError;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006589
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006590 e = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006591 data = PyUnicode_1BYTE_DATA(unicode);
6592 outpos = ascii_decode(s, e, (Py_UCS1 *)data);
6593 if (outpos == size)
6594 return unicode;
6595
6596 s += outpos;
6597 kind = PyUnicode_1BYTE_KIND;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006598 while (s < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006599 register unsigned char c = (unsigned char)*s;
6600 if (c < 128) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006601 PyUnicode_WRITE(kind, data, outpos++, c);
Benjamin Peterson29060642009-01-31 22:14:21 +00006602 ++s;
6603 }
6604 else {
6605 startinpos = s-starts;
6606 endinpos = startinpos + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00006607 if (unicode_decode_call_errorhandler(
6608 errors, &errorHandler,
6609 "ascii", "ordinal not in range(128)",
6610 &starts, &e, &startinpos, &endinpos, &exc, &s,
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006611 &unicode, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00006612 goto onError;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006613 kind = PyUnicode_KIND(unicode);
6614 data = PyUnicode_DATA(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00006615 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006616 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006617 if (unicode_resize(&unicode, outpos) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006618 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006619 Py_XDECREF(errorHandler);
6620 Py_XDECREF(exc);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006621 assert(_PyUnicode_CheckConsistency(unicode, 1));
6622 return unicode;
Tim Petersced69f82003-09-16 20:30:58 +00006623
Benjamin Peterson29060642009-01-31 22:14:21 +00006624 onError:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006625 Py_XDECREF(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006626 Py_XDECREF(errorHandler);
6627 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006628 return NULL;
6629}
6630
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006631/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006632PyObject *
6633PyUnicode_EncodeASCII(const Py_UNICODE *p,
6634 Py_ssize_t size,
6635 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006636{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006637 PyObject *result;
6638 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6639 if (unicode == NULL)
6640 return NULL;
6641 result = unicode_encode_ucs1(unicode, errors, 128);
6642 Py_DECREF(unicode);
6643 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006644}
6645
Alexander Belopolsky40018472011-02-26 01:02:56 +00006646PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006647_PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006648{
6649 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006650 PyErr_BadArgument();
6651 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006652 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006653 if (PyUnicode_READY(unicode) == -1)
6654 return NULL;
6655 /* Fast path: if it is an ASCII-only string, construct bytes object
6656 directly. Else defer to above function to raise the exception. */
6657 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
6658 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6659 PyUnicode_GET_LENGTH(unicode));
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006660 return unicode_encode_ucs1(unicode, errors, 128);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006661}
6662
6663PyObject *
6664PyUnicode_AsASCIIString(PyObject *unicode)
6665{
6666 return _PyUnicode_AsASCIIString(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006667}
6668
Victor Stinner99b95382011-07-04 14:23:54 +02006669#ifdef HAVE_MBCS
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006670
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006671/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006672
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00006673#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006674#define NEED_RETRY
6675#endif
6676
Victor Stinner3a50e702011-10-18 21:21:00 +02006677#ifndef WC_ERR_INVALID_CHARS
6678# define WC_ERR_INVALID_CHARS 0x0080
6679#endif
6680
6681static char*
6682code_page_name(UINT code_page, PyObject **obj)
6683{
6684 *obj = NULL;
6685 if (code_page == CP_ACP)
6686 return "mbcs";
6687 if (code_page == CP_UTF7)
6688 return "CP_UTF7";
6689 if (code_page == CP_UTF8)
6690 return "CP_UTF8";
6691
6692 *obj = PyBytes_FromFormat("cp%u", code_page);
6693 if (*obj == NULL)
6694 return NULL;
6695 return PyBytes_AS_STRING(*obj);
6696}
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006697
Alexander Belopolsky40018472011-02-26 01:02:56 +00006698static int
Victor Stinner3a50e702011-10-18 21:21:00 +02006699is_dbcs_lead_byte(UINT code_page, const char *s, int offset)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006700{
6701 const char *curr = s + offset;
Victor Stinner3a50e702011-10-18 21:21:00 +02006702 const char *prev;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006703
Victor Stinner3a50e702011-10-18 21:21:00 +02006704 if (!IsDBCSLeadByteEx(code_page, *curr))
6705 return 0;
6706
6707 prev = CharPrevExA(code_page, s, curr, 0);
6708 if (prev == curr)
6709 return 1;
6710 /* FIXME: This code is limited to "true" double-byte encodings,
6711 as it assumes an incomplete character consists of a single
6712 byte. */
6713 if (curr - prev == 2)
6714 return 1;
6715 if (!IsDBCSLeadByteEx(code_page, *prev))
6716 return 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006717 return 0;
6718}
6719
Victor Stinner3a50e702011-10-18 21:21:00 +02006720static DWORD
6721decode_code_page_flags(UINT code_page)
6722{
6723 if (code_page == CP_UTF7) {
6724 /* The CP_UTF7 decoder only supports flags=0 */
6725 return 0;
6726 }
6727 else
6728 return MB_ERR_INVALID_CHARS;
6729}
6730
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006731/*
Victor Stinner3a50e702011-10-18 21:21:00 +02006732 * Decode a byte string from a Windows code page into unicode object in strict
6733 * mode.
6734 *
6735 * Returns consumed size if succeed, returns -2 on decode error, or raise a
6736 * WindowsError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006737 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006738static int
Victor Stinner3a50e702011-10-18 21:21:00 +02006739decode_code_page_strict(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01006740 PyObject **v,
Victor Stinner3a50e702011-10-18 21:21:00 +02006741 const char *in,
6742 int insize)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006743{
Victor Stinner3a50e702011-10-18 21:21:00 +02006744 const DWORD flags = decode_code_page_flags(code_page);
Victor Stinner24729f32011-11-10 20:31:37 +01006745 wchar_t *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02006746 DWORD outsize;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006747
6748 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02006749 assert(insize > 0);
6750 outsize = MultiByteToWideChar(code_page, flags, in, insize, NULL, 0);
6751 if (outsize <= 0)
6752 goto error;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006753
6754 if (*v == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006755 /* Create unicode object */
Victor Stinnerab595942011-12-17 04:59:06 +01006756 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01006757 *v = (PyObject*)_PyUnicode_New(outsize);
Benjamin Peterson29060642009-01-31 22:14:21 +00006758 if (*v == NULL)
6759 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02006760 out = PyUnicode_AS_UNICODE(*v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006761 }
6762 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006763 /* Extend unicode object */
Victor Stinner3a50e702011-10-18 21:21:00 +02006764 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
Victor Stinner16e6a802011-12-12 13:24:15 +01006765 if (unicode_resize(v, n + outsize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006766 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02006767 out = PyUnicode_AS_UNICODE(*v) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006768 }
6769
6770 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02006771 outsize = MultiByteToWideChar(code_page, flags, in, insize, out, outsize);
6772 if (outsize <= 0)
6773 goto error;
6774 return insize;
Victor Stinner554f3f02010-06-16 23:33:54 +00006775
Victor Stinner3a50e702011-10-18 21:21:00 +02006776error:
6777 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
6778 return -2;
6779 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00006780 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006781}
6782
Victor Stinner3a50e702011-10-18 21:21:00 +02006783/*
6784 * Decode a byte string from a code page into unicode object with an error
6785 * handler.
6786 *
6787 * Returns consumed size if succeed, or raise a WindowsError or
6788 * UnicodeDecodeError exception and returns -1 on error.
6789 */
6790static int
6791decode_code_page_errors(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01006792 PyObject **v,
6793 const char *in, const int size,
Victor Stinner3a50e702011-10-18 21:21:00 +02006794 const char *errors)
6795{
6796 const char *startin = in;
6797 const char *endin = in + size;
6798 const DWORD flags = decode_code_page_flags(code_page);
6799 /* Ideally, we should get reason from FormatMessage. This is the Windows
6800 2000 English version of the message. */
6801 const char *reason = "No mapping for the Unicode character exists "
6802 "in the target code page.";
6803 /* each step cannot decode more than 1 character, but a character can be
6804 represented as a surrogate pair */
6805 wchar_t buffer[2], *startout, *out;
6806 int insize, outsize;
6807 PyObject *errorHandler = NULL;
6808 PyObject *exc = NULL;
6809 PyObject *encoding_obj = NULL;
6810 char *encoding;
6811 DWORD err;
6812 int ret = -1;
6813
6814 assert(size > 0);
6815
6816 encoding = code_page_name(code_page, &encoding_obj);
6817 if (encoding == NULL)
6818 return -1;
6819
6820 if (errors == NULL || strcmp(errors, "strict") == 0) {
6821 /* The last error was ERROR_NO_UNICODE_TRANSLATION, then we raise a
6822 UnicodeDecodeError. */
6823 make_decode_exception(&exc, encoding, in, size, 0, 0, reason);
6824 if (exc != NULL) {
6825 PyCodec_StrictErrors(exc);
6826 Py_CLEAR(exc);
6827 }
6828 goto error;
6829 }
6830
6831 if (*v == NULL) {
6832 /* Create unicode object */
6833 if (size > PY_SSIZE_T_MAX / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
6834 PyErr_NoMemory();
6835 goto error;
6836 }
Victor Stinnerab595942011-12-17 04:59:06 +01006837 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01006838 *v = (PyObject*)_PyUnicode_New(size * Py_ARRAY_LENGTH(buffer));
Victor Stinner3a50e702011-10-18 21:21:00 +02006839 if (*v == NULL)
6840 goto error;
6841 startout = PyUnicode_AS_UNICODE(*v);
6842 }
6843 else {
6844 /* Extend unicode object */
6845 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
6846 if (size > (PY_SSIZE_T_MAX - n) / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
6847 PyErr_NoMemory();
6848 goto error;
6849 }
Victor Stinner16e6a802011-12-12 13:24:15 +01006850 if (unicode_resize(v, n + size * Py_ARRAY_LENGTH(buffer)) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02006851 goto error;
6852 startout = PyUnicode_AS_UNICODE(*v) + n;
6853 }
6854
6855 /* Decode the byte string character per character */
6856 out = startout;
6857 while (in < endin)
6858 {
6859 /* Decode a character */
6860 insize = 1;
6861 do
6862 {
6863 outsize = MultiByteToWideChar(code_page, flags,
6864 in, insize,
6865 buffer, Py_ARRAY_LENGTH(buffer));
6866 if (outsize > 0)
6867 break;
6868 err = GetLastError();
6869 if (err != ERROR_NO_UNICODE_TRANSLATION
6870 && err != ERROR_INSUFFICIENT_BUFFER)
6871 {
6872 PyErr_SetFromWindowsErr(0);
6873 goto error;
6874 }
6875 insize++;
6876 }
6877 /* 4=maximum length of a UTF-8 sequence */
6878 while (insize <= 4 && (in + insize) <= endin);
6879
6880 if (outsize <= 0) {
6881 Py_ssize_t startinpos, endinpos, outpos;
6882
6883 startinpos = in - startin;
6884 endinpos = startinpos + 1;
6885 outpos = out - PyUnicode_AS_UNICODE(*v);
6886 if (unicode_decode_call_errorhandler(
6887 errors, &errorHandler,
6888 encoding, reason,
6889 &startin, &endin, &startinpos, &endinpos, &exc, &in,
Victor Stinner596a6c42011-11-09 00:02:18 +01006890 v, &outpos))
Victor Stinner3a50e702011-10-18 21:21:00 +02006891 {
6892 goto error;
6893 }
Victor Stinner596a6c42011-11-09 00:02:18 +01006894 out = PyUnicode_AS_UNICODE(*v) + outpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02006895 }
6896 else {
6897 in += insize;
6898 memcpy(out, buffer, outsize * sizeof(wchar_t));
6899 out += outsize;
6900 }
6901 }
6902
6903 /* write a NUL character at the end */
6904 *out = 0;
6905
6906 /* Extend unicode object */
6907 outsize = out - startout;
6908 assert(outsize <= PyUnicode_WSTR_LENGTH(*v));
Victor Stinner16e6a802011-12-12 13:24:15 +01006909 if (unicode_resize(v, outsize) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02006910 goto error;
Victor Stinner76a31a62011-11-04 00:05:13 +01006911 ret = size;
Victor Stinner3a50e702011-10-18 21:21:00 +02006912
6913error:
6914 Py_XDECREF(encoding_obj);
6915 Py_XDECREF(errorHandler);
6916 Py_XDECREF(exc);
6917 return ret;
6918}
6919
Victor Stinner3a50e702011-10-18 21:21:00 +02006920static PyObject *
6921decode_code_page_stateful(int code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01006922 const char *s, Py_ssize_t size,
6923 const char *errors, Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006924{
Victor Stinner76a31a62011-11-04 00:05:13 +01006925 PyObject *v = NULL;
6926 int chunk_size, final, converted, done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006927
Victor Stinner3a50e702011-10-18 21:21:00 +02006928 if (code_page < 0) {
6929 PyErr_SetString(PyExc_ValueError, "invalid code page number");
6930 return NULL;
6931 }
6932
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006933 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00006934 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006935
Victor Stinner76a31a62011-11-04 00:05:13 +01006936 do
6937 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006938#ifdef NEED_RETRY
Victor Stinner76a31a62011-11-04 00:05:13 +01006939 if (size > INT_MAX) {
6940 chunk_size = INT_MAX;
6941 final = 0;
6942 done = 0;
6943 }
6944 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006945#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01006946 {
6947 chunk_size = (int)size;
6948 final = (consumed == NULL);
6949 done = 1;
6950 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006951
Victor Stinner76a31a62011-11-04 00:05:13 +01006952 /* Skip trailing lead-byte unless 'final' is set */
6953 if (!final && is_dbcs_lead_byte(code_page, s, chunk_size - 1))
6954 --chunk_size;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006955
Victor Stinner76a31a62011-11-04 00:05:13 +01006956 if (chunk_size == 0 && done) {
6957 if (v != NULL)
6958 break;
6959 Py_INCREF(unicode_empty);
6960 return unicode_empty;
6961 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006962
Victor Stinner76a31a62011-11-04 00:05:13 +01006963
6964 converted = decode_code_page_strict(code_page, &v,
6965 s, chunk_size);
6966 if (converted == -2)
6967 converted = decode_code_page_errors(code_page, &v,
6968 s, chunk_size,
6969 errors);
6970 assert(converted != 0);
6971
6972 if (converted < 0) {
6973 Py_XDECREF(v);
6974 return NULL;
6975 }
6976
6977 if (consumed)
6978 *consumed += converted;
6979
6980 s += converted;
6981 size -= converted;
6982 } while (!done);
Victor Stinner3a50e702011-10-18 21:21:00 +02006983
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006984 return unicode_result(v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006985}
6986
Alexander Belopolsky40018472011-02-26 01:02:56 +00006987PyObject *
Victor Stinner3a50e702011-10-18 21:21:00 +02006988PyUnicode_DecodeCodePageStateful(int code_page,
6989 const char *s,
6990 Py_ssize_t size,
6991 const char *errors,
6992 Py_ssize_t *consumed)
6993{
6994 return decode_code_page_stateful(code_page, s, size, errors, consumed);
6995}
6996
6997PyObject *
6998PyUnicode_DecodeMBCSStateful(const char *s,
6999 Py_ssize_t size,
7000 const char *errors,
7001 Py_ssize_t *consumed)
7002{
7003 return decode_code_page_stateful(CP_ACP, s, size, errors, consumed);
7004}
7005
7006PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00007007PyUnicode_DecodeMBCS(const char *s,
7008 Py_ssize_t size,
7009 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007010{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007011 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
7012}
7013
Victor Stinner3a50e702011-10-18 21:21:00 +02007014static DWORD
7015encode_code_page_flags(UINT code_page, const char *errors)
7016{
7017 if (code_page == CP_UTF8) {
7018 if (winver.dwMajorVersion >= 6)
7019 /* CP_UTF8 supports WC_ERR_INVALID_CHARS on Windows Vista
7020 and later */
7021 return WC_ERR_INVALID_CHARS;
7022 else
7023 /* CP_UTF8 only supports flags=0 on Windows older than Vista */
7024 return 0;
7025 }
7026 else if (code_page == CP_UTF7) {
7027 /* CP_UTF7 only supports flags=0 */
7028 return 0;
7029 }
7030 else {
7031 if (errors != NULL && strcmp(errors, "replace") == 0)
7032 return 0;
7033 else
7034 return WC_NO_BEST_FIT_CHARS;
7035 }
7036}
7037
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007038/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007039 * Encode a Unicode string to a Windows code page into a byte string in strict
7040 * mode.
7041 *
7042 * Returns consumed characters if succeed, returns -2 on encode error, or raise
7043 * a WindowsError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007044 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007045static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007046encode_code_page_strict(UINT code_page, PyObject **outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007047 PyObject *unicode, Py_ssize_t offset, int len,
Victor Stinner3a50e702011-10-18 21:21:00 +02007048 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007049{
Victor Stinner554f3f02010-06-16 23:33:54 +00007050 BOOL usedDefaultChar = FALSE;
Victor Stinner3a50e702011-10-18 21:21:00 +02007051 BOOL *pusedDefaultChar = &usedDefaultChar;
7052 int outsize;
Victor Stinner554f3f02010-06-16 23:33:54 +00007053 PyObject *exc = NULL;
Victor Stinner24729f32011-11-10 20:31:37 +01007054 wchar_t *p;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007055 Py_ssize_t size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007056 const DWORD flags = encode_code_page_flags(code_page, NULL);
7057 char *out;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007058 /* Create a substring so that we can get the UTF-16 representation
7059 of just the slice under consideration. */
7060 PyObject *substring;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007061
Martin v. Löwis3d325192011-11-04 18:23:06 +01007062 assert(len > 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007063
Victor Stinner3a50e702011-10-18 21:21:00 +02007064 if (code_page != CP_UTF8 && code_page != CP_UTF7)
Victor Stinner554f3f02010-06-16 23:33:54 +00007065 pusedDefaultChar = &usedDefaultChar;
Victor Stinner3a50e702011-10-18 21:21:00 +02007066 else
Victor Stinner554f3f02010-06-16 23:33:54 +00007067 pusedDefaultChar = NULL;
Victor Stinner554f3f02010-06-16 23:33:54 +00007068
Victor Stinner2fc507f2011-11-04 20:06:39 +01007069 substring = PyUnicode_Substring(unicode, offset, offset+len);
7070 if (substring == NULL)
7071 return -1;
7072 p = PyUnicode_AsUnicodeAndSize(substring, &size);
7073 if (p == NULL) {
7074 Py_DECREF(substring);
7075 return -1;
7076 }
Martin v. Löwis3d325192011-11-04 18:23:06 +01007077
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007078 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007079 outsize = WideCharToMultiByte(code_page, flags,
7080 p, size,
7081 NULL, 0,
7082 NULL, pusedDefaultChar);
7083 if (outsize <= 0)
7084 goto error;
7085 /* If we used a default char, then we failed! */
Victor Stinner2fc507f2011-11-04 20:06:39 +01007086 if (pusedDefaultChar && *pusedDefaultChar) {
7087 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007088 return -2;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007089 }
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007090
Victor Stinner3a50e702011-10-18 21:21:00 +02007091 if (*outbytes == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007092 /* Create string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007093 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007094 if (*outbytes == NULL) {
7095 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007096 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007097 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007098 out = PyBytes_AS_STRING(*outbytes);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007099 }
7100 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007101 /* Extend string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007102 const Py_ssize_t n = PyBytes_Size(*outbytes);
7103 if (outsize > PY_SSIZE_T_MAX - n) {
7104 PyErr_NoMemory();
Victor Stinner2fc507f2011-11-04 20:06:39 +01007105 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007106 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007107 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007108 if (_PyBytes_Resize(outbytes, n + outsize) < 0) {
7109 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007110 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007111 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007112 out = PyBytes_AS_STRING(*outbytes) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007113 }
7114
7115 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007116 outsize = WideCharToMultiByte(code_page, flags,
7117 p, size,
7118 out, outsize,
7119 NULL, pusedDefaultChar);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007120 Py_CLEAR(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007121 if (outsize <= 0)
7122 goto error;
7123 if (pusedDefaultChar && *pusedDefaultChar)
7124 return -2;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007125 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00007126
Victor Stinner3a50e702011-10-18 21:21:00 +02007127error:
Victor Stinner2fc507f2011-11-04 20:06:39 +01007128 Py_XDECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007129 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7130 return -2;
7131 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007132 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007133}
7134
Victor Stinner3a50e702011-10-18 21:21:00 +02007135/*
7136 * Encode a Unicode string to a Windows code page into a byte string using a
7137 * error handler.
7138 *
7139 * Returns consumed characters if succeed, or raise a WindowsError and returns
7140 * -1 on other error.
7141 */
7142static int
7143encode_code_page_errors(UINT code_page, PyObject **outbytes,
Victor Stinner7581cef2011-11-03 22:32:33 +01007144 PyObject *unicode, Py_ssize_t unicode_offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007145 Py_ssize_t insize, const char* errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007146{
Victor Stinner3a50e702011-10-18 21:21:00 +02007147 const DWORD flags = encode_code_page_flags(code_page, errors);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007148 Py_ssize_t pos = unicode_offset;
7149 Py_ssize_t endin = unicode_offset + insize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007150 /* Ideally, we should get reason from FormatMessage. This is the Windows
7151 2000 English version of the message. */
7152 const char *reason = "invalid character";
7153 /* 4=maximum length of a UTF-8 sequence */
7154 char buffer[4];
7155 BOOL usedDefaultChar = FALSE, *pusedDefaultChar;
7156 Py_ssize_t outsize;
7157 char *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007158 PyObject *errorHandler = NULL;
7159 PyObject *exc = NULL;
7160 PyObject *encoding_obj = NULL;
7161 char *encoding;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007162 Py_ssize_t newpos, newoutsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007163 PyObject *rep;
7164 int ret = -1;
7165
7166 assert(insize > 0);
7167
7168 encoding = code_page_name(code_page, &encoding_obj);
7169 if (encoding == NULL)
7170 return -1;
7171
7172 if (errors == NULL || strcmp(errors, "strict") == 0) {
7173 /* The last error was ERROR_NO_UNICODE_TRANSLATION,
7174 then we raise a UnicodeEncodeError. */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007175 make_encode_exception(&exc, encoding, unicode, 0, 0, reason);
Victor Stinner3a50e702011-10-18 21:21:00 +02007176 if (exc != NULL) {
7177 PyCodec_StrictErrors(exc);
7178 Py_DECREF(exc);
7179 }
7180 Py_XDECREF(encoding_obj);
7181 return -1;
7182 }
7183
7184 if (code_page != CP_UTF8 && code_page != CP_UTF7)
7185 pusedDefaultChar = &usedDefaultChar;
7186 else
7187 pusedDefaultChar = NULL;
7188
7189 if (Py_ARRAY_LENGTH(buffer) > PY_SSIZE_T_MAX / insize) {
7190 PyErr_NoMemory();
7191 goto error;
7192 }
7193 outsize = insize * Py_ARRAY_LENGTH(buffer);
7194
7195 if (*outbytes == NULL) {
7196 /* Create string object */
7197 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
7198 if (*outbytes == NULL)
7199 goto error;
7200 out = PyBytes_AS_STRING(*outbytes);
7201 }
7202 else {
7203 /* Extend string object */
7204 Py_ssize_t n = PyBytes_Size(*outbytes);
7205 if (n > PY_SSIZE_T_MAX - outsize) {
7206 PyErr_NoMemory();
7207 goto error;
7208 }
7209 if (_PyBytes_Resize(outbytes, n + outsize) < 0)
7210 goto error;
7211 out = PyBytes_AS_STRING(*outbytes) + n;
7212 }
7213
7214 /* Encode the string character per character */
Martin v. Löwis3d325192011-11-04 18:23:06 +01007215 while (pos < endin)
Victor Stinner3a50e702011-10-18 21:21:00 +02007216 {
Victor Stinner2fc507f2011-11-04 20:06:39 +01007217 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, pos);
7218 wchar_t chars[2];
7219 int charsize;
7220 if (ch < 0x10000) {
7221 chars[0] = (wchar_t)ch;
7222 charsize = 1;
7223 }
7224 else {
7225 ch -= 0x10000;
7226 chars[0] = 0xd800 + (ch >> 10);
7227 chars[1] = 0xdc00 + (ch & 0x3ff);
7228 charsize = 2;
7229 }
7230
Victor Stinner3a50e702011-10-18 21:21:00 +02007231 outsize = WideCharToMultiByte(code_page, flags,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007232 chars, charsize,
Victor Stinner3a50e702011-10-18 21:21:00 +02007233 buffer, Py_ARRAY_LENGTH(buffer),
7234 NULL, pusedDefaultChar);
7235 if (outsize > 0) {
7236 if (pusedDefaultChar == NULL || !(*pusedDefaultChar))
7237 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007238 pos++;
Victor Stinner3a50e702011-10-18 21:21:00 +02007239 memcpy(out, buffer, outsize);
7240 out += outsize;
7241 continue;
7242 }
7243 }
7244 else if (GetLastError() != ERROR_NO_UNICODE_TRANSLATION) {
7245 PyErr_SetFromWindowsErr(0);
7246 goto error;
7247 }
7248
Victor Stinner3a50e702011-10-18 21:21:00 +02007249 rep = unicode_encode_call_errorhandler(
7250 errors, &errorHandler, encoding, reason,
Victor Stinner7581cef2011-11-03 22:32:33 +01007251 unicode, &exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007252 pos, pos + 1, &newpos);
Victor Stinner3a50e702011-10-18 21:21:00 +02007253 if (rep == NULL)
7254 goto error;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007255 pos = newpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007256
7257 if (PyBytes_Check(rep)) {
7258 outsize = PyBytes_GET_SIZE(rep);
7259 if (outsize != 1) {
7260 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7261 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7262 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7263 Py_DECREF(rep);
7264 goto error;
7265 }
7266 out = PyBytes_AS_STRING(*outbytes) + offset;
7267 }
7268 memcpy(out, PyBytes_AS_STRING(rep), outsize);
7269 out += outsize;
7270 }
7271 else {
7272 Py_ssize_t i;
7273 enum PyUnicode_Kind kind;
7274 void *data;
7275
Benjamin Petersonbac79492012-01-14 13:34:47 -05007276 if (PyUnicode_READY(rep) == -1) {
Victor Stinner3a50e702011-10-18 21:21:00 +02007277 Py_DECREF(rep);
7278 goto error;
7279 }
7280
7281 outsize = PyUnicode_GET_LENGTH(rep);
7282 if (outsize != 1) {
7283 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7284 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7285 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7286 Py_DECREF(rep);
7287 goto error;
7288 }
7289 out = PyBytes_AS_STRING(*outbytes) + offset;
7290 }
7291 kind = PyUnicode_KIND(rep);
7292 data = PyUnicode_DATA(rep);
7293 for (i=0; i < outsize; i++) {
7294 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7295 if (ch > 127) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007296 raise_encode_exception(&exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007297 encoding, unicode,
7298 pos, pos + 1,
Victor Stinner3a50e702011-10-18 21:21:00 +02007299 "unable to encode error handler result to ASCII");
7300 Py_DECREF(rep);
7301 goto error;
7302 }
7303 *out = (unsigned char)ch;
7304 out++;
7305 }
7306 }
7307 Py_DECREF(rep);
7308 }
7309 /* write a NUL byte */
7310 *out = 0;
7311 outsize = out - PyBytes_AS_STRING(*outbytes);
7312 assert(outsize <= PyBytes_GET_SIZE(*outbytes));
7313 if (_PyBytes_Resize(outbytes, outsize) < 0)
7314 goto error;
7315 ret = 0;
7316
7317error:
7318 Py_XDECREF(encoding_obj);
7319 Py_XDECREF(errorHandler);
7320 Py_XDECREF(exc);
7321 return ret;
7322}
7323
Victor Stinner3a50e702011-10-18 21:21:00 +02007324static PyObject *
7325encode_code_page(int code_page,
Victor Stinner7581cef2011-11-03 22:32:33 +01007326 PyObject *unicode,
Victor Stinner3a50e702011-10-18 21:21:00 +02007327 const char *errors)
7328{
Martin v. Löwis3d325192011-11-04 18:23:06 +01007329 Py_ssize_t len;
Victor Stinner3a50e702011-10-18 21:21:00 +02007330 PyObject *outbytes = NULL;
Victor Stinner7581cef2011-11-03 22:32:33 +01007331 Py_ssize_t offset;
Victor Stinner76a31a62011-11-04 00:05:13 +01007332 int chunk_len, ret, done;
Victor Stinner7581cef2011-11-03 22:32:33 +01007333
Benjamin Petersonbac79492012-01-14 13:34:47 -05007334 if (PyUnicode_READY(unicode) == -1)
Victor Stinner2fc507f2011-11-04 20:06:39 +01007335 return NULL;
7336 len = PyUnicode_GET_LENGTH(unicode);
Guido van Rossum03e29f12000-05-04 15:52:20 +00007337
Victor Stinner3a50e702011-10-18 21:21:00 +02007338 if (code_page < 0) {
7339 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7340 return NULL;
7341 }
7342
Martin v. Löwis3d325192011-11-04 18:23:06 +01007343 if (len == 0)
Victor Stinner76a31a62011-11-04 00:05:13 +01007344 return PyBytes_FromStringAndSize(NULL, 0);
7345
Victor Stinner7581cef2011-11-03 22:32:33 +01007346 offset = 0;
7347 do
7348 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007349#ifdef NEED_RETRY
Victor Stinner2fc507f2011-11-04 20:06:39 +01007350 /* UTF-16 encoding may double the size, so use only INT_MAX/2
Martin v. Löwis3d325192011-11-04 18:23:06 +01007351 chunks. */
7352 if (len > INT_MAX/2) {
7353 chunk_len = INT_MAX/2;
Victor Stinner76a31a62011-11-04 00:05:13 +01007354 done = 0;
7355 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007356 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007357#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007358 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007359 chunk_len = (int)len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007360 done = 1;
7361 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007362
Victor Stinner76a31a62011-11-04 00:05:13 +01007363 ret = encode_code_page_strict(code_page, &outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007364 unicode, offset, chunk_len,
Victor Stinner76a31a62011-11-04 00:05:13 +01007365 errors);
7366 if (ret == -2)
7367 ret = encode_code_page_errors(code_page, &outbytes,
7368 unicode, offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007369 chunk_len, errors);
Victor Stinner7581cef2011-11-03 22:32:33 +01007370 if (ret < 0) {
7371 Py_XDECREF(outbytes);
7372 return NULL;
7373 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007374
Victor Stinner7581cef2011-11-03 22:32:33 +01007375 offset += chunk_len;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007376 len -= chunk_len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007377 } while (!done);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007378
Victor Stinner3a50e702011-10-18 21:21:00 +02007379 return outbytes;
7380}
7381
7382PyObject *
7383PyUnicode_EncodeMBCS(const Py_UNICODE *p,
7384 Py_ssize_t size,
7385 const char *errors)
7386{
Victor Stinner7581cef2011-11-03 22:32:33 +01007387 PyObject *unicode, *res;
7388 unicode = PyUnicode_FromUnicode(p, size);
7389 if (unicode == NULL)
7390 return NULL;
7391 res = encode_code_page(CP_ACP, unicode, errors);
7392 Py_DECREF(unicode);
7393 return res;
Victor Stinner3a50e702011-10-18 21:21:00 +02007394}
7395
7396PyObject *
7397PyUnicode_EncodeCodePage(int code_page,
7398 PyObject *unicode,
7399 const char *errors)
7400{
Victor Stinner7581cef2011-11-03 22:32:33 +01007401 return encode_code_page(code_page, unicode, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007402}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007403
Alexander Belopolsky40018472011-02-26 01:02:56 +00007404PyObject *
7405PyUnicode_AsMBCSString(PyObject *unicode)
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007406{
7407 if (!PyUnicode_Check(unicode)) {
7408 PyErr_BadArgument();
7409 return NULL;
7410 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007411 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007412}
7413
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007414#undef NEED_RETRY
7415
Victor Stinner99b95382011-07-04 14:23:54 +02007416#endif /* HAVE_MBCS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007417
Guido van Rossumd57fd912000-03-10 22:53:23 +00007418/* --- Character Mapping Codec -------------------------------------------- */
7419
Alexander Belopolsky40018472011-02-26 01:02:56 +00007420PyObject *
7421PyUnicode_DecodeCharmap(const char *s,
7422 Py_ssize_t size,
7423 PyObject *mapping,
7424 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007425{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007426 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007427 Py_ssize_t startinpos;
7428 Py_ssize_t endinpos;
7429 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007430 const char *e;
Victor Stinner7931d9a2011-11-04 00:22:48 +01007431 PyObject *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007432 Py_ssize_t extrachars = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007433 PyObject *errorHandler = NULL;
7434 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00007435
Guido van Rossumd57fd912000-03-10 22:53:23 +00007436 /* Default to Latin-1 */
7437 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007438 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007439
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007440 v = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007441 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007442 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007443 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01007444 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007445 outpos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007446 e = s + size;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007447 if (PyUnicode_CheckExact(mapping)) {
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007448 Py_ssize_t maplen;
7449 enum PyUnicode_Kind kind;
7450 void *data;
7451 Py_UCS4 x;
7452
Benjamin Petersonbac79492012-01-14 13:34:47 -05007453 if (PyUnicode_READY(mapping) == -1)
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007454 return NULL;
7455
7456 maplen = PyUnicode_GET_LENGTH(mapping);
7457 data = PyUnicode_DATA(mapping);
7458 kind = PyUnicode_KIND(mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00007459 while (s < e) {
7460 unsigned char ch = *s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007461
Benjamin Peterson29060642009-01-31 22:14:21 +00007462 if (ch < maplen)
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007463 x = PyUnicode_READ(kind, data, ch);
7464 else
7465 x = 0xfffe; /* invalid value */
Guido van Rossumd57fd912000-03-10 22:53:23 +00007466
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007467 if (x == 0xfffe)
7468 {
Benjamin Peterson29060642009-01-31 22:14:21 +00007469 /* undefined mapping */
Benjamin Peterson29060642009-01-31 22:14:21 +00007470 startinpos = s-starts;
7471 endinpos = startinpos+1;
7472 if (unicode_decode_call_errorhandler(
7473 errors, &errorHandler,
7474 "charmap", "character maps to <undefined>",
7475 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007476 &v, &outpos)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007477 goto onError;
7478 }
7479 continue;
7480 }
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007481
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007482 if (unicode_putchar(&v, &outpos, x) < 0)
7483 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00007484 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007485 }
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007486 }
7487 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007488 while (s < e) {
7489 unsigned char ch = *s;
7490 PyObject *w, *x;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007491
Benjamin Peterson29060642009-01-31 22:14:21 +00007492 /* Get mapping (char ordinal -> integer, Unicode char or None) */
7493 w = PyLong_FromLong((long)ch);
7494 if (w == NULL)
7495 goto onError;
7496 x = PyObject_GetItem(mapping, w);
7497 Py_DECREF(w);
7498 if (x == NULL) {
7499 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7500 /* No mapping found means: mapping is undefined. */
7501 PyErr_Clear();
7502 x = Py_None;
7503 Py_INCREF(x);
7504 } else
7505 goto onError;
7506 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007507
Benjamin Peterson29060642009-01-31 22:14:21 +00007508 /* Apply mapping */
7509 if (PyLong_Check(x)) {
7510 long value = PyLong_AS_LONG(x);
7511 if (value < 0 || value > 65535) {
7512 PyErr_SetString(PyExc_TypeError,
7513 "character mapping must be in range(65536)");
7514 Py_DECREF(x);
7515 goto onError;
7516 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007517 if (unicode_putchar(&v, &outpos, value) < 0)
7518 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00007519 }
7520 else if (x == Py_None) {
7521 /* undefined mapping */
Benjamin Peterson29060642009-01-31 22:14:21 +00007522 startinpos = s-starts;
7523 endinpos = startinpos+1;
7524 if (unicode_decode_call_errorhandler(
7525 errors, &errorHandler,
7526 "charmap", "character maps to <undefined>",
7527 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007528 &v, &outpos)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007529 Py_DECREF(x);
7530 goto onError;
7531 }
7532 Py_DECREF(x);
7533 continue;
7534 }
7535 else if (PyUnicode_Check(x)) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007536 Py_ssize_t targetsize;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007537
Benjamin Petersonbac79492012-01-14 13:34:47 -05007538 if (PyUnicode_READY(x) == -1)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007539 goto onError;
7540 targetsize = PyUnicode_GET_LENGTH(x);
7541
7542 if (targetsize == 1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007543 /* 1-1 mapping */
Victor Stinner62aa4d02011-11-09 00:03:45 +01007544 if (unicode_putchar(&v, &outpos,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007545 PyUnicode_READ_CHAR(x, 0)) < 0)
7546 goto onError;
7547 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007548 else if (targetsize > 1) {
7549 /* 1-n mapping */
7550 if (targetsize > extrachars) {
7551 /* resize first */
Benjamin Peterson29060642009-01-31 22:14:21 +00007552 Py_ssize_t needed = (targetsize - extrachars) + \
7553 (targetsize << 2);
7554 extrachars += needed;
7555 /* XXX overflow detection missing */
Victor Stinner16e6a802011-12-12 13:24:15 +01007556 if (unicode_resize(&v,
7557 PyUnicode_GET_LENGTH(v) + needed) < 0)
7558 {
Benjamin Peterson29060642009-01-31 22:14:21 +00007559 Py_DECREF(x);
7560 goto onError;
7561 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007562 }
Victor Stinner1b487b42012-05-03 12:29:04 +02007563 if (unicode_widen(&v, outpos, PyUnicode_MAX_CHAR_VALUE(x)) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007564 goto onError;
7565 PyUnicode_CopyCharacters(v, outpos, x, 0, targetsize);
7566 outpos += targetsize;
Benjamin Peterson29060642009-01-31 22:14:21 +00007567 extrachars -= targetsize;
7568 }
7569 /* 1-0 mapping: skip the character */
7570 }
7571 else {
7572 /* wrong return value */
7573 PyErr_SetString(PyExc_TypeError,
7574 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00007575 Py_DECREF(x);
7576 goto onError;
7577 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007578 Py_DECREF(x);
7579 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007580 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00007581 }
Victor Stinner16e6a802011-12-12 13:24:15 +01007582 if (unicode_resize(&v, outpos) < 0)
Antoine Pitroua8f63c02011-11-08 18:37:16 +01007583 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007584 Py_XDECREF(errorHandler);
7585 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01007586 return unicode_result(v);
Tim Petersced69f82003-09-16 20:30:58 +00007587
Benjamin Peterson29060642009-01-31 22:14:21 +00007588 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007589 Py_XDECREF(errorHandler);
7590 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007591 Py_XDECREF(v);
7592 return NULL;
7593}
7594
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007595/* Charmap encoding: the lookup table */
7596
Alexander Belopolsky40018472011-02-26 01:02:56 +00007597struct encoding_map {
Benjamin Peterson29060642009-01-31 22:14:21 +00007598 PyObject_HEAD
7599 unsigned char level1[32];
7600 int count2, count3;
7601 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007602};
7603
7604static PyObject*
7605encoding_map_size(PyObject *obj, PyObject* args)
7606{
7607 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007608 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00007609 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007610}
7611
7612static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007613 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00007614 PyDoc_STR("Return the size (in bytes) of this object") },
7615 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007616};
7617
7618static void
7619encoding_map_dealloc(PyObject* o)
7620{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007621 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007622}
7623
7624static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007625 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007626 "EncodingMap", /*tp_name*/
7627 sizeof(struct encoding_map), /*tp_basicsize*/
7628 0, /*tp_itemsize*/
7629 /* methods */
7630 encoding_map_dealloc, /*tp_dealloc*/
7631 0, /*tp_print*/
7632 0, /*tp_getattr*/
7633 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00007634 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00007635 0, /*tp_repr*/
7636 0, /*tp_as_number*/
7637 0, /*tp_as_sequence*/
7638 0, /*tp_as_mapping*/
7639 0, /*tp_hash*/
7640 0, /*tp_call*/
7641 0, /*tp_str*/
7642 0, /*tp_getattro*/
7643 0, /*tp_setattro*/
7644 0, /*tp_as_buffer*/
7645 Py_TPFLAGS_DEFAULT, /*tp_flags*/
7646 0, /*tp_doc*/
7647 0, /*tp_traverse*/
7648 0, /*tp_clear*/
7649 0, /*tp_richcompare*/
7650 0, /*tp_weaklistoffset*/
7651 0, /*tp_iter*/
7652 0, /*tp_iternext*/
7653 encoding_map_methods, /*tp_methods*/
7654 0, /*tp_members*/
7655 0, /*tp_getset*/
7656 0, /*tp_base*/
7657 0, /*tp_dict*/
7658 0, /*tp_descr_get*/
7659 0, /*tp_descr_set*/
7660 0, /*tp_dictoffset*/
7661 0, /*tp_init*/
7662 0, /*tp_alloc*/
7663 0, /*tp_new*/
7664 0, /*tp_free*/
7665 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007666};
7667
7668PyObject*
7669PyUnicode_BuildEncodingMap(PyObject* string)
7670{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007671 PyObject *result;
7672 struct encoding_map *mresult;
7673 int i;
7674 int need_dict = 0;
7675 unsigned char level1[32];
7676 unsigned char level2[512];
7677 unsigned char *mlevel1, *mlevel2, *mlevel3;
7678 int count2 = 0, count3 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007679 int kind;
7680 void *data;
7681 Py_UCS4 ch;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007682
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007683 if (!PyUnicode_Check(string) || PyUnicode_GET_LENGTH(string) != 256) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007684 PyErr_BadArgument();
7685 return NULL;
7686 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007687 kind = PyUnicode_KIND(string);
7688 data = PyUnicode_DATA(string);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007689 memset(level1, 0xFF, sizeof level1);
7690 memset(level2, 0xFF, sizeof level2);
7691
7692 /* If there isn't a one-to-one mapping of NULL to \0,
7693 or if there are non-BMP characters, we need to use
7694 a mapping dictionary. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007695 if (PyUnicode_READ(kind, data, 0) != 0)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007696 need_dict = 1;
7697 for (i = 1; i < 256; i++) {
7698 int l1, l2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007699 ch = PyUnicode_READ(kind, data, i);
7700 if (ch == 0 || ch > 0xFFFF) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007701 need_dict = 1;
7702 break;
7703 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007704 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007705 /* unmapped character */
7706 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007707 l1 = ch >> 11;
7708 l2 = ch >> 7;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007709 if (level1[l1] == 0xFF)
7710 level1[l1] = count2++;
7711 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00007712 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007713 }
7714
7715 if (count2 >= 0xFF || count3 >= 0xFF)
7716 need_dict = 1;
7717
7718 if (need_dict) {
7719 PyObject *result = PyDict_New();
7720 PyObject *key, *value;
7721 if (!result)
7722 return NULL;
7723 for (i = 0; i < 256; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007724 key = PyLong_FromLong(PyUnicode_READ(kind, data, i));
Christian Heimes217cfd12007-12-02 14:31:20 +00007725 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007726 if (!key || !value)
7727 goto failed1;
7728 if (PyDict_SetItem(result, key, value) == -1)
7729 goto failed1;
7730 Py_DECREF(key);
7731 Py_DECREF(value);
7732 }
7733 return result;
7734 failed1:
7735 Py_XDECREF(key);
7736 Py_XDECREF(value);
7737 Py_DECREF(result);
7738 return NULL;
7739 }
7740
7741 /* Create a three-level trie */
7742 result = PyObject_MALLOC(sizeof(struct encoding_map) +
7743 16*count2 + 128*count3 - 1);
7744 if (!result)
7745 return PyErr_NoMemory();
7746 PyObject_Init(result, &EncodingMapType);
7747 mresult = (struct encoding_map*)result;
7748 mresult->count2 = count2;
7749 mresult->count3 = count3;
7750 mlevel1 = mresult->level1;
7751 mlevel2 = mresult->level23;
7752 mlevel3 = mresult->level23 + 16*count2;
7753 memcpy(mlevel1, level1, 32);
7754 memset(mlevel2, 0xFF, 16*count2);
7755 memset(mlevel3, 0, 128*count3);
7756 count3 = 0;
7757 for (i = 1; i < 256; i++) {
7758 int o1, o2, o3, i2, i3;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007759 if (PyUnicode_READ(kind, data, i) == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007760 /* unmapped character */
7761 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007762 o1 = PyUnicode_READ(kind, data, i)>>11;
7763 o2 = (PyUnicode_READ(kind, data, i)>>7) & 0xF;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007764 i2 = 16*mlevel1[o1] + o2;
7765 if (mlevel2[i2] == 0xFF)
7766 mlevel2[i2] = count3++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007767 o3 = PyUnicode_READ(kind, data, i) & 0x7F;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007768 i3 = 128*mlevel2[i2] + o3;
7769 mlevel3[i3] = i;
7770 }
7771 return result;
7772}
7773
7774static int
Victor Stinner22168992011-11-20 17:09:18 +01007775encoding_map_lookup(Py_UCS4 c, PyObject *mapping)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007776{
7777 struct encoding_map *map = (struct encoding_map*)mapping;
7778 int l1 = c>>11;
7779 int l2 = (c>>7) & 0xF;
7780 int l3 = c & 0x7F;
7781 int i;
7782
Victor Stinner22168992011-11-20 17:09:18 +01007783 if (c > 0xFFFF)
Benjamin Peterson29060642009-01-31 22:14:21 +00007784 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007785 if (c == 0)
7786 return 0;
7787 /* level 1*/
7788 i = map->level1[l1];
7789 if (i == 0xFF) {
7790 return -1;
7791 }
7792 /* level 2*/
7793 i = map->level23[16*i+l2];
7794 if (i == 0xFF) {
7795 return -1;
7796 }
7797 /* level 3 */
7798 i = map->level23[16*map->count2 + 128*i + l3];
7799 if (i == 0) {
7800 return -1;
7801 }
7802 return i;
7803}
7804
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007805/* Lookup the character ch in the mapping. If the character
7806 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00007807 error occurred). */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007808static PyObject *
Victor Stinner22168992011-11-20 17:09:18 +01007809charmapencode_lookup(Py_UCS4 c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007810{
Christian Heimes217cfd12007-12-02 14:31:20 +00007811 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007812 PyObject *x;
7813
7814 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007815 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007816 x = PyObject_GetItem(mapping, w);
7817 Py_DECREF(w);
7818 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007819 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7820 /* No mapping found means: mapping is undefined. */
7821 PyErr_Clear();
7822 x = Py_None;
7823 Py_INCREF(x);
7824 return x;
7825 } else
7826 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007827 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00007828 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00007829 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00007830 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007831 long value = PyLong_AS_LONG(x);
7832 if (value < 0 || value > 255) {
7833 PyErr_SetString(PyExc_TypeError,
7834 "character mapping must be in range(256)");
7835 Py_DECREF(x);
7836 return NULL;
7837 }
7838 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007839 }
Christian Heimes72b710a2008-05-26 13:28:38 +00007840 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00007841 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007842 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007843 /* wrong return value */
7844 PyErr_Format(PyExc_TypeError,
7845 "character mapping must return integer, bytes or None, not %.400s",
7846 x->ob_type->tp_name);
7847 Py_DECREF(x);
7848 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007849 }
7850}
7851
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007852static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00007853charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007854{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007855 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
7856 /* exponentially overallocate to minimize reallocations */
7857 if (requiredsize < 2*outsize)
7858 requiredsize = 2*outsize;
7859 if (_PyBytes_Resize(outobj, requiredsize))
7860 return -1;
7861 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007862}
7863
Benjamin Peterson14339b62009-01-31 16:36:08 +00007864typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00007865 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Alexander Belopolsky40018472011-02-26 01:02:56 +00007866} charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007867/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00007868 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007869 space is available. Return a new reference to the object that
7870 was put in the output buffer, or Py_None, if the mapping was undefined
7871 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00007872 reallocation error occurred. The caller must decref the result */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007873static charmapencode_result
Victor Stinner22168992011-11-20 17:09:18 +01007874charmapencode_output(Py_UCS4 c, PyObject *mapping,
Alexander Belopolsky40018472011-02-26 01:02:56 +00007875 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007876{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007877 PyObject *rep;
7878 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00007879 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007880
Christian Heimes90aa7642007-12-19 02:45:37 +00007881 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007882 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00007883 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007884 if (res == -1)
7885 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00007886 if (outsize<requiredsize)
7887 if (charmapencode_resize(outobj, outpos, requiredsize))
7888 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00007889 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00007890 outstart[(*outpos)++] = (char)res;
7891 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007892 }
7893
7894 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007895 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007896 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007897 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007898 Py_DECREF(rep);
7899 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007900 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007901 if (PyLong_Check(rep)) {
7902 Py_ssize_t requiredsize = *outpos+1;
7903 if (outsize<requiredsize)
7904 if (charmapencode_resize(outobj, outpos, requiredsize)) {
7905 Py_DECREF(rep);
7906 return enc_EXCEPTION;
7907 }
Christian Heimes72b710a2008-05-26 13:28:38 +00007908 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00007909 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00007910 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007911 else {
7912 const char *repchars = PyBytes_AS_STRING(rep);
7913 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
7914 Py_ssize_t requiredsize = *outpos+repsize;
7915 if (outsize<requiredsize)
7916 if (charmapencode_resize(outobj, outpos, requiredsize)) {
7917 Py_DECREF(rep);
7918 return enc_EXCEPTION;
7919 }
Christian Heimes72b710a2008-05-26 13:28:38 +00007920 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00007921 memcpy(outstart + *outpos, repchars, repsize);
7922 *outpos += repsize;
7923 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007924 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007925 Py_DECREF(rep);
7926 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007927}
7928
7929/* handle an error in PyUnicode_EncodeCharmap
7930 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007931static int
7932charmap_encoding_error(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007933 PyObject *unicode, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007934 PyObject **exceptionObject,
Walter Dörwalde5402fb2003-08-14 20:25:29 +00007935 int *known_errorHandler, PyObject **errorHandler, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00007936 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007937{
7938 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007939 Py_ssize_t size, repsize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007940 Py_ssize_t newpos;
Victor Stinnerae4f7c82011-11-20 18:28:55 +01007941 enum PyUnicode_Kind kind;
7942 void *data;
7943 Py_ssize_t index;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007944 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00007945 Py_ssize_t collstartpos = *inpos;
7946 Py_ssize_t collendpos = *inpos+1;
7947 Py_ssize_t collpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007948 char *encoding = "charmap";
7949 char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007950 charmapencode_result x;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007951 Py_UCS4 ch;
Brian Curtin2787ea42011-11-02 15:09:37 -05007952 int val;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007953
Benjamin Petersonbac79492012-01-14 13:34:47 -05007954 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007955 return -1;
7956 size = PyUnicode_GET_LENGTH(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007957 /* find all unencodable characters */
7958 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007959 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00007960 if (Py_TYPE(mapping) == &EncodingMapType) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007961 ch = PyUnicode_READ_CHAR(unicode, collendpos);
Brian Curtin2787ea42011-11-02 15:09:37 -05007962 val = encoding_map_lookup(ch, mapping);
7963 if (val != -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00007964 break;
7965 ++collendpos;
7966 continue;
7967 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007968
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007969 ch = PyUnicode_READ_CHAR(unicode, collendpos);
7970 rep = charmapencode_lookup(ch, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00007971 if (rep==NULL)
7972 return -1;
7973 else if (rep!=Py_None) {
7974 Py_DECREF(rep);
7975 break;
7976 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007977 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00007978 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007979 }
7980 /* cache callback name lookup
7981 * (if not done yet, i.e. it's the first error) */
7982 if (*known_errorHandler==-1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007983 if ((errors==NULL) || (!strcmp(errors, "strict")))
7984 *known_errorHandler = 1;
7985 else if (!strcmp(errors, "replace"))
7986 *known_errorHandler = 2;
7987 else if (!strcmp(errors, "ignore"))
7988 *known_errorHandler = 3;
7989 else if (!strcmp(errors, "xmlcharrefreplace"))
7990 *known_errorHandler = 4;
7991 else
7992 *known_errorHandler = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007993 }
7994 switch (*known_errorHandler) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007995 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007996 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00007997 return -1;
7998 case 2: /* replace */
7999 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008000 x = charmapencode_output('?', mapping, res, respos);
8001 if (x==enc_EXCEPTION) {
8002 return -1;
8003 }
8004 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008005 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008006 return -1;
8007 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008008 }
8009 /* fall through */
8010 case 3: /* ignore */
8011 *inpos = collendpos;
8012 break;
8013 case 4: /* xmlcharrefreplace */
8014 /* generate replacement (temporarily (mis)uses p) */
8015 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008016 char buffer[2+29+1+1];
8017 char *cp;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008018 sprintf(buffer, "&#%d;", (int)PyUnicode_READ_CHAR(unicode, collpos));
Benjamin Peterson29060642009-01-31 22:14:21 +00008019 for (cp = buffer; *cp; ++cp) {
8020 x = charmapencode_output(*cp, mapping, res, respos);
8021 if (x==enc_EXCEPTION)
8022 return -1;
8023 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008024 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008025 return -1;
8026 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008027 }
8028 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008029 *inpos = collendpos;
8030 break;
8031 default:
8032 repunicode = unicode_encode_call_errorhandler(errors, errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008033 encoding, reason, unicode, exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00008034 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008035 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008036 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00008037 if (PyBytes_Check(repunicode)) {
8038 /* Directly copy bytes result to output. */
8039 Py_ssize_t outsize = PyBytes_Size(*res);
8040 Py_ssize_t requiredsize;
8041 repsize = PyBytes_Size(repunicode);
8042 requiredsize = *respos + repsize;
8043 if (requiredsize > outsize)
8044 /* Make room for all additional bytes. */
8045 if (charmapencode_resize(res, respos, requiredsize)) {
8046 Py_DECREF(repunicode);
8047 return -1;
8048 }
8049 memcpy(PyBytes_AsString(*res) + *respos,
8050 PyBytes_AsString(repunicode), repsize);
8051 *respos += repsize;
8052 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008053 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00008054 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008055 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008056 /* generate replacement */
Benjamin Petersonbac79492012-01-14 13:34:47 -05008057 if (PyUnicode_READY(repunicode) == -1) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008058 Py_DECREF(repunicode);
8059 return -1;
8060 }
Victor Stinner9e30aa52011-11-21 02:49:52 +01008061 repsize = PyUnicode_GET_LENGTH(repunicode);
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008062 data = PyUnicode_DATA(repunicode);
8063 kind = PyUnicode_KIND(repunicode);
8064 for (index = 0; index < repsize; index++) {
8065 Py_UCS4 repch = PyUnicode_READ(kind, data, index);
8066 x = charmapencode_output(repch, mapping, res, respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008067 if (x==enc_EXCEPTION) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008068 Py_DECREF(repunicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00008069 return -1;
8070 }
8071 else if (x==enc_FAILED) {
8072 Py_DECREF(repunicode);
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008073 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008074 return -1;
8075 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008076 }
8077 *inpos = newpos;
8078 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008079 }
8080 return 0;
8081}
8082
Alexander Belopolsky40018472011-02-26 01:02:56 +00008083PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008084_PyUnicode_EncodeCharmap(PyObject *unicode,
8085 PyObject *mapping,
8086 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008087{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008088 /* output object */
8089 PyObject *res = NULL;
8090 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008091 Py_ssize_t inpos = 0;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008092 Py_ssize_t size;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008093 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008094 Py_ssize_t respos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008095 PyObject *errorHandler = NULL;
8096 PyObject *exc = NULL;
8097 /* the following variable is used for caching string comparisons
8098 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8099 * 3=ignore, 4=xmlcharrefreplace */
8100 int known_errorHandler = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008101
Benjamin Petersonbac79492012-01-14 13:34:47 -05008102 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008103 return NULL;
8104 size = PyUnicode_GET_LENGTH(unicode);
8105
Guido van Rossumd57fd912000-03-10 22:53:23 +00008106 /* Default to Latin-1 */
8107 if (mapping == NULL)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008108 return unicode_encode_ucs1(unicode, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008109
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008110 /* allocate enough for a simple encoding without
8111 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00008112 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008113 if (res == NULL)
8114 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00008115 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008116 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008117
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008118 while (inpos<size) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008119 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, inpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008120 /* try to encode it */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008121 charmapencode_result x = charmapencode_output(ch, mapping, &res, &respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008122 if (x==enc_EXCEPTION) /* error */
8123 goto onError;
8124 if (x==enc_FAILED) { /* unencodable character */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008125 if (charmap_encoding_error(unicode, &inpos, mapping,
Benjamin Peterson29060642009-01-31 22:14:21 +00008126 &exc,
8127 &known_errorHandler, &errorHandler, errors,
8128 &res, &respos)) {
8129 goto onError;
8130 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008131 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008132 else
8133 /* done with this character => adjust input position */
8134 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008135 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008136
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008137 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00008138 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00008139 if (_PyBytes_Resize(&res, respos) < 0)
8140 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00008141
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008142 Py_XDECREF(exc);
8143 Py_XDECREF(errorHandler);
8144 return res;
8145
Benjamin Peterson29060642009-01-31 22:14:21 +00008146 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008147 Py_XDECREF(res);
8148 Py_XDECREF(exc);
8149 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008150 return NULL;
8151}
8152
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008153/* Deprecated */
8154PyObject *
8155PyUnicode_EncodeCharmap(const Py_UNICODE *p,
8156 Py_ssize_t size,
8157 PyObject *mapping,
8158 const char *errors)
8159{
8160 PyObject *result;
8161 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8162 if (unicode == NULL)
8163 return NULL;
8164 result = _PyUnicode_EncodeCharmap(unicode, mapping, errors);
8165 Py_DECREF(unicode);
Victor Stinnerfc026c92011-11-04 00:24:51 +01008166 return result;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008167}
8168
Alexander Belopolsky40018472011-02-26 01:02:56 +00008169PyObject *
8170PyUnicode_AsCharmapString(PyObject *unicode,
8171 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008172{
8173 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008174 PyErr_BadArgument();
8175 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008176 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008177 return _PyUnicode_EncodeCharmap(unicode, mapping, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008178}
8179
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008180/* create or adjust a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008181static void
8182make_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008183 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008184 Py_ssize_t startpos, Py_ssize_t endpos,
8185 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008186{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008187 if (*exceptionObject == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008188 *exceptionObject = _PyUnicodeTranslateError_Create(
8189 unicode, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008190 }
8191 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008192 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
8193 goto onError;
8194 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
8195 goto onError;
8196 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
8197 goto onError;
8198 return;
8199 onError:
8200 Py_DECREF(*exceptionObject);
8201 *exceptionObject = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008202 }
8203}
8204
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008205/* raises a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008206static void
8207raise_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008208 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008209 Py_ssize_t startpos, Py_ssize_t endpos,
8210 const char *reason)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008211{
8212 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008213 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008214 if (*exceptionObject != NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008215 PyCodec_StrictErrors(*exceptionObject);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008216}
8217
8218/* error handling callback helper:
8219 build arguments, call the callback and check the arguments,
8220 put the result into newpos and return the replacement string, which
8221 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008222static PyObject *
8223unicode_translate_call_errorhandler(const char *errors,
8224 PyObject **errorHandler,
8225 const char *reason,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008226 PyObject *unicode, PyObject **exceptionObject,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008227 Py_ssize_t startpos, Py_ssize_t endpos,
8228 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008229{
Benjamin Peterson142957c2008-07-04 19:55:29 +00008230 static char *argparse = "O!n;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008231
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008232 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008233 PyObject *restuple;
8234 PyObject *resunicode;
8235
8236 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008237 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008238 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008239 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008240 }
8241
8242 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008243 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008244 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008245 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008246
8247 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00008248 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008249 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008250 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008251 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00008252 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00008253 Py_DECREF(restuple);
8254 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008255 }
8256 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type,
Benjamin Peterson29060642009-01-31 22:14:21 +00008257 &resunicode, &i_newpos)) {
8258 Py_DECREF(restuple);
8259 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008260 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00008261 if (i_newpos<0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008262 *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008263 else
8264 *newpos = i_newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008265 if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008266 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
8267 Py_DECREF(restuple);
8268 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00008269 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008270 Py_INCREF(resunicode);
8271 Py_DECREF(restuple);
8272 return resunicode;
8273}
8274
8275/* Lookup the character ch in the mapping and put the result in result,
8276 which must be decrefed by the caller.
8277 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008278static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008279charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008280{
Christian Heimes217cfd12007-12-02 14:31:20 +00008281 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008282 PyObject *x;
8283
8284 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008285 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008286 x = PyObject_GetItem(mapping, w);
8287 Py_DECREF(w);
8288 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008289 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8290 /* No mapping found means: use 1:1 mapping. */
8291 PyErr_Clear();
8292 *result = NULL;
8293 return 0;
8294 } else
8295 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008296 }
8297 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008298 *result = x;
8299 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008300 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008301 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008302 long value = PyLong_AS_LONG(x);
8303 long max = PyUnicode_GetMax();
8304 if (value < 0 || value > max) {
8305 PyErr_Format(PyExc_TypeError,
Guido van Rossum5a2f7e602007-10-24 21:13:09 +00008306 "character mapping must be in range(0x%x)", max+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00008307 Py_DECREF(x);
8308 return -1;
8309 }
8310 *result = x;
8311 return 0;
8312 }
8313 else if (PyUnicode_Check(x)) {
8314 *result = x;
8315 return 0;
8316 }
8317 else {
8318 /* wrong return value */
8319 PyErr_SetString(PyExc_TypeError,
8320 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00008321 Py_DECREF(x);
8322 return -1;
8323 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008324}
8325/* ensure that *outobj is at least requiredsize characters long,
Benjamin Peterson29060642009-01-31 22:14:21 +00008326 if not reallocate and adjust various state variables.
8327 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008328static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008329charmaptranslate_makespace(Py_UCS4 **outobj, Py_ssize_t *psize,
Benjamin Peterson29060642009-01-31 22:14:21 +00008330 Py_ssize_t requiredsize)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008331{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008332 Py_ssize_t oldsize = *psize;
Kristjan Valur Jonsson85634d72012-05-31 09:37:31 +00008333 Py_UCS4 *new_outobj;
Walter Dörwald4894c302003-10-24 14:25:28 +00008334 if (requiredsize > oldsize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008335 /* exponentially overallocate to minimize reallocations */
8336 if (requiredsize < 2 * oldsize)
8337 requiredsize = 2 * oldsize;
Kristjan Valur Jonsson85634d72012-05-31 09:37:31 +00008338 new_outobj = PyMem_Realloc(*outobj, requiredsize * sizeof(Py_UCS4));
8339 if (new_outobj == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008340 return -1;
Kristjan Valur Jonsson85634d72012-05-31 09:37:31 +00008341 *outobj = new_outobj;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008342 *psize = requiredsize;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008343 }
8344 return 0;
8345}
8346/* lookup the character, put the result in the output string and adjust
8347 various state variables. Return a new reference to the object that
8348 was put in the output buffer in *result, or Py_None, if the mapping was
8349 undefined (in which case no character was written).
8350 The called must decref result.
8351 Return 0 on success, -1 on error. */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008352static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008353charmaptranslate_output(PyObject *input, Py_ssize_t ipos,
8354 PyObject *mapping, Py_UCS4 **output,
8355 Py_ssize_t *osize, Py_ssize_t *opos,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008356 PyObject **res)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008357{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008358 Py_UCS4 curinp = PyUnicode_READ_CHAR(input, ipos);
8359 if (charmaptranslate_lookup(curinp, mapping, res))
Benjamin Peterson29060642009-01-31 22:14:21 +00008360 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008361 if (*res==NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008362 /* not found => default to 1:1 mapping */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008363 (*output)[(*opos)++] = curinp;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008364 }
8365 else if (*res==Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008366 ;
Christian Heimes217cfd12007-12-02 14:31:20 +00008367 else if (PyLong_Check(*res)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008368 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008369 (*output)[(*opos)++] = (Py_UCS4)PyLong_AS_LONG(*res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008370 }
8371 else if (PyUnicode_Check(*res)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008372 Py_ssize_t repsize;
8373 if (PyUnicode_READY(*res) == -1)
8374 return -1;
8375 repsize = PyUnicode_GET_LENGTH(*res);
Benjamin Peterson29060642009-01-31 22:14:21 +00008376 if (repsize==1) {
8377 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008378 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +00008379 }
8380 else if (repsize!=0) {
8381 /* more than one character */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008382 Py_ssize_t requiredsize = *opos +
8383 (PyUnicode_GET_LENGTH(input) - ipos) +
Benjamin Peterson29060642009-01-31 22:14:21 +00008384 repsize - 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008385 Py_ssize_t i;
8386 if (charmaptranslate_makespace(output, osize, requiredsize))
Benjamin Peterson29060642009-01-31 22:14:21 +00008387 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008388 for(i = 0; i < repsize; i++)
8389 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00008390 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008391 }
8392 else
Benjamin Peterson29060642009-01-31 22:14:21 +00008393 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008394 return 0;
8395}
8396
Alexander Belopolsky40018472011-02-26 01:02:56 +00008397PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008398_PyUnicode_TranslateCharmap(PyObject *input,
8399 PyObject *mapping,
8400 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008401{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008402 /* input object */
8403 char *idata;
8404 Py_ssize_t size, i;
8405 int kind;
8406 /* output buffer */
8407 Py_UCS4 *output = NULL;
8408 Py_ssize_t osize;
8409 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008410 /* current output position */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008411 Py_ssize_t opos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008412 char *reason = "character maps to <undefined>";
8413 PyObject *errorHandler = NULL;
8414 PyObject *exc = NULL;
8415 /* the following variable is used for caching string comparisons
8416 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8417 * 3=ignore, 4=xmlcharrefreplace */
8418 int known_errorHandler = -1;
8419
Guido van Rossumd57fd912000-03-10 22:53:23 +00008420 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008421 PyErr_BadArgument();
8422 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008423 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008424
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008425 if (PyUnicode_READY(input) == -1)
8426 return NULL;
8427 idata = (char*)PyUnicode_DATA(input);
8428 kind = PyUnicode_KIND(input);
8429 size = PyUnicode_GET_LENGTH(input);
8430 i = 0;
8431
8432 if (size == 0) {
8433 Py_INCREF(input);
8434 return input;
8435 }
8436
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008437 /* allocate enough for a simple 1:1 translation without
8438 replacements, if we need more, we'll resize */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008439 osize = size;
8440 output = PyMem_Malloc(osize * sizeof(Py_UCS4));
8441 opos = 0;
8442 if (output == NULL) {
8443 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00008444 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008445 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008446
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008447 while (i<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008448 /* try to encode it */
8449 PyObject *x = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008450 if (charmaptranslate_output(input, i, mapping,
8451 &output, &osize, &opos, &x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008452 Py_XDECREF(x);
8453 goto onError;
8454 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008455 Py_XDECREF(x);
Benjamin Peterson29060642009-01-31 22:14:21 +00008456 if (x!=Py_None) /* it worked => adjust input pointer */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008457 ++i;
Benjamin Peterson29060642009-01-31 22:14:21 +00008458 else { /* untranslatable character */
8459 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
8460 Py_ssize_t repsize;
8461 Py_ssize_t newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008462 Py_ssize_t uni2;
Benjamin Peterson29060642009-01-31 22:14:21 +00008463 /* startpos for collecting untranslatable chars */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008464 Py_ssize_t collstart = i;
8465 Py_ssize_t collend = i+1;
8466 Py_ssize_t coll;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008467
Benjamin Peterson29060642009-01-31 22:14:21 +00008468 /* find all untranslatable characters */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008469 while (collend < size) {
8470 if (charmaptranslate_lookup(PyUnicode_READ(kind,idata, collend), mapping, &x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008471 goto onError;
8472 Py_XDECREF(x);
8473 if (x!=Py_None)
8474 break;
8475 ++collend;
8476 }
8477 /* cache callback name lookup
8478 * (if not done yet, i.e. it's the first error) */
8479 if (known_errorHandler==-1) {
8480 if ((errors==NULL) || (!strcmp(errors, "strict")))
8481 known_errorHandler = 1;
8482 else if (!strcmp(errors, "replace"))
8483 known_errorHandler = 2;
8484 else if (!strcmp(errors, "ignore"))
8485 known_errorHandler = 3;
8486 else if (!strcmp(errors, "xmlcharrefreplace"))
8487 known_errorHandler = 4;
8488 else
8489 known_errorHandler = 0;
8490 }
8491 switch (known_errorHandler) {
8492 case 1: /* strict */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008493 raise_translate_exception(&exc, input, collstart,
8494 collend, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008495 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00008496 case 2: /* replace */
8497 /* No need to check for space, this is a 1:1 replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008498 for (coll = collstart; coll<collend; coll++)
8499 output[opos++] = '?';
Benjamin Peterson29060642009-01-31 22:14:21 +00008500 /* fall through */
8501 case 3: /* ignore */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008502 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008503 break;
8504 case 4: /* xmlcharrefreplace */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008505 /* generate replacement (temporarily (mis)uses i) */
8506 for (i = collstart; i < collend; ++i) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008507 char buffer[2+29+1+1];
8508 char *cp;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008509 sprintf(buffer, "&#%d;", PyUnicode_READ(kind, idata, i));
8510 if (charmaptranslate_makespace(&output, &osize,
8511 opos+strlen(buffer)+(size-collend)))
Benjamin Peterson29060642009-01-31 22:14:21 +00008512 goto onError;
8513 for (cp = buffer; *cp; ++cp)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008514 output[opos++] = *cp;
Benjamin Peterson29060642009-01-31 22:14:21 +00008515 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008516 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008517 break;
8518 default:
8519 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008520 reason, input, &exc,
8521 collstart, collend, &newpos);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008522 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008523 goto onError;
Benjamin Peterson9ca3ffa2012-01-01 16:04:29 -06008524 if (PyUnicode_READY(repunicode) == -1) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008525 Py_DECREF(repunicode);
8526 goto onError;
8527 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008528 /* generate replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008529 repsize = PyUnicode_GET_LENGTH(repunicode);
8530 if (charmaptranslate_makespace(&output, &osize,
8531 opos+repsize+(size-collend))) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008532 Py_DECREF(repunicode);
8533 goto onError;
8534 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008535 for (uni2 = 0; repsize-->0; ++uni2)
8536 output[opos++] = PyUnicode_READ_CHAR(repunicode, uni2);
8537 i = newpos;
Benjamin Peterson29060642009-01-31 22:14:21 +00008538 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008539 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008540 }
8541 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008542 res = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND, output, opos);
8543 if (!res)
8544 goto onError;
8545 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008546 Py_XDECREF(exc);
8547 Py_XDECREF(errorHandler);
8548 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008549
Benjamin Peterson29060642009-01-31 22:14:21 +00008550 onError:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008551 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008552 Py_XDECREF(exc);
8553 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008554 return NULL;
8555}
8556
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008557/* Deprecated. Use PyUnicode_Translate instead. */
8558PyObject *
8559PyUnicode_TranslateCharmap(const Py_UNICODE *p,
8560 Py_ssize_t size,
8561 PyObject *mapping,
8562 const char *errors)
8563{
8564 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8565 if (!unicode)
8566 return NULL;
8567 return _PyUnicode_TranslateCharmap(unicode, mapping, errors);
8568}
8569
Alexander Belopolsky40018472011-02-26 01:02:56 +00008570PyObject *
8571PyUnicode_Translate(PyObject *str,
8572 PyObject *mapping,
8573 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008574{
8575 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +00008576
Guido van Rossumd57fd912000-03-10 22:53:23 +00008577 str = PyUnicode_FromObject(str);
8578 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008579 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008580 result = _PyUnicode_TranslateCharmap(str, mapping, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008581 Py_DECREF(str);
8582 return result;
Tim Petersced69f82003-09-16 20:30:58 +00008583
Benjamin Peterson29060642009-01-31 22:14:21 +00008584 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00008585 Py_XDECREF(str);
8586 return NULL;
8587}
Tim Petersced69f82003-09-16 20:30:58 +00008588
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008589static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02008590fix_decimal_and_space_to_ascii(PyObject *self)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008591{
8592 /* No need to call PyUnicode_READY(self) because this function is only
8593 called as a callback from fixup() which does it already. */
8594 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
8595 const int kind = PyUnicode_KIND(self);
8596 void *data = PyUnicode_DATA(self);
Victor Stinnere6abb482012-05-02 01:15:40 +02008597 Py_UCS4 maxchar = 127, ch, fixed;
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008598 int modified = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008599 Py_ssize_t i;
8600
8601 for (i = 0; i < len; ++i) {
8602 ch = PyUnicode_READ(kind, data, i);
8603 fixed = 0;
8604 if (ch > 127) {
8605 if (Py_UNICODE_ISSPACE(ch))
8606 fixed = ' ';
8607 else {
8608 const int decimal = Py_UNICODE_TODECIMAL(ch);
8609 if (decimal >= 0)
8610 fixed = '0' + decimal;
8611 }
8612 if (fixed != 0) {
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008613 modified = 1;
Victor Stinnere6abb482012-05-02 01:15:40 +02008614 maxchar = MAX_MAXCHAR(maxchar, fixed);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008615 PyUnicode_WRITE(kind, data, i, fixed);
8616 }
Victor Stinnere6abb482012-05-02 01:15:40 +02008617 else
8618 maxchar = MAX_MAXCHAR(maxchar, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008619 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008620 }
8621
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008622 return (modified) ? maxchar : 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008623}
8624
8625PyObject *
8626_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
8627{
8628 if (!PyUnicode_Check(unicode)) {
8629 PyErr_BadInternalCall();
8630 return NULL;
8631 }
8632 if (PyUnicode_READY(unicode) == -1)
8633 return NULL;
8634 if (PyUnicode_MAX_CHAR_VALUE(unicode) <= 127) {
8635 /* If the string is already ASCII, just return the same string */
8636 Py_INCREF(unicode);
8637 return unicode;
8638 }
Victor Stinner9310abb2011-10-05 00:59:23 +02008639 return fixup(unicode, fix_decimal_and_space_to_ascii);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008640}
8641
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008642PyObject *
8643PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
8644 Py_ssize_t length)
8645{
Victor Stinnerf0124502011-11-21 23:12:56 +01008646 PyObject *decimal;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008647 Py_ssize_t i;
Victor Stinnerf0124502011-11-21 23:12:56 +01008648 Py_UCS4 maxchar;
8649 enum PyUnicode_Kind kind;
8650 void *data;
8651
Victor Stinner99d7ad02012-02-22 13:37:39 +01008652 maxchar = 127;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008653 for (i = 0; i < length; i++) {
Victor Stinnerf0124502011-11-21 23:12:56 +01008654 Py_UNICODE ch = s[i];
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008655 if (ch > 127) {
8656 int decimal = Py_UNICODE_TODECIMAL(ch);
8657 if (decimal >= 0)
Victor Stinnerf0124502011-11-21 23:12:56 +01008658 ch = '0' + decimal;
Victor Stinnere6abb482012-05-02 01:15:40 +02008659 maxchar = MAX_MAXCHAR(maxchar, ch);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008660 }
8661 }
Victor Stinnerf0124502011-11-21 23:12:56 +01008662
8663 /* Copy to a new string */
8664 decimal = PyUnicode_New(length, maxchar);
8665 if (decimal == NULL)
8666 return decimal;
8667 kind = PyUnicode_KIND(decimal);
8668 data = PyUnicode_DATA(decimal);
8669 /* Iterate over code points */
8670 for (i = 0; i < length; i++) {
8671 Py_UNICODE ch = s[i];
8672 if (ch > 127) {
8673 int decimal = Py_UNICODE_TODECIMAL(ch);
8674 if (decimal >= 0)
8675 ch = '0' + decimal;
8676 }
8677 PyUnicode_WRITE(kind, data, i, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008678 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008679 return unicode_result(decimal);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008680}
Guido van Rossum9e896b32000-04-05 20:11:21 +00008681/* --- Decimal Encoder ---------------------------------------------------- */
8682
Alexander Belopolsky40018472011-02-26 01:02:56 +00008683int
8684PyUnicode_EncodeDecimal(Py_UNICODE *s,
8685 Py_ssize_t length,
8686 char *output,
8687 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00008688{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008689 PyObject *unicode;
Victor Stinner6345be92011-11-25 20:09:01 +01008690 Py_ssize_t i;
Victor Stinner42bf7752011-11-21 22:52:58 +01008691 enum PyUnicode_Kind kind;
8692 void *data;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008693
8694 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008695 PyErr_BadArgument();
8696 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008697 }
8698
Victor Stinner42bf7752011-11-21 22:52:58 +01008699 unicode = PyUnicode_FromUnicode(s, length);
8700 if (unicode == NULL)
8701 return -1;
8702
Benjamin Petersonbac79492012-01-14 13:34:47 -05008703 if (PyUnicode_READY(unicode) == -1) {
Victor Stinner6345be92011-11-25 20:09:01 +01008704 Py_DECREF(unicode);
8705 return -1;
8706 }
Victor Stinner42bf7752011-11-21 22:52:58 +01008707 kind = PyUnicode_KIND(unicode);
8708 data = PyUnicode_DATA(unicode);
8709
Victor Stinnerb84d7232011-11-22 01:50:07 +01008710 for (i=0; i < length; ) {
Victor Stinner6345be92011-11-25 20:09:01 +01008711 PyObject *exc;
8712 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00008713 int decimal;
Victor Stinner6345be92011-11-25 20:09:01 +01008714 Py_ssize_t startpos;
8715
8716 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +00008717
Benjamin Peterson29060642009-01-31 22:14:21 +00008718 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008719 *output++ = ' ';
Victor Stinnerb84d7232011-11-22 01:50:07 +01008720 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00008721 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008722 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008723 decimal = Py_UNICODE_TODECIMAL(ch);
8724 if (decimal >= 0) {
8725 *output++ = '0' + decimal;
Victor Stinnerb84d7232011-11-22 01:50:07 +01008726 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00008727 continue;
8728 }
8729 if (0 < ch && ch < 256) {
8730 *output++ = (char)ch;
Victor Stinnerb84d7232011-11-22 01:50:07 +01008731 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00008732 continue;
8733 }
Victor Stinner6345be92011-11-25 20:09:01 +01008734
Victor Stinner42bf7752011-11-21 22:52:58 +01008735 startpos = i;
Victor Stinner6345be92011-11-25 20:09:01 +01008736 exc = NULL;
8737 raise_encode_exception(&exc, "decimal", unicode,
8738 startpos, startpos+1,
8739 "invalid decimal Unicode string");
8740 Py_XDECREF(exc);
8741 Py_DECREF(unicode);
8742 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008743 }
8744 /* 0-terminate the output string */
8745 *output++ = '\0';
Victor Stinner42bf7752011-11-21 22:52:58 +01008746 Py_DECREF(unicode);
Guido van Rossum9e896b32000-04-05 20:11:21 +00008747 return 0;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008748}
8749
Guido van Rossumd57fd912000-03-10 22:53:23 +00008750/* --- Helpers ------------------------------------------------------------ */
8751
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008752static Py_ssize_t
Victor Stinner794d5672011-10-10 03:21:36 +02008753any_find_slice(int direction, PyObject* s1, PyObject* s2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008754 Py_ssize_t start,
8755 Py_ssize_t end)
8756{
8757 int kind1, kind2, kind;
8758 void *buf1, *buf2;
8759 Py_ssize_t len1, len2, result;
8760
8761 kind1 = PyUnicode_KIND(s1);
8762 kind2 = PyUnicode_KIND(s2);
8763 kind = kind1 > kind2 ? kind1 : kind2;
8764 buf1 = PyUnicode_DATA(s1);
8765 buf2 = PyUnicode_DATA(s2);
8766 if (kind1 != kind)
8767 buf1 = _PyUnicode_AsKind(s1, kind);
8768 if (!buf1)
8769 return -2;
8770 if (kind2 != kind)
8771 buf2 = _PyUnicode_AsKind(s2, kind);
8772 if (!buf2) {
8773 if (kind1 != kind) PyMem_Free(buf1);
8774 return -2;
8775 }
8776 len1 = PyUnicode_GET_LENGTH(s1);
8777 len2 = PyUnicode_GET_LENGTH(s2);
8778
Victor Stinner794d5672011-10-10 03:21:36 +02008779 if (direction > 0) {
Benjamin Petersonead6b532011-12-20 17:23:42 -06008780 switch (kind) {
Victor Stinner794d5672011-10-10 03:21:36 +02008781 case PyUnicode_1BYTE_KIND:
8782 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
8783 result = asciilib_find_slice(buf1, len1, buf2, len2, start, end);
8784 else
8785 result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end);
8786 break;
8787 case PyUnicode_2BYTE_KIND:
8788 result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end);
8789 break;
8790 case PyUnicode_4BYTE_KIND:
8791 result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end);
8792 break;
8793 default:
8794 assert(0); result = -2;
8795 }
8796 }
8797 else {
Benjamin Petersonead6b532011-12-20 17:23:42 -06008798 switch (kind) {
Victor Stinner794d5672011-10-10 03:21:36 +02008799 case PyUnicode_1BYTE_KIND:
8800 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
8801 result = asciilib_rfind_slice(buf1, len1, buf2, len2, start, end);
8802 else
8803 result = ucs1lib_rfind_slice(buf1, len1, buf2, len2, start, end);
8804 break;
8805 case PyUnicode_2BYTE_KIND:
8806 result = ucs2lib_rfind_slice(buf1, len1, buf2, len2, start, end);
8807 break;
8808 case PyUnicode_4BYTE_KIND:
8809 result = ucs4lib_rfind_slice(buf1, len1, buf2, len2, start, end);
8810 break;
8811 default:
8812 assert(0); result = -2;
8813 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008814 }
8815
8816 if (kind1 != kind)
8817 PyMem_Free(buf1);
8818 if (kind2 != kind)
8819 PyMem_Free(buf2);
8820
8821 return result;
8822}
8823
8824Py_ssize_t
Victor Stinner41a863c2012-02-24 00:37:51 +01008825_PyUnicode_InsertThousandsGrouping(
8826 PyObject *unicode, Py_ssize_t index,
8827 Py_ssize_t n_buffer,
8828 void *digits, Py_ssize_t n_digits,
8829 Py_ssize_t min_width,
8830 const char *grouping, PyObject *thousands_sep,
8831 Py_UCS4 *maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008832{
Victor Stinner41a863c2012-02-24 00:37:51 +01008833 unsigned int kind, thousands_sep_kind;
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008834 char *data, *thousands_sep_data;
Victor Stinner41a863c2012-02-24 00:37:51 +01008835 Py_ssize_t thousands_sep_len;
8836 Py_ssize_t len;
8837
8838 if (unicode != NULL) {
8839 kind = PyUnicode_KIND(unicode);
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008840 data = (char *) PyUnicode_DATA(unicode) + index * kind;
Victor Stinner41a863c2012-02-24 00:37:51 +01008841 }
8842 else {
8843 kind = PyUnicode_1BYTE_KIND;
8844 data = NULL;
8845 }
8846 thousands_sep_kind = PyUnicode_KIND(thousands_sep);
8847 thousands_sep_data = PyUnicode_DATA(thousands_sep);
8848 thousands_sep_len = PyUnicode_GET_LENGTH(thousands_sep);
8849 if (unicode != NULL && thousands_sep_kind != kind) {
Victor Stinner90f50d42012-02-24 01:44:47 +01008850 if (thousands_sep_kind < kind) {
8851 thousands_sep_data = _PyUnicode_AsKind(thousands_sep, kind);
8852 if (!thousands_sep_data)
8853 return -1;
8854 }
8855 else {
8856 data = _PyUnicode_AsKind(unicode, thousands_sep_kind);
8857 if (!data)
8858 return -1;
8859 }
Victor Stinner41a863c2012-02-24 00:37:51 +01008860 }
8861
Benjamin Petersonead6b532011-12-20 17:23:42 -06008862 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008863 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02008864 if (unicode != NULL && PyUnicode_IS_ASCII(unicode))
Victor Stinner41a863c2012-02-24 00:37:51 +01008865 len = asciilib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008866 (Py_UCS1 *) data, n_buffer, (Py_UCS1 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01008867 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008868 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinnerc3cec782011-10-05 21:24:08 +02008869 else
Victor Stinner41a863c2012-02-24 00:37:51 +01008870 len = ucs1lib_InsertThousandsGrouping(
Victor Stinnerc3cec782011-10-05 21:24:08 +02008871 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01008872 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008873 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01008874 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008875 case PyUnicode_2BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01008876 len = ucs2lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008877 (Py_UCS2 *) data, n_buffer, (Py_UCS2 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01008878 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008879 (Py_UCS2 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01008880 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008881 case PyUnicode_4BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01008882 len = ucs4lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008883 (Py_UCS4 *) data, n_buffer, (Py_UCS4 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01008884 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008885 (Py_UCS4 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01008886 break;
8887 default:
8888 assert(0);
8889 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008890 }
Victor Stinner90f50d42012-02-24 01:44:47 +01008891 if (unicode != NULL && thousands_sep_kind != kind) {
8892 if (thousands_sep_kind < kind)
8893 PyMem_Free(thousands_sep_data);
8894 else
8895 PyMem_Free(data);
8896 }
Victor Stinner41a863c2012-02-24 00:37:51 +01008897 if (unicode == NULL) {
8898 *maxchar = 127;
8899 if (len != n_digits) {
Victor Stinnere6abb482012-05-02 01:15:40 +02008900 *maxchar = MAX_MAXCHAR(*maxchar,
8901 PyUnicode_MAX_CHAR_VALUE(thousands_sep));
Victor Stinner41a863c2012-02-24 00:37:51 +01008902 }
8903 }
8904 return len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008905}
8906
8907
Thomas Wouters477c8d52006-05-27 19:21:47 +00008908/* helper macro to fixup start/end slice values */
Antoine Pitrouf2c54842010-01-13 08:07:53 +00008909#define ADJUST_INDICES(start, end, len) \
8910 if (end > len) \
8911 end = len; \
8912 else if (end < 0) { \
8913 end += len; \
8914 if (end < 0) \
8915 end = 0; \
8916 } \
8917 if (start < 0) { \
8918 start += len; \
8919 if (start < 0) \
8920 start = 0; \
8921 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00008922
Alexander Belopolsky40018472011-02-26 01:02:56 +00008923Py_ssize_t
8924PyUnicode_Count(PyObject *str,
8925 PyObject *substr,
8926 Py_ssize_t start,
8927 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008928{
Martin v. Löwis18e16552006-02-15 17:27:45 +00008929 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02008930 PyObject* str_obj;
8931 PyObject* sub_obj;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008932 int kind1, kind2, kind;
8933 void *buf1 = NULL, *buf2 = NULL;
8934 Py_ssize_t len1, len2;
Tim Petersced69f82003-09-16 20:30:58 +00008935
Victor Stinner9db1a8b2011-10-23 20:04:37 +02008936 str_obj = PyUnicode_FromObject(str);
Benjamin Peterson22a29702012-01-02 09:00:30 -06008937 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +00008938 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02008939 sub_obj = PyUnicode_FromObject(substr);
Benjamin Peterson22a29702012-01-02 09:00:30 -06008940 if (!sub_obj) {
8941 Py_DECREF(str_obj);
8942 return -1;
8943 }
Benjamin Peterson4c13a4a2012-01-02 09:07:38 -06008944 if (PyUnicode_READY(sub_obj) == -1 || PyUnicode_READY(str_obj) == -1) {
Benjamin Peterson5e458f52012-01-02 10:12:13 -06008945 Py_DECREF(sub_obj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008946 Py_DECREF(str_obj);
8947 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008948 }
Tim Petersced69f82003-09-16 20:30:58 +00008949
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008950 kind1 = PyUnicode_KIND(str_obj);
8951 kind2 = PyUnicode_KIND(sub_obj);
Antoine Pitroue45c0c52012-05-12 15:49:07 +02008952 kind = kind1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008953 buf1 = PyUnicode_DATA(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008954 buf2 = PyUnicode_DATA(sub_obj);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -05008955 if (kind2 != kind) {
Antoine Pitrou758153b2012-05-12 15:51:51 +02008956 if (kind2 > kind) {
8957 Py_DECREF(sub_obj);
8958 Py_DECREF(str_obj);
Antoine Pitroue45c0c52012-05-12 15:49:07 +02008959 return 0;
Antoine Pitrou758153b2012-05-12 15:51:51 +02008960 }
Victor Stinner7931d9a2011-11-04 00:22:48 +01008961 buf2 = _PyUnicode_AsKind(sub_obj, kind);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -05008962 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008963 if (!buf2)
8964 goto onError;
8965 len1 = PyUnicode_GET_LENGTH(str_obj);
8966 len2 = PyUnicode_GET_LENGTH(sub_obj);
8967
8968 ADJUST_INDICES(start, end, len1);
Benjamin Petersonead6b532011-12-20 17:23:42 -06008969 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008970 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02008971 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sub_obj))
8972 result = asciilib_count(
8973 ((Py_UCS1*)buf1) + start, end - start,
8974 buf2, len2, PY_SSIZE_T_MAX
8975 );
8976 else
8977 result = ucs1lib_count(
8978 ((Py_UCS1*)buf1) + start, end - start,
8979 buf2, len2, PY_SSIZE_T_MAX
8980 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008981 break;
8982 case PyUnicode_2BYTE_KIND:
8983 result = ucs2lib_count(
8984 ((Py_UCS2*)buf1) + start, end - start,
8985 buf2, len2, PY_SSIZE_T_MAX
8986 );
8987 break;
8988 case PyUnicode_4BYTE_KIND:
8989 result = ucs4lib_count(
8990 ((Py_UCS4*)buf1) + start, end - start,
8991 buf2, len2, PY_SSIZE_T_MAX
8992 );
8993 break;
8994 default:
8995 assert(0); result = 0;
8996 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00008997
8998 Py_DECREF(sub_obj);
8999 Py_DECREF(str_obj);
9000
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009001 if (kind2 != kind)
9002 PyMem_Free(buf2);
9003
Guido van Rossumd57fd912000-03-10 22:53:23 +00009004 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009005 onError:
9006 Py_DECREF(sub_obj);
9007 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009008 if (kind2 != kind && buf2)
9009 PyMem_Free(buf2);
9010 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009011}
9012
Alexander Belopolsky40018472011-02-26 01:02:56 +00009013Py_ssize_t
9014PyUnicode_Find(PyObject *str,
9015 PyObject *sub,
9016 Py_ssize_t start,
9017 Py_ssize_t end,
9018 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009019{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009020 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009021
Guido van Rossumd57fd912000-03-10 22:53:23 +00009022 str = PyUnicode_FromObject(str);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009023 if (!str)
Benjamin Peterson29060642009-01-31 22:14:21 +00009024 return -2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009025 sub = PyUnicode_FromObject(sub);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009026 if (!sub) {
9027 Py_DECREF(str);
9028 return -2;
9029 }
9030 if (PyUnicode_READY(sub) == -1 || PyUnicode_READY(str) == -1) {
9031 Py_DECREF(sub);
Benjamin Peterson29060642009-01-31 22:14:21 +00009032 Py_DECREF(str);
9033 return -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009034 }
Tim Petersced69f82003-09-16 20:30:58 +00009035
Victor Stinner794d5672011-10-10 03:21:36 +02009036 result = any_find_slice(direction,
9037 str, sub, start, end
9038 );
Thomas Wouters477c8d52006-05-27 19:21:47 +00009039
Guido van Rossumd57fd912000-03-10 22:53:23 +00009040 Py_DECREF(str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009041 Py_DECREF(sub);
9042
Guido van Rossumd57fd912000-03-10 22:53:23 +00009043 return result;
9044}
9045
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009046Py_ssize_t
9047PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
9048 Py_ssize_t start, Py_ssize_t end,
9049 int direction)
9050{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009051 int kind;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009052 Py_ssize_t result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009053 if (PyUnicode_READY(str) == -1)
9054 return -2;
Victor Stinner267aa242011-10-02 01:08:37 +02009055 if (start < 0 || end < 0) {
9056 PyErr_SetString(PyExc_IndexError, "string index out of range");
9057 return -2;
9058 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009059 if (end > PyUnicode_GET_LENGTH(str))
9060 end = PyUnicode_GET_LENGTH(str);
9061 kind = PyUnicode_KIND(str);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009062 result = findchar(PyUnicode_1BYTE_DATA(str) + kind*start,
9063 kind, end-start, ch, direction);
9064 if (result == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009065 return -1;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009066 else
9067 return start + result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009068}
9069
Alexander Belopolsky40018472011-02-26 01:02:56 +00009070static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009071tailmatch(PyObject *self,
9072 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009073 Py_ssize_t start,
9074 Py_ssize_t end,
9075 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009076{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009077 int kind_self;
9078 int kind_sub;
9079 void *data_self;
9080 void *data_sub;
9081 Py_ssize_t offset;
9082 Py_ssize_t i;
9083 Py_ssize_t end_sub;
9084
9085 if (PyUnicode_READY(self) == -1 ||
9086 PyUnicode_READY(substring) == -1)
9087 return 0;
9088
9089 if (PyUnicode_GET_LENGTH(substring) == 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009090 return 1;
9091
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009092 ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
9093 end -= PyUnicode_GET_LENGTH(substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009094 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00009095 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009096
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009097 kind_self = PyUnicode_KIND(self);
9098 data_self = PyUnicode_DATA(self);
9099 kind_sub = PyUnicode_KIND(substring);
9100 data_sub = PyUnicode_DATA(substring);
9101 end_sub = PyUnicode_GET_LENGTH(substring) - 1;
9102
9103 if (direction > 0)
9104 offset = end;
9105 else
9106 offset = start;
9107
9108 if (PyUnicode_READ(kind_self, data_self, offset) ==
9109 PyUnicode_READ(kind_sub, data_sub, 0) &&
9110 PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
9111 PyUnicode_READ(kind_sub, data_sub, end_sub)) {
9112 /* If both are of the same kind, memcmp is sufficient */
9113 if (kind_self == kind_sub) {
9114 return ! memcmp((char *)data_self +
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009115 (offset * PyUnicode_KIND(substring)),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009116 data_sub,
9117 PyUnicode_GET_LENGTH(substring) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009118 PyUnicode_KIND(substring));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009119 }
9120 /* otherwise we have to compare each character by first accesing it */
9121 else {
9122 /* We do not need to compare 0 and len(substring)-1 because
9123 the if statement above ensured already that they are equal
9124 when we end up here. */
9125 // TODO: honor direction and do a forward or backwards search
9126 for (i = 1; i < end_sub; ++i) {
9127 if (PyUnicode_READ(kind_self, data_self, offset + i) !=
9128 PyUnicode_READ(kind_sub, data_sub, i))
9129 return 0;
9130 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009131 return 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009132 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009133 }
9134
9135 return 0;
9136}
9137
Alexander Belopolsky40018472011-02-26 01:02:56 +00009138Py_ssize_t
9139PyUnicode_Tailmatch(PyObject *str,
9140 PyObject *substr,
9141 Py_ssize_t start,
9142 Py_ssize_t end,
9143 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009144{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009145 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009146
Guido van Rossumd57fd912000-03-10 22:53:23 +00009147 str = PyUnicode_FromObject(str);
9148 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009149 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009150 substr = PyUnicode_FromObject(substr);
9151 if (substr == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009152 Py_DECREF(str);
9153 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009154 }
Tim Petersced69f82003-09-16 20:30:58 +00009155
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009156 result = tailmatch(str, substr,
Benjamin Peterson29060642009-01-31 22:14:21 +00009157 start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009158 Py_DECREF(str);
9159 Py_DECREF(substr);
9160 return result;
9161}
9162
Guido van Rossumd57fd912000-03-10 22:53:23 +00009163/* Apply fixfct filter to the Unicode object self and return a
9164 reference to the modified object */
9165
Alexander Belopolsky40018472011-02-26 01:02:56 +00009166static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009167fixup(PyObject *self,
9168 Py_UCS4 (*fixfct)(PyObject *s))
Guido van Rossumd57fd912000-03-10 22:53:23 +00009169{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009170 PyObject *u;
9171 Py_UCS4 maxchar_old, maxchar_new = 0;
Victor Stinnereaab6042011-12-11 22:22:39 +01009172 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009173
Victor Stinnerbf6e5602011-12-12 01:53:47 +01009174 u = _PyUnicode_Copy(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009175 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009176 return NULL;
Victor Stinner87af4f22011-11-21 23:03:47 +01009177 maxchar_old = PyUnicode_MAX_CHAR_VALUE(u);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009178
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009179 /* fix functions return the new maximum character in a string,
9180 if the kind of the resulting unicode object does not change,
9181 everything is fine. Otherwise we need to change the string kind
9182 and re-run the fix function. */
Victor Stinner9310abb2011-10-05 00:59:23 +02009183 maxchar_new = fixfct(u);
Victor Stinnereaab6042011-12-11 22:22:39 +01009184
9185 if (maxchar_new == 0) {
9186 /* no changes */;
9187 if (PyUnicode_CheckExact(self)) {
9188 Py_DECREF(u);
9189 Py_INCREF(self);
9190 return self;
9191 }
9192 else
9193 return u;
9194 }
9195
Victor Stinnere6abb482012-05-02 01:15:40 +02009196 maxchar_new = align_maxchar(maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009197
Victor Stinnereaab6042011-12-11 22:22:39 +01009198 if (maxchar_new == maxchar_old)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009199 return u;
Victor Stinnereaab6042011-12-11 22:22:39 +01009200
9201 /* In case the maximum character changed, we need to
9202 convert the string to the new category. */
9203 v = PyUnicode_New(PyUnicode_GET_LENGTH(self), maxchar_new);
9204 if (v == NULL) {
9205 Py_DECREF(u);
9206 return NULL;
9207 }
9208 if (maxchar_new > maxchar_old) {
9209 /* If the maxchar increased so that the kind changed, not all
9210 characters are representable anymore and we need to fix the
9211 string again. This only happens in very few cases. */
Victor Stinnerd3f08822012-05-29 12:57:52 +02009212 _PyUnicode_FastCopyCharacters(v, 0,
9213 self, 0, PyUnicode_GET_LENGTH(self));
Victor Stinnereaab6042011-12-11 22:22:39 +01009214 maxchar_old = fixfct(v);
9215 assert(maxchar_old > 0 && maxchar_old <= maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009216 }
9217 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02009218 _PyUnicode_FastCopyCharacters(v, 0,
9219 u, 0, PyUnicode_GET_LENGTH(self));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009220 }
Victor Stinnereaab6042011-12-11 22:22:39 +01009221 Py_DECREF(u);
9222 assert(_PyUnicode_CheckConsistency(v, 1));
9223 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009224}
9225
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009226static PyObject *
9227ascii_upper_or_lower(PyObject *self, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009228{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009229 Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9230 char *resdata, *data = PyUnicode_DATA(self);
9231 PyObject *res;
Tim Petersced69f82003-09-16 20:30:58 +00009232
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009233 res = PyUnicode_New(len, 127);
9234 if (res == NULL)
9235 return NULL;
9236 resdata = PyUnicode_DATA(res);
9237 if (lower)
9238 _Py_bytes_lower(resdata, data, len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009239 else
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009240 _Py_bytes_upper(resdata, data, len);
9241 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009242}
9243
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009244static Py_UCS4
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009245handle_capital_sigma(int kind, void *data, Py_ssize_t length, Py_ssize_t i)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009246{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009247 Py_ssize_t j;
9248 int final_sigma;
9249 Py_UCS4 c;
9250 /* U+03A3 is in the Final_Sigma context when, it is found like this:
Tim Petersced69f82003-09-16 20:30:58 +00009251
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009252 \p{cased}\p{case-ignorable}*U+03A3!(\p{case-ignorable}*\p{cased})
9253
9254 where ! is a negation and \p{xxx} is a character with property xxx.
9255 */
9256 for (j = i - 1; j >= 0; j--) {
9257 c = PyUnicode_READ(kind, data, j);
9258 if (!_PyUnicode_IsCaseIgnorable(c))
9259 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009260 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009261 final_sigma = j >= 0 && _PyUnicode_IsCased(c);
9262 if (final_sigma) {
9263 for (j = i + 1; j < length; j++) {
9264 c = PyUnicode_READ(kind, data, j);
9265 if (!_PyUnicode_IsCaseIgnorable(c))
9266 break;
9267 }
9268 final_sigma = j == length || !_PyUnicode_IsCased(c);
9269 }
9270 return (final_sigma) ? 0x3C2 : 0x3C3;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009271}
9272
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009273static int
9274lower_ucs4(int kind, void *data, Py_ssize_t length, Py_ssize_t i,
9275 Py_UCS4 c, Py_UCS4 *mapped)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009276{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009277 /* Obscure special case. */
9278 if (c == 0x3A3) {
9279 mapped[0] = handle_capital_sigma(kind, data, length, i);
9280 return 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009281 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009282 return _PyUnicode_ToLowerFull(c, mapped);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009283}
9284
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009285static Py_ssize_t
9286do_capitalize(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009287{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009288 Py_ssize_t i, k = 0;
9289 int n_res, j;
9290 Py_UCS4 c, mapped[3];
Tim Petersced69f82003-09-16 20:30:58 +00009291
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009292 c = PyUnicode_READ(kind, data, 0);
9293 n_res = _PyUnicode_ToUpperFull(c, mapped);
9294 for (j = 0; j < n_res; j++) {
Victor Stinnere6abb482012-05-02 01:15:40 +02009295 *maxchar = MAX_MAXCHAR(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009296 res[k++] = mapped[j];
Guido van Rossumd57fd912000-03-10 22:53:23 +00009297 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009298 for (i = 1; i < length; i++) {
9299 c = PyUnicode_READ(kind, data, i);
9300 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9301 for (j = 0; j < n_res; j++) {
Victor Stinnere6abb482012-05-02 01:15:40 +02009302 *maxchar = MAX_MAXCHAR(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009303 res[k++] = mapped[j];
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009304 }
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009305 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009306 return k;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009307}
9308
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009309static Py_ssize_t
9310do_swapcase(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar) {
9311 Py_ssize_t i, k = 0;
9312
9313 for (i = 0; i < length; i++) {
9314 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9315 int n_res, j;
9316 if (Py_UNICODE_ISUPPER(c)) {
9317 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9318 }
9319 else if (Py_UNICODE_ISLOWER(c)) {
9320 n_res = _PyUnicode_ToUpperFull(c, mapped);
9321 }
9322 else {
9323 n_res = 1;
9324 mapped[0] = c;
9325 }
9326 for (j = 0; j < n_res; j++) {
Victor Stinnere6abb482012-05-02 01:15:40 +02009327 *maxchar = MAX_MAXCHAR(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009328 res[k++] = mapped[j];
9329 }
9330 }
9331 return k;
9332}
9333
9334static Py_ssize_t
9335do_upper_or_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res,
9336 Py_UCS4 *maxchar, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009337{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009338 Py_ssize_t i, k = 0;
9339
9340 for (i = 0; i < length; i++) {
9341 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9342 int n_res, j;
9343 if (lower)
9344 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9345 else
9346 n_res = _PyUnicode_ToUpperFull(c, mapped);
9347 for (j = 0; j < n_res; j++) {
Victor Stinnere6abb482012-05-02 01:15:40 +02009348 *maxchar = MAX_MAXCHAR(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009349 res[k++] = mapped[j];
9350 }
9351 }
9352 return k;
9353}
9354
9355static Py_ssize_t
9356do_upper(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9357{
9358 return do_upper_or_lower(kind, data, length, res, maxchar, 0);
9359}
9360
9361static Py_ssize_t
9362do_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9363{
9364 return do_upper_or_lower(kind, data, length, res, maxchar, 1);
9365}
9366
Benjamin Petersone51757f2012-01-12 21:10:29 -05009367static Py_ssize_t
Benjamin Petersond5890c82012-01-14 13:23:30 -05009368do_casefold(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9369{
9370 Py_ssize_t i, k = 0;
9371
9372 for (i = 0; i < length; i++) {
9373 Py_UCS4 c = PyUnicode_READ(kind, data, i);
9374 Py_UCS4 mapped[3];
9375 int j, n_res = _PyUnicode_ToFoldedFull(c, mapped);
9376 for (j = 0; j < n_res; j++) {
Victor Stinnere6abb482012-05-02 01:15:40 +02009377 *maxchar = MAX_MAXCHAR(*maxchar, mapped[j]);
Benjamin Petersond5890c82012-01-14 13:23:30 -05009378 res[k++] = mapped[j];
9379 }
9380 }
9381 return k;
9382}
9383
9384static Py_ssize_t
Benjamin Petersone51757f2012-01-12 21:10:29 -05009385do_title(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9386{
9387 Py_ssize_t i, k = 0;
9388 int previous_is_cased;
9389
9390 previous_is_cased = 0;
9391 for (i = 0; i < length; i++) {
9392 const Py_UCS4 c = PyUnicode_READ(kind, data, i);
9393 Py_UCS4 mapped[3];
9394 int n_res, j;
9395
9396 if (previous_is_cased)
9397 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9398 else
9399 n_res = _PyUnicode_ToTitleFull(c, mapped);
9400
9401 for (j = 0; j < n_res; j++) {
Victor Stinnere6abb482012-05-02 01:15:40 +02009402 *maxchar = MAX_MAXCHAR(*maxchar, mapped[j]);
Benjamin Petersone51757f2012-01-12 21:10:29 -05009403 res[k++] = mapped[j];
9404 }
9405
9406 previous_is_cased = _PyUnicode_IsCased(c);
9407 }
9408 return k;
9409}
9410
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009411static PyObject *
9412case_operation(PyObject *self,
9413 Py_ssize_t (*perform)(int, void *, Py_ssize_t, Py_UCS4 *, Py_UCS4 *))
9414{
9415 PyObject *res = NULL;
9416 Py_ssize_t length, newlength = 0;
9417 int kind, outkind;
9418 void *data, *outdata;
9419 Py_UCS4 maxchar = 0, *tmp, *tmpend;
9420
Benjamin Petersoneea48462012-01-16 14:28:50 -05009421 assert(PyUnicode_IS_READY(self));
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009422
9423 kind = PyUnicode_KIND(self);
9424 data = PyUnicode_DATA(self);
9425 length = PyUnicode_GET_LENGTH(self);
9426 tmp = PyMem_MALLOC(sizeof(Py_UCS4) * 3 * length);
9427 if (tmp == NULL)
9428 return PyErr_NoMemory();
9429 newlength = perform(kind, data, length, tmp, &maxchar);
9430 res = PyUnicode_New(newlength, maxchar);
9431 if (res == NULL)
9432 goto leave;
9433 tmpend = tmp + newlength;
9434 outdata = PyUnicode_DATA(res);
9435 outkind = PyUnicode_KIND(res);
9436 switch (outkind) {
9437 case PyUnicode_1BYTE_KIND:
9438 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, tmp, tmpend, outdata);
9439 break;
9440 case PyUnicode_2BYTE_KIND:
9441 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, tmp, tmpend, outdata);
9442 break;
9443 case PyUnicode_4BYTE_KIND:
9444 memcpy(outdata, tmp, sizeof(Py_UCS4) * newlength);
9445 break;
9446 default:
9447 assert(0);
9448 break;
9449 }
9450 leave:
9451 PyMem_FREE(tmp);
9452 return res;
9453}
9454
Tim Peters8ce9f162004-08-27 01:49:32 +00009455PyObject *
9456PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009457{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009458 PyObject *sep = NULL;
Victor Stinnerdd077322011-10-07 17:02:31 +02009459 Py_ssize_t seplen;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009460 PyObject *res = NULL; /* the result */
Tim Peters05eba1f2004-08-27 21:32:02 +00009461 PyObject *fseq; /* PySequence_Fast(seq) */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009462 Py_ssize_t seqlen; /* len(fseq) -- number of items in sequence */
9463 PyObject **items;
Tim Peters8ce9f162004-08-27 01:49:32 +00009464 PyObject *item;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009465 Py_ssize_t sz, i, res_offset;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009466 Py_UCS4 maxchar;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009467 Py_UCS4 item_maxchar;
Victor Stinnerdd077322011-10-07 17:02:31 +02009468 int use_memcpy;
9469 unsigned char *res_data = NULL, *sep_data = NULL;
9470 PyObject *last_obj;
9471 unsigned int kind = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009472
Tim Peters05eba1f2004-08-27 21:32:02 +00009473 fseq = PySequence_Fast(seq, "");
9474 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009475 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00009476 }
9477
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009478 /* NOTE: the following code can't call back into Python code,
9479 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00009480 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009481
Tim Peters05eba1f2004-08-27 21:32:02 +00009482 seqlen = PySequence_Fast_GET_SIZE(fseq);
9483 /* If empty sequence, return u"". */
9484 if (seqlen == 0) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009485 Py_DECREF(fseq);
9486 Py_INCREF(unicode_empty);
9487 res = unicode_empty;
9488 return res;
Tim Peters05eba1f2004-08-27 21:32:02 +00009489 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009490
Tim Peters05eba1f2004-08-27 21:32:02 +00009491 /* If singleton sequence with an exact Unicode, return that. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009492 last_obj = NULL;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009493 items = PySequence_Fast_ITEMS(fseq);
Victor Stinneracf47b82011-10-06 12:32:37 +02009494 if (seqlen == 1) {
9495 if (PyUnicode_CheckExact(items[0])) {
9496 res = items[0];
9497 Py_INCREF(res);
9498 Py_DECREF(fseq);
9499 return res;
9500 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009501 seplen = 0;
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009502 maxchar = 0;
Tim Peters8ce9f162004-08-27 01:49:32 +00009503 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009504 else {
Victor Stinneracf47b82011-10-06 12:32:37 +02009505 /* Set up sep and seplen */
9506 if (separator == NULL) {
9507 /* fall back to a blank space separator */
9508 sep = PyUnicode_FromOrdinal(' ');
9509 if (!sep)
9510 goto onError;
Victor Stinnerdd077322011-10-07 17:02:31 +02009511 seplen = 1;
Victor Stinneracf47b82011-10-06 12:32:37 +02009512 maxchar = 32;
Tim Peters05eba1f2004-08-27 21:32:02 +00009513 }
Victor Stinneracf47b82011-10-06 12:32:37 +02009514 else {
9515 if (!PyUnicode_Check(separator)) {
9516 PyErr_Format(PyExc_TypeError,
9517 "separator: expected str instance,"
9518 " %.80s found",
9519 Py_TYPE(separator)->tp_name);
9520 goto onError;
9521 }
9522 if (PyUnicode_READY(separator))
9523 goto onError;
9524 sep = separator;
9525 seplen = PyUnicode_GET_LENGTH(separator);
9526 maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
9527 /* inc refcount to keep this code path symmetric with the
9528 above case of a blank separator */
9529 Py_INCREF(sep);
9530 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009531 last_obj = sep;
Tim Peters05eba1f2004-08-27 21:32:02 +00009532 }
9533
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009534 /* There are at least two things to join, or else we have a subclass
9535 * of str in the sequence.
9536 * Do a pre-pass to figure out the total amount of space we'll
9537 * need (sz), and see whether all argument are strings.
9538 */
9539 sz = 0;
Victor Stinnerdd077322011-10-07 17:02:31 +02009540#ifdef Py_DEBUG
9541 use_memcpy = 0;
9542#else
9543 use_memcpy = 1;
9544#endif
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009545 for (i = 0; i < seqlen; i++) {
9546 const Py_ssize_t old_sz = sz;
9547 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009548 if (!PyUnicode_Check(item)) {
9549 PyErr_Format(PyExc_TypeError,
9550 "sequence item %zd: expected str instance,"
9551 " %.80s found",
9552 i, Py_TYPE(item)->tp_name);
9553 goto onError;
9554 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009555 if (PyUnicode_READY(item) == -1)
9556 goto onError;
9557 sz += PyUnicode_GET_LENGTH(item);
9558 item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
Victor Stinnere6abb482012-05-02 01:15:40 +02009559 maxchar = MAX_MAXCHAR(maxchar, item_maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009560 if (i != 0)
9561 sz += seplen;
9562 if (sz < old_sz || sz > PY_SSIZE_T_MAX) {
9563 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009564 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009565 goto onError;
9566 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009567 if (use_memcpy && last_obj != NULL) {
9568 if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
9569 use_memcpy = 0;
9570 }
9571 last_obj = item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009572 }
Tim Petersced69f82003-09-16 20:30:58 +00009573
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009574 res = PyUnicode_New(sz, maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009575 if (res == NULL)
9576 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +00009577
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009578 /* Catenate everything. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009579#ifdef Py_DEBUG
9580 use_memcpy = 0;
9581#else
9582 if (use_memcpy) {
9583 res_data = PyUnicode_1BYTE_DATA(res);
9584 kind = PyUnicode_KIND(res);
9585 if (seplen != 0)
9586 sep_data = PyUnicode_1BYTE_DATA(sep);
9587 }
9588#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009589 for (i = 0, res_offset = 0; i < seqlen; ++i) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009590 Py_ssize_t itemlen;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009591 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009592 /* Copy item, and maybe the separator. */
Victor Stinner9ce5a832011-10-03 23:36:02 +02009593 if (i && seplen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009594 if (use_memcpy) {
9595 Py_MEMCPY(res_data,
9596 sep_data,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009597 kind * seplen);
9598 res_data += kind * seplen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009599 }
9600 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02009601 _PyUnicode_FastCopyCharacters(res, res_offset, sep, 0, seplen);
Victor Stinnerdd077322011-10-07 17:02:31 +02009602 res_offset += seplen;
9603 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009604 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009605 itemlen = PyUnicode_GET_LENGTH(item);
9606 if (itemlen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009607 if (use_memcpy) {
9608 Py_MEMCPY(res_data,
9609 PyUnicode_DATA(item),
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009610 kind * itemlen);
9611 res_data += kind * itemlen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009612 }
9613 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02009614 _PyUnicode_FastCopyCharacters(res, res_offset, item, 0, itemlen);
Victor Stinnerdd077322011-10-07 17:02:31 +02009615 res_offset += itemlen;
9616 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009617 }
Tim Peters05eba1f2004-08-27 21:32:02 +00009618 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009619 if (use_memcpy)
9620 assert(res_data == PyUnicode_1BYTE_DATA(res)
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009621 + kind * PyUnicode_GET_LENGTH(res));
Victor Stinnerdd077322011-10-07 17:02:31 +02009622 else
9623 assert(res_offset == PyUnicode_GET_LENGTH(res));
Tim Peters8ce9f162004-08-27 01:49:32 +00009624
Tim Peters05eba1f2004-08-27 21:32:02 +00009625 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009626 Py_XDECREF(sep);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009627 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009628 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009629
Benjamin Peterson29060642009-01-31 22:14:21 +00009630 onError:
Tim Peters05eba1f2004-08-27 21:32:02 +00009631 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009632 Py_XDECREF(sep);
Tim Peters8ce9f162004-08-27 01:49:32 +00009633 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009634 return NULL;
9635}
9636
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009637#define FILL(kind, data, value, start, length) \
9638 do { \
9639 Py_ssize_t i_ = 0; \
9640 assert(kind != PyUnicode_WCHAR_KIND); \
9641 switch ((kind)) { \
9642 case PyUnicode_1BYTE_KIND: { \
9643 unsigned char * to_ = (unsigned char *)((data)) + (start); \
Victor Stinnerf2c76aa2012-05-03 13:10:40 +02009644 memset(to_, (unsigned char)value, (length)); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009645 break; \
9646 } \
9647 case PyUnicode_2BYTE_KIND: { \
9648 Py_UCS2 * to_ = (Py_UCS2 *)((data)) + (start); \
9649 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9650 break; \
9651 } \
Benjamin Petersone157cf12012-01-01 15:56:20 -06009652 case PyUnicode_4BYTE_KIND: { \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009653 Py_UCS4 * to_ = (Py_UCS4 *)((data)) + (start); \
9654 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9655 break; \
Benjamin Petersone157cf12012-01-01 15:56:20 -06009656 default: assert(0); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009657 } \
9658 } \
9659 } while (0)
9660
Victor Stinnerd3f08822012-05-29 12:57:52 +02009661void
9662_PyUnicode_FastFill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
9663 Py_UCS4 fill_char)
9664{
9665 const enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
9666 const void *data = PyUnicode_DATA(unicode);
9667 assert(PyUnicode_IS_READY(unicode));
9668 assert(unicode_modifiable(unicode));
9669 assert(fill_char <= PyUnicode_MAX_CHAR_VALUE(unicode));
9670 assert(start >= 0);
9671 assert(start + length <= PyUnicode_GET_LENGTH(unicode));
9672 FILL(kind, data, fill_char, start, length);
9673}
9674
Victor Stinner3fe55312012-01-04 00:33:50 +01009675Py_ssize_t
9676PyUnicode_Fill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
9677 Py_UCS4 fill_char)
9678{
9679 Py_ssize_t maxlen;
Victor Stinner3fe55312012-01-04 00:33:50 +01009680
9681 if (!PyUnicode_Check(unicode)) {
9682 PyErr_BadInternalCall();
9683 return -1;
9684 }
9685 if (PyUnicode_READY(unicode) == -1)
9686 return -1;
9687 if (unicode_check_modifiable(unicode))
9688 return -1;
9689
Victor Stinnerd3f08822012-05-29 12:57:52 +02009690 if (start < 0) {
9691 PyErr_SetString(PyExc_IndexError, "string index out of range");
9692 return -1;
9693 }
Victor Stinner3fe55312012-01-04 00:33:50 +01009694 if (fill_char > PyUnicode_MAX_CHAR_VALUE(unicode)) {
9695 PyErr_SetString(PyExc_ValueError,
9696 "fill character is bigger than "
9697 "the string maximum character");
9698 return -1;
9699 }
9700
9701 maxlen = PyUnicode_GET_LENGTH(unicode) - start;
9702 length = Py_MIN(maxlen, length);
9703 if (length <= 0)
9704 return 0;
9705
Victor Stinnerd3f08822012-05-29 12:57:52 +02009706 _PyUnicode_FastFill(unicode, start, length, fill_char);
Victor Stinner3fe55312012-01-04 00:33:50 +01009707 return length;
9708}
9709
Victor Stinner9310abb2011-10-05 00:59:23 +02009710static PyObject *
9711pad(PyObject *self,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009712 Py_ssize_t left,
9713 Py_ssize_t right,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009714 Py_UCS4 fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009715{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009716 PyObject *u;
9717 Py_UCS4 maxchar;
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009718 int kind;
9719 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009720
9721 if (left < 0)
9722 left = 0;
9723 if (right < 0)
9724 right = 0;
9725
Victor Stinnerc4b49542011-12-11 22:44:26 +01009726 if (left == 0 && right == 0)
9727 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009728
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009729 if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
9730 right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +00009731 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
9732 return NULL;
9733 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009734 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Victor Stinnere6abb482012-05-02 01:15:40 +02009735 maxchar = MAX_MAXCHAR(maxchar, fill);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009736 u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009737 if (!u)
9738 return NULL;
9739
9740 kind = PyUnicode_KIND(u);
9741 data = PyUnicode_DATA(u);
9742 if (left)
9743 FILL(kind, data, fill, 0, left);
9744 if (right)
9745 FILL(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
Victor Stinnerd3f08822012-05-29 12:57:52 +02009746 _PyUnicode_FastCopyCharacters(u, left, self, 0, _PyUnicode_LENGTH(self));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009747 assert(_PyUnicode_CheckConsistency(u, 1));
9748 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009749}
9750
Alexander Belopolsky40018472011-02-26 01:02:56 +00009751PyObject *
9752PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009753{
Guido van Rossumd57fd912000-03-10 22:53:23 +00009754 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009755
9756 string = PyUnicode_FromObject(string);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009757 if (string == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009758 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -06009759 if (PyUnicode_READY(string) == -1) {
9760 Py_DECREF(string);
9761 return NULL;
9762 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009763
Benjamin Petersonead6b532011-12-20 17:23:42 -06009764 switch (PyUnicode_KIND(string)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009765 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009766 if (PyUnicode_IS_ASCII(string))
9767 list = asciilib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009768 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009769 PyUnicode_GET_LENGTH(string), keepends);
9770 else
9771 list = ucs1lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009772 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009773 PyUnicode_GET_LENGTH(string), keepends);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009774 break;
9775 case PyUnicode_2BYTE_KIND:
9776 list = ucs2lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009777 string, PyUnicode_2BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009778 PyUnicode_GET_LENGTH(string), keepends);
9779 break;
9780 case PyUnicode_4BYTE_KIND:
9781 list = ucs4lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009782 string, PyUnicode_4BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009783 PyUnicode_GET_LENGTH(string), keepends);
9784 break;
9785 default:
9786 assert(0);
9787 list = 0;
9788 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009789 Py_DECREF(string);
9790 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009791}
9792
Alexander Belopolsky40018472011-02-26 01:02:56 +00009793static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009794split(PyObject *self,
9795 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009796 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009797{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009798 int kind1, kind2, kind;
9799 void *buf1, *buf2;
9800 Py_ssize_t len1, len2;
9801 PyObject* out;
9802
Guido van Rossumd57fd912000-03-10 22:53:23 +00009803 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00009804 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009805
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009806 if (PyUnicode_READY(self) == -1)
9807 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009808
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009809 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -06009810 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009811 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009812 if (PyUnicode_IS_ASCII(self))
9813 return asciilib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009814 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009815 PyUnicode_GET_LENGTH(self), maxcount
9816 );
9817 else
9818 return ucs1lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009819 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009820 PyUnicode_GET_LENGTH(self), maxcount
9821 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009822 case PyUnicode_2BYTE_KIND:
9823 return ucs2lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009824 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009825 PyUnicode_GET_LENGTH(self), maxcount
9826 );
9827 case PyUnicode_4BYTE_KIND:
9828 return ucs4lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009829 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009830 PyUnicode_GET_LENGTH(self), maxcount
9831 );
9832 default:
9833 assert(0);
9834 return NULL;
9835 }
9836
9837 if (PyUnicode_READY(substring) == -1)
9838 return NULL;
9839
9840 kind1 = PyUnicode_KIND(self);
9841 kind2 = PyUnicode_KIND(substring);
9842 kind = kind1 > kind2 ? kind1 : kind2;
9843 buf1 = PyUnicode_DATA(self);
9844 buf2 = PyUnicode_DATA(substring);
9845 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009846 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009847 if (!buf1)
9848 return NULL;
9849 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009850 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009851 if (!buf2) {
9852 if (kind1 != kind) PyMem_Free(buf1);
9853 return NULL;
9854 }
9855 len1 = PyUnicode_GET_LENGTH(self);
9856 len2 = PyUnicode_GET_LENGTH(substring);
9857
Benjamin Petersonead6b532011-12-20 17:23:42 -06009858 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009859 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009860 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
9861 out = asciilib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009862 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +02009863 else
9864 out = ucs1lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009865 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009866 break;
9867 case PyUnicode_2BYTE_KIND:
9868 out = ucs2lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009869 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009870 break;
9871 case PyUnicode_4BYTE_KIND:
9872 out = ucs4lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009873 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009874 break;
9875 default:
9876 out = NULL;
9877 }
9878 if (kind1 != kind)
9879 PyMem_Free(buf1);
9880 if (kind2 != kind)
9881 PyMem_Free(buf2);
9882 return out;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009883}
9884
Alexander Belopolsky40018472011-02-26 01:02:56 +00009885static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009886rsplit(PyObject *self,
9887 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009888 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009889{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009890 int kind1, kind2, kind;
9891 void *buf1, *buf2;
9892 Py_ssize_t len1, len2;
9893 PyObject* out;
9894
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009895 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00009896 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009897
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009898 if (PyUnicode_READY(self) == -1)
9899 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009900
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009901 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -06009902 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009903 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009904 if (PyUnicode_IS_ASCII(self))
9905 return asciilib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009906 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009907 PyUnicode_GET_LENGTH(self), maxcount
9908 );
9909 else
9910 return ucs1lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009911 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009912 PyUnicode_GET_LENGTH(self), maxcount
9913 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009914 case PyUnicode_2BYTE_KIND:
9915 return ucs2lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009916 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009917 PyUnicode_GET_LENGTH(self), maxcount
9918 );
9919 case PyUnicode_4BYTE_KIND:
9920 return ucs4lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009921 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009922 PyUnicode_GET_LENGTH(self), maxcount
9923 );
9924 default:
9925 assert(0);
9926 return NULL;
9927 }
9928
9929 if (PyUnicode_READY(substring) == -1)
9930 return NULL;
9931
9932 kind1 = PyUnicode_KIND(self);
9933 kind2 = PyUnicode_KIND(substring);
9934 kind = kind1 > kind2 ? kind1 : kind2;
9935 buf1 = PyUnicode_DATA(self);
9936 buf2 = PyUnicode_DATA(substring);
9937 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009938 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009939 if (!buf1)
9940 return NULL;
9941 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009942 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009943 if (!buf2) {
9944 if (kind1 != kind) PyMem_Free(buf1);
9945 return NULL;
9946 }
9947 len1 = PyUnicode_GET_LENGTH(self);
9948 len2 = PyUnicode_GET_LENGTH(substring);
9949
Benjamin Petersonead6b532011-12-20 17:23:42 -06009950 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009951 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009952 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
9953 out = asciilib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009954 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +02009955 else
9956 out = ucs1lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009957 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009958 break;
9959 case PyUnicode_2BYTE_KIND:
9960 out = ucs2lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009961 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009962 break;
9963 case PyUnicode_4BYTE_KIND:
9964 out = ucs4lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009965 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009966 break;
9967 default:
9968 out = NULL;
9969 }
9970 if (kind1 != kind)
9971 PyMem_Free(buf1);
9972 if (kind2 != kind)
9973 PyMem_Free(buf2);
9974 return out;
9975}
9976
9977static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +02009978anylib_find(int kind, PyObject *str1, void *buf1, Py_ssize_t len1,
9979 PyObject *str2, void *buf2, Py_ssize_t len2, Py_ssize_t offset)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009980{
Benjamin Petersonead6b532011-12-20 17:23:42 -06009981 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009982 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009983 if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
9984 return asciilib_find(buf1, len1, buf2, len2, offset);
9985 else
9986 return ucs1lib_find(buf1, len1, buf2, len2, offset);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009987 case PyUnicode_2BYTE_KIND:
9988 return ucs2lib_find(buf1, len1, buf2, len2, offset);
9989 case PyUnicode_4BYTE_KIND:
9990 return ucs4lib_find(buf1, len1, buf2, len2, offset);
9991 }
9992 assert(0);
9993 return -1;
9994}
9995
9996static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +02009997anylib_count(int kind, PyObject *sstr, void* sbuf, Py_ssize_t slen,
9998 PyObject *str1, void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009999{
Benjamin Petersonc0b95d12011-12-20 17:24:05 -060010000 switch (kind) {
10001 case PyUnicode_1BYTE_KIND:
10002 if (PyUnicode_IS_ASCII(sstr) && PyUnicode_IS_ASCII(str1))
10003 return asciilib_count(sbuf, slen, buf1, len1, maxcount);
10004 else
10005 return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
10006 case PyUnicode_2BYTE_KIND:
10007 return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
10008 case PyUnicode_4BYTE_KIND:
10009 return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
10010 }
10011 assert(0);
10012 return 0;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010013}
10014
Alexander Belopolsky40018472011-02-26 01:02:56 +000010015static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010016replace(PyObject *self, PyObject *str1,
10017 PyObject *str2, Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010018{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010019 PyObject *u;
10020 char *sbuf = PyUnicode_DATA(self);
10021 char *buf1 = PyUnicode_DATA(str1);
10022 char *buf2 = PyUnicode_DATA(str2);
10023 int srelease = 0, release1 = 0, release2 = 0;
10024 int skind = PyUnicode_KIND(self);
10025 int kind1 = PyUnicode_KIND(str1);
10026 int kind2 = PyUnicode_KIND(str2);
10027 Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
10028 Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
10029 Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010030 int mayshrink;
10031 Py_UCS4 maxchar, maxchar_str2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010032
10033 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010034 maxcount = PY_SSIZE_T_MAX;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010035 else if (maxcount == 0 || slen == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010036 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010037
Victor Stinner59de0ee2011-10-07 10:01:28 +020010038 if (str1 == str2)
10039 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010040 if (skind < kind1)
10041 /* substring too wide to be present */
10042 goto nothing;
10043
Victor Stinner49a0a212011-10-12 23:46:10 +020010044 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
10045 maxchar_str2 = PyUnicode_MAX_CHAR_VALUE(str2);
10046 /* Replacing str1 with str2 may cause a maxchar reduction in the
10047 result string. */
10048 mayshrink = (maxchar_str2 < maxchar);
Victor Stinnere6abb482012-05-02 01:15:40 +020010049 maxchar = MAX_MAXCHAR(maxchar, maxchar_str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010050
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010051 if (len1 == len2) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010052 /* same length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010053 if (len1 == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010054 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010055 if (len1 == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010056 /* replace characters */
Victor Stinner49a0a212011-10-12 23:46:10 +020010057 Py_UCS4 u1, u2;
10058 int rkind;
Victor Stinnerf6441102011-12-18 02:43:08 +010010059 Py_ssize_t index, pos;
10060 char *src;
10061
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010062 u1 = PyUnicode_READ_CHAR(str1, 0);
Victor Stinnerf6441102011-12-18 02:43:08 +010010063 pos = findchar(sbuf, PyUnicode_KIND(self), slen, u1, 1);
10064 if (pos < 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010065 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010066 u2 = PyUnicode_READ_CHAR(str2, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010067 u = PyUnicode_New(slen, maxchar);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010068 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010069 goto error;
Victor Stinnerd3f08822012-05-29 12:57:52 +020010070 _PyUnicode_FastCopyCharacters(u, 0, self, 0, slen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010071 rkind = PyUnicode_KIND(u);
Victor Stinnerf6441102011-12-18 02:43:08 +010010072
10073 PyUnicode_WRITE(rkind, PyUnicode_DATA(u), pos, u2);
10074 index = 0;
10075 src = sbuf;
10076 while (--maxcount)
10077 {
10078 pos++;
10079 src += pos * PyUnicode_KIND(self);
10080 slen -= pos;
10081 index += pos;
10082 pos = findchar(src, PyUnicode_KIND(self), slen, u1, 1);
10083 if (pos < 0)
10084 break;
10085 PyUnicode_WRITE(rkind, PyUnicode_DATA(u), index + pos, u2);
10086 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010087 }
10088 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010089 int rkind = skind;
10090 char *res;
Victor Stinnerf6441102011-12-18 02:43:08 +010010091 Py_ssize_t i;
Victor Stinner25a4b292011-10-06 12:31:55 +020010092
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010093 if (kind1 < rkind) {
10094 /* widen substring */
10095 buf1 = _PyUnicode_AsKind(str1, rkind);
10096 if (!buf1) goto error;
10097 release1 = 1;
10098 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010099 i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010100 if (i < 0)
10101 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010102 if (rkind > kind2) {
10103 /* widen replacement */
10104 buf2 = _PyUnicode_AsKind(str2, rkind);
10105 if (!buf2) goto error;
10106 release2 = 1;
10107 }
10108 else if (rkind < kind2) {
10109 /* widen self and buf1 */
10110 rkind = kind2;
10111 if (release1) PyMem_Free(buf1);
10112 sbuf = _PyUnicode_AsKind(self, rkind);
10113 if (!sbuf) goto error;
10114 srelease = 1;
10115 buf1 = _PyUnicode_AsKind(str1, rkind);
10116 if (!buf1) goto error;
10117 release1 = 1;
10118 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010119 u = PyUnicode_New(slen, maxchar);
10120 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010121 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010122 assert(PyUnicode_KIND(u) == rkind);
10123 res = PyUnicode_DATA(u);
Victor Stinner25a4b292011-10-06 12:31:55 +020010124
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010125 memcpy(res, sbuf, rkind * slen);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010126 /* change everything in-place, starting with this one */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010127 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010128 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010129 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010130 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010131
10132 while ( --maxcount > 0) {
Victor Stinnerc3cec782011-10-05 21:24:08 +020010133 i = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010134 sbuf+rkind*i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010135 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010136 if (i == -1)
10137 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010138 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010139 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010140 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010141 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010142 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010143 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010144 }
10145 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010146 Py_ssize_t n, i, j, ires;
10147 Py_ssize_t product, new_size;
10148 int rkind = skind;
10149 char *res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010150
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010151 if (kind1 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010152 /* widen substring */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010153 buf1 = _PyUnicode_AsKind(str1, rkind);
10154 if (!buf1) goto error;
10155 release1 = 1;
10156 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010157 n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010158 if (n == 0)
10159 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010160 if (kind2 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010161 /* widen replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010162 buf2 = _PyUnicode_AsKind(str2, rkind);
10163 if (!buf2) goto error;
10164 release2 = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010165 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010166 else if (kind2 > rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010167 /* widen self and buf1 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010168 rkind = kind2;
10169 sbuf = _PyUnicode_AsKind(self, rkind);
10170 if (!sbuf) goto error;
10171 srelease = 1;
10172 if (release1) PyMem_Free(buf1);
10173 buf1 = _PyUnicode_AsKind(str1, rkind);
10174 if (!buf1) goto error;
10175 release1 = 1;
10176 }
10177 /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
10178 PyUnicode_GET_LENGTH(str1))); */
10179 product = n * (len2-len1);
10180 if ((product / (len2-len1)) != n) {
10181 PyErr_SetString(PyExc_OverflowError,
10182 "replace string is too long");
10183 goto error;
10184 }
10185 new_size = slen + product;
Victor Stinner49a0a212011-10-12 23:46:10 +020010186 if (new_size == 0) {
10187 Py_INCREF(unicode_empty);
10188 u = unicode_empty;
10189 goto done;
10190 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010191 if (new_size < 0 || new_size > (PY_SSIZE_T_MAX >> (rkind-1))) {
10192 PyErr_SetString(PyExc_OverflowError,
10193 "replace string is too long");
10194 goto error;
10195 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010196 u = PyUnicode_New(new_size, maxchar);
10197 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010198 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010199 assert(PyUnicode_KIND(u) == rkind);
10200 res = PyUnicode_DATA(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010201 ires = i = 0;
10202 if (len1 > 0) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010203 while (n-- > 0) {
10204 /* look for next match */
Victor Stinnerc3cec782011-10-05 21:24:08 +020010205 j = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010206 sbuf + rkind * i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010207 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010208 if (j == -1)
10209 break;
10210 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010211 /* copy unchanged part [i:j] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010212 memcpy(res + rkind * ires,
10213 sbuf + rkind * i,
10214 rkind * (j-i));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010215 ires += j - i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010216 }
10217 /* copy substitution string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010218 if (len2 > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010219 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010220 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010221 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010222 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010223 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010224 i = j + len1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010225 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010226 if (i < slen)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010227 /* copy tail [i:] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010228 memcpy(res + rkind * ires,
10229 sbuf + rkind * i,
10230 rkind * (slen-i));
Victor Stinner49a0a212011-10-12 23:46:10 +020010231 }
10232 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010233 /* interleave */
10234 while (n > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010235 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010236 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010237 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010238 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010239 if (--n <= 0)
10240 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010241 memcpy(res + rkind * ires,
10242 sbuf + rkind * i,
10243 rkind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010244 ires++;
10245 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010246 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010247 memcpy(res + rkind * ires,
10248 sbuf + rkind * i,
10249 rkind * (slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +000010250 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010251 }
10252
10253 if (mayshrink) {
Victor Stinner25a4b292011-10-06 12:31:55 +020010254 unicode_adjust_maxchar(&u);
10255 if (u == NULL)
10256 goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010257 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010258
10259 done:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010260 if (srelease)
10261 PyMem_FREE(sbuf);
10262 if (release1)
10263 PyMem_FREE(buf1);
10264 if (release2)
10265 PyMem_FREE(buf2);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010266 assert(_PyUnicode_CheckConsistency(u, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010267 return u;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010268
Benjamin Peterson29060642009-01-31 22:14:21 +000010269 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +000010270 /* nothing to replace; return original string (when possible) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010271 if (srelease)
10272 PyMem_FREE(sbuf);
10273 if (release1)
10274 PyMem_FREE(buf1);
10275 if (release2)
10276 PyMem_FREE(buf2);
Victor Stinnerc4b49542011-12-11 22:44:26 +010010277 return unicode_result_unchanged(self);
10278
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010279 error:
10280 if (srelease && sbuf)
10281 PyMem_FREE(sbuf);
10282 if (release1 && buf1)
10283 PyMem_FREE(buf1);
10284 if (release2 && buf2)
10285 PyMem_FREE(buf2);
10286 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010287}
10288
10289/* --- Unicode Object Methods --------------------------------------------- */
10290
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010291PyDoc_STRVAR(title__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010292 "S.title() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010293\n\
10294Return a titlecased version of S, i.e. words start with title case\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010295characters, all remaining cased characters have lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010296
10297static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010298unicode_title(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010299{
Benjamin Petersoneea48462012-01-16 14:28:50 -050010300 if (PyUnicode_READY(self) == -1)
10301 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010302 return case_operation(self, do_title);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010303}
10304
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010305PyDoc_STRVAR(capitalize__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010306 "S.capitalize() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010307\n\
10308Return a capitalized version of S, i.e. make the first character\n\
Senthil Kumarane51ee8a2010-07-05 12:00:56 +000010309have upper case and the rest lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010310
10311static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010312unicode_capitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010313{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050010314 if (PyUnicode_READY(self) == -1)
10315 return NULL;
10316 if (PyUnicode_GET_LENGTH(self) == 0)
10317 return unicode_result_unchanged(self);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010318 return case_operation(self, do_capitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010319}
10320
Benjamin Petersond5890c82012-01-14 13:23:30 -050010321PyDoc_STRVAR(casefold__doc__,
10322 "S.casefold() -> str\n\
10323\n\
10324Return a version of S suitable for caseless comparisons.");
10325
10326static PyObject *
10327unicode_casefold(PyObject *self)
10328{
10329 if (PyUnicode_READY(self) == -1)
10330 return NULL;
10331 if (PyUnicode_IS_ASCII(self))
10332 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010333 return case_operation(self, do_casefold);
Benjamin Petersond5890c82012-01-14 13:23:30 -050010334}
10335
10336
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010337/* Argument converter. Coerces to a single unicode character */
10338
10339static int
10340convert_uc(PyObject *obj, void *addr)
10341{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010342 Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010343 PyObject *uniobj;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010344
Benjamin Peterson14339b62009-01-31 16:36:08 +000010345 uniobj = PyUnicode_FromObject(obj);
10346 if (uniobj == NULL) {
10347 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010348 "The fill character cannot be converted to Unicode");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010349 return 0;
10350 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010351 if (PyUnicode_GET_LENGTH(uniobj) != 1) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010352 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010353 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010354 Py_DECREF(uniobj);
10355 return 0;
10356 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010357 *fillcharloc = PyUnicode_READ_CHAR(uniobj, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010358 Py_DECREF(uniobj);
10359 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010360}
10361
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010362PyDoc_STRVAR(center__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010363 "S.center(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010364\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010365Return S centered in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010366done using the specified fill character (default is a space)");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010367
10368static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010369unicode_center(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010370{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010371 Py_ssize_t marg, left;
10372 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010373 Py_UCS4 fillchar = ' ';
10374
Victor Stinnere9a29352011-10-01 02:14:59 +020010375 if (!PyArg_ParseTuple(args, "n|O&:center", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010376 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010377
Benjamin Petersonbac79492012-01-14 13:34:47 -050010378 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010379 return NULL;
10380
Victor Stinnerc4b49542011-12-11 22:44:26 +010010381 if (PyUnicode_GET_LENGTH(self) >= width)
10382 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010383
Victor Stinnerc4b49542011-12-11 22:44:26 +010010384 marg = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010385 left = marg / 2 + (marg & width & 1);
10386
Victor Stinner9310abb2011-10-05 00:59:23 +020010387 return pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010388}
10389
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010390/* This function assumes that str1 and str2 are readied by the caller. */
10391
Marc-André Lemburge5034372000-08-08 08:04:29 +000010392static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010393unicode_compare(PyObject *str1, PyObject *str2)
Marc-André Lemburge5034372000-08-08 08:04:29 +000010394{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010395 int kind1, kind2;
10396 void *data1, *data2;
10397 Py_ssize_t len1, len2, i;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010398
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010399 kind1 = PyUnicode_KIND(str1);
10400 kind2 = PyUnicode_KIND(str2);
10401 data1 = PyUnicode_DATA(str1);
10402 data2 = PyUnicode_DATA(str2);
10403 len1 = PyUnicode_GET_LENGTH(str1);
10404 len2 = PyUnicode_GET_LENGTH(str2);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010405
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010406 for (i = 0; i < len1 && i < len2; ++i) {
10407 Py_UCS4 c1, c2;
10408 c1 = PyUnicode_READ(kind1, data1, i);
10409 c2 = PyUnicode_READ(kind2, data2, i);
Fredrik Lundh45714e92001-06-26 16:39:36 +000010410
10411 if (c1 != c2)
10412 return (c1 < c2) ? -1 : 1;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010413 }
10414
10415 return (len1 < len2) ? -1 : (len1 != len2);
10416}
10417
Alexander Belopolsky40018472011-02-26 01:02:56 +000010418int
10419PyUnicode_Compare(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010420{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010421 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10422 if (PyUnicode_READY(left) == -1 ||
10423 PyUnicode_READY(right) == -1)
10424 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010425 return unicode_compare(left, right);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010426 }
Guido van Rossum09dc34f2007-05-04 04:17:33 +000010427 PyErr_Format(PyExc_TypeError,
10428 "Can't compare %.100s and %.100s",
10429 left->ob_type->tp_name,
10430 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010431 return -1;
10432}
10433
Martin v. Löwis5b222132007-06-10 09:51:05 +000010434int
10435PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
10436{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010437 Py_ssize_t i;
10438 int kind;
10439 void *data;
10440 Py_UCS4 chr;
10441
Victor Stinner910337b2011-10-03 03:20:16 +020010442 assert(_PyUnicode_CHECK(uni));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010443 if (PyUnicode_READY(uni) == -1)
10444 return -1;
10445 kind = PyUnicode_KIND(uni);
10446 data = PyUnicode_DATA(uni);
Martin v. Löwis5b222132007-06-10 09:51:05 +000010447 /* Compare Unicode string and source character set string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010448 for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
10449 if (chr != str[i])
10450 return (chr < (unsigned char)(str[i])) ? -1 : 1;
Benjamin Peterson8667a9b2010-01-09 21:45:28 +000010451 /* This check keeps Python strings that end in '\0' from comparing equal
10452 to C strings identical up to that point. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010453 if (PyUnicode_GET_LENGTH(uni) != i || chr)
Benjamin Peterson29060642009-01-31 22:14:21 +000010454 return 1; /* uni is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010455 if (str[i])
Benjamin Peterson29060642009-01-31 22:14:21 +000010456 return -1; /* str is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010457 return 0;
10458}
10459
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010460
Benjamin Peterson29060642009-01-31 22:14:21 +000010461#define TEST_COND(cond) \
Benjamin Peterson14339b62009-01-31 16:36:08 +000010462 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010463
Alexander Belopolsky40018472011-02-26 01:02:56 +000010464PyObject *
10465PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010466{
10467 int result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010468
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010469 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10470 PyObject *v;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010471 if (PyUnicode_READY(left) == -1 ||
10472 PyUnicode_READY(right) == -1)
10473 return NULL;
10474 if (PyUnicode_GET_LENGTH(left) != PyUnicode_GET_LENGTH(right) ||
10475 PyUnicode_KIND(left) != PyUnicode_KIND(right)) {
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010476 if (op == Py_EQ) {
10477 Py_INCREF(Py_False);
10478 return Py_False;
10479 }
10480 if (op == Py_NE) {
10481 Py_INCREF(Py_True);
10482 return Py_True;
10483 }
10484 }
10485 if (left == right)
10486 result = 0;
10487 else
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010488 result = unicode_compare(left, right);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010489
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010490 /* Convert the return value to a Boolean */
10491 switch (op) {
10492 case Py_EQ:
10493 v = TEST_COND(result == 0);
10494 break;
10495 case Py_NE:
10496 v = TEST_COND(result != 0);
10497 break;
10498 case Py_LE:
10499 v = TEST_COND(result <= 0);
10500 break;
10501 case Py_GE:
10502 v = TEST_COND(result >= 0);
10503 break;
10504 case Py_LT:
10505 v = TEST_COND(result == -1);
10506 break;
10507 case Py_GT:
10508 v = TEST_COND(result == 1);
10509 break;
10510 default:
10511 PyErr_BadArgument();
10512 return NULL;
10513 }
10514 Py_INCREF(v);
10515 return v;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010516 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000010517
Brian Curtindfc80e32011-08-10 20:28:54 -050010518 Py_RETURN_NOTIMPLEMENTED;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010519}
10520
Alexander Belopolsky40018472011-02-26 01:02:56 +000010521int
10522PyUnicode_Contains(PyObject *container, PyObject *element)
Guido van Rossum403d68b2000-03-13 15:55:09 +000010523{
Thomas Wouters477c8d52006-05-27 19:21:47 +000010524 PyObject *str, *sub;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010525 int kind1, kind2, kind;
10526 void *buf1, *buf2;
10527 Py_ssize_t len1, len2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010528 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010529
10530 /* Coerce the two arguments */
Thomas Wouters477c8d52006-05-27 19:21:47 +000010531 sub = PyUnicode_FromObject(element);
10532 if (!sub) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010533 PyErr_Format(PyExc_TypeError,
10534 "'in <string>' requires string as left operand, not %s",
10535 element->ob_type->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010536 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010537 }
10538
Thomas Wouters477c8d52006-05-27 19:21:47 +000010539 str = PyUnicode_FromObject(container);
Benjamin Peterson22a29702012-01-02 09:00:30 -060010540 if (!str) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010541 Py_DECREF(sub);
10542 return -1;
10543 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060010544 if (PyUnicode_READY(sub) == -1 || PyUnicode_READY(str) == -1) {
10545 Py_DECREF(sub);
10546 Py_DECREF(str);
10547 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000010548
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010549 kind1 = PyUnicode_KIND(str);
10550 kind2 = PyUnicode_KIND(sub);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010551 kind = kind1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010552 buf1 = PyUnicode_DATA(str);
10553 buf2 = PyUnicode_DATA(sub);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010554 if (kind2 != kind) {
Antoine Pitrou758153b2012-05-12 15:51:51 +020010555 if (kind2 > kind) {
10556 Py_DECREF(sub);
10557 Py_DECREF(str);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010558 return 0;
Antoine Pitrou758153b2012-05-12 15:51:51 +020010559 }
Victor Stinner7931d9a2011-11-04 00:22:48 +010010560 buf2 = _PyUnicode_AsKind(sub, kind);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010561 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010562 if (!buf2) {
10563 Py_DECREF(sub);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010564 Py_DECREF(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010565 return -1;
10566 }
10567 len1 = PyUnicode_GET_LENGTH(str);
10568 len2 = PyUnicode_GET_LENGTH(sub);
10569
Benjamin Petersonead6b532011-12-20 17:23:42 -060010570 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010571 case PyUnicode_1BYTE_KIND:
10572 result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
10573 break;
10574 case PyUnicode_2BYTE_KIND:
10575 result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
10576 break;
10577 case PyUnicode_4BYTE_KIND:
10578 result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
10579 break;
10580 default:
10581 result = -1;
10582 assert(0);
10583 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000010584
10585 Py_DECREF(str);
10586 Py_DECREF(sub);
10587
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010588 if (kind2 != kind)
10589 PyMem_Free(buf2);
10590
Guido van Rossum403d68b2000-03-13 15:55:09 +000010591 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010592}
10593
Guido van Rossumd57fd912000-03-10 22:53:23 +000010594/* Concat to string or Unicode object giving a new Unicode object. */
10595
Alexander Belopolsky40018472011-02-26 01:02:56 +000010596PyObject *
10597PyUnicode_Concat(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010598{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010599 PyObject *u = NULL, *v = NULL, *w;
Victor Stinner127226b2011-10-13 01:12:34 +020010600 Py_UCS4 maxchar, maxchar2;
Victor Stinner488fa492011-12-12 00:01:39 +010010601 Py_ssize_t u_len, v_len, new_len;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010602
10603 /* Coerce the two arguments */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010604 u = PyUnicode_FromObject(left);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010605 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010606 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010607 v = PyUnicode_FromObject(right);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010608 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010609 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010610
10611 /* Shortcuts */
Victor Stinnera464fc12011-10-02 20:39:30 +020010612 if (v == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010613 Py_DECREF(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010614 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010615 }
Victor Stinnera464fc12011-10-02 20:39:30 +020010616 if (u == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010617 Py_DECREF(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010618 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010619 }
10620
Victor Stinner488fa492011-12-12 00:01:39 +010010621 u_len = PyUnicode_GET_LENGTH(u);
10622 v_len = PyUnicode_GET_LENGTH(v);
10623 if (u_len > PY_SSIZE_T_MAX - v_len) {
10624 PyErr_SetString(PyExc_OverflowError,
10625 "strings are too large to concat");
10626 goto onError;
10627 }
10628 new_len = u_len + v_len;
10629
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010630 maxchar = PyUnicode_MAX_CHAR_VALUE(u);
Victor Stinner127226b2011-10-13 01:12:34 +020010631 maxchar2 = PyUnicode_MAX_CHAR_VALUE(v);
Victor Stinnere6abb482012-05-02 01:15:40 +020010632 maxchar = MAX_MAXCHAR(maxchar, maxchar2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010633
Guido van Rossumd57fd912000-03-10 22:53:23 +000010634 /* Concat the two Unicode strings */
Victor Stinner488fa492011-12-12 00:01:39 +010010635 w = PyUnicode_New(new_len, maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010636 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010637 goto onError;
Victor Stinnerd3f08822012-05-29 12:57:52 +020010638 _PyUnicode_FastCopyCharacters(w, 0, u, 0, u_len);
10639 _PyUnicode_FastCopyCharacters(w, u_len, v, 0, v_len);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010640 Py_DECREF(u);
10641 Py_DECREF(v);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010642 assert(_PyUnicode_CheckConsistency(w, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010643 return w;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010644
Benjamin Peterson29060642009-01-31 22:14:21 +000010645 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000010646 Py_XDECREF(u);
10647 Py_XDECREF(v);
10648 return NULL;
10649}
10650
Walter Dörwald1ab83302007-05-18 17:15:44 +000010651void
Victor Stinner23e56682011-10-03 03:54:37 +020010652PyUnicode_Append(PyObject **p_left, PyObject *right)
Walter Dörwald1ab83302007-05-18 17:15:44 +000010653{
Victor Stinner23e56682011-10-03 03:54:37 +020010654 PyObject *left, *res;
Victor Stinner488fa492011-12-12 00:01:39 +010010655 Py_UCS4 maxchar, maxchar2;
10656 Py_ssize_t left_len, right_len, new_len;
Victor Stinner23e56682011-10-03 03:54:37 +020010657
10658 if (p_left == NULL) {
10659 if (!PyErr_Occurred())
10660 PyErr_BadInternalCall();
Benjamin Peterson14339b62009-01-31 16:36:08 +000010661 return;
10662 }
Victor Stinner23e56682011-10-03 03:54:37 +020010663 left = *p_left;
10664 if (right == NULL || !PyUnicode_Check(left)) {
10665 if (!PyErr_Occurred())
10666 PyErr_BadInternalCall();
10667 goto error;
10668 }
10669
Benjamin Petersonbac79492012-01-14 13:34:47 -050010670 if (PyUnicode_READY(left) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020010671 goto error;
Benjamin Petersonbac79492012-01-14 13:34:47 -050010672 if (PyUnicode_READY(right) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020010673 goto error;
10674
Victor Stinner488fa492011-12-12 00:01:39 +010010675 /* Shortcuts */
10676 if (left == unicode_empty) {
10677 Py_DECREF(left);
10678 Py_INCREF(right);
10679 *p_left = right;
10680 return;
10681 }
10682 if (right == unicode_empty)
10683 return;
10684
10685 left_len = PyUnicode_GET_LENGTH(left);
10686 right_len = PyUnicode_GET_LENGTH(right);
10687 if (left_len > PY_SSIZE_T_MAX - right_len) {
10688 PyErr_SetString(PyExc_OverflowError,
10689 "strings are too large to concat");
10690 goto error;
10691 }
10692 new_len = left_len + right_len;
10693
10694 if (unicode_modifiable(left)
10695 && PyUnicode_CheckExact(right)
10696 && PyUnicode_KIND(right) <= PyUnicode_KIND(left)
Victor Stinnerb0923652011-10-04 01:17:31 +020010697 /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
10698 to change the structure size, but characters are stored just after
Georg Brandl7597add2011-10-05 16:36:47 +020010699 the structure, and so it requires to move all characters which is
Victor Stinnerb0923652011-10-04 01:17:31 +020010700 not so different than duplicating the string. */
Victor Stinner488fa492011-12-12 00:01:39 +010010701 && !(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
10702 {
10703 /* append inplace */
10704 if (unicode_resize(p_left, new_len) != 0) {
10705 /* XXX if _PyUnicode_Resize() fails, 'left' has been
10706 * deallocated so it cannot be put back into
10707 * 'variable'. The MemoryError is raised when there
10708 * is no value in 'variable', which might (very
10709 * remotely) be a cause of incompatibilities.
10710 */
10711 goto error;
Victor Stinner23e56682011-10-03 03:54:37 +020010712 }
Victor Stinner488fa492011-12-12 00:01:39 +010010713 /* copy 'right' into the newly allocated area of 'left' */
Victor Stinnerd3f08822012-05-29 12:57:52 +020010714 _PyUnicode_FastCopyCharacters(*p_left, left_len, right, 0, right_len);
Victor Stinner23e56682011-10-03 03:54:37 +020010715 }
Victor Stinner488fa492011-12-12 00:01:39 +010010716 else {
10717 maxchar = PyUnicode_MAX_CHAR_VALUE(left);
10718 maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
Victor Stinnere6abb482012-05-02 01:15:40 +020010719 maxchar = MAX_MAXCHAR(maxchar, maxchar2);
Victor Stinner23e56682011-10-03 03:54:37 +020010720
Victor Stinner488fa492011-12-12 00:01:39 +010010721 /* Concat the two Unicode strings */
10722 res = PyUnicode_New(new_len, maxchar);
10723 if (res == NULL)
10724 goto error;
Victor Stinnerd3f08822012-05-29 12:57:52 +020010725 _PyUnicode_FastCopyCharacters(res, 0, left, 0, left_len);
10726 _PyUnicode_FastCopyCharacters(res, left_len, right, 0, right_len);
Victor Stinner488fa492011-12-12 00:01:39 +010010727 Py_DECREF(left);
10728 *p_left = res;
10729 }
10730 assert(_PyUnicode_CheckConsistency(*p_left, 1));
Victor Stinner23e56682011-10-03 03:54:37 +020010731 return;
10732
10733error:
Victor Stinner488fa492011-12-12 00:01:39 +010010734 Py_CLEAR(*p_left);
Walter Dörwald1ab83302007-05-18 17:15:44 +000010735}
10736
10737void
10738PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
10739{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010740 PyUnicode_Append(pleft, right);
10741 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +000010742}
10743
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010744PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010745 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010746\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000010747Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010748string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010749interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010750
10751static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010752unicode_count(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010753{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010754 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010755 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010756 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010757 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010758 int kind1, kind2, kind;
10759 void *buf1, *buf2;
10760 Py_ssize_t len1, len2, iresult;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010761
Jesus Ceaac451502011-04-20 17:09:23 +020010762 if (!stringlib_parse_args_finds_unicode("count", args, &substring,
10763 &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000010764 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000010765
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010766 kind1 = PyUnicode_KIND(self);
10767 kind2 = PyUnicode_KIND(substring);
Benjamin Petersonb63f49f2012-05-03 18:31:07 -040010768 if (kind2 > kind1)
10769 return PyLong_FromLong(0);
10770 kind = kind1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010771 buf1 = PyUnicode_DATA(self);
10772 buf2 = PyUnicode_DATA(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010773 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010774 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010775 if (!buf2) {
10776 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010777 return NULL;
10778 }
10779 len1 = PyUnicode_GET_LENGTH(self);
10780 len2 = PyUnicode_GET_LENGTH(substring);
10781
10782 ADJUST_INDICES(start, end, len1);
Benjamin Petersonead6b532011-12-20 17:23:42 -060010783 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010784 case PyUnicode_1BYTE_KIND:
10785 iresult = ucs1lib_count(
10786 ((Py_UCS1*)buf1) + start, end - start,
10787 buf2, len2, PY_SSIZE_T_MAX
10788 );
10789 break;
10790 case PyUnicode_2BYTE_KIND:
10791 iresult = ucs2lib_count(
10792 ((Py_UCS2*)buf1) + start, end - start,
10793 buf2, len2, PY_SSIZE_T_MAX
10794 );
10795 break;
10796 case PyUnicode_4BYTE_KIND:
10797 iresult = ucs4lib_count(
10798 ((Py_UCS4*)buf1) + start, end - start,
10799 buf2, len2, PY_SSIZE_T_MAX
10800 );
10801 break;
10802 default:
10803 assert(0); iresult = 0;
10804 }
10805
10806 result = PyLong_FromSsize_t(iresult);
10807
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010808 if (kind2 != kind)
10809 PyMem_Free(buf2);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010810
10811 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010812
Guido van Rossumd57fd912000-03-10 22:53:23 +000010813 return result;
10814}
10815
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010816PyDoc_STRVAR(encode__doc__,
Victor Stinnerc911bbf2010-11-07 19:04:46 +000010817 "S.encode(encoding='utf-8', errors='strict') -> bytes\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010818\n\
Victor Stinnere14e2122010-11-07 18:41:46 +000010819Encode S using the codec registered for encoding. Default encoding\n\
10820is 'utf-8'. errors may be given to set a different error\n\
Fred Drakee4315f52000-05-09 19:53:39 +000010821handling scheme. Default is 'strict' meaning that encoding errors raise\n\
Walter Dörwald3aeb6322002-09-02 13:14:32 +000010822a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
10823'xmlcharrefreplace' as well as any other name registered with\n\
10824codecs.register_error that can handle UnicodeEncodeErrors.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010825
10826static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010827unicode_encode(PyObject *self, PyObject *args, PyObject *kwargs)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010828{
Benjamin Peterson308d6372009-09-18 21:42:35 +000010829 static char *kwlist[] = {"encoding", "errors", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000010830 char *encoding = NULL;
10831 char *errors = NULL;
Guido van Rossum35d94282007-08-27 18:20:11 +000010832
Benjamin Peterson308d6372009-09-18 21:42:35 +000010833 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:encode",
10834 kwlist, &encoding, &errors))
Guido van Rossumd57fd912000-03-10 22:53:23 +000010835 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010836 return PyUnicode_AsEncodedString(self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +000010837}
10838
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010839PyDoc_STRVAR(expandtabs__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010840 "S.expandtabs([tabsize]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010841\n\
10842Return a copy of S where all tab characters are expanded using spaces.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010843If tabsize is not given, a tab size of 8 characters is assumed.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010844
10845static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010846unicode_expandtabs(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010847{
Antoine Pitroue71d5742011-10-04 15:55:09 +020010848 Py_ssize_t i, j, line_pos, src_len, incr;
10849 Py_UCS4 ch;
10850 PyObject *u;
10851 void *src_data, *dest_data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010852 int tabsize = 8;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010853 int kind;
Antoine Pitroue19aa382011-10-04 16:04:01 +020010854 int found;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010855
10856 if (!PyArg_ParseTuple(args, "|i:expandtabs", &tabsize))
Benjamin Peterson29060642009-01-31 22:14:21 +000010857 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010858
Antoine Pitrou22425222011-10-04 19:10:51 +020010859 if (PyUnicode_READY(self) == -1)
10860 return NULL;
10861
Thomas Wouters7e474022000-07-16 12:04:32 +000010862 /* First pass: determine size of output string */
Antoine Pitroue71d5742011-10-04 15:55:09 +020010863 src_len = PyUnicode_GET_LENGTH(self);
10864 i = j = line_pos = 0;
10865 kind = PyUnicode_KIND(self);
10866 src_data = PyUnicode_DATA(self);
Antoine Pitroue19aa382011-10-04 16:04:01 +020010867 found = 0;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010868 for (; i < src_len; i++) {
10869 ch = PyUnicode_READ(kind, src_data, i);
10870 if (ch == '\t') {
Antoine Pitroue19aa382011-10-04 16:04:01 +020010871 found = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000010872 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020010873 incr = tabsize - (line_pos % tabsize); /* cannot overflow */
Benjamin Peterson29060642009-01-31 22:14:21 +000010874 if (j > PY_SSIZE_T_MAX - incr)
Antoine Pitroue71d5742011-10-04 15:55:09 +020010875 goto overflow;
10876 line_pos += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000010877 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010878 }
Benjamin Peterson29060642009-01-31 22:14:21 +000010879 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010880 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000010881 if (j > PY_SSIZE_T_MAX - 1)
Antoine Pitroue71d5742011-10-04 15:55:09 +020010882 goto overflow;
10883 line_pos++;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010884 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010885 if (ch == '\n' || ch == '\r')
10886 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010887 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020010888 }
Victor Stinnerc4b49542011-12-11 22:44:26 +010010889 if (!found)
10890 return unicode_result_unchanged(self);
Guido van Rossumcd16bf62007-06-13 18:07:49 +000010891
Guido van Rossumd57fd912000-03-10 22:53:23 +000010892 /* Second pass: create output string and fill it */
Antoine Pitroue71d5742011-10-04 15:55:09 +020010893 u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +000010894 if (!u)
10895 return NULL;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010896 dest_data = PyUnicode_DATA(u);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010897
Antoine Pitroue71d5742011-10-04 15:55:09 +020010898 i = j = line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010899
Antoine Pitroue71d5742011-10-04 15:55:09 +020010900 for (; i < src_len; i++) {
10901 ch = PyUnicode_READ(kind, src_data, i);
10902 if (ch == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +000010903 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020010904 incr = tabsize - (line_pos % tabsize);
10905 line_pos += incr;
Victor Stinnerda79e632012-02-22 13:37:04 +010010906 FILL(kind, dest_data, ' ', j, incr);
10907 j += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000010908 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000010909 }
Benjamin Peterson29060642009-01-31 22:14:21 +000010910 else {
Antoine Pitroue71d5742011-10-04 15:55:09 +020010911 line_pos++;
10912 PyUnicode_WRITE(kind, dest_data, j, ch);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010913 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010914 if (ch == '\n' || ch == '\r')
10915 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010916 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020010917 }
10918 assert (j == PyUnicode_GET_LENGTH(u));
Victor Stinnerd3df8ab2011-11-22 01:22:34 +010010919 return unicode_result(u);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010920
Antoine Pitroue71d5742011-10-04 15:55:09 +020010921 overflow:
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010922 PyErr_SetString(PyExc_OverflowError, "new string is too long");
10923 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010924}
10925
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010926PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010927 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010928\n\
10929Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080010930such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010931arguments start and end are interpreted as in slice notation.\n\
10932\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010933Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010934
10935static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010936unicode_find(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010937{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010938 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000010939 Py_ssize_t start;
10940 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010941 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010942
Jesus Ceaac451502011-04-20 17:09:23 +020010943 if (!stringlib_parse_args_finds_unicode("find", args, &substring,
10944 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000010945 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010946
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010947 if (PyUnicode_READY(self) == -1)
10948 return NULL;
10949 if (PyUnicode_READY(substring) == -1)
10950 return NULL;
10951
Victor Stinner7931d9a2011-11-04 00:22:48 +010010952 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010953
10954 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010955
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010956 if (result == -2)
10957 return NULL;
10958
Christian Heimes217cfd12007-12-02 14:31:20 +000010959 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010960}
10961
10962static PyObject *
Victor Stinner2fe5ced2011-10-02 00:25:40 +020010963unicode_getitem(PyObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010964{
Victor Stinnerb6cd0142012-05-03 02:17:04 +020010965 void *data;
10966 enum PyUnicode_Kind kind;
10967 Py_UCS4 ch;
10968 PyObject *res;
10969
10970 if (!PyUnicode_Check(self) || PyUnicode_READY(self) == -1) {
10971 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010972 return NULL;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020010973 }
10974 if (index < 0 || index >= PyUnicode_GET_LENGTH(self)) {
10975 PyErr_SetString(PyExc_IndexError, "string index out of range");
10976 return NULL;
10977 }
10978 kind = PyUnicode_KIND(self);
10979 data = PyUnicode_DATA(self);
10980 ch = PyUnicode_READ(kind, data, index);
10981 if (ch < 256)
10982 return get_latin1_char(ch);
10983
10984 res = PyUnicode_New(1, ch);
10985 if (res == NULL)
10986 return NULL;
10987 kind = PyUnicode_KIND(res);
10988 data = PyUnicode_DATA(res);
10989 PyUnicode_WRITE(kind, data, 0, ch);
10990 assert(_PyUnicode_CheckConsistency(res, 1));
10991 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010992}
10993
Guido van Rossumc2504932007-09-18 19:42:40 +000010994/* Believe it or not, this produces the same value for ASCII strings
Mark Dickinson57e683e2011-09-24 18:18:40 +010010995 as bytes_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +000010996static Py_hash_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010997unicode_hash(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010998{
Guido van Rossumc2504932007-09-18 19:42:40 +000010999 Py_ssize_t len;
Mark Dickinson57e683e2011-09-24 18:18:40 +010011000 Py_uhash_t x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011001
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011002#ifdef Py_DEBUG
Benjamin Peterson69e97272012-02-21 11:08:50 -050011003 assert(_Py_HashSecret_Initialized);
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011004#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011005 if (_PyUnicode_HASH(self) != -1)
11006 return _PyUnicode_HASH(self);
11007 if (PyUnicode_READY(self) == -1)
11008 return -1;
11009 len = PyUnicode_GET_LENGTH(self);
Georg Brandl16fa2a12012-02-21 00:50:13 +010011010 /*
11011 We make the hash of the empty string be 0, rather than using
11012 (prefix ^ suffix), since this slightly obfuscates the hash secret
11013 */
11014 if (len == 0) {
11015 _PyUnicode_HASH(self) = 0;
11016 return 0;
11017 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011018
11019 /* The hash function as a macro, gets expanded three times below. */
Georg Brandl2fb477c2012-02-21 00:33:36 +010011020#define HASH(P) \
11021 x ^= (Py_uhash_t) *P << 7; \
11022 while (--len >= 0) \
11023 x = (_PyHASH_MULTIPLIER * x) ^ (Py_uhash_t) *P++; \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011024
Georg Brandl2fb477c2012-02-21 00:33:36 +010011025 x = (Py_uhash_t) _Py_HashSecret.prefix;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011026 switch (PyUnicode_KIND(self)) {
11027 case PyUnicode_1BYTE_KIND: {
11028 const unsigned char *c = PyUnicode_1BYTE_DATA(self);
11029 HASH(c);
11030 break;
11031 }
11032 case PyUnicode_2BYTE_KIND: {
11033 const Py_UCS2 *s = PyUnicode_2BYTE_DATA(self);
11034 HASH(s);
11035 break;
11036 }
11037 default: {
11038 Py_UCS4 *l;
11039 assert(PyUnicode_KIND(self) == PyUnicode_4BYTE_KIND &&
11040 "Impossible switch case in unicode_hash");
11041 l = PyUnicode_4BYTE_DATA(self);
11042 HASH(l);
11043 break;
11044 }
11045 }
Georg Brandl2fb477c2012-02-21 00:33:36 +010011046 x ^= (Py_uhash_t) PyUnicode_GET_LENGTH(self);
11047 x ^= (Py_uhash_t) _Py_HashSecret.suffix;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011048
Guido van Rossumc2504932007-09-18 19:42:40 +000011049 if (x == -1)
11050 x = -2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011051 _PyUnicode_HASH(self) = x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011052 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011053}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011054#undef HASH
Guido van Rossumd57fd912000-03-10 22:53:23 +000011055
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011056PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011057 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011058\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011059Like S.find() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011060
11061static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011062unicode_index(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011063{
Martin v. Löwis18e16552006-02-15 17:27:45 +000011064 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011065 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011066 Py_ssize_t start;
11067 Py_ssize_t end;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011068
Jesus Ceaac451502011-04-20 17:09:23 +020011069 if (!stringlib_parse_args_finds_unicode("index", args, &substring,
11070 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011071 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011072
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011073 if (PyUnicode_READY(self) == -1)
11074 return NULL;
11075 if (PyUnicode_READY(substring) == -1)
11076 return NULL;
11077
Victor Stinner7931d9a2011-11-04 00:22:48 +010011078 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011079
11080 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011081
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011082 if (result == -2)
11083 return NULL;
11084
Guido van Rossumd57fd912000-03-10 22:53:23 +000011085 if (result < 0) {
11086 PyErr_SetString(PyExc_ValueError, "substring not found");
11087 return NULL;
11088 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011089
Christian Heimes217cfd12007-12-02 14:31:20 +000011090 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011091}
11092
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011093PyDoc_STRVAR(islower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011094 "S.islower() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011095\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011096Return True if all cased characters in S are lowercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011097at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011098
11099static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011100unicode_islower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011101{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011102 Py_ssize_t i, length;
11103 int kind;
11104 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011105 int cased;
11106
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011107 if (PyUnicode_READY(self) == -1)
11108 return NULL;
11109 length = PyUnicode_GET_LENGTH(self);
11110 kind = PyUnicode_KIND(self);
11111 data = PyUnicode_DATA(self);
11112
Guido van Rossumd57fd912000-03-10 22:53:23 +000011113 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011114 if (length == 1)
11115 return PyBool_FromLong(
11116 Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011117
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011118 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011119 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011120 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011121
Guido van Rossumd57fd912000-03-10 22:53:23 +000011122 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011123 for (i = 0; i < length; i++) {
11124 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011125
Benjamin Peterson29060642009-01-31 22:14:21 +000011126 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
11127 return PyBool_FromLong(0);
11128 else if (!cased && Py_UNICODE_ISLOWER(ch))
11129 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011130 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011131 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011132}
11133
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011134PyDoc_STRVAR(isupper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011135 "S.isupper() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011136\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011137Return True if all cased characters in S are uppercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011138at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011139
11140static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011141unicode_isupper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011142{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011143 Py_ssize_t i, length;
11144 int kind;
11145 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011146 int cased;
11147
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011148 if (PyUnicode_READY(self) == -1)
11149 return NULL;
11150 length = PyUnicode_GET_LENGTH(self);
11151 kind = PyUnicode_KIND(self);
11152 data = PyUnicode_DATA(self);
11153
Guido van Rossumd57fd912000-03-10 22:53:23 +000011154 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011155 if (length == 1)
11156 return PyBool_FromLong(
11157 Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011158
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011159 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011160 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011161 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011162
Guido van Rossumd57fd912000-03-10 22:53:23 +000011163 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011164 for (i = 0; i < length; i++) {
11165 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011166
Benjamin Peterson29060642009-01-31 22:14:21 +000011167 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
11168 return PyBool_FromLong(0);
11169 else if (!cased && Py_UNICODE_ISUPPER(ch))
11170 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011171 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011172 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011173}
11174
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011175PyDoc_STRVAR(istitle__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011176 "S.istitle() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011177\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011178Return True if S is a titlecased string and there is at least one\n\
11179character in S, i.e. upper- and titlecase characters may only\n\
11180follow uncased characters and lowercase characters only cased ones.\n\
11181Return False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011182
11183static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011184unicode_istitle(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011185{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011186 Py_ssize_t i, length;
11187 int kind;
11188 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011189 int cased, previous_is_cased;
11190
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011191 if (PyUnicode_READY(self) == -1)
11192 return NULL;
11193 length = PyUnicode_GET_LENGTH(self);
11194 kind = PyUnicode_KIND(self);
11195 data = PyUnicode_DATA(self);
11196
Guido van Rossumd57fd912000-03-10 22:53:23 +000011197 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011198 if (length == 1) {
11199 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11200 return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
11201 (Py_UNICODE_ISUPPER(ch) != 0));
11202 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011203
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011204 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011205 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011206 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011207
Guido van Rossumd57fd912000-03-10 22:53:23 +000011208 cased = 0;
11209 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011210 for (i = 0; i < length; i++) {
11211 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011212
Benjamin Peterson29060642009-01-31 22:14:21 +000011213 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
11214 if (previous_is_cased)
11215 return PyBool_FromLong(0);
11216 previous_is_cased = 1;
11217 cased = 1;
11218 }
11219 else if (Py_UNICODE_ISLOWER(ch)) {
11220 if (!previous_is_cased)
11221 return PyBool_FromLong(0);
11222 previous_is_cased = 1;
11223 cased = 1;
11224 }
11225 else
11226 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011227 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011228 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011229}
11230
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011231PyDoc_STRVAR(isspace__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011232 "S.isspace() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011233\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011234Return True if all characters in S are whitespace\n\
11235and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011236
11237static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011238unicode_isspace(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011239{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011240 Py_ssize_t i, length;
11241 int kind;
11242 void *data;
11243
11244 if (PyUnicode_READY(self) == -1)
11245 return NULL;
11246 length = PyUnicode_GET_LENGTH(self);
11247 kind = PyUnicode_KIND(self);
11248 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011249
Guido van Rossumd57fd912000-03-10 22:53:23 +000011250 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011251 if (length == 1)
11252 return PyBool_FromLong(
11253 Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011254
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011255 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011256 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011257 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011258
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011259 for (i = 0; i < length; i++) {
11260 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011261 if (!Py_UNICODE_ISSPACE(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011262 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011263 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011264 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011265}
11266
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011267PyDoc_STRVAR(isalpha__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011268 "S.isalpha() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011269\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011270Return True if all characters in S are alphabetic\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011271and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011272
11273static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011274unicode_isalpha(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011275{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011276 Py_ssize_t i, length;
11277 int kind;
11278 void *data;
11279
11280 if (PyUnicode_READY(self) == -1)
11281 return NULL;
11282 length = PyUnicode_GET_LENGTH(self);
11283 kind = PyUnicode_KIND(self);
11284 data = PyUnicode_DATA(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011285
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011286 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011287 if (length == 1)
11288 return PyBool_FromLong(
11289 Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011290
11291 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011292 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011293 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011294
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011295 for (i = 0; i < length; i++) {
11296 if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011297 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011298 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011299 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011300}
11301
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011302PyDoc_STRVAR(isalnum__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011303 "S.isalnum() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011304\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011305Return True if all characters in S are alphanumeric\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011306and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011307
11308static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011309unicode_isalnum(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011310{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011311 int kind;
11312 void *data;
11313 Py_ssize_t len, i;
11314
11315 if (PyUnicode_READY(self) == -1)
11316 return NULL;
11317
11318 kind = PyUnicode_KIND(self);
11319 data = PyUnicode_DATA(self);
11320 len = PyUnicode_GET_LENGTH(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011321
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011322 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011323 if (len == 1) {
11324 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11325 return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
11326 }
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011327
11328 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011329 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011330 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011331
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011332 for (i = 0; i < len; i++) {
11333 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011334 if (!Py_UNICODE_ISALNUM(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011335 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011336 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011337 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011338}
11339
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011340PyDoc_STRVAR(isdecimal__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011341 "S.isdecimal() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011342\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011343Return True if there are only decimal characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011344False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011345
11346static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011347unicode_isdecimal(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011348{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011349 Py_ssize_t i, length;
11350 int kind;
11351 void *data;
11352
11353 if (PyUnicode_READY(self) == -1)
11354 return NULL;
11355 length = PyUnicode_GET_LENGTH(self);
11356 kind = PyUnicode_KIND(self);
11357 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011358
Guido van Rossumd57fd912000-03-10 22:53:23 +000011359 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011360 if (length == 1)
11361 return PyBool_FromLong(
11362 Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011363
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011364 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011365 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011366 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011367
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011368 for (i = 0; i < length; i++) {
11369 if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011370 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011371 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011372 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011373}
11374
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011375PyDoc_STRVAR(isdigit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011376 "S.isdigit() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011377\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011378Return True if all characters in S are digits\n\
11379and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011380
11381static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011382unicode_isdigit(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011383{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011384 Py_ssize_t i, length;
11385 int kind;
11386 void *data;
11387
11388 if (PyUnicode_READY(self) == -1)
11389 return NULL;
11390 length = PyUnicode_GET_LENGTH(self);
11391 kind = PyUnicode_KIND(self);
11392 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011393
Guido van Rossumd57fd912000-03-10 22:53:23 +000011394 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011395 if (length == 1) {
11396 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11397 return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
11398 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011399
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011400 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011401 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011402 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011403
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011404 for (i = 0; i < length; i++) {
11405 if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011406 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011407 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011408 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011409}
11410
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011411PyDoc_STRVAR(isnumeric__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011412 "S.isnumeric() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011413\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011414Return True if there are only numeric characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011415False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011416
11417static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011418unicode_isnumeric(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011419{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011420 Py_ssize_t i, length;
11421 int kind;
11422 void *data;
11423
11424 if (PyUnicode_READY(self) == -1)
11425 return NULL;
11426 length = PyUnicode_GET_LENGTH(self);
11427 kind = PyUnicode_KIND(self);
11428 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011429
Guido van Rossumd57fd912000-03-10 22:53:23 +000011430 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011431 if (length == 1)
11432 return PyBool_FromLong(
11433 Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011434
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011435 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011436 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011437 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011438
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011439 for (i = 0; i < length; i++) {
11440 if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011441 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011442 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011443 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011444}
11445
Martin v. Löwis47383402007-08-15 07:32:56 +000011446int
11447PyUnicode_IsIdentifier(PyObject *self)
11448{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011449 int kind;
11450 void *data;
11451 Py_ssize_t i;
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011452 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +000011453
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011454 if (PyUnicode_READY(self) == -1) {
11455 Py_FatalError("identifier not ready");
Benjamin Peterson29060642009-01-31 22:14:21 +000011456 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011457 }
11458
11459 /* Special case for empty strings */
11460 if (PyUnicode_GET_LENGTH(self) == 0)
11461 return 0;
11462 kind = PyUnicode_KIND(self);
11463 data = PyUnicode_DATA(self);
Martin v. Löwis47383402007-08-15 07:32:56 +000011464
11465 /* PEP 3131 says that the first character must be in
11466 XID_Start and subsequent characters in XID_Continue,
11467 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +000011468 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +000011469 letters, digits, underscore). However, given the current
11470 definition of XID_Start and XID_Continue, it is sufficient
11471 to check just for these, except that _ must be allowed
11472 as starting an identifier. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011473 first = PyUnicode_READ(kind, data, 0);
Benjamin Petersonf413b802011-08-12 22:17:18 -050011474 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +000011475 return 0;
11476
Benjamin Peterson9c6e6a02011-09-28 08:09:05 -040011477 for (i = 1; i < PyUnicode_GET_LENGTH(self); i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011478 if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011479 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +000011480 return 1;
11481}
11482
11483PyDoc_STRVAR(isidentifier__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011484 "S.isidentifier() -> bool\n\
Martin v. Löwis47383402007-08-15 07:32:56 +000011485\n\
11486Return True if S is a valid identifier according\n\
11487to the language definition.");
11488
11489static PyObject*
11490unicode_isidentifier(PyObject *self)
11491{
11492 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
11493}
11494
Georg Brandl559e5d72008-06-11 18:37:52 +000011495PyDoc_STRVAR(isprintable__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011496 "S.isprintable() -> bool\n\
Georg Brandl559e5d72008-06-11 18:37:52 +000011497\n\
11498Return True if all characters in S are considered\n\
11499printable in repr() or S is empty, False otherwise.");
11500
11501static PyObject*
11502unicode_isprintable(PyObject *self)
11503{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011504 Py_ssize_t i, length;
11505 int kind;
11506 void *data;
11507
11508 if (PyUnicode_READY(self) == -1)
11509 return NULL;
11510 length = PyUnicode_GET_LENGTH(self);
11511 kind = PyUnicode_KIND(self);
11512 data = PyUnicode_DATA(self);
Georg Brandl559e5d72008-06-11 18:37:52 +000011513
11514 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011515 if (length == 1)
11516 return PyBool_FromLong(
11517 Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
Georg Brandl559e5d72008-06-11 18:37:52 +000011518
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011519 for (i = 0; i < length; i++) {
11520 if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
Georg Brandl559e5d72008-06-11 18:37:52 +000011521 Py_RETURN_FALSE;
11522 }
11523 }
11524 Py_RETURN_TRUE;
11525}
11526
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011527PyDoc_STRVAR(join__doc__,
Georg Brandl495f7b52009-10-27 15:28:25 +000011528 "S.join(iterable) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011529\n\
11530Return a string which is the concatenation of the strings in the\n\
Georg Brandl495f7b52009-10-27 15:28:25 +000011531iterable. The separator between elements is S.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011532
11533static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011534unicode_join(PyObject *self, PyObject *data)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011535{
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011536 return PyUnicode_Join(self, data);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011537}
11538
Martin v. Löwis18e16552006-02-15 17:27:45 +000011539static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011540unicode_length(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011541{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011542 if (PyUnicode_READY(self) == -1)
11543 return -1;
11544 return PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011545}
11546
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011547PyDoc_STRVAR(ljust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011548 "S.ljust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011549\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000011550Return S left-justified in a Unicode string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011551done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011552
11553static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020011554unicode_ljust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011555{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011556 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011557 Py_UCS4 fillchar = ' ';
11558
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011559 if (!PyArg_ParseTuple(args, "n|O&:ljust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011560 return NULL;
11561
Benjamin Petersonbac79492012-01-14 13:34:47 -050011562 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010011563 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011564
Victor Stinnerc4b49542011-12-11 22:44:26 +010011565 if (PyUnicode_GET_LENGTH(self) >= width)
11566 return unicode_result_unchanged(self);
11567
11568 return pad(self, 0, width - PyUnicode_GET_LENGTH(self), fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011569}
11570
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011571PyDoc_STRVAR(lower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011572 "S.lower() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011573\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011574Return a copy of the string S converted to lowercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011575
11576static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020011577unicode_lower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011578{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050011579 if (PyUnicode_READY(self) == -1)
11580 return NULL;
11581 if (PyUnicode_IS_ASCII(self))
11582 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010011583 return case_operation(self, do_lower);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011584}
11585
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011586#define LEFTSTRIP 0
11587#define RIGHTSTRIP 1
11588#define BOTHSTRIP 2
11589
11590/* Arrays indexed by above */
11591static const char *stripformat[] = {"|O:lstrip", "|O:rstrip", "|O:strip"};
11592
11593#define STRIPNAME(i) (stripformat[i]+3)
11594
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011595/* externally visible for str.strip(unicode) */
11596PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011597_PyUnicode_XStrip(PyObject *self, int striptype, PyObject *sepobj)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011598{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011599 void *data;
11600 int kind;
11601 Py_ssize_t i, j, len;
11602 BLOOM_MASK sepmask;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011603
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011604 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
11605 return NULL;
11606
11607 kind = PyUnicode_KIND(self);
11608 data = PyUnicode_DATA(self);
11609 len = PyUnicode_GET_LENGTH(self);
11610 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
11611 PyUnicode_DATA(sepobj),
11612 PyUnicode_GET_LENGTH(sepobj));
Thomas Wouters477c8d52006-05-27 19:21:47 +000011613
Benjamin Peterson14339b62009-01-31 16:36:08 +000011614 i = 0;
11615 if (striptype != RIGHTSTRIP) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011616 while (i < len &&
11617 BLOOM_MEMBER(sepmask, PyUnicode_READ(kind, data, i), sepobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011618 i++;
11619 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011620 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011621
Benjamin Peterson14339b62009-01-31 16:36:08 +000011622 j = len;
11623 if (striptype != LEFTSTRIP) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011624 do {
11625 j--;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011626 } while (j >= i &&
11627 BLOOM_MEMBER(sepmask, PyUnicode_READ(kind, data, j), sepobj));
Benjamin Peterson29060642009-01-31 22:14:21 +000011628 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011629 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011630
Victor Stinner7931d9a2011-11-04 00:22:48 +010011631 return PyUnicode_Substring(self, i, j);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011632}
11633
11634PyObject*
11635PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
11636{
11637 unsigned char *data;
11638 int kind;
Victor Stinner12bab6d2011-10-01 01:53:49 +020011639 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011640
Victor Stinnerde636f32011-10-01 03:55:54 +020011641 if (PyUnicode_READY(self) == -1)
11642 return NULL;
11643
Victor Stinner684d5fd2012-05-03 02:32:34 +020011644 length = PyUnicode_GET_LENGTH(self);
11645 end = Py_MIN(end, length);
Victor Stinnerde636f32011-10-01 03:55:54 +020011646
Victor Stinner684d5fd2012-05-03 02:32:34 +020011647 if (start == 0 && end == length)
Victor Stinnerc4b49542011-12-11 22:44:26 +010011648 return unicode_result_unchanged(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011649
Victor Stinnerde636f32011-10-01 03:55:54 +020011650 if (start < 0 || end < 0) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020011651 PyErr_SetString(PyExc_IndexError, "string index out of range");
11652 return NULL;
11653 }
Victor Stinner684d5fd2012-05-03 02:32:34 +020011654 if (start >= length || end < start) {
Victor Stinner3a7f79772012-05-03 03:36:40 +020011655 Py_INCREF(unicode_empty);
11656 return unicode_empty;
Victor Stinner684d5fd2012-05-03 02:32:34 +020011657 }
Victor Stinner12bab6d2011-10-01 01:53:49 +020011658
Victor Stinner684d5fd2012-05-03 02:32:34 +020011659 length = end - start;
Victor Stinnerb9275c12011-10-05 14:01:42 +020011660 if (PyUnicode_IS_ASCII(self)) {
Victor Stinnerb9275c12011-10-05 14:01:42 +020011661 data = PyUnicode_1BYTE_DATA(self);
Victor Stinnerd3f08822012-05-29 12:57:52 +020011662 return _PyUnicode_FromASCII((char*)(data + start), length);
Victor Stinnerb9275c12011-10-05 14:01:42 +020011663 }
11664 else {
11665 kind = PyUnicode_KIND(self);
11666 data = PyUnicode_1BYTE_DATA(self);
11667 return PyUnicode_FromKindAndData(kind,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020011668 data + kind * start,
Victor Stinnerb9275c12011-10-05 14:01:42 +020011669 length);
11670 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011671}
Guido van Rossumd57fd912000-03-10 22:53:23 +000011672
11673static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011674do_strip(PyObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011675{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011676 int kind;
11677 void *data;
11678 Py_ssize_t len, i, j;
11679
11680 if (PyUnicode_READY(self) == -1)
11681 return NULL;
11682
11683 kind = PyUnicode_KIND(self);
11684 data = PyUnicode_DATA(self);
11685 len = PyUnicode_GET_LENGTH(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011686
Benjamin Peterson14339b62009-01-31 16:36:08 +000011687 i = 0;
11688 if (striptype != RIGHTSTRIP) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011689 while (i < len && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, i))) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000011690 i++;
11691 }
11692 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011693
Benjamin Peterson14339b62009-01-31 16:36:08 +000011694 j = len;
11695 if (striptype != LEFTSTRIP) {
11696 do {
11697 j--;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011698 } while (j >= i && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, j)));
Benjamin Peterson14339b62009-01-31 16:36:08 +000011699 j++;
11700 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011701
Victor Stinner7931d9a2011-11-04 00:22:48 +010011702 return PyUnicode_Substring(self, i, j);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011703}
11704
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011705
11706static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011707do_argstrip(PyObject *self, int striptype, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011708{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011709 PyObject *sep = NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011710
Benjamin Peterson14339b62009-01-31 16:36:08 +000011711 if (!PyArg_ParseTuple(args, (char *)stripformat[striptype], &sep))
11712 return NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011713
Benjamin Peterson14339b62009-01-31 16:36:08 +000011714 if (sep != NULL && sep != Py_None) {
11715 if (PyUnicode_Check(sep))
11716 return _PyUnicode_XStrip(self, striptype, sep);
11717 else {
11718 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000011719 "%s arg must be None or str",
11720 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +000011721 return NULL;
11722 }
11723 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011724
Benjamin Peterson14339b62009-01-31 16:36:08 +000011725 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011726}
11727
11728
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011729PyDoc_STRVAR(strip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011730 "S.strip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011731\n\
11732Return a copy of the string S with leading and trailing\n\
11733whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011734If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011735
11736static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011737unicode_strip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011738{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011739 if (PyTuple_GET_SIZE(args) == 0)
11740 return do_strip(self, BOTHSTRIP); /* Common case */
11741 else
11742 return do_argstrip(self, BOTHSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011743}
11744
11745
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011746PyDoc_STRVAR(lstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011747 "S.lstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011748\n\
11749Return a copy of the string S with leading whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011750If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011751
11752static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011753unicode_lstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011754{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011755 if (PyTuple_GET_SIZE(args) == 0)
11756 return do_strip(self, LEFTSTRIP); /* Common case */
11757 else
11758 return do_argstrip(self, LEFTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011759}
11760
11761
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011762PyDoc_STRVAR(rstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011763 "S.rstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011764\n\
11765Return a copy of the string S with trailing whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011766If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011767
11768static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011769unicode_rstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011770{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011771 if (PyTuple_GET_SIZE(args) == 0)
11772 return do_strip(self, RIGHTSTRIP); /* Common case */
11773 else
11774 return do_argstrip(self, RIGHTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011775}
11776
11777
Guido van Rossumd57fd912000-03-10 22:53:23 +000011778static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011779unicode_repeat(PyObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011780{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011781 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011782 Py_ssize_t nchars, n;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011783
Georg Brandl222de0f2009-04-12 12:01:50 +000011784 if (len < 1) {
11785 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +020011786 return unicode_empty;
Georg Brandl222de0f2009-04-12 12:01:50 +000011787 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011788
Victor Stinnerc4b49542011-12-11 22:44:26 +010011789 /* no repeat, return original string */
11790 if (len == 1)
11791 return unicode_result_unchanged(str);
Tim Peters8f422462000-09-09 06:13:41 +000011792
Benjamin Petersonbac79492012-01-14 13:34:47 -050011793 if (PyUnicode_READY(str) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011794 return NULL;
11795
Victor Stinnerc759f3e2011-10-01 03:09:58 +020011796 if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
Victor Stinner67ca64c2011-10-01 02:47:29 +020011797 PyErr_SetString(PyExc_OverflowError,
11798 "repeated string is too long");
11799 return NULL;
11800 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011801 nchars = len * PyUnicode_GET_LENGTH(str);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011802
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011803 u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011804 if (!u)
11805 return NULL;
Victor Stinner67ca64c2011-10-01 02:47:29 +020011806 assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011807
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011808 if (PyUnicode_GET_LENGTH(str) == 1) {
11809 const int kind = PyUnicode_KIND(str);
11810 const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
Victor Stinner73f53b52011-12-18 03:26:31 +010011811 if (kind == PyUnicode_1BYTE_KIND) {
11812 void *to = PyUnicode_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011813 memset(to, (unsigned char)fill_char, len);
Victor Stinner73f53b52011-12-18 03:26:31 +010011814 }
11815 else if (kind == PyUnicode_2BYTE_KIND) {
11816 Py_UCS2 *ucs2 = PyUnicode_2BYTE_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011817 for (n = 0; n < len; ++n)
Victor Stinner73f53b52011-12-18 03:26:31 +010011818 ucs2[n] = fill_char;
11819 } else {
11820 Py_UCS4 *ucs4 = PyUnicode_4BYTE_DATA(u);
11821 assert(kind == PyUnicode_4BYTE_KIND);
11822 for (n = 0; n < len; ++n)
11823 ucs4[n] = fill_char;
Victor Stinner67ca64c2011-10-01 02:47:29 +020011824 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011825 }
11826 else {
11827 /* number of characters copied this far */
11828 Py_ssize_t done = PyUnicode_GET_LENGTH(str);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020011829 const Py_ssize_t char_size = PyUnicode_KIND(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011830 char *to = (char *) PyUnicode_DATA(u);
11831 Py_MEMCPY(to, PyUnicode_DATA(str),
11832 PyUnicode_GET_LENGTH(str) * char_size);
Benjamin Peterson29060642009-01-31 22:14:21 +000011833 while (done < nchars) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011834 n = (done <= nchars-done) ? done : nchars-done;
11835 Py_MEMCPY(to + (done * char_size), to, n * char_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011836 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +000011837 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011838 }
11839
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020011840 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011841 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011842}
11843
Alexander Belopolsky40018472011-02-26 01:02:56 +000011844PyObject *
11845PyUnicode_Replace(PyObject *obj,
11846 PyObject *subobj,
11847 PyObject *replobj,
11848 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011849{
11850 PyObject *self;
11851 PyObject *str1;
11852 PyObject *str2;
11853 PyObject *result;
11854
11855 self = PyUnicode_FromObject(obj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060011856 if (self == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000011857 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011858 str1 = PyUnicode_FromObject(subobj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060011859 if (str1 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011860 Py_DECREF(self);
11861 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011862 }
11863 str2 = PyUnicode_FromObject(replobj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060011864 if (str2 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011865 Py_DECREF(self);
11866 Py_DECREF(str1);
11867 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011868 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060011869 if (PyUnicode_READY(self) == -1 ||
11870 PyUnicode_READY(str1) == -1 ||
11871 PyUnicode_READY(str2) == -1)
11872 result = NULL;
11873 else
11874 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011875 Py_DECREF(self);
11876 Py_DECREF(str1);
11877 Py_DECREF(str2);
11878 return result;
11879}
11880
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011881PyDoc_STRVAR(replace__doc__,
Ezio Melottic1897e72010-06-26 18:50:39 +000011882 "S.replace(old, new[, count]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011883\n\
11884Return a copy of S with all occurrences of substring\n\
Georg Brandlf08a9dd2008-06-10 16:57:31 +000011885old replaced by new. If the optional argument count is\n\
11886given, only the first count occurrences are replaced.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011887
11888static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011889unicode_replace(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011890{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011891 PyObject *str1;
11892 PyObject *str2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011893 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011894 PyObject *result;
11895
Martin v. Löwis18e16552006-02-15 17:27:45 +000011896 if (!PyArg_ParseTuple(args, "OO|n:replace", &str1, &str2, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011897 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060011898 if (PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000011899 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011900 str1 = PyUnicode_FromObject(str1);
Benjamin Peterson22a29702012-01-02 09:00:30 -060011901 if (str1 == NULL)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011902 return NULL;
11903 str2 = PyUnicode_FromObject(str2);
Benjamin Peterson22a29702012-01-02 09:00:30 -060011904 if (str2 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011905 Py_DECREF(str1);
11906 return NULL;
Walter Dörwaldf6b56ae2003-02-09 23:42:56 +000011907 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060011908 if (PyUnicode_READY(str1) == -1 || PyUnicode_READY(str2) == -1)
11909 result = NULL;
11910 else
11911 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011912
11913 Py_DECREF(str1);
11914 Py_DECREF(str2);
11915 return result;
11916}
11917
Alexander Belopolsky40018472011-02-26 01:02:56 +000011918static PyObject *
11919unicode_repr(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011920{
Walter Dörwald79e913e2007-05-12 11:08:06 +000011921 PyObject *repr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011922 Py_ssize_t isize;
11923 Py_ssize_t osize, squote, dquote, i, o;
11924 Py_UCS4 max, quote;
11925 int ikind, okind;
11926 void *idata, *odata;
Walter Dörwald79e913e2007-05-12 11:08:06 +000011927
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011928 if (PyUnicode_READY(unicode) == -1)
Walter Dörwald79e913e2007-05-12 11:08:06 +000011929 return NULL;
11930
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011931 isize = PyUnicode_GET_LENGTH(unicode);
11932 idata = PyUnicode_DATA(unicode);
Walter Dörwald79e913e2007-05-12 11:08:06 +000011933
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011934 /* Compute length of output, quote characters, and
11935 maximum character */
11936 osize = 2; /* quotes */
11937 max = 127;
11938 squote = dquote = 0;
11939 ikind = PyUnicode_KIND(unicode);
11940 for (i = 0; i < isize; i++) {
11941 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
11942 switch (ch) {
11943 case '\'': squote++; osize++; break;
11944 case '"': dquote++; osize++; break;
11945 case '\\': case '\t': case '\r': case '\n':
11946 osize += 2; break;
11947 default:
11948 /* Fast-path ASCII */
11949 if (ch < ' ' || ch == 0x7f)
11950 osize += 4; /* \xHH */
11951 else if (ch < 0x7f)
11952 osize++;
11953 else if (Py_UNICODE_ISPRINTABLE(ch)) {
11954 osize++;
11955 max = ch > max ? ch : max;
11956 }
11957 else if (ch < 0x100)
11958 osize += 4; /* \xHH */
11959 else if (ch < 0x10000)
11960 osize += 6; /* \uHHHH */
11961 else
11962 osize += 10; /* \uHHHHHHHH */
11963 }
11964 }
11965
11966 quote = '\'';
11967 if (squote) {
11968 if (dquote)
11969 /* Both squote and dquote present. Use squote,
11970 and escape them */
11971 osize += squote;
11972 else
11973 quote = '"';
11974 }
11975
11976 repr = PyUnicode_New(osize, max);
11977 if (repr == NULL)
11978 return NULL;
11979 okind = PyUnicode_KIND(repr);
11980 odata = PyUnicode_DATA(repr);
11981
11982 PyUnicode_WRITE(okind, odata, 0, quote);
11983 PyUnicode_WRITE(okind, odata, osize-1, quote);
11984
11985 for (i = 0, o = 1; i < isize; i++) {
11986 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Walter Dörwald79e913e2007-05-12 11:08:06 +000011987
11988 /* Escape quotes and backslashes */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011989 if ((ch == quote) || (ch == '\\')) {
11990 PyUnicode_WRITE(okind, odata, o++, '\\');
11991 PyUnicode_WRITE(okind, odata, o++, ch);
Walter Dörwald79e913e2007-05-12 11:08:06 +000011992 continue;
11993 }
11994
Benjamin Peterson29060642009-01-31 22:14:21 +000011995 /* Map special whitespace to '\t', \n', '\r' */
Georg Brandl559e5d72008-06-11 18:37:52 +000011996 if (ch == '\t') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011997 PyUnicode_WRITE(okind, odata, o++, '\\');
11998 PyUnicode_WRITE(okind, odata, o++, 't');
Walter Dörwald79e913e2007-05-12 11:08:06 +000011999 }
12000 else if (ch == '\n') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012001 PyUnicode_WRITE(okind, odata, o++, '\\');
12002 PyUnicode_WRITE(okind, odata, o++, 'n');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012003 }
12004 else if (ch == '\r') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012005 PyUnicode_WRITE(okind, odata, o++, '\\');
12006 PyUnicode_WRITE(okind, odata, o++, 'r');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012007 }
12008
12009 /* Map non-printable US ASCII to '\xhh' */
Georg Brandl559e5d72008-06-11 18:37:52 +000012010 else if (ch < ' ' || ch == 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012011 PyUnicode_WRITE(okind, odata, o++, '\\');
12012 PyUnicode_WRITE(okind, odata, o++, 'x');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012013 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12014 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012015 }
12016
Georg Brandl559e5d72008-06-11 18:37:52 +000012017 /* Copy ASCII characters as-is */
12018 else if (ch < 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012019 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000012020 }
12021
Benjamin Peterson29060642009-01-31 22:14:21 +000012022 /* Non-ASCII characters */
Georg Brandl559e5d72008-06-11 18:37:52 +000012023 else {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012024 /* Map Unicode whitespace and control characters
Georg Brandl559e5d72008-06-11 18:37:52 +000012025 (categories Z* and C* except ASCII space)
12026 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012027 if (!Py_UNICODE_ISPRINTABLE(ch)) {
Kristján Valur Jónsson55e5dc82012-06-06 21:58:08 +000012028 PyUnicode_WRITE(okind, odata, o++, '\\');
Georg Brandl559e5d72008-06-11 18:37:52 +000012029 /* Map 8-bit characters to '\xhh' */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012030 if (ch <= 0xff) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012031 PyUnicode_WRITE(okind, odata, o++, 'x');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012032 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12033 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012034 }
Kristján Valur Jónsson55e5dc82012-06-06 21:58:08 +000012035 /* Map 16-bit characters to '\uxxxx' */
12036 else if (ch <= 0xffff) {
12037 PyUnicode_WRITE(okind, odata, o++, 'u');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012038 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12039 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12040 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12041 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012042 }
Kristján Valur Jónsson55e5dc82012-06-06 21:58:08 +000012043 /* Map 21-bit characters to '\U00xxxxxx' */
Georg Brandl559e5d72008-06-11 18:37:52 +000012044 else {
Kristján Valur Jónsson55e5dc82012-06-06 21:58:08 +000012045 PyUnicode_WRITE(okind, odata, o++, 'U');
12046 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 28) & 0xF]);
12047 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 24) & 0xF]);
12048 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 20) & 0xF]);
12049 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 16) & 0xF]);
Victor Stinnerf5cff562011-10-14 02:13:11 +020012050 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12051 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12052 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12053 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012054 }
12055 }
12056 /* Copy characters as-is */
12057 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012058 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000012059 }
12060 }
Walter Dörwald79e913e2007-05-12 11:08:06 +000012061 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012062 /* Closing quote already added at the beginning */
Victor Stinner05d11892011-10-06 01:13:58 +020012063 assert(_PyUnicode_CheckConsistency(repr, 1));
Walter Dörwald79e913e2007-05-12 11:08:06 +000012064 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012065}
12066
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012067PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012068 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012069\n\
12070Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080012071such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012072arguments start and end are interpreted as in slice notation.\n\
12073\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012074Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012075
12076static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012077unicode_rfind(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012078{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012079 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012080 Py_ssize_t start;
12081 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012082 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012083
Jesus Ceaac451502011-04-20 17:09:23 +020012084 if (!stringlib_parse_args_finds_unicode("rfind", args, &substring,
12085 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012086 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012087
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012088 if (PyUnicode_READY(self) == -1)
12089 return NULL;
12090 if (PyUnicode_READY(substring) == -1)
12091 return NULL;
12092
Victor Stinner7931d9a2011-11-04 00:22:48 +010012093 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012094
12095 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012096
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012097 if (result == -2)
12098 return NULL;
12099
Christian Heimes217cfd12007-12-02 14:31:20 +000012100 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012101}
12102
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012103PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012104 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012105\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012106Like S.rfind() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012107
12108static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012109unicode_rindex(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012110{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012111 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012112 Py_ssize_t start;
12113 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012114 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012115
Jesus Ceaac451502011-04-20 17:09:23 +020012116 if (!stringlib_parse_args_finds_unicode("rindex", args, &substring,
12117 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012118 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012119
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012120 if (PyUnicode_READY(self) == -1)
12121 return NULL;
12122 if (PyUnicode_READY(substring) == -1)
12123 return NULL;
12124
Victor Stinner7931d9a2011-11-04 00:22:48 +010012125 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012126
12127 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012128
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012129 if (result == -2)
12130 return NULL;
12131
Guido van Rossumd57fd912000-03-10 22:53:23 +000012132 if (result < 0) {
12133 PyErr_SetString(PyExc_ValueError, "substring not found");
12134 return NULL;
12135 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012136
Christian Heimes217cfd12007-12-02 14:31:20 +000012137 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012138}
12139
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012140PyDoc_STRVAR(rjust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012141 "S.rjust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012142\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012143Return S right-justified in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012144done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012145
12146static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012147unicode_rjust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012148{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012149 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012150 Py_UCS4 fillchar = ' ';
12151
Victor Stinnere9a29352011-10-01 02:14:59 +020012152 if (!PyArg_ParseTuple(args, "n|O&:rjust", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012153 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012154
Benjamin Petersonbac79492012-01-14 13:34:47 -050012155 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012156 return NULL;
12157
Victor Stinnerc4b49542011-12-11 22:44:26 +010012158 if (PyUnicode_GET_LENGTH(self) >= width)
12159 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012160
Victor Stinnerc4b49542011-12-11 22:44:26 +010012161 return pad(self, width - PyUnicode_GET_LENGTH(self), 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012162}
12163
Alexander Belopolsky40018472011-02-26 01:02:56 +000012164PyObject *
12165PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012166{
12167 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +000012168
Guido van Rossumd57fd912000-03-10 22:53:23 +000012169 s = PyUnicode_FromObject(s);
12170 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012171 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012172 if (sep != NULL) {
12173 sep = PyUnicode_FromObject(sep);
12174 if (sep == NULL) {
12175 Py_DECREF(s);
12176 return NULL;
12177 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012178 }
12179
Victor Stinner9310abb2011-10-05 00:59:23 +020012180 result = split(s, sep, maxsplit);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012181
12182 Py_DECREF(s);
12183 Py_XDECREF(sep);
12184 return result;
12185}
12186
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012187PyDoc_STRVAR(split__doc__,
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012188 "S.split(sep=None, maxsplit=-1) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012189\n\
12190Return a list of the words in S, using sep as the\n\
12191delimiter string. If maxsplit is given, at most maxsplit\n\
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000012192splits are done. If sep is not specified or is None, any\n\
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +000012193whitespace string is a separator and empty strings are\n\
12194removed from the result.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012195
12196static PyObject*
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012197unicode_split(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012198{
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012199 static char *kwlist[] = {"sep", "maxsplit", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000012200 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012201 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012202
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012203 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:split",
12204 kwlist, &substring, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012205 return NULL;
12206
12207 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012208 return split(self, NULL, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012209 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012210 return split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012211 else
Victor Stinner7931d9a2011-11-04 00:22:48 +010012212 return PyUnicode_Split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012213}
12214
Thomas Wouters477c8d52006-05-27 19:21:47 +000012215PyObject *
12216PyUnicode_Partition(PyObject *str_in, PyObject *sep_in)
12217{
12218 PyObject* str_obj;
12219 PyObject* sep_obj;
12220 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012221 int kind1, kind2, kind;
12222 void *buf1 = NULL, *buf2 = NULL;
12223 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012224
12225 str_obj = PyUnicode_FromObject(str_in);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012226 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012227 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012228 sep_obj = PyUnicode_FromObject(sep_in);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012229 if (!sep_obj) {
12230 Py_DECREF(str_obj);
12231 return NULL;
12232 }
12233 if (PyUnicode_READY(sep_obj) == -1 || PyUnicode_READY(str_obj) == -1) {
12234 Py_DECREF(sep_obj);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012235 Py_DECREF(str_obj);
12236 return NULL;
12237 }
12238
Victor Stinner14f8f022011-10-05 20:58:25 +020012239 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012240 kind2 = PyUnicode_KIND(sep_obj);
Victor Stinner14f8f022011-10-05 20:58:25 +020012241 kind = Py_MAX(kind1, kind2);
12242 buf1 = PyUnicode_DATA(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012243 if (kind1 != kind)
Victor Stinner14f8f022011-10-05 20:58:25 +020012244 buf1 = _PyUnicode_AsKind(str_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012245 if (!buf1)
12246 goto onError;
12247 buf2 = PyUnicode_DATA(sep_obj);
12248 if (kind2 != kind)
12249 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12250 if (!buf2)
12251 goto onError;
12252 len1 = PyUnicode_GET_LENGTH(str_obj);
12253 len2 = PyUnicode_GET_LENGTH(sep_obj);
12254
Benjamin Petersonead6b532011-12-20 17:23:42 -060012255 switch (PyUnicode_KIND(str_obj)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012256 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012257 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12258 out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12259 else
12260 out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012261 break;
12262 case PyUnicode_2BYTE_KIND:
12263 out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12264 break;
12265 case PyUnicode_4BYTE_KIND:
12266 out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12267 break;
12268 default:
12269 assert(0);
12270 out = 0;
12271 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012272
12273 Py_DECREF(sep_obj);
12274 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012275 if (kind1 != kind)
12276 PyMem_Free(buf1);
12277 if (kind2 != kind)
12278 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012279
12280 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012281 onError:
12282 Py_DECREF(sep_obj);
12283 Py_DECREF(str_obj);
12284 if (kind1 != kind && buf1)
12285 PyMem_Free(buf1);
12286 if (kind2 != kind && buf2)
12287 PyMem_Free(buf2);
12288 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012289}
12290
12291
12292PyObject *
12293PyUnicode_RPartition(PyObject *str_in, PyObject *sep_in)
12294{
12295 PyObject* str_obj;
12296 PyObject* sep_obj;
12297 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012298 int kind1, kind2, kind;
12299 void *buf1 = NULL, *buf2 = NULL;
12300 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012301
12302 str_obj = PyUnicode_FromObject(str_in);
12303 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012304 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012305 sep_obj = PyUnicode_FromObject(sep_in);
12306 if (!sep_obj) {
12307 Py_DECREF(str_obj);
12308 return NULL;
12309 }
12310
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012311 kind1 = PyUnicode_KIND(str_in);
12312 kind2 = PyUnicode_KIND(sep_obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +020012313 kind = Py_MAX(kind1, kind2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012314 buf1 = PyUnicode_DATA(str_in);
12315 if (kind1 != kind)
12316 buf1 = _PyUnicode_AsKind(str_in, kind);
12317 if (!buf1)
12318 goto onError;
12319 buf2 = PyUnicode_DATA(sep_obj);
12320 if (kind2 != kind)
12321 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12322 if (!buf2)
12323 goto onError;
12324 len1 = PyUnicode_GET_LENGTH(str_obj);
12325 len2 = PyUnicode_GET_LENGTH(sep_obj);
12326
Benjamin Petersonead6b532011-12-20 17:23:42 -060012327 switch (PyUnicode_KIND(str_in)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012328 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012329 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12330 out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12331 else
12332 out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012333 break;
12334 case PyUnicode_2BYTE_KIND:
12335 out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12336 break;
12337 case PyUnicode_4BYTE_KIND:
12338 out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12339 break;
12340 default:
12341 assert(0);
12342 out = 0;
12343 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012344
12345 Py_DECREF(sep_obj);
12346 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012347 if (kind1 != kind)
12348 PyMem_Free(buf1);
12349 if (kind2 != kind)
12350 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012351
12352 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012353 onError:
12354 Py_DECREF(sep_obj);
12355 Py_DECREF(str_obj);
12356 if (kind1 != kind && buf1)
12357 PyMem_Free(buf1);
12358 if (kind2 != kind && buf2)
12359 PyMem_Free(buf2);
12360 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012361}
12362
12363PyDoc_STRVAR(partition__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012364 "S.partition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012365\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012366Search for the separator sep in S, and return the part before it,\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012367the separator itself, and the part after it. If the separator is not\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012368found, return S and two empty strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012369
12370static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012371unicode_partition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012372{
Victor Stinner9310abb2011-10-05 00:59:23 +020012373 return PyUnicode_Partition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012374}
12375
12376PyDoc_STRVAR(rpartition__doc__,
Ezio Melotti5b2b2422010-01-25 11:58:28 +000012377 "S.rpartition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012378\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012379Search for the separator sep in S, starting at the end of S, and return\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012380the part before it, the separator itself, and the part after it. If the\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012381separator is not found, return two empty strings and S.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012382
12383static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012384unicode_rpartition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012385{
Victor Stinner9310abb2011-10-05 00:59:23 +020012386 return PyUnicode_RPartition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012387}
12388
Alexander Belopolsky40018472011-02-26 01:02:56 +000012389PyObject *
12390PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012391{
12392 PyObject *result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012393
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012394 s = PyUnicode_FromObject(s);
12395 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012396 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012397 if (sep != NULL) {
12398 sep = PyUnicode_FromObject(sep);
12399 if (sep == NULL) {
12400 Py_DECREF(s);
12401 return NULL;
12402 }
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012403 }
12404
Victor Stinner9310abb2011-10-05 00:59:23 +020012405 result = rsplit(s, sep, maxsplit);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012406
12407 Py_DECREF(s);
12408 Py_XDECREF(sep);
12409 return result;
12410}
12411
12412PyDoc_STRVAR(rsplit__doc__,
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012413 "S.rsplit(sep=None, maxsplit=-1) -> list of strings\n\
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012414\n\
12415Return a list of the words in S, using sep as the\n\
12416delimiter string, starting at the end of the string and\n\
12417working to the front. If maxsplit is given, at most maxsplit\n\
12418splits are done. If sep is not specified, any whitespace string\n\
12419is a separator.");
12420
12421static PyObject*
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012422unicode_rsplit(PyObject *self, PyObject *args, PyObject *kwds)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012423{
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012424 static char *kwlist[] = {"sep", "maxsplit", 0};
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012425 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012426 Py_ssize_t maxcount = -1;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012427
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012428 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:rsplit",
12429 kwlist, &substring, &maxcount))
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012430 return NULL;
12431
12432 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012433 return rsplit(self, NULL, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012434 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012435 return rsplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012436 else
Victor Stinner9310abb2011-10-05 00:59:23 +020012437 return PyUnicode_RSplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012438}
12439
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012440PyDoc_STRVAR(splitlines__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012441 "S.splitlines([keepends]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012442\n\
12443Return a list of the lines in S, breaking at line boundaries.\n\
Guido van Rossum86662912000-04-11 15:38:46 +000012444Line breaks are not included in the resulting list unless keepends\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012445is given and true.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012446
12447static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012448unicode_splitlines(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012449{
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012450 static char *kwlist[] = {"keepends", 0};
Guido van Rossum86662912000-04-11 15:38:46 +000012451 int keepends = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012452
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012453 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:splitlines",
12454 kwlist, &keepends))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012455 return NULL;
12456
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012457 return PyUnicode_Splitlines(self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012458}
12459
12460static
Guido van Rossumf15a29f2007-05-04 00:41:39 +000012461PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012462{
Victor Stinnerc4b49542011-12-11 22:44:26 +010012463 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012464}
12465
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012466PyDoc_STRVAR(swapcase__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012467 "S.swapcase() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012468\n\
12469Return a copy of S with uppercase characters converted to lowercase\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012470and vice versa.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012471
12472static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012473unicode_swapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012474{
Benjamin Petersoneea48462012-01-16 14:28:50 -050012475 if (PyUnicode_READY(self) == -1)
12476 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010012477 return case_operation(self, do_swapcase);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012478}
12479
Georg Brandlceee0772007-11-27 23:48:05 +000012480PyDoc_STRVAR(maketrans__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012481 "str.maketrans(x[, y[, z]]) -> dict (static method)\n\
Georg Brandlceee0772007-11-27 23:48:05 +000012482\n\
12483Return a translation table usable for str.translate().\n\
12484If there is only one argument, it must be a dictionary mapping Unicode\n\
12485ordinals (integers) or characters to Unicode ordinals, strings or None.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012486Character keys will be then converted to ordinals.\n\
Georg Brandlceee0772007-11-27 23:48:05 +000012487If there are two arguments, they must be strings of equal length, and\n\
12488in the resulting dictionary, each character in x will be mapped to the\n\
12489character at the same position in y. If there is a third argument, it\n\
12490must be a string, whose characters will be mapped to None in the result.");
12491
12492static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012493unicode_maketrans(PyObject *null, PyObject *args)
Georg Brandlceee0772007-11-27 23:48:05 +000012494{
12495 PyObject *x, *y = NULL, *z = NULL;
12496 PyObject *new = NULL, *key, *value;
12497 Py_ssize_t i = 0;
12498 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012499
Georg Brandlceee0772007-11-27 23:48:05 +000012500 if (!PyArg_ParseTuple(args, "O|UU:maketrans", &x, &y, &z))
12501 return NULL;
12502 new = PyDict_New();
12503 if (!new)
12504 return NULL;
12505 if (y != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012506 int x_kind, y_kind, z_kind;
12507 void *x_data, *y_data, *z_data;
12508
Georg Brandlceee0772007-11-27 23:48:05 +000012509 /* x must be a string too, of equal length */
Georg Brandlceee0772007-11-27 23:48:05 +000012510 if (!PyUnicode_Check(x)) {
12511 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
12512 "be a string if there is a second argument");
12513 goto err;
12514 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012515 if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012516 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
12517 "arguments must have equal length");
12518 goto err;
12519 }
12520 /* create entries for translating chars in x to those in y */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012521 x_kind = PyUnicode_KIND(x);
12522 y_kind = PyUnicode_KIND(y);
12523 x_data = PyUnicode_DATA(x);
12524 y_data = PyUnicode_DATA(y);
12525 for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
12526 key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060012527 if (!key)
Georg Brandlceee0772007-11-27 23:48:05 +000012528 goto err;
Benjamin Peterson822c7902011-12-20 13:32:50 -060012529 value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060012530 if (!value) {
12531 Py_DECREF(key);
12532 goto err;
12533 }
Georg Brandlceee0772007-11-27 23:48:05 +000012534 res = PyDict_SetItem(new, key, value);
12535 Py_DECREF(key);
12536 Py_DECREF(value);
12537 if (res < 0)
12538 goto err;
12539 }
12540 /* create entries for deleting chars in z */
12541 if (z != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012542 z_kind = PyUnicode_KIND(z);
12543 z_data = PyUnicode_DATA(z);
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012544 for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012545 key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000012546 if (!key)
12547 goto err;
12548 res = PyDict_SetItem(new, key, Py_None);
12549 Py_DECREF(key);
12550 if (res < 0)
12551 goto err;
12552 }
12553 }
12554 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012555 int kind;
12556 void *data;
12557
Georg Brandlceee0772007-11-27 23:48:05 +000012558 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +000012559 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012560 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
12561 "to maketrans it must be a dict");
12562 goto err;
12563 }
12564 /* copy entries into the new dict, converting string keys to int keys */
12565 while (PyDict_Next(x, &i, &key, &value)) {
12566 if (PyUnicode_Check(key)) {
12567 /* convert string keys to integer keys */
12568 PyObject *newkey;
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012569 if (PyUnicode_GET_LENGTH(key) != 1) {
Georg Brandlceee0772007-11-27 23:48:05 +000012570 PyErr_SetString(PyExc_ValueError, "string keys in translate "
12571 "table must be of length 1");
12572 goto err;
12573 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012574 kind = PyUnicode_KIND(key);
12575 data = PyUnicode_DATA(key);
12576 newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
Georg Brandlceee0772007-11-27 23:48:05 +000012577 if (!newkey)
12578 goto err;
12579 res = PyDict_SetItem(new, newkey, value);
12580 Py_DECREF(newkey);
12581 if (res < 0)
12582 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +000012583 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012584 /* just keep integer keys */
12585 if (PyDict_SetItem(new, key, value) < 0)
12586 goto err;
12587 } else {
12588 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
12589 "be strings or integers");
12590 goto err;
12591 }
12592 }
12593 }
12594 return new;
12595 err:
12596 Py_DECREF(new);
12597 return NULL;
12598}
12599
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012600PyDoc_STRVAR(translate__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012601 "S.translate(table) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012602\n\
12603Return a copy of the string S, where all characters have been mapped\n\
12604through the given translation table, which must be a mapping of\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012605Unicode ordinals to Unicode ordinals, strings, or None.\n\
Walter Dörwald5c1ee172002-09-04 20:31:32 +000012606Unmapped characters are left untouched. Characters mapped to None\n\
12607are deleted.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012608
12609static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012610unicode_translate(PyObject *self, PyObject *table)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012611{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012612 return _PyUnicode_TranslateCharmap(self, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012613}
12614
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012615PyDoc_STRVAR(upper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012616 "S.upper() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012617\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012618Return a copy of S converted to uppercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012619
12620static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012621unicode_upper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012622{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050012623 if (PyUnicode_READY(self) == -1)
12624 return NULL;
12625 if (PyUnicode_IS_ASCII(self))
12626 return ascii_upper_or_lower(self, 0);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010012627 return case_operation(self, do_upper);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012628}
12629
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012630PyDoc_STRVAR(zfill__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012631 "S.zfill(width) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012632\n\
Benjamin Peterson9aa42992008-09-10 21:57:34 +000012633Pad a numeric string S with zeros on the left, to fill a field\n\
12634of the specified width. The string S is never truncated.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012635
12636static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012637unicode_zfill(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012638{
Martin v. Löwis18e16552006-02-15 17:27:45 +000012639 Py_ssize_t fill;
Victor Stinner9310abb2011-10-05 00:59:23 +020012640 PyObject *u;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012641 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012642 int kind;
12643 void *data;
12644 Py_UCS4 chr;
12645
Martin v. Löwis18e16552006-02-15 17:27:45 +000012646 if (!PyArg_ParseTuple(args, "n:zfill", &width))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012647 return NULL;
12648
Benjamin Petersonbac79492012-01-14 13:34:47 -050012649 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010012650 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012651
Victor Stinnerc4b49542011-12-11 22:44:26 +010012652 if (PyUnicode_GET_LENGTH(self) >= width)
12653 return unicode_result_unchanged(self);
12654
12655 fill = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012656
12657 u = pad(self, fill, 0, '0');
12658
Walter Dörwald068325e2002-04-15 13:36:47 +000012659 if (u == NULL)
12660 return NULL;
12661
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012662 kind = PyUnicode_KIND(u);
12663 data = PyUnicode_DATA(u);
12664 chr = PyUnicode_READ(kind, data, fill);
12665
12666 if (chr == '+' || chr == '-') {
Guido van Rossumd57fd912000-03-10 22:53:23 +000012667 /* move sign to beginning of string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012668 PyUnicode_WRITE(kind, data, 0, chr);
12669 PyUnicode_WRITE(kind, data, fill, '0');
Guido van Rossumd57fd912000-03-10 22:53:23 +000012670 }
12671
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012672 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +010012673 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012674}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012675
12676#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012677static PyObject *
12678unicode__decimal2ascii(PyObject *self)
12679{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012680 return PyUnicode_TransformDecimalAndSpaceToASCII(self);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012681}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012682#endif
12683
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012684PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012685 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012686\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000012687Return True if S starts with the specified prefix, False otherwise.\n\
12688With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012689With optional end, stop comparing S at that position.\n\
12690prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012691
12692static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012693unicode_startswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000012694 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012695{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012696 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012697 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012698 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012699 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012700 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012701
Jesus Ceaac451502011-04-20 17:09:23 +020012702 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000012703 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012704 if (PyTuple_Check(subobj)) {
12705 Py_ssize_t i;
12706 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012707 substring = PyUnicode_FromObject(PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012708 if (substring == NULL)
12709 return NULL;
12710 result = tailmatch(self, substring, start, end, -1);
12711 Py_DECREF(substring);
12712 if (result) {
12713 Py_RETURN_TRUE;
12714 }
12715 }
12716 /* nothing matched */
12717 Py_RETURN_FALSE;
12718 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012719 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030012720 if (substring == NULL) {
12721 if (PyErr_ExceptionMatches(PyExc_TypeError))
12722 PyErr_Format(PyExc_TypeError, "startswith first arg must be str or "
12723 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000012724 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030012725 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012726 result = tailmatch(self, substring, start, end, -1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012727 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012728 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012729}
12730
12731
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012732PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012733 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012734\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000012735Return True if S ends with the specified suffix, False otherwise.\n\
12736With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012737With optional end, stop comparing S at that position.\n\
12738suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012739
12740static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012741unicode_endswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000012742 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012743{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012744 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012745 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012746 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012747 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012748 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012749
Jesus Ceaac451502011-04-20 17:09:23 +020012750 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000012751 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012752 if (PyTuple_Check(subobj)) {
12753 Py_ssize_t i;
12754 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012755 substring = PyUnicode_FromObject(
Benjamin Peterson29060642009-01-31 22:14:21 +000012756 PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012757 if (substring == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000012758 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012759 result = tailmatch(self, substring, start, end, +1);
12760 Py_DECREF(substring);
12761 if (result) {
12762 Py_RETURN_TRUE;
12763 }
12764 }
12765 Py_RETURN_FALSE;
12766 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012767 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030012768 if (substring == NULL) {
12769 if (PyErr_ExceptionMatches(PyExc_TypeError))
12770 PyErr_Format(PyExc_TypeError, "endswith first arg must be str or "
12771 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000012772 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030012773 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012774 result = tailmatch(self, substring, start, end, +1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012775 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012776 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012777}
12778
Victor Stinner202fdca2012-05-07 12:47:02 +020012779Py_LOCAL_INLINE(void)
Victor Stinner3b1a74a2012-05-09 22:25:00 +020012780_PyUnicodeWriter_Update(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020012781{
Victor Stinnerd3f08822012-05-29 12:57:52 +020012782 writer->size = PyUnicode_GET_LENGTH(writer->buffer);
Victor Stinner202fdca2012-05-07 12:47:02 +020012783 writer->maxchar = PyUnicode_MAX_CHAR_VALUE(writer->buffer);
12784 writer->data = PyUnicode_DATA(writer->buffer);
12785 writer->kind = PyUnicode_KIND(writer->buffer);
12786}
12787
Victor Stinnerd3f08822012-05-29 12:57:52 +020012788void
12789_PyUnicodeWriter_Init(_PyUnicodeWriter *writer, Py_ssize_t min_length)
Victor Stinner202fdca2012-05-07 12:47:02 +020012790{
Victor Stinnerd3f08822012-05-29 12:57:52 +020012791 memset(writer, 0, sizeof(*writer));
12792#ifdef Py_DEBUG
12793 writer->kind = 5; /* invalid kind */
12794#endif
12795 writer->min_length = Py_MAX(min_length, 100);
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012796 writer->overallocate = (min_length > 0);
Victor Stinner202fdca2012-05-07 12:47:02 +020012797}
12798
Victor Stinnerd3f08822012-05-29 12:57:52 +020012799int
12800_PyUnicodeWriter_PrepareInternal(_PyUnicodeWriter *writer,
12801 Py_ssize_t length, Py_UCS4 maxchar)
Victor Stinner202fdca2012-05-07 12:47:02 +020012802{
12803 Py_ssize_t newlen;
12804 PyObject *newbuffer;
12805
Victor Stinnerd3f08822012-05-29 12:57:52 +020012806 assert(length > 0);
12807
Victor Stinner202fdca2012-05-07 12:47:02 +020012808 if (length > PY_SSIZE_T_MAX - writer->pos) {
12809 PyErr_NoMemory();
12810 return -1;
12811 }
12812 newlen = writer->pos + length;
12813
Victor Stinnerd3f08822012-05-29 12:57:52 +020012814 if (writer->buffer == NULL) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012815 if (writer->overallocate) {
Victor Stinnerd3f08822012-05-29 12:57:52 +020012816 /* overallocate 25% to limit the number of resize */
12817 if (newlen <= (PY_SSIZE_T_MAX - newlen / 4))
12818 newlen += newlen / 4;
12819 if (newlen < writer->min_length)
12820 newlen = writer->min_length;
12821 }
12822 writer->buffer = PyUnicode_New(newlen, maxchar);
12823 if (writer->buffer == NULL)
12824 return -1;
12825 _PyUnicodeWriter_Update(writer);
12826 return 0;
12827 }
Victor Stinner202fdca2012-05-07 12:47:02 +020012828
Victor Stinnerd3f08822012-05-29 12:57:52 +020012829 if (newlen > writer->size) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012830 if (writer->overallocate) {
Victor Stinnerd3f08822012-05-29 12:57:52 +020012831 /* overallocate 25% to limit the number of resize */
12832 if (newlen <= (PY_SSIZE_T_MAX - newlen / 4))
12833 newlen += newlen / 4;
12834 if (newlen < writer->min_length)
12835 newlen = writer->min_length;
12836 }
12837
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012838 if (maxchar > writer->maxchar || writer->readonly) {
Victor Stinner202fdca2012-05-07 12:47:02 +020012839 /* resize + widen */
12840 newbuffer = PyUnicode_New(newlen, maxchar);
12841 if (newbuffer == NULL)
12842 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020012843 _PyUnicode_FastCopyCharacters(newbuffer, 0,
12844 writer->buffer, 0, writer->pos);
Victor Stinner202fdca2012-05-07 12:47:02 +020012845 Py_DECREF(writer->buffer);
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012846 writer->readonly = 0;
Victor Stinner202fdca2012-05-07 12:47:02 +020012847 }
12848 else {
12849 newbuffer = resize_compact(writer->buffer, newlen);
12850 if (newbuffer == NULL)
12851 return -1;
12852 }
12853 writer->buffer = newbuffer;
Victor Stinner3b1a74a2012-05-09 22:25:00 +020012854 _PyUnicodeWriter_Update(writer);
Victor Stinner202fdca2012-05-07 12:47:02 +020012855 }
12856 else if (maxchar > writer->maxchar) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012857 assert(!writer->readonly);
Victor Stinnerd3f08822012-05-29 12:57:52 +020012858 newbuffer = PyUnicode_New(writer->size, maxchar);
12859 if (newbuffer == NULL)
Victor Stinner202fdca2012-05-07 12:47:02 +020012860 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020012861 _PyUnicode_FastCopyCharacters(newbuffer, 0,
12862 writer->buffer, 0, writer->pos);
12863 Py_DECREF(writer->buffer);
12864 writer->buffer = newbuffer;
Victor Stinner3b1a74a2012-05-09 22:25:00 +020012865 _PyUnicodeWriter_Update(writer);
Victor Stinner202fdca2012-05-07 12:47:02 +020012866 }
12867 return 0;
12868}
12869
Victor Stinnerd3f08822012-05-29 12:57:52 +020012870int
12871_PyUnicodeWriter_WriteStr(_PyUnicodeWriter *writer, PyObject *str)
12872{
12873 Py_UCS4 maxchar;
12874 Py_ssize_t len;
12875
12876 if (PyUnicode_READY(str) == -1)
12877 return -1;
12878 len = PyUnicode_GET_LENGTH(str);
12879 if (len == 0)
12880 return 0;
12881 maxchar = PyUnicode_MAX_CHAR_VALUE(str);
12882 if (maxchar > writer->maxchar || len > writer->size - writer->pos) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012883 if (writer->buffer == NULL && !writer->overallocate) {
Victor Stinnerd3f08822012-05-29 12:57:52 +020012884 Py_INCREF(str);
12885 writer->buffer = str;
12886 _PyUnicodeWriter_Update(writer);
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012887 writer->readonly = 1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020012888 writer->size = 0;
12889 writer->pos += len;
12890 return 0;
12891 }
12892 if (_PyUnicodeWriter_PrepareInternal(writer, len, maxchar) == -1)
12893 return -1;
12894 }
12895 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
12896 str, 0, len);
12897 writer->pos += len;
12898 return 0;
12899}
12900
12901PyObject *
Victor Stinner3b1a74a2012-05-09 22:25:00 +020012902_PyUnicodeWriter_Finish(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020012903{
Victor Stinnerd3f08822012-05-29 12:57:52 +020012904 if (writer->pos == 0) {
12905 Py_XDECREF(writer->buffer);
12906 Py_INCREF(unicode_empty);
12907 return unicode_empty;
12908 }
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012909 if (writer->readonly) {
Victor Stinnerd3f08822012-05-29 12:57:52 +020012910 assert(PyUnicode_GET_LENGTH(writer->buffer) == writer->pos);
12911 return writer->buffer;
12912 }
12913 if (PyUnicode_GET_LENGTH(writer->buffer) != writer->pos) {
12914 PyObject *newbuffer;
12915 newbuffer = resize_compact(writer->buffer, writer->pos);
12916 if (newbuffer == NULL) {
12917 Py_DECREF(writer->buffer);
12918 return NULL;
12919 }
12920 writer->buffer = newbuffer;
Victor Stinner202fdca2012-05-07 12:47:02 +020012921 }
Victor Stinnerf59c28c2012-05-09 03:24:14 +020012922 assert(_PyUnicode_CheckConsistency(writer->buffer, 1));
Victor Stinner202fdca2012-05-07 12:47:02 +020012923 return writer->buffer;
12924}
12925
Victor Stinnerd3f08822012-05-29 12:57:52 +020012926void
Victor Stinner3b1a74a2012-05-09 22:25:00 +020012927_PyUnicodeWriter_Dealloc(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020012928{
12929 Py_CLEAR(writer->buffer);
12930}
12931
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012932#include "stringlib/unicode_format.h"
Eric Smith8c663262007-08-25 02:26:07 +000012933
12934PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012935 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000012936\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012937Return a formatted version of S, using substitutions from args and kwargs.\n\
12938The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +000012939
Eric Smith27bbca62010-11-04 17:06:58 +000012940PyDoc_STRVAR(format_map__doc__,
12941 "S.format_map(mapping) -> str\n\
12942\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012943Return a formatted version of S, using substitutions from mapping.\n\
12944The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +000012945
Eric Smith4a7d76d2008-05-30 18:10:19 +000012946static PyObject *
12947unicode__format__(PyObject* self, PyObject* args)
12948{
Victor Stinnerd3f08822012-05-29 12:57:52 +020012949 PyObject *format_spec;
12950 _PyUnicodeWriter writer;
12951 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +000012952
12953 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
12954 return NULL;
12955
Victor Stinnerd3f08822012-05-29 12:57:52 +020012956 if (PyUnicode_READY(self) == -1)
12957 return NULL;
12958 _PyUnicodeWriter_Init(&writer, 0);
12959 ret = _PyUnicode_FormatAdvancedWriter(&writer,
12960 self, format_spec, 0,
12961 PyUnicode_GET_LENGTH(format_spec));
12962 if (ret == -1) {
12963 _PyUnicodeWriter_Dealloc(&writer);
12964 return NULL;
12965 }
12966 return _PyUnicodeWriter_Finish(&writer);
Eric Smith4a7d76d2008-05-30 18:10:19 +000012967}
12968
Eric Smith8c663262007-08-25 02:26:07 +000012969PyDoc_STRVAR(p_format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012970 "S.__format__(format_spec) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000012971\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012972Return a formatted version of S as described by format_spec.");
Eric Smith8c663262007-08-25 02:26:07 +000012973
12974static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012975unicode__sizeof__(PyObject *v)
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012976{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012977 Py_ssize_t size;
12978
12979 /* If it's a compact object, account for base structure +
12980 character data. */
12981 if (PyUnicode_IS_COMPACT_ASCII(v))
12982 size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(v) + 1;
12983 else if (PyUnicode_IS_COMPACT(v))
12984 size = sizeof(PyCompactUnicodeObject) +
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012985 (PyUnicode_GET_LENGTH(v) + 1) * PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012986 else {
12987 /* If it is a two-block object, account for base object, and
12988 for character block if present. */
12989 size = sizeof(PyUnicodeObject);
Victor Stinnerc3c74152011-10-02 20:39:55 +020012990 if (_PyUnicode_DATA_ANY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012991 size += (PyUnicode_GET_LENGTH(v) + 1) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012992 PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012993 }
12994 /* If the wstr pointer is present, account for it unless it is shared
Victor Stinnera3be6132011-10-03 02:16:37 +020012995 with the data pointer. Check if the data is not shared. */
Victor Stinner03490912011-10-03 23:45:12 +020012996 if (_PyUnicode_HAS_WSTR_MEMORY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012997 size += (PyUnicode_WSTR_LENGTH(v) + 1) * sizeof(wchar_t);
Victor Stinner829c0ad2011-10-03 01:08:02 +020012998 if (_PyUnicode_HAS_UTF8_MEMORY(v))
Victor Stinnere90fe6a2011-10-01 16:48:13 +020012999 size += PyUnicode_UTF8_LENGTH(v) + 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013000
13001 return PyLong_FromSsize_t(size);
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013002}
13003
13004PyDoc_STRVAR(sizeof__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013005 "S.__sizeof__() -> size of S in memory, in bytes");
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013006
13007static PyObject *
Victor Stinner034f6cf2011-09-30 02:26:44 +020013008unicode_getnewargs(PyObject *v)
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013009{
Victor Stinnerbf6e5602011-12-12 01:53:47 +010013010 PyObject *copy = _PyUnicode_Copy(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013011 if (!copy)
13012 return NULL;
13013 return Py_BuildValue("(N)", copy);
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013014}
13015
Guido van Rossumd57fd912000-03-10 22:53:23 +000013016static PyMethodDef unicode_methods[] = {
Benjamin Peterson28a4dce2010-12-12 01:33:04 +000013017 {"encode", (PyCFunction) unicode_encode, METH_VARARGS | METH_KEYWORDS, encode__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013018 {"replace", (PyCFunction) unicode_replace, METH_VARARGS, replace__doc__},
Ezio Melotticda6b6d2012-02-26 09:39:55 +020013019 {"split", (PyCFunction) unicode_split, METH_VARARGS | METH_KEYWORDS, split__doc__},
13020 {"rsplit", (PyCFunction) unicode_rsplit, METH_VARARGS | METH_KEYWORDS, rsplit__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013021 {"join", (PyCFunction) unicode_join, METH_O, join__doc__},
13022 {"capitalize", (PyCFunction) unicode_capitalize, METH_NOARGS, capitalize__doc__},
Benjamin Petersond5890c82012-01-14 13:23:30 -050013023 {"casefold", (PyCFunction) unicode_casefold, METH_NOARGS, casefold__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013024 {"title", (PyCFunction) unicode_title, METH_NOARGS, title__doc__},
13025 {"center", (PyCFunction) unicode_center, METH_VARARGS, center__doc__},
13026 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
13027 {"expandtabs", (PyCFunction) unicode_expandtabs, METH_VARARGS, expandtabs__doc__},
13028 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013029 {"partition", (PyCFunction) unicode_partition, METH_O, partition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013030 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
13031 {"ljust", (PyCFunction) unicode_ljust, METH_VARARGS, ljust__doc__},
13032 {"lower", (PyCFunction) unicode_lower, METH_NOARGS, lower__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013033 {"lstrip", (PyCFunction) unicode_lstrip, METH_VARARGS, lstrip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013034 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
13035 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
13036 {"rjust", (PyCFunction) unicode_rjust, METH_VARARGS, rjust__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013037 {"rstrip", (PyCFunction) unicode_rstrip, METH_VARARGS, rstrip__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013038 {"rpartition", (PyCFunction) unicode_rpartition, METH_O, rpartition__doc__},
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010013039 {"splitlines", (PyCFunction) unicode_splitlines, METH_VARARGS | METH_KEYWORDS, splitlines__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013040 {"strip", (PyCFunction) unicode_strip, METH_VARARGS, strip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013041 {"swapcase", (PyCFunction) unicode_swapcase, METH_NOARGS, swapcase__doc__},
13042 {"translate", (PyCFunction) unicode_translate, METH_O, translate__doc__},
13043 {"upper", (PyCFunction) unicode_upper, METH_NOARGS, upper__doc__},
13044 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
13045 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
13046 {"islower", (PyCFunction) unicode_islower, METH_NOARGS, islower__doc__},
13047 {"isupper", (PyCFunction) unicode_isupper, METH_NOARGS, isupper__doc__},
13048 {"istitle", (PyCFunction) unicode_istitle, METH_NOARGS, istitle__doc__},
13049 {"isspace", (PyCFunction) unicode_isspace, METH_NOARGS, isspace__doc__},
13050 {"isdecimal", (PyCFunction) unicode_isdecimal, METH_NOARGS, isdecimal__doc__},
13051 {"isdigit", (PyCFunction) unicode_isdigit, METH_NOARGS, isdigit__doc__},
13052 {"isnumeric", (PyCFunction) unicode_isnumeric, METH_NOARGS, isnumeric__doc__},
13053 {"isalpha", (PyCFunction) unicode_isalpha, METH_NOARGS, isalpha__doc__},
13054 {"isalnum", (PyCFunction) unicode_isalnum, METH_NOARGS, isalnum__doc__},
Martin v. Löwis47383402007-08-15 07:32:56 +000013055 {"isidentifier", (PyCFunction) unicode_isidentifier, METH_NOARGS, isidentifier__doc__},
Georg Brandl559e5d72008-06-11 18:37:52 +000013056 {"isprintable", (PyCFunction) unicode_isprintable, METH_NOARGS, isprintable__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013057 {"zfill", (PyCFunction) unicode_zfill, METH_VARARGS, zfill__doc__},
Eric Smith9cd1e092007-08-31 18:39:38 +000013058 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +000013059 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
Eric Smith4a7d76d2008-05-30 18:10:19 +000013060 {"__format__", (PyCFunction) unicode__format__, METH_VARARGS, p_format__doc__},
Georg Brandlceee0772007-11-27 23:48:05 +000013061 {"maketrans", (PyCFunction) unicode_maketrans,
13062 METH_VARARGS | METH_STATIC, maketrans__doc__},
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013063 {"__sizeof__", (PyCFunction) unicode__sizeof__, METH_NOARGS, sizeof__doc__},
Walter Dörwald068325e2002-04-15 13:36:47 +000013064#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013065 /* These methods are just used for debugging the implementation. */
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013066 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013067#endif
13068
Benjamin Peterson14339b62009-01-31 16:36:08 +000013069 {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013070 {NULL, NULL}
13071};
13072
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013073static PyObject *
13074unicode_mod(PyObject *v, PyObject *w)
13075{
Brian Curtindfc80e32011-08-10 20:28:54 -050013076 if (!PyUnicode_Check(v))
13077 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson29060642009-01-31 22:14:21 +000013078 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013079}
13080
13081static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013082 0, /*nb_add*/
13083 0, /*nb_subtract*/
13084 0, /*nb_multiply*/
13085 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013086};
13087
Guido van Rossumd57fd912000-03-10 22:53:23 +000013088static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013089 (lenfunc) unicode_length, /* sq_length */
13090 PyUnicode_Concat, /* sq_concat */
13091 (ssizeargfunc) unicode_repeat, /* sq_repeat */
13092 (ssizeargfunc) unicode_getitem, /* sq_item */
13093 0, /* sq_slice */
13094 0, /* sq_ass_item */
13095 0, /* sq_ass_slice */
13096 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013097};
13098
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013099static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013100unicode_subscript(PyObject* self, PyObject* item)
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013101{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013102 if (PyUnicode_READY(self) == -1)
13103 return NULL;
13104
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000013105 if (PyIndex_Check(item)) {
13106 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013107 if (i == -1 && PyErr_Occurred())
13108 return NULL;
13109 if (i < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013110 i += PyUnicode_GET_LENGTH(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013111 return unicode_getitem(self, i);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013112 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000013113 Py_ssize_t start, stop, step, slicelength, cur, i;
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013114 PyObject *result;
13115 void *src_data, *dest_data;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013116 int src_kind, dest_kind;
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013117 Py_UCS4 ch, max_char, kind_limit;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013118
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013119 if (PySlice_GetIndicesEx(item, PyUnicode_GET_LENGTH(self),
Benjamin Peterson29060642009-01-31 22:14:21 +000013120 &start, &stop, &step, &slicelength) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013121 return NULL;
13122 }
13123
13124 if (slicelength <= 0) {
Victor Stinner382955f2011-12-11 21:44:00 +010013125 Py_INCREF(unicode_empty);
13126 return unicode_empty;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013127 } else if (start == 0 && step == 1 &&
Victor Stinnerc4b49542011-12-11 22:44:26 +010013128 slicelength == PyUnicode_GET_LENGTH(self)) {
13129 return unicode_result_unchanged(self);
Thomas Woutersed03b412007-08-28 21:37:11 +000013130 } else if (step == 1) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013131 return PyUnicode_Substring(self,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013132 start, start + slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013133 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013134 /* General case */
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013135 src_kind = PyUnicode_KIND(self);
13136 src_data = PyUnicode_DATA(self);
Victor Stinner55c99112011-10-13 01:17:06 +020013137 if (!PyUnicode_IS_ASCII(self)) {
13138 kind_limit = kind_maxchar_limit(src_kind);
13139 max_char = 0;
13140 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
13141 ch = PyUnicode_READ(src_kind, src_data, cur);
13142 if (ch > max_char) {
13143 max_char = ch;
13144 if (max_char >= kind_limit)
13145 break;
13146 }
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013147 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013148 }
Victor Stinner55c99112011-10-13 01:17:06 +020013149 else
13150 max_char = 127;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013151 result = PyUnicode_New(slicelength, max_char);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013152 if (result == NULL)
13153 return NULL;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013154 dest_kind = PyUnicode_KIND(result);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013155 dest_data = PyUnicode_DATA(result);
13156
13157 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013158 Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
13159 PyUnicode_WRITE(dest_kind, dest_data, i, ch);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013160 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013161 assert(_PyUnicode_CheckConsistency(result, 1));
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013162 return result;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013163 } else {
13164 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
13165 return NULL;
13166 }
13167}
13168
13169static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013170 (lenfunc)unicode_length, /* mp_length */
13171 (binaryfunc)unicode_subscript, /* mp_subscript */
13172 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013173};
13174
Guido van Rossumd57fd912000-03-10 22:53:23 +000013175
Guido van Rossumd57fd912000-03-10 22:53:23 +000013176/* Helpers for PyUnicode_Format() */
13177
13178static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +000013179getnextarg(PyObject *args, Py_ssize_t arglen, Py_ssize_t *p_argidx)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013180{
Martin v. Löwis18e16552006-02-15 17:27:45 +000013181 Py_ssize_t argidx = *p_argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013182 if (argidx < arglen) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013183 (*p_argidx)++;
13184 if (arglen < 0)
13185 return args;
13186 else
13187 return PyTuple_GetItem(args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013188 }
13189 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013190 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013191 return NULL;
13192}
13193
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013194/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013195
Victor Stinnerd3f08822012-05-29 12:57:52 +020013196static int
13197formatfloat(PyObject *v, int flags, int prec, int type,
13198 PyObject **p_output, _PyUnicodeWriter *writer)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013199{
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013200 char *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013201 double x;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013202 Py_ssize_t len;
Tim Petersced69f82003-09-16 20:30:58 +000013203
Guido van Rossumd57fd912000-03-10 22:53:23 +000013204 x = PyFloat_AsDouble(v);
13205 if (x == -1.0 && PyErr_Occurred())
Victor Stinnerd3f08822012-05-29 12:57:52 +020013206 return -1;
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013207
Guido van Rossumd57fd912000-03-10 22:53:23 +000013208 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000013209 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +000013210
Eric Smith0923d1d2009-04-16 20:16:10 +000013211 p = PyOS_double_to_string(x, type, prec,
13212 (flags & F_ALT) ? Py_DTSF_ALT : 0, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013213 if (p == NULL)
Victor Stinnerd3f08822012-05-29 12:57:52 +020013214 return -1;
13215 len = strlen(p);
13216 if (writer) {
13217 if (_PyUnicodeWriter_Prepare(writer, len, 127) == -1)
13218 return -1;
Victor Stinner184252a2012-06-16 02:57:41 +020013219 unicode_write_cstr(writer->buffer, writer->pos, p, len);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013220 writer->pos += len;
13221 }
13222 else
13223 *p_output = _PyUnicode_FromASCII(p, len);
Eric Smith0923d1d2009-04-16 20:16:10 +000013224 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013225 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013226}
13227
Victor Stinnerd0880d52012-04-27 23:40:13 +020013228/* formatlong() emulates the format codes d, u, o, x and X, and
13229 * the F_ALT flag, for Python's long (unbounded) ints. It's not used for
13230 * Python's regular ints.
13231 * Return value: a new PyUnicodeObject*, or NULL if error.
13232 * The output string is of the form
13233 * "-"? ("0x" | "0X")? digit+
13234 * "0x"/"0X" are present only for x and X conversions, with F_ALT
13235 * set in flags. The case of hex digits will be correct,
13236 * There will be at least prec digits, zero-filled on the left if
13237 * necessary to get that many.
13238 * val object to be converted
13239 * flags bitmask of format flags; only F_ALT is looked at
13240 * prec minimum number of digits; 0-fill on left if needed
13241 * type a character in [duoxX]; u acts the same as d
13242 *
13243 * CAUTION: o, x and X conversions on regular ints can never
13244 * produce a '-' sign, but can for Python's unbounded ints.
13245 */
Tim Peters38fd5b62000-09-21 05:43:11 +000013246static PyObject*
13247formatlong(PyObject *val, int flags, int prec, int type)
13248{
Victor Stinnerd0880d52012-04-27 23:40:13 +020013249 PyObject *result = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013250 char *buf;
Victor Stinnerd0880d52012-04-27 23:40:13 +020013251 Py_ssize_t i;
13252 int sign; /* 1 if '-', else 0 */
13253 int len; /* number of characters */
13254 Py_ssize_t llen;
13255 int numdigits; /* len == numnondigits + numdigits */
13256 int numnondigits = 0;
Tim Peters38fd5b62000-09-21 05:43:11 +000013257
Victor Stinnerd0880d52012-04-27 23:40:13 +020013258 /* Avoid exceeding SSIZE_T_MAX */
13259 if (prec > INT_MAX-3) {
13260 PyErr_SetString(PyExc_OverflowError,
13261 "precision too large");
Benjamin Peterson14339b62009-01-31 16:36:08 +000013262 return NULL;
Victor Stinnerd0880d52012-04-27 23:40:13 +020013263 }
13264
13265 assert(PyLong_Check(val));
13266
13267 switch (type) {
13268 case 'd':
13269 case 'u':
13270 /* Special-case boolean: we want 0/1 */
Victor Stinnerb11d91d2012-04-28 00:25:34 +020013271 if (PyBool_Check(val))
13272 result = PyNumber_ToBase(val, 10);
13273 else
13274 result = Py_TYPE(val)->tp_str(val);
Victor Stinnerd0880d52012-04-27 23:40:13 +020013275 break;
13276 case 'o':
13277 numnondigits = 2;
13278 result = PyNumber_ToBase(val, 8);
13279 break;
13280 case 'x':
13281 case 'X':
13282 numnondigits = 2;
13283 result = PyNumber_ToBase(val, 16);
13284 break;
13285 default:
13286 assert(!"'type' not in [duoxX]");
13287 }
13288 if (!result)
13289 return NULL;
13290
13291 assert(unicode_modifiable(result));
13292 assert(PyUnicode_IS_READY(result));
13293 assert(PyUnicode_IS_ASCII(result));
13294
13295 /* To modify the string in-place, there can only be one reference. */
13296 if (Py_REFCNT(result) != 1) {
13297 PyErr_BadInternalCall();
13298 return NULL;
13299 }
13300 buf = PyUnicode_DATA(result);
13301 llen = PyUnicode_GET_LENGTH(result);
13302 if (llen > INT_MAX) {
13303 PyErr_SetString(PyExc_ValueError,
13304 "string too large in _PyBytes_FormatLong");
13305 return NULL;
13306 }
13307 len = (int)llen;
13308 sign = buf[0] == '-';
13309 numnondigits += sign;
13310 numdigits = len - numnondigits;
13311 assert(numdigits > 0);
13312
13313 /* Get rid of base marker unless F_ALT */
13314 if (((flags & F_ALT) == 0 &&
13315 (type == 'o' || type == 'x' || type == 'X'))) {
13316 assert(buf[sign] == '0');
13317 assert(buf[sign+1] == 'x' || buf[sign+1] == 'X' ||
13318 buf[sign+1] == 'o');
13319 numnondigits -= 2;
13320 buf += 2;
13321 len -= 2;
13322 if (sign)
13323 buf[0] = '-';
13324 assert(len == numnondigits + numdigits);
13325 assert(numdigits > 0);
13326 }
13327
13328 /* Fill with leading zeroes to meet minimum width. */
13329 if (prec > numdigits) {
13330 PyObject *r1 = PyBytes_FromStringAndSize(NULL,
13331 numnondigits + prec);
13332 char *b1;
13333 if (!r1) {
13334 Py_DECREF(result);
13335 return NULL;
13336 }
13337 b1 = PyBytes_AS_STRING(r1);
13338 for (i = 0; i < numnondigits; ++i)
13339 *b1++ = *buf++;
13340 for (i = 0; i < prec - numdigits; i++)
13341 *b1++ = '0';
13342 for (i = 0; i < numdigits; i++)
13343 *b1++ = *buf++;
13344 *b1 = '\0';
13345 Py_DECREF(result);
13346 result = r1;
13347 buf = PyBytes_AS_STRING(result);
13348 len = numnondigits + prec;
13349 }
13350
13351 /* Fix up case for hex conversions. */
13352 if (type == 'X') {
13353 /* Need to convert all lower case letters to upper case.
13354 and need to convert 0x to 0X (and -0x to -0X). */
13355 for (i = 0; i < len; i++)
13356 if (buf[i] >= 'a' && buf[i] <= 'x')
13357 buf[i] -= 'a'-'A';
13358 }
13359 if (!PyUnicode_Check(result) || len != PyUnicode_GET_LENGTH(result)) {
13360 PyObject *unicode;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013361 unicode = _PyUnicode_FromASCII(buf, len);
Victor Stinnerd0880d52012-04-27 23:40:13 +020013362 Py_DECREF(result);
13363 result = unicode;
13364 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000013365 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +000013366}
13367
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013368static Py_UCS4
13369formatchar(PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013370{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000013371 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000013372 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013373 if (PyUnicode_GET_LENGTH(v) == 1) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013374 return PyUnicode_READ_CHAR(v, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +000013375 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013376 goto onError;
13377 }
13378 else {
13379 /* Integer input truncated to a character */
13380 long x;
13381 x = PyLong_AsLong(v);
13382 if (x == -1 && PyErr_Occurred())
13383 goto onError;
13384
Victor Stinner8faf8212011-12-08 22:14:11 +010013385 if (x < 0 || x > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013386 PyErr_SetString(PyExc_OverflowError,
13387 "%c arg not in range(0x110000)");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013388 return (Py_UCS4) -1;
Benjamin Peterson29060642009-01-31 22:14:21 +000013389 }
13390
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013391 return (Py_UCS4) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013392 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000013393
Benjamin Peterson29060642009-01-31 22:14:21 +000013394 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000013395 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013396 "%c requires int or char");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013397 return (Py_UCS4) -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013398}
13399
Alexander Belopolsky40018472011-02-26 01:02:56 +000013400PyObject *
13401PyUnicode_Format(PyObject *format, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013402{
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013403 Py_ssize_t fmtcnt, fmtpos, arglen, argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013404 int args_owned = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013405 PyObject *dict = NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013406 PyObject *temp = NULL;
13407 PyObject *second = NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013408 PyObject *uformat;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013409 void *fmt;
13410 enum PyUnicode_Kind kind, fmtkind;
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013411 _PyUnicodeWriter writer;
Victor Stinneree4544c2012-05-09 22:24:08 +020013412 Py_ssize_t sublen;
13413 Py_UCS4 maxchar;
Tim Petersced69f82003-09-16 20:30:58 +000013414
Guido van Rossumd57fd912000-03-10 22:53:23 +000013415 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013416 PyErr_BadInternalCall();
13417 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013418 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013419 uformat = PyUnicode_FromObject(format);
Benjamin Peterson22a29702012-01-02 09:00:30 -060013420 if (uformat == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000013421 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060013422 if (PyUnicode_READY(uformat) == -1)
13423 Py_DECREF(uformat);
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013424
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013425 fmt = PyUnicode_DATA(uformat);
13426 fmtkind = PyUnicode_KIND(uformat);
13427 fmtcnt = PyUnicode_GET_LENGTH(uformat);
13428 fmtpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013429
Victor Stinnerd3f08822012-05-29 12:57:52 +020013430 _PyUnicodeWriter_Init(&writer, fmtcnt + 100);
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013431
Guido van Rossumd57fd912000-03-10 22:53:23 +000013432 if (PyTuple_Check(args)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013433 arglen = PyTuple_Size(args);
13434 argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013435 }
13436 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013437 arglen = -1;
13438 argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013439 }
Christian Heimes90aa7642007-12-19 02:45:37 +000013440 if (Py_TYPE(args)->tp_as_mapping && !PyTuple_Check(args) &&
Christian Heimesf3863112007-11-22 07:46:41 +000013441 !PyUnicode_Check(args))
Benjamin Peterson29060642009-01-31 22:14:21 +000013442 dict = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013443
13444 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013445 if (PyUnicode_READ(fmtkind, fmt, fmtpos) != '%') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013446 Py_ssize_t nonfmtpos;
13447 nonfmtpos = fmtpos++;
13448 while (fmtcnt >= 0 &&
13449 PyUnicode_READ(fmtkind, fmt, fmtpos) != '%') {
13450 fmtpos++;
13451 fmtcnt--;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013452 }
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013453 if (fmtcnt < 0)
13454 fmtpos--;
Victor Stinneree4544c2012-05-09 22:24:08 +020013455 sublen = fmtpos - nonfmtpos;
13456 maxchar = _PyUnicode_FindMaxChar(uformat,
13457 nonfmtpos, nonfmtpos + sublen);
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013458 if (_PyUnicodeWriter_Prepare(&writer, sublen, maxchar) == -1)
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013459 goto onError;
Victor Stinneree4544c2012-05-09 22:24:08 +020013460
Victor Stinnerd3f08822012-05-29 12:57:52 +020013461 _PyUnicode_FastCopyCharacters(writer.buffer, writer.pos,
13462 uformat, nonfmtpos, sublen);
Victor Stinneree4544c2012-05-09 22:24:08 +020013463 writer.pos += sublen;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013464 }
13465 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013466 /* Got a format specifier */
13467 int flags = 0;
13468 Py_ssize_t width = -1;
13469 int prec = -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013470 Py_UCS4 c = '\0';
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013471 Py_UCS4 fill;
13472 int sign;
13473 Py_UCS4 signchar;
Benjamin Peterson29060642009-01-31 22:14:21 +000013474 int isnumok;
13475 PyObject *v = NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013476 void *pbuf = NULL;
13477 Py_ssize_t pindex, len;
Victor Stinneree4544c2012-05-09 22:24:08 +020013478 Py_UCS4 bufmaxchar;
13479 Py_ssize_t buflen;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013480
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013481 fmtpos++;
Victor Stinner438106b2012-05-02 00:41:57 +020013482 c = PyUnicode_READ(fmtkind, fmt, fmtpos);
13483 if (c == '(') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013484 Py_ssize_t keystart;
Benjamin Peterson29060642009-01-31 22:14:21 +000013485 Py_ssize_t keylen;
13486 PyObject *key;
13487 int pcount = 1;
Christian Heimesa612dc02008-02-24 13:08:18 +000013488
Benjamin Peterson29060642009-01-31 22:14:21 +000013489 if (dict == NULL) {
13490 PyErr_SetString(PyExc_TypeError,
13491 "format requires a mapping");
13492 goto onError;
13493 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013494 ++fmtpos;
Benjamin Peterson29060642009-01-31 22:14:21 +000013495 --fmtcnt;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013496 keystart = fmtpos;
Benjamin Peterson29060642009-01-31 22:14:21 +000013497 /* Skip over balanced parentheses */
13498 while (pcount > 0 && --fmtcnt >= 0) {
Victor Stinnerbff7c962012-05-03 01:44:59 +020013499 c = PyUnicode_READ(fmtkind, fmt, fmtpos);
13500 if (c == ')')
Benjamin Peterson29060642009-01-31 22:14:21 +000013501 --pcount;
Victor Stinnerbff7c962012-05-03 01:44:59 +020013502 else if (c == '(')
Benjamin Peterson29060642009-01-31 22:14:21 +000013503 ++pcount;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013504 fmtpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +000013505 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013506 keylen = fmtpos - keystart - 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000013507 if (fmtcnt < 0 || pcount > 0) {
13508 PyErr_SetString(PyExc_ValueError,
13509 "incomplete format key");
13510 goto onError;
13511 }
Victor Stinner7931d9a2011-11-04 00:22:48 +010013512 key = PyUnicode_Substring(uformat,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013513 keystart, keystart + keylen);
Benjamin Peterson29060642009-01-31 22:14:21 +000013514 if (key == NULL)
13515 goto onError;
13516 if (args_owned) {
13517 Py_DECREF(args);
13518 args_owned = 0;
13519 }
13520 args = PyObject_GetItem(dict, key);
13521 Py_DECREF(key);
13522 if (args == NULL) {
13523 goto onError;
13524 }
13525 args_owned = 1;
13526 arglen = -1;
13527 argidx = -2;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013528 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013529 while (--fmtcnt >= 0) {
Victor Stinner438106b2012-05-02 00:41:57 +020013530 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
13531 switch (c) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013532 case '-': flags |= F_LJUST; continue;
13533 case '+': flags |= F_SIGN; continue;
13534 case ' ': flags |= F_BLANK; continue;
13535 case '#': flags |= F_ALT; continue;
13536 case '0': flags |= F_ZERO; continue;
13537 }
13538 break;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013539 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013540 if (c == '*') {
13541 v = getnextarg(args, arglen, &argidx);
13542 if (v == NULL)
13543 goto onError;
13544 if (!PyLong_Check(v)) {
13545 PyErr_SetString(PyExc_TypeError,
13546 "* wants int");
13547 goto onError;
13548 }
13549 width = PyLong_AsLong(v);
13550 if (width == -1 && PyErr_Occurred())
13551 goto onError;
13552 if (width < 0) {
13553 flags |= F_LJUST;
13554 width = -width;
13555 }
13556 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013557 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013558 }
13559 else if (c >= '0' && c <= '9') {
13560 width = c - '0';
13561 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013562 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013563 if (c < '0' || c > '9')
13564 break;
Martin v. Löwisb05c0732012-05-15 13:45:49 +020013565 /* Since c is unsigned, the RHS would end up as unsigned,
13566 mixing signed and unsigned comparison. Since c is between
13567 '0' and '9', casting to int is safe. */
13568 if (width > (PY_SSIZE_T_MAX - ((int)c - '0')) / 10) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013569 PyErr_SetString(PyExc_ValueError,
13570 "width too big");
Benjamin Peterson14339b62009-01-31 16:36:08 +000013571 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +000013572 }
13573 width = width*10 + (c - '0');
13574 }
13575 }
13576 if (c == '.') {
13577 prec = 0;
13578 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013579 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013580 if (c == '*') {
13581 v = getnextarg(args, arglen, &argidx);
13582 if (v == NULL)
13583 goto onError;
13584 if (!PyLong_Check(v)) {
13585 PyErr_SetString(PyExc_TypeError,
13586 "* wants int");
13587 goto onError;
13588 }
13589 prec = PyLong_AsLong(v);
13590 if (prec == -1 && PyErr_Occurred())
13591 goto onError;
13592 if (prec < 0)
13593 prec = 0;
13594 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013595 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013596 }
13597 else if (c >= '0' && c <= '9') {
13598 prec = c - '0';
13599 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013600 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013601 if (c < '0' || c > '9')
13602 break;
Martin v. Löwisb05c0732012-05-15 13:45:49 +020013603 if (prec > (INT_MAX - ((int)c - '0')) / 10) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013604 PyErr_SetString(PyExc_ValueError,
13605 "prec too big");
13606 goto onError;
13607 }
13608 prec = prec*10 + (c - '0');
13609 }
13610 }
13611 } /* prec */
13612 if (fmtcnt >= 0) {
13613 if (c == 'h' || c == 'l' || c == 'L') {
13614 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013615 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013616 }
13617 }
13618 if (fmtcnt < 0) {
13619 PyErr_SetString(PyExc_ValueError,
13620 "incomplete format");
13621 goto onError;
13622 }
Victor Stinnerd3f08822012-05-29 12:57:52 +020013623 if (fmtcnt == 0)
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013624 writer.overallocate = 0;
Victor Stinneraff3cc62012-04-30 05:19:21 +020013625
13626 if (c == '%') {
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013627 if (_PyUnicodeWriter_Prepare(&writer, 1, '%') == -1)
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013628 goto onError;
Victor Stinneree4544c2012-05-09 22:24:08 +020013629 PyUnicode_WRITE(writer.kind, writer.data, writer.pos, '%');
13630 writer.pos += 1;
Victor Stinneraff3cc62012-04-30 05:19:21 +020013631 continue;
Benjamin Peterson29060642009-01-31 22:14:21 +000013632 }
Victor Stinneraff3cc62012-04-30 05:19:21 +020013633
Victor Stinneraff3cc62012-04-30 05:19:21 +020013634 v = getnextarg(args, arglen, &argidx);
13635 if (v == NULL)
13636 goto onError;
13637
Benjamin Peterson29060642009-01-31 22:14:21 +000013638 sign = 0;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013639 signchar = '\0';
Benjamin Peterson29060642009-01-31 22:14:21 +000013640 fill = ' ';
13641 switch (c) {
13642
Benjamin Peterson29060642009-01-31 22:14:21 +000013643 case 's':
13644 case 'r':
13645 case 'a':
Victor Stinnerd3f08822012-05-29 12:57:52 +020013646 if (PyLong_CheckExact(v) && width == -1 && prec == -1) {
13647 /* Fast path */
13648 if (_PyLong_FormatWriter(&writer, v, 10, flags & F_ALT) == -1)
13649 goto onError;
13650 goto nextarg;
13651 }
13652
Victor Stinner808fc0a2010-03-22 12:50:40 +000013653 if (PyUnicode_CheckExact(v) && c == 's') {
Benjamin Peterson29060642009-01-31 22:14:21 +000013654 temp = v;
13655 Py_INCREF(temp);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013656 }
13657 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013658 if (c == 's')
13659 temp = PyObject_Str(v);
13660 else if (c == 'r')
13661 temp = PyObject_Repr(v);
13662 else
13663 temp = PyObject_ASCII(v);
Benjamin Peterson29060642009-01-31 22:14:21 +000013664 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013665 break;
13666
13667 case 'i':
13668 case 'd':
13669 case 'u':
13670 case 'o':
13671 case 'x':
13672 case 'X':
Victor Stinnerd3f08822012-05-29 12:57:52 +020013673 if (PyLong_CheckExact(v)
13674 && width == -1 && prec == -1
13675 && !(flags & (F_SIGN | F_BLANK)))
13676 {
13677 /* Fast path */
13678 switch(c)
13679 {
13680 case 'd':
13681 case 'i':
13682 case 'u':
13683 if (_PyLong_FormatWriter(&writer, v, 10, flags & F_ALT) == -1)
13684 goto onError;
13685 goto nextarg;
13686 case 'x':
13687 if (_PyLong_FormatWriter(&writer, v, 16, flags & F_ALT) == -1)
13688 goto onError;
13689 goto nextarg;
13690 case 'o':
13691 if (_PyLong_FormatWriter(&writer, v, 8, flags & F_ALT) == -1)
13692 goto onError;
13693 goto nextarg;
13694 default:
13695 break;
13696 }
13697 }
13698
Benjamin Peterson29060642009-01-31 22:14:21 +000013699 isnumok = 0;
13700 if (PyNumber_Check(v)) {
13701 PyObject *iobj=NULL;
13702
13703 if (PyLong_Check(v)) {
13704 iobj = v;
13705 Py_INCREF(iobj);
13706 }
13707 else {
13708 iobj = PyNumber_Long(v);
13709 }
13710 if (iobj!=NULL) {
13711 if (PyLong_Check(iobj)) {
13712 isnumok = 1;
Victor Stinneraff3cc62012-04-30 05:19:21 +020013713 sign = 1;
Senthil Kumaran9ebe08d2011-07-03 21:03:16 -070013714 temp = formatlong(iobj, flags, prec, (c == 'i'? 'd': c));
Benjamin Peterson29060642009-01-31 22:14:21 +000013715 Py_DECREF(iobj);
Benjamin Peterson29060642009-01-31 22:14:21 +000013716 }
13717 else {
13718 Py_DECREF(iobj);
13719 }
13720 }
13721 }
13722 if (!isnumok) {
13723 PyErr_Format(PyExc_TypeError,
13724 "%%%c format: a number is required, "
13725 "not %.200s", (char)c, Py_TYPE(v)->tp_name);
13726 goto onError;
13727 }
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013728 if (flags & F_ZERO)
Benjamin Peterson29060642009-01-31 22:14:21 +000013729 fill = '0';
13730 break;
13731
13732 case 'e':
13733 case 'E':
13734 case 'f':
13735 case 'F':
13736 case 'g':
13737 case 'G':
Victor Stinnerd3f08822012-05-29 12:57:52 +020013738 if (width == -1 && prec == -1
13739 && !(flags & (F_SIGN | F_BLANK)))
13740 {
13741 /* Fast path */
13742 if (formatfloat(v, flags, prec, c, NULL, &writer) == -1)
13743 goto onError;
13744 goto nextarg;
13745 }
13746
Benjamin Peterson29060642009-01-31 22:14:21 +000013747 sign = 1;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013748 if (flags & F_ZERO)
Benjamin Peterson29060642009-01-31 22:14:21 +000013749 fill = '0';
Victor Stinnerd3f08822012-05-29 12:57:52 +020013750 if (formatfloat(v, flags, prec, c, &temp, NULL) == -1)
13751 temp = NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000013752 break;
13753
13754 case 'c':
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013755 {
13756 Py_UCS4 ch = formatchar(v);
13757 if (ch == (Py_UCS4) -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000013758 goto onError;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013759 if (width == -1 && prec == -1) {
13760 /* Fast path */
13761 if (_PyUnicodeWriter_Prepare(&writer, 1, ch) == -1)
13762 goto onError;
13763 PyUnicode_WRITE(writer.kind, writer.data, writer.pos, ch);
13764 writer.pos += 1;
13765 goto nextarg;
13766 }
Victor Stinnerb5c3ea32012-05-02 00:29:36 +020013767 temp = PyUnicode_FromOrdinal(ch);
Benjamin Peterson29060642009-01-31 22:14:21 +000013768 break;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013769 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013770
13771 default:
13772 PyErr_Format(PyExc_ValueError,
13773 "unsupported format character '%c' (0x%x) "
13774 "at index %zd",
13775 (31<=c && c<=126) ? (char)c : '?',
13776 (int)c,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013777 fmtpos - 1);
Benjamin Peterson29060642009-01-31 22:14:21 +000013778 goto onError;
13779 }
Victor Stinneraff3cc62012-04-30 05:19:21 +020013780 if (temp == NULL)
13781 goto onError;
13782 assert (PyUnicode_Check(temp));
Victor Stinnerd3f08822012-05-29 12:57:52 +020013783
13784 if (width == -1 && prec == -1
13785 && !(flags & (F_SIGN | F_BLANK)))
13786 {
13787 /* Fast path */
13788 if (_PyUnicodeWriter_WriteStr(&writer, temp) == -1)
13789 goto onError;
13790 goto nextarg;
13791 }
13792
Victor Stinneraff3cc62012-04-30 05:19:21 +020013793 if (PyUnicode_READY(temp) == -1) {
13794 Py_CLEAR(temp);
13795 goto onError;
13796 }
13797 kind = PyUnicode_KIND(temp);
13798 pbuf = PyUnicode_DATA(temp);
13799 len = PyUnicode_GET_LENGTH(temp);
13800
13801 if (c == 's' || c == 'r' || c == 'a') {
13802 if (prec >= 0 && len > prec)
13803 len = prec;
13804 }
13805
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013806 /* pbuf is initialized here. */
13807 pindex = 0;
Benjamin Peterson29060642009-01-31 22:14:21 +000013808 if (sign) {
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013809 Py_UCS4 ch = PyUnicode_READ(kind, pbuf, pindex);
13810 if (ch == '-' || ch == '+') {
13811 signchar = ch;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013812 len--;
13813 pindex++;
Benjamin Peterson29060642009-01-31 22:14:21 +000013814 }
13815 else if (flags & F_SIGN)
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013816 signchar = '+';
Benjamin Peterson29060642009-01-31 22:14:21 +000013817 else if (flags & F_BLANK)
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013818 signchar = ' ';
Benjamin Peterson29060642009-01-31 22:14:21 +000013819 else
13820 sign = 0;
13821 }
13822 if (width < len)
13823 width = len;
Victor Stinneree4544c2012-05-09 22:24:08 +020013824
13825 /* Compute the length and maximum character of the
13826 written characters */
13827 bufmaxchar = 127;
13828 if (!(flags & F_LJUST)) {
13829 if (sign) {
13830 if ((width-1) > len)
Victor Stinnerd3f08822012-05-29 12:57:52 +020013831 bufmaxchar = MAX_MAXCHAR(bufmaxchar, fill);
Victor Stinneree4544c2012-05-09 22:24:08 +020013832 }
13833 else {
13834 if (width > len)
Victor Stinnerd3f08822012-05-29 12:57:52 +020013835 bufmaxchar = MAX_MAXCHAR(bufmaxchar, fill);
Victor Stinneree4544c2012-05-09 22:24:08 +020013836 }
13837 }
13838 maxchar = _PyUnicode_FindMaxChar(temp, 0, pindex+len);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013839 bufmaxchar = MAX_MAXCHAR(bufmaxchar, maxchar);
Victor Stinneree4544c2012-05-09 22:24:08 +020013840
13841 buflen = width;
13842 if (sign && len == width)
13843 buflen++;
13844
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013845 if (_PyUnicodeWriter_Prepare(&writer, buflen, bufmaxchar) == -1)
Victor Stinneree4544c2012-05-09 22:24:08 +020013846 goto onError;
13847
13848 /* Write characters */
Benjamin Peterson29060642009-01-31 22:14:21 +000013849 if (sign) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013850 if (fill != ' ') {
Victor Stinneree4544c2012-05-09 22:24:08 +020013851 PyUnicode_WRITE(writer.kind, writer.data, writer.pos, signchar);
13852 writer.pos += 1;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013853 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013854 if (width > len)
13855 width--;
13856 }
13857 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013858 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013859 assert(PyUnicode_READ(kind, pbuf, pindex + 1) == c);
Benjamin Peterson29060642009-01-31 22:14:21 +000013860 if (fill != ' ') {
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013861 PyUnicode_WRITE(writer.kind, writer.data, writer.pos, '0');
13862 PyUnicode_WRITE(writer.kind, writer.data, writer.pos+1, c);
13863 writer.pos += 2;
13864 pindex += 2;
Benjamin Peterson29060642009-01-31 22:14:21 +000013865 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013866 width -= 2;
13867 if (width < 0)
13868 width = 0;
13869 len -= 2;
13870 }
13871 if (width > len && !(flags & F_LJUST)) {
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013872 sublen = width - len;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013873 FILL(writer.kind, writer.data, fill, writer.pos, sublen);
13874 writer.pos += sublen;
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013875 width = len;
Benjamin Peterson29060642009-01-31 22:14:21 +000013876 }
13877 if (fill == ' ') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013878 if (sign) {
Victor Stinneree4544c2012-05-09 22:24:08 +020013879 PyUnicode_WRITE(writer.kind, writer.data, writer.pos, signchar);
13880 writer.pos += 1;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013881 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013882 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013883 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
13884 assert(PyUnicode_READ(kind, pbuf, pindex+1) == c);
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013885 PyUnicode_WRITE(writer.kind, writer.data, writer.pos, '0');
13886 PyUnicode_WRITE(writer.kind, writer.data, writer.pos+1, c);
13887 writer.pos += 2;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013888 pindex += 2;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013889 }
13890 }
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013891
Victor Stinnerc9d369f2012-06-16 02:22:37 +020013892 if (len) {
13893 _PyUnicode_FastCopyCharacters(writer.buffer, writer.pos,
13894 temp, pindex, len);
13895 writer.pos += len;
13896 }
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013897 if (width > len) {
Victor Stinneree4544c2012-05-09 22:24:08 +020013898 sublen = width - len;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013899 FILL(writer.kind, writer.data, ' ', writer.pos, sublen);
13900 writer.pos += sublen;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013901 }
Victor Stinneree4544c2012-05-09 22:24:08 +020013902
Victor Stinnerd3f08822012-05-29 12:57:52 +020013903nextarg:
Benjamin Peterson29060642009-01-31 22:14:21 +000013904 if (dict && (argidx < arglen) && c != '%') {
13905 PyErr_SetString(PyExc_TypeError,
13906 "not all arguments converted during string formatting");
Benjamin Peterson29060642009-01-31 22:14:21 +000013907 goto onError;
13908 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013909 Py_CLEAR(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013910 } /* '%' */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013911 } /* until end */
13912 if (argidx < arglen && !dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013913 PyErr_SetString(PyExc_TypeError,
13914 "not all arguments converted during string formatting");
13915 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013916 }
13917
13918 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013919 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013920 }
13921 Py_DECREF(uformat);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013922 Py_XDECREF(temp);
13923 Py_XDECREF(second);
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013924 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013925
Benjamin Peterson29060642009-01-31 22:14:21 +000013926 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000013927 Py_DECREF(uformat);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013928 Py_XDECREF(temp);
13929 Py_XDECREF(second);
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013930 _PyUnicodeWriter_Dealloc(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013931 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013932 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013933 }
13934 return NULL;
13935}
13936
Jeremy Hylton938ace62002-07-17 16:30:39 +000013937static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +000013938unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
13939
Tim Peters6d6c1a32001-08-02 04:15:00 +000013940static PyObject *
13941unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
13942{
Benjamin Peterson29060642009-01-31 22:14:21 +000013943 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013944 static char *kwlist[] = {"object", "encoding", "errors", 0};
13945 char *encoding = NULL;
13946 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000013947
Benjamin Peterson14339b62009-01-31 16:36:08 +000013948 if (type != &PyUnicode_Type)
13949 return unicode_subtype_new(type, args, kwds);
13950 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +000013951 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +000013952 return NULL;
Victor Stinner382955f2011-12-11 21:44:00 +010013953 if (x == NULL) {
13954 Py_INCREF(unicode_empty);
13955 return unicode_empty;
13956 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000013957 if (encoding == NULL && errors == NULL)
13958 return PyObject_Str(x);
13959 else
Benjamin Peterson29060642009-01-31 22:14:21 +000013960 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +000013961}
13962
Guido van Rossume023fe02001-08-30 03:12:59 +000013963static PyObject *
13964unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
13965{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013966 PyObject *unicode, *self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013967 Py_ssize_t length, char_size;
13968 int share_wstr, share_utf8;
13969 unsigned int kind;
13970 void *data;
Guido van Rossume023fe02001-08-30 03:12:59 +000013971
Benjamin Peterson14339b62009-01-31 16:36:08 +000013972 assert(PyType_IsSubtype(type, &PyUnicode_Type));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013973
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013974 unicode = unicode_new(&PyUnicode_Type, args, kwds);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013975 if (unicode == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000013976 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020013977 assert(_PyUnicode_CHECK(unicode));
Benjamin Petersonbac79492012-01-14 13:34:47 -050013978 if (PyUnicode_READY(unicode) == -1) {
Benjamin Peterson22a29702012-01-02 09:00:30 -060013979 Py_DECREF(unicode);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013980 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060013981 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013982
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013983 self = type->tp_alloc(type, 0);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013984 if (self == NULL) {
13985 Py_DECREF(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013986 return NULL;
13987 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013988 kind = PyUnicode_KIND(unicode);
13989 length = PyUnicode_GET_LENGTH(unicode);
13990
13991 _PyUnicode_LENGTH(self) = length;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020013992#ifdef Py_DEBUG
13993 _PyUnicode_HASH(self) = -1;
13994#else
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013995 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020013996#endif
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013997 _PyUnicode_STATE(self).interned = 0;
13998 _PyUnicode_STATE(self).kind = kind;
13999 _PyUnicode_STATE(self).compact = 0;
Victor Stinner3cf46372011-10-03 14:42:15 +020014000 _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014001 _PyUnicode_STATE(self).ready = 1;
14002 _PyUnicode_WSTR(self) = NULL;
14003 _PyUnicode_UTF8_LENGTH(self) = 0;
14004 _PyUnicode_UTF8(self) = NULL;
14005 _PyUnicode_WSTR_LENGTH(self) = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +020014006 _PyUnicode_DATA_ANY(self) = NULL;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014007
14008 share_utf8 = 0;
14009 share_wstr = 0;
14010 if (kind == PyUnicode_1BYTE_KIND) {
14011 char_size = 1;
14012 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
14013 share_utf8 = 1;
14014 }
14015 else if (kind == PyUnicode_2BYTE_KIND) {
14016 char_size = 2;
14017 if (sizeof(wchar_t) == 2)
14018 share_wstr = 1;
14019 }
14020 else {
14021 assert(kind == PyUnicode_4BYTE_KIND);
14022 char_size = 4;
14023 if (sizeof(wchar_t) == 4)
14024 share_wstr = 1;
14025 }
14026
14027 /* Ensure we won't overflow the length. */
14028 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
14029 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014030 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014031 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014032 data = PyObject_MALLOC((length + 1) * char_size);
14033 if (data == NULL) {
14034 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014035 goto onError;
14036 }
14037
Victor Stinnerc3c74152011-10-02 20:39:55 +020014038 _PyUnicode_DATA_ANY(self) = data;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014039 if (share_utf8) {
14040 _PyUnicode_UTF8_LENGTH(self) = length;
14041 _PyUnicode_UTF8(self) = data;
14042 }
14043 if (share_wstr) {
14044 _PyUnicode_WSTR_LENGTH(self) = length;
14045 _PyUnicode_WSTR(self) = (wchar_t *)data;
14046 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014047
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014048 Py_MEMCPY(data, PyUnicode_DATA(unicode),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020014049 kind * (length + 1));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020014050 assert(_PyUnicode_CheckConsistency(self, 1));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014051#ifdef Py_DEBUG
14052 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
14053#endif
Victor Stinnerdd18d3a2011-10-22 11:08:10 +020014054 Py_DECREF(unicode);
Victor Stinner7931d9a2011-11-04 00:22:48 +010014055 return self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014056
14057onError:
14058 Py_DECREF(unicode);
14059 Py_DECREF(self);
14060 return NULL;
Guido van Rossume023fe02001-08-30 03:12:59 +000014061}
14062
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000014063PyDoc_STRVAR(unicode_doc,
Benjamin Peterson29060642009-01-31 22:14:21 +000014064 "str(string[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +000014065\n\
Collin Winterd474ce82007-08-07 19:42:11 +000014066Create a new string object from the given encoded string.\n\
Skip Montanaro35b37a52002-07-26 16:22:46 +000014067encoding defaults to the current default string encoding.\n\
14068errors can be 'strict', 'replace' or 'ignore' and defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +000014069
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014070static PyObject *unicode_iter(PyObject *seq);
14071
Guido van Rossumd57fd912000-03-10 22:53:23 +000014072PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000014073 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Benjamin Peterson14339b62009-01-31 16:36:08 +000014074 "str", /* tp_name */
14075 sizeof(PyUnicodeObject), /* tp_size */
14076 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014077 /* Slots */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014078 (destructor)unicode_dealloc, /* tp_dealloc */
14079 0, /* tp_print */
14080 0, /* tp_getattr */
14081 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000014082 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014083 unicode_repr, /* tp_repr */
14084 &unicode_as_number, /* tp_as_number */
14085 &unicode_as_sequence, /* tp_as_sequence */
14086 &unicode_as_mapping, /* tp_as_mapping */
14087 (hashfunc) unicode_hash, /* tp_hash*/
14088 0, /* tp_call*/
14089 (reprfunc) unicode_str, /* tp_str */
14090 PyObject_GenericGetAttr, /* tp_getattro */
14091 0, /* tp_setattro */
14092 0, /* tp_as_buffer */
14093 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Benjamin Peterson29060642009-01-31 22:14:21 +000014094 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014095 unicode_doc, /* tp_doc */
14096 0, /* tp_traverse */
14097 0, /* tp_clear */
14098 PyUnicode_RichCompare, /* tp_richcompare */
14099 0, /* tp_weaklistoffset */
14100 unicode_iter, /* tp_iter */
14101 0, /* tp_iternext */
14102 unicode_methods, /* tp_methods */
14103 0, /* tp_members */
14104 0, /* tp_getset */
14105 &PyBaseObject_Type, /* tp_base */
14106 0, /* tp_dict */
14107 0, /* tp_descr_get */
14108 0, /* tp_descr_set */
14109 0, /* tp_dictoffset */
14110 0, /* tp_init */
14111 0, /* tp_alloc */
14112 unicode_new, /* tp_new */
14113 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014114};
14115
14116/* Initialize the Unicode implementation */
14117
Victor Stinner3a50e702011-10-18 21:21:00 +020014118int _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014119{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014120 int i;
14121
Thomas Wouters477c8d52006-05-27 19:21:47 +000014122 /* XXX - move this array to unicodectype.c ? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014123 Py_UCS2 linebreak[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +000014124 0x000A, /* LINE FEED */
14125 0x000D, /* CARRIAGE RETURN */
14126 0x001C, /* FILE SEPARATOR */
14127 0x001D, /* GROUP SEPARATOR */
14128 0x001E, /* RECORD SEPARATOR */
14129 0x0085, /* NEXT LINE */
14130 0x2028, /* LINE SEPARATOR */
14131 0x2029, /* PARAGRAPH SEPARATOR */
14132 };
14133
Fred Drakee4315f52000-05-09 19:53:39 +000014134 /* Init the implementation */
Victor Stinnera464fc12011-10-02 20:39:30 +020014135 unicode_empty = PyUnicode_New(0, 0);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014136 if (!unicode_empty)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014137 Py_FatalError("Can't create empty string");
Victor Stinnerd3df8ab2011-11-22 01:22:34 +010014138 assert(_PyUnicode_CheckConsistency(unicode_empty, 1));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014139
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014140 for (i = 0; i < 256; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +000014141 unicode_latin1[i] = NULL;
Guido van Rossumcacfc072002-05-24 19:01:59 +000014142 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000014143 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +000014144
14145 /* initialize the linebreak bloom filter */
14146 bloom_linebreak = make_bloom_mask(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014147 PyUnicode_2BYTE_KIND, linebreak,
Victor Stinner63941882011-09-29 00:42:28 +020014148 Py_ARRAY_LENGTH(linebreak));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014149
14150 PyType_Ready(&EncodingMapType);
Victor Stinner3a50e702011-10-18 21:21:00 +020014151
14152#ifdef HAVE_MBCS
14153 winver.dwOSVersionInfoSize = sizeof(winver);
14154 if (!GetVersionEx((OSVERSIONINFO*)&winver)) {
14155 PyErr_SetFromWindowsErr(0);
14156 return -1;
14157 }
14158#endif
14159 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014160}
14161
14162/* Finalize the Unicode implementation */
14163
Christian Heimesa156e092008-02-16 07:38:31 +000014164int
14165PyUnicode_ClearFreeList(void)
14166{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014167 return 0;
Christian Heimesa156e092008-02-16 07:38:31 +000014168}
14169
Guido van Rossumd57fd912000-03-10 22:53:23 +000014170void
Thomas Wouters78890102000-07-22 19:25:51 +000014171_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014172{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014173 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014174
Guido van Rossum4ae8ef82000-10-03 18:09:04 +000014175 Py_XDECREF(unicode_empty);
14176 unicode_empty = NULL;
Barry Warsaw5b4c2282000-10-03 20:45:26 +000014177
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014178 for (i = 0; i < 256; i++) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014179 if (unicode_latin1[i]) {
14180 Py_DECREF(unicode_latin1[i]);
14181 unicode_latin1[i] = NULL;
14182 }
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014183 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020014184 _PyUnicode_ClearStaticStrings();
Christian Heimesa156e092008-02-16 07:38:31 +000014185 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +000014186}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000014187
Walter Dörwald16807132007-05-25 13:52:07 +000014188void
14189PyUnicode_InternInPlace(PyObject **p)
14190{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014191 register PyObject *s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014192 PyObject *t;
Victor Stinner4fae54c2011-10-03 02:01:52 +020014193#ifdef Py_DEBUG
14194 assert(s != NULL);
14195 assert(_PyUnicode_CHECK(s));
14196#else
Benjamin Peterson14339b62009-01-31 16:36:08 +000014197 if (s == NULL || !PyUnicode_Check(s))
Victor Stinner4fae54c2011-10-03 02:01:52 +020014198 return;
14199#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000014200 /* If it's a subclass, we don't really know what putting
14201 it in the interned dict might do. */
14202 if (!PyUnicode_CheckExact(s))
14203 return;
14204 if (PyUnicode_CHECK_INTERNED(s))
14205 return;
14206 if (interned == NULL) {
14207 interned = PyDict_New();
14208 if (interned == NULL) {
14209 PyErr_Clear(); /* Don't leave an exception */
14210 return;
14211 }
14212 }
14213 /* It might be that the GetItem call fails even
14214 though the key is present in the dictionary,
14215 namely when this happens during a stack overflow. */
14216 Py_ALLOW_RECURSION
Victor Stinner7931d9a2011-11-04 00:22:48 +010014217 t = PyDict_GetItem(interned, s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014218 Py_END_ALLOW_RECURSION
Martin v. Löwis5b222132007-06-10 09:51:05 +000014219
Benjamin Peterson29060642009-01-31 22:14:21 +000014220 if (t) {
14221 Py_INCREF(t);
14222 Py_DECREF(*p);
14223 *p = t;
14224 return;
14225 }
Walter Dörwald16807132007-05-25 13:52:07 +000014226
Benjamin Peterson14339b62009-01-31 16:36:08 +000014227 PyThreadState_GET()->recursion_critical = 1;
Victor Stinner7931d9a2011-11-04 00:22:48 +010014228 if (PyDict_SetItem(interned, s, s) < 0) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014229 PyErr_Clear();
14230 PyThreadState_GET()->recursion_critical = 0;
14231 return;
14232 }
14233 PyThreadState_GET()->recursion_critical = 0;
14234 /* The two references in interned are not counted by refcnt.
14235 The deallocator will take care of this */
14236 Py_REFCNT(s) -= 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014237 _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000014238}
14239
14240void
14241PyUnicode_InternImmortal(PyObject **p)
14242{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014243 PyUnicode_InternInPlace(p);
14244 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
Victor Stinneraf9e4b82011-10-23 20:07:00 +020014245 _PyUnicode_STATE(*p).interned = SSTATE_INTERNED_IMMORTAL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014246 Py_INCREF(*p);
14247 }
Walter Dörwald16807132007-05-25 13:52:07 +000014248}
14249
14250PyObject *
14251PyUnicode_InternFromString(const char *cp)
14252{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014253 PyObject *s = PyUnicode_FromString(cp);
14254 if (s == NULL)
14255 return NULL;
14256 PyUnicode_InternInPlace(&s);
14257 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000014258}
14259
Alexander Belopolsky40018472011-02-26 01:02:56 +000014260void
14261_Py_ReleaseInternedUnicodeStrings(void)
Walter Dörwald16807132007-05-25 13:52:07 +000014262{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014263 PyObject *keys;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014264 PyObject *s;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014265 Py_ssize_t i, n;
14266 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000014267
Benjamin Peterson14339b62009-01-31 16:36:08 +000014268 if (interned == NULL || !PyDict_Check(interned))
14269 return;
14270 keys = PyDict_Keys(interned);
14271 if (keys == NULL || !PyList_Check(keys)) {
14272 PyErr_Clear();
14273 return;
14274 }
Walter Dörwald16807132007-05-25 13:52:07 +000014275
Benjamin Peterson14339b62009-01-31 16:36:08 +000014276 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
14277 detector, interned unicode strings are not forcibly deallocated;
14278 rather, we give them their stolen references back, and then clear
14279 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000014280
Benjamin Peterson14339b62009-01-31 16:36:08 +000014281 n = PyList_GET_SIZE(keys);
14282 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000014283 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014284 for (i = 0; i < n; i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014285 s = PyList_GET_ITEM(keys, i);
Victor Stinner6b56a7f2011-10-04 20:04:52 +020014286 if (PyUnicode_READY(s) == -1) {
14287 assert(0 && "could not ready string");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014288 fprintf(stderr, "could not ready string\n");
Victor Stinner6b56a7f2011-10-04 20:04:52 +020014289 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014290 switch (PyUnicode_CHECK_INTERNED(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014291 case SSTATE_NOT_INTERNED:
14292 /* XXX Shouldn't happen */
14293 break;
14294 case SSTATE_INTERNED_IMMORTAL:
14295 Py_REFCNT(s) += 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014296 immortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014297 break;
14298 case SSTATE_INTERNED_MORTAL:
14299 Py_REFCNT(s) += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014300 mortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014301 break;
14302 default:
14303 Py_FatalError("Inconsistent interned string state.");
14304 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014305 _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014306 }
14307 fprintf(stderr, "total size of all interned strings: "
14308 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
14309 "mortal/immortal\n", mortal_size, immortal_size);
14310 Py_DECREF(keys);
14311 PyDict_Clear(interned);
14312 Py_DECREF(interned);
14313 interned = NULL;
Walter Dörwald16807132007-05-25 13:52:07 +000014314}
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014315
14316
14317/********************* Unicode Iterator **************************/
14318
14319typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014320 PyObject_HEAD
14321 Py_ssize_t it_index;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014322 PyObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014323} unicodeiterobject;
14324
14325static void
14326unicodeiter_dealloc(unicodeiterobject *it)
14327{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014328 _PyObject_GC_UNTRACK(it);
14329 Py_XDECREF(it->it_seq);
14330 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014331}
14332
14333static int
14334unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
14335{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014336 Py_VISIT(it->it_seq);
14337 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014338}
14339
14340static PyObject *
14341unicodeiter_next(unicodeiterobject *it)
14342{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014343 PyObject *seq, *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014344
Benjamin Peterson14339b62009-01-31 16:36:08 +000014345 assert(it != NULL);
14346 seq = it->it_seq;
14347 if (seq == NULL)
14348 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020014349 assert(_PyUnicode_CHECK(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014350
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014351 if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
14352 int kind = PyUnicode_KIND(seq);
14353 void *data = PyUnicode_DATA(seq);
14354 Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
14355 item = PyUnicode_FromOrdinal(chr);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014356 if (item != NULL)
14357 ++it->it_index;
14358 return item;
14359 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014360
Benjamin Peterson14339b62009-01-31 16:36:08 +000014361 Py_DECREF(seq);
14362 it->it_seq = NULL;
14363 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014364}
14365
14366static PyObject *
14367unicodeiter_len(unicodeiterobject *it)
14368{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014369 Py_ssize_t len = 0;
14370 if (it->it_seq)
Victor Stinnerc4f281e2011-10-11 22:11:42 +020014371 len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014372 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014373}
14374
14375PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
14376
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000014377static PyObject *
14378unicodeiter_reduce(unicodeiterobject *it)
14379{
14380 if (it->it_seq != NULL) {
Antoine Pitroua7013882012-04-05 00:04:20 +020014381 return Py_BuildValue("N(O)n", _PyObject_GetBuiltin("iter"),
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000014382 it->it_seq, it->it_index);
14383 } else {
14384 PyObject *u = PyUnicode_FromUnicode(NULL, 0);
14385 if (u == NULL)
14386 return NULL;
Antoine Pitroua7013882012-04-05 00:04:20 +020014387 return Py_BuildValue("N(N)", _PyObject_GetBuiltin("iter"), u);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000014388 }
14389}
14390
14391PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
14392
14393static PyObject *
14394unicodeiter_setstate(unicodeiterobject *it, PyObject *state)
14395{
14396 Py_ssize_t index = PyLong_AsSsize_t(state);
14397 if (index == -1 && PyErr_Occurred())
14398 return NULL;
14399 if (index < 0)
14400 index = 0;
14401 it->it_index = index;
14402 Py_RETURN_NONE;
14403}
14404
14405PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
14406
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014407static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014408 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000014409 length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000014410 {"__reduce__", (PyCFunction)unicodeiter_reduce, METH_NOARGS,
14411 reduce_doc},
14412 {"__setstate__", (PyCFunction)unicodeiter_setstate, METH_O,
14413 setstate_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000014414 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014415};
14416
14417PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014418 PyVarObject_HEAD_INIT(&PyType_Type, 0)
14419 "str_iterator", /* tp_name */
14420 sizeof(unicodeiterobject), /* tp_basicsize */
14421 0, /* tp_itemsize */
14422 /* methods */
14423 (destructor)unicodeiter_dealloc, /* tp_dealloc */
14424 0, /* tp_print */
14425 0, /* tp_getattr */
14426 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000014427 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014428 0, /* tp_repr */
14429 0, /* tp_as_number */
14430 0, /* tp_as_sequence */
14431 0, /* tp_as_mapping */
14432 0, /* tp_hash */
14433 0, /* tp_call */
14434 0, /* tp_str */
14435 PyObject_GenericGetAttr, /* tp_getattro */
14436 0, /* tp_setattro */
14437 0, /* tp_as_buffer */
14438 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
14439 0, /* tp_doc */
14440 (traverseproc)unicodeiter_traverse, /* tp_traverse */
14441 0, /* tp_clear */
14442 0, /* tp_richcompare */
14443 0, /* tp_weaklistoffset */
14444 PyObject_SelfIter, /* tp_iter */
14445 (iternextfunc)unicodeiter_next, /* tp_iternext */
14446 unicodeiter_methods, /* tp_methods */
14447 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014448};
14449
14450static PyObject *
14451unicode_iter(PyObject *seq)
14452{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014453 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014454
Benjamin Peterson14339b62009-01-31 16:36:08 +000014455 if (!PyUnicode_Check(seq)) {
14456 PyErr_BadInternalCall();
14457 return NULL;
14458 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014459 if (PyUnicode_READY(seq) == -1)
14460 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014461 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
14462 if (it == NULL)
14463 return NULL;
14464 it->it_index = 0;
14465 Py_INCREF(seq);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014466 it->it_seq = seq;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014467 _PyObject_GC_TRACK(it);
14468 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014469}
14470
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010014471
14472size_t
14473Py_UNICODE_strlen(const Py_UNICODE *u)
14474{
14475 int res = 0;
14476 while(*u++)
14477 res++;
14478 return res;
14479}
14480
14481Py_UNICODE*
14482Py_UNICODE_strcpy(Py_UNICODE *s1, const Py_UNICODE *s2)
14483{
14484 Py_UNICODE *u = s1;
14485 while ((*u++ = *s2++));
14486 return s1;
14487}
14488
14489Py_UNICODE*
14490Py_UNICODE_strncpy(Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
14491{
14492 Py_UNICODE *u = s1;
14493 while ((*u++ = *s2++))
14494 if (n-- == 0)
14495 break;
14496 return s1;
14497}
14498
14499Py_UNICODE*
14500Py_UNICODE_strcat(Py_UNICODE *s1, const Py_UNICODE *s2)
14501{
14502 Py_UNICODE *u1 = s1;
14503 u1 += Py_UNICODE_strlen(u1);
14504 Py_UNICODE_strcpy(u1, s2);
14505 return s1;
14506}
14507
14508int
14509Py_UNICODE_strcmp(const Py_UNICODE *s1, const Py_UNICODE *s2)
14510{
14511 while (*s1 && *s2 && *s1 == *s2)
14512 s1++, s2++;
14513 if (*s1 && *s2)
14514 return (*s1 < *s2) ? -1 : +1;
14515 if (*s1)
14516 return 1;
14517 if (*s2)
14518 return -1;
14519 return 0;
14520}
14521
14522int
14523Py_UNICODE_strncmp(const Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
14524{
14525 register Py_UNICODE u1, u2;
14526 for (; n != 0; n--) {
14527 u1 = *s1;
14528 u2 = *s2;
14529 if (u1 != u2)
14530 return (u1 < u2) ? -1 : +1;
14531 if (u1 == '\0')
14532 return 0;
14533 s1++;
14534 s2++;
14535 }
14536 return 0;
14537}
14538
14539Py_UNICODE*
14540Py_UNICODE_strchr(const Py_UNICODE *s, Py_UNICODE c)
14541{
14542 const Py_UNICODE *p;
14543 for (p = s; *p; p++)
14544 if (*p == c)
14545 return (Py_UNICODE*)p;
14546 return NULL;
14547}
14548
14549Py_UNICODE*
14550Py_UNICODE_strrchr(const Py_UNICODE *s, Py_UNICODE c)
14551{
14552 const Py_UNICODE *p;
14553 p = s + Py_UNICODE_strlen(s);
14554 while (p != s) {
14555 p--;
14556 if (*p == c)
14557 return (Py_UNICODE*)p;
14558 }
14559 return NULL;
14560}
Victor Stinner331ea922010-08-10 16:37:20 +000014561
Victor Stinner71133ff2010-09-01 23:43:53 +000014562Py_UNICODE*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014563PyUnicode_AsUnicodeCopy(PyObject *unicode)
Victor Stinner71133ff2010-09-01 23:43:53 +000014564{
Victor Stinner577db2c2011-10-11 22:12:48 +020014565 Py_UNICODE *u, *copy;
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014566 Py_ssize_t len, size;
Victor Stinner71133ff2010-09-01 23:43:53 +000014567
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014568 if (!PyUnicode_Check(unicode)) {
14569 PyErr_BadArgument();
14570 return NULL;
14571 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014572 u = PyUnicode_AsUnicodeAndSize(unicode, &len);
Victor Stinner577db2c2011-10-11 22:12:48 +020014573 if (u == NULL)
14574 return NULL;
Victor Stinner71133ff2010-09-01 23:43:53 +000014575 /* Ensure we won't overflow the size. */
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014576 if (len > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
Victor Stinner71133ff2010-09-01 23:43:53 +000014577 PyErr_NoMemory();
14578 return NULL;
14579 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014580 size = len + 1; /* copy the null character */
Victor Stinner71133ff2010-09-01 23:43:53 +000014581 size *= sizeof(Py_UNICODE);
14582 copy = PyMem_Malloc(size);
14583 if (copy == NULL) {
14584 PyErr_NoMemory();
14585 return NULL;
14586 }
Victor Stinner577db2c2011-10-11 22:12:48 +020014587 memcpy(copy, u, size);
Victor Stinner71133ff2010-09-01 23:43:53 +000014588 return copy;
14589}
Martin v. Löwis5b222132007-06-10 09:51:05 +000014590
Georg Brandl66c221e2010-10-14 07:04:07 +000014591/* A _string module, to export formatter_parser and formatter_field_name_split
14592 to the string.Formatter class implemented in Python. */
14593
14594static PyMethodDef _string_methods[] = {
14595 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
14596 METH_O, PyDoc_STR("split the argument as a field name")},
14597 {"formatter_parser", (PyCFunction) formatter_parser,
14598 METH_O, PyDoc_STR("parse the argument as a format string")},
14599 {NULL, NULL}
14600};
14601
14602static struct PyModuleDef _string_module = {
14603 PyModuleDef_HEAD_INIT,
14604 "_string",
14605 PyDoc_STR("string helper module"),
14606 0,
14607 _string_methods,
14608 NULL,
14609 NULL,
14610 NULL,
14611 NULL
14612};
14613
14614PyMODINIT_FUNC
14615PyInit__string(void)
14616{
14617 return PyModule_Create(&_string_module);
14618}
14619
14620
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000014621#ifdef __cplusplus
14622}
14623#endif