blob: 4a1cce24192fb885a43c71cf9b509899f70ab962 [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 Stinnerfb9ea8c2011-10-06 01:45:57 +0200228static void copy_characters(
229 PyObject *to, Py_ssize_t to_start,
230 PyObject *from, Py_ssize_t from_start,
231 Py_ssize_t how_many);
Victor Stinner488fa492011-12-12 00:01:39 +0100232static int unicode_modifiable(PyObject *unicode);
233
Victor Stinnerfe226c02011-10-03 03:52:20 +0200234
Alexander Belopolsky40018472011-02-26 01:02:56 +0000235static PyObject *
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200236unicode_fromascii(const unsigned char *s, Py_ssize_t size);
237static PyObject *
238_PyUnicode_FromUCS1(const unsigned char *s, Py_ssize_t size);
239static PyObject *
240_PyUnicode_FromUCS2(const Py_UCS2 *s, Py_ssize_t size);
241static PyObject *
242_PyUnicode_FromUCS4(const Py_UCS4 *s, Py_ssize_t size);
243
244static PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +0000245unicode_encode_call_errorhandler(const char *errors,
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000246 PyObject **errorHandler,const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +0100247 PyObject *unicode, PyObject **exceptionObject,
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000248 Py_ssize_t startpos, Py_ssize_t endpos, Py_ssize_t *newpos);
249
Alexander Belopolsky40018472011-02-26 01:02:56 +0000250static void
251raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +0300252 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +0100253 PyObject *unicode,
254 Py_ssize_t startpos, Py_ssize_t endpos,
255 const char *reason);
Victor Stinner31be90b2010-04-22 19:38:16 +0000256
Christian Heimes190d79e2008-01-30 11:58:22 +0000257/* Same for linebreaks */
258static unsigned char ascii_linebreak[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000259 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000260/* 0x000A, * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000261/* 0x000B, * LINE TABULATION */
262/* 0x000C, * FORM FEED */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000263/* 0x000D, * CARRIAGE RETURN */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000264 0, 0, 1, 1, 1, 1, 0, 0,
Benjamin Peterson14339b62009-01-31 16:36:08 +0000265 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000266/* 0x001C, * FILE SEPARATOR */
267/* 0x001D, * GROUP SEPARATOR */
268/* 0x001E, * RECORD SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000269 0, 0, 0, 0, 1, 1, 1, 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,
Christian Heimes190d79e2008-01-30 11:58:22 +0000274
Benjamin Peterson14339b62009-01-31 16:36:08 +0000275 0, 0, 0, 0, 0, 0, 0, 0,
276 0, 0, 0, 0, 0, 0, 0, 0,
277 0, 0, 0, 0, 0, 0, 0, 0,
278 0, 0, 0, 0, 0, 0, 0, 0,
279 0, 0, 0, 0, 0, 0, 0, 0,
280 0, 0, 0, 0, 0, 0, 0, 0,
281 0, 0, 0, 0, 0, 0, 0, 0,
282 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000283};
284
Ezio Melotti48a2f8f2011-09-29 00:18:19 +0300285/* The max unicode value is always 0x10FFFF while using the PEP-393 API.
286 This function is kept for backward compatibility with the old API. */
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000287Py_UNICODE
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +0000288PyUnicode_GetMax(void)
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000289{
Fredrik Lundh8f455852001-06-27 18:59:43 +0000290#ifdef Py_UNICODE_WIDE
Benjamin Peterson14339b62009-01-31 16:36:08 +0000291 return 0x10FFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000292#else
Benjamin Peterson14339b62009-01-31 16:36:08 +0000293 /* This is actually an illegal character, so it should
294 not be passed to unichr. */
295 return 0xFFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000296#endif
297}
298
Victor Stinner910337b2011-10-03 03:20:16 +0200299#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200300int
Victor Stinner7931d9a2011-11-04 00:22:48 +0100301_PyUnicode_CheckConsistency(PyObject *op, int check_content)
Victor Stinner910337b2011-10-03 03:20:16 +0200302{
303 PyASCIIObject *ascii;
304 unsigned int kind;
305
306 assert(PyUnicode_Check(op));
307
308 ascii = (PyASCIIObject *)op;
309 kind = ascii->state.kind;
310
Victor Stinnera3b334d2011-10-03 13:53:37 +0200311 if (ascii->state.ascii == 1 && ascii->state.compact == 1) {
Victor Stinner910337b2011-10-03 03:20:16 +0200312 assert(kind == PyUnicode_1BYTE_KIND);
Victor Stinner910337b2011-10-03 03:20:16 +0200313 assert(ascii->state.ready == 1);
314 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200315 else {
Victor Stinner85041a52011-10-03 14:42:39 +0200316 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
Victor Stinner7f11ad42011-10-04 00:00:20 +0200317 void *data;
Victor Stinner910337b2011-10-03 03:20:16 +0200318
Victor Stinnera41463c2011-10-04 01:05:08 +0200319 if (ascii->state.compact == 1) {
320 data = compact + 1;
Victor Stinner910337b2011-10-03 03:20:16 +0200321 assert(kind == PyUnicode_1BYTE_KIND
322 || kind == PyUnicode_2BYTE_KIND
323 || kind == PyUnicode_4BYTE_KIND);
Victor Stinnera41463c2011-10-04 01:05:08 +0200324 assert(ascii->state.ascii == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200325 assert(ascii->state.ready == 1);
Victor Stinnera41463c2011-10-04 01:05:08 +0200326 assert (compact->utf8 != data);
Victor Stinnere30c0a12011-11-04 20:54:05 +0100327 }
328 else {
Victor Stinnera41463c2011-10-04 01:05:08 +0200329 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
330
331 data = unicode->data.any;
332 if (kind == PyUnicode_WCHAR_KIND) {
Victor Stinnere30c0a12011-11-04 20:54:05 +0100333 assert(ascii->length == 0);
334 assert(ascii->hash == -1);
Victor Stinnera41463c2011-10-04 01:05:08 +0200335 assert(ascii->state.compact == 0);
336 assert(ascii->state.ascii == 0);
337 assert(ascii->state.ready == 0);
Victor Stinnere30c0a12011-11-04 20:54:05 +0100338 assert(ascii->state.interned == SSTATE_NOT_INTERNED);
Victor Stinnera41463c2011-10-04 01:05:08 +0200339 assert(ascii->wstr != NULL);
340 assert(data == NULL);
341 assert(compact->utf8 == NULL);
Victor Stinnera41463c2011-10-04 01:05:08 +0200342 }
343 else {
344 assert(kind == PyUnicode_1BYTE_KIND
345 || kind == PyUnicode_2BYTE_KIND
346 || kind == PyUnicode_4BYTE_KIND);
347 assert(ascii->state.compact == 0);
348 assert(ascii->state.ready == 1);
349 assert(data != NULL);
350 if (ascii->state.ascii) {
351 assert (compact->utf8 == data);
352 assert (compact->utf8_length == ascii->length);
353 }
354 else
355 assert (compact->utf8 != data);
356 }
357 }
358 if (kind != PyUnicode_WCHAR_KIND) {
Victor Stinner7f11ad42011-10-04 00:00:20 +0200359 if (
360#if SIZEOF_WCHAR_T == 2
361 kind == PyUnicode_2BYTE_KIND
362#else
363 kind == PyUnicode_4BYTE_KIND
364#endif
365 )
Victor Stinnera41463c2011-10-04 01:05:08 +0200366 {
367 assert(ascii->wstr == data);
368 assert(compact->wstr_length == ascii->length);
369 } else
370 assert(ascii->wstr != data);
Victor Stinner910337b2011-10-03 03:20:16 +0200371 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200372
373 if (compact->utf8 == NULL)
374 assert(compact->utf8_length == 0);
375 if (ascii->wstr == NULL)
376 assert(compact->wstr_length == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200377 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200378 /* check that the best kind is used */
379 if (check_content && kind != PyUnicode_WCHAR_KIND)
380 {
381 Py_ssize_t i;
382 Py_UCS4 maxchar = 0;
Victor Stinner718fbf02012-04-26 00:39:37 +0200383 void *data;
384 Py_UCS4 ch;
385
386 data = PyUnicode_DATA(ascii);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200387 for (i=0; i < ascii->length; i++)
388 {
Victor Stinner718fbf02012-04-26 00:39:37 +0200389 ch = PyUnicode_READ(kind, data, i);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200390 if (ch > maxchar)
391 maxchar = ch;
392 }
393 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinner77faf692011-11-20 18:56:05 +0100394 if (ascii->state.ascii == 0) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200395 assert(maxchar >= 128);
Victor Stinner77faf692011-11-20 18:56:05 +0100396 assert(maxchar <= 255);
397 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200398 else
399 assert(maxchar < 128);
400 }
Victor Stinner77faf692011-11-20 18:56:05 +0100401 else if (kind == PyUnicode_2BYTE_KIND) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200402 assert(maxchar >= 0x100);
Victor Stinner77faf692011-11-20 18:56:05 +0100403 assert(maxchar <= 0xFFFF);
404 }
405 else {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200406 assert(maxchar >= 0x10000);
Victor Stinner8faf8212011-12-08 22:14:11 +0100407 assert(maxchar <= MAX_UNICODE);
Victor Stinner77faf692011-11-20 18:56:05 +0100408 }
Victor Stinner718fbf02012-04-26 00:39:37 +0200409 assert(PyUnicode_READ(kind, data, ascii->length) == 0);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200410 }
Benjamin Petersonccc51c12011-10-03 19:34:12 -0400411 return 1;
412}
Victor Stinner910337b2011-10-03 03:20:16 +0200413#endif
414
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100415static PyObject*
416unicode_result_wchar(PyObject *unicode)
417{
418#ifndef Py_DEBUG
419 Py_ssize_t len;
420
421 assert(Py_REFCNT(unicode) == 1);
422
423 len = _PyUnicode_WSTR_LENGTH(unicode);
424 if (len == 0) {
425 Py_INCREF(unicode_empty);
426 Py_DECREF(unicode);
427 return unicode_empty;
428 }
429
430 if (len == 1) {
431 wchar_t ch = _PyUnicode_WSTR(unicode)[0];
432 if (ch < 256) {
433 PyObject *latin1_char = get_latin1_char((unsigned char)ch);
434 Py_DECREF(unicode);
435 return latin1_char;
436 }
437 }
438
439 if (_PyUnicode_Ready(unicode) < 0) {
440 Py_XDECREF(unicode);
441 return NULL;
442 }
443#else
444 /* don't make the result ready in debug mode to ensure that the caller
445 makes the string ready before using it */
446 assert(_PyUnicode_CheckConsistency(unicode, 1));
447#endif
448 return unicode;
449}
450
451static PyObject*
452unicode_result_ready(PyObject *unicode)
453{
454 Py_ssize_t length;
455
456 length = PyUnicode_GET_LENGTH(unicode);
457 if (length == 0) {
458 if (unicode != unicode_empty) {
459 Py_INCREF(unicode_empty);
460 Py_DECREF(unicode);
461 }
462 return unicode_empty;
463 }
464
465 if (length == 1) {
466 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, 0);
467 if (ch < 256) {
468 PyObject *latin1_char = unicode_latin1[ch];
469 if (latin1_char != NULL) {
470 if (unicode != latin1_char) {
471 Py_INCREF(latin1_char);
472 Py_DECREF(unicode);
473 }
474 return latin1_char;
475 }
476 else {
477 assert(_PyUnicode_CheckConsistency(unicode, 1));
478 Py_INCREF(unicode);
479 unicode_latin1[ch] = unicode;
480 return unicode;
481 }
482 }
483 }
484
485 assert(_PyUnicode_CheckConsistency(unicode, 1));
486 return unicode;
487}
488
489static PyObject*
490unicode_result(PyObject *unicode)
491{
492 assert(_PyUnicode_CHECK(unicode));
493 if (PyUnicode_IS_READY(unicode))
494 return unicode_result_ready(unicode);
495 else
496 return unicode_result_wchar(unicode);
497}
498
Victor Stinnerc4b49542011-12-11 22:44:26 +0100499static PyObject*
500unicode_result_unchanged(PyObject *unicode)
501{
502 if (PyUnicode_CheckExact(unicode)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -0500503 if (PyUnicode_READY(unicode) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +0100504 return NULL;
505 Py_INCREF(unicode);
506 return unicode;
507 }
508 else
509 /* Subtype -- return genuine unicode string with the same value. */
Victor Stinnerbf6e5602011-12-12 01:53:47 +0100510 return _PyUnicode_Copy(unicode);
Victor Stinnerc4b49542011-12-11 22:44:26 +0100511}
512
Victor Stinner3a50e702011-10-18 21:21:00 +0200513#ifdef HAVE_MBCS
514static OSVERSIONINFOEX winver;
515#endif
516
Thomas Wouters477c8d52006-05-27 19:21:47 +0000517/* --- Bloom Filters ----------------------------------------------------- */
518
519/* stuff to implement simple "bloom filters" for Unicode characters.
520 to keep things simple, we use a single bitmask, using the least 5
521 bits from each unicode characters as the bit index. */
522
523/* the linebreak mask is set up by Unicode_Init below */
524
Antoine Pitrouf068f942010-01-13 14:19:12 +0000525#if LONG_BIT >= 128
526#define BLOOM_WIDTH 128
527#elif LONG_BIT >= 64
528#define BLOOM_WIDTH 64
529#elif LONG_BIT >= 32
530#define BLOOM_WIDTH 32
531#else
532#error "LONG_BIT is smaller than 32"
533#endif
534
Thomas Wouters477c8d52006-05-27 19:21:47 +0000535#define BLOOM_MASK unsigned long
536
537static BLOOM_MASK bloom_linebreak;
538
Antoine Pitrouf068f942010-01-13 14:19:12 +0000539#define BLOOM_ADD(mask, ch) ((mask |= (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
540#define BLOOM(mask, ch) ((mask & (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000541
Benjamin Peterson29060642009-01-31 22:14:21 +0000542#define BLOOM_LINEBREAK(ch) \
543 ((ch) < 128U ? ascii_linebreak[(ch)] : \
544 (BLOOM(bloom_linebreak, (ch)) && Py_UNICODE_ISLINEBREAK(ch)))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000545
Alexander Belopolsky40018472011-02-26 01:02:56 +0000546Py_LOCAL_INLINE(BLOOM_MASK)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200547make_bloom_mask(int kind, void* ptr, Py_ssize_t len)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000548{
549 /* calculate simple bloom-style bitmask for a given unicode string */
550
Antoine Pitrouf068f942010-01-13 14:19:12 +0000551 BLOOM_MASK mask;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000552 Py_ssize_t i;
553
554 mask = 0;
555 for (i = 0; i < len; i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200556 BLOOM_ADD(mask, PyUnicode_READ(kind, ptr, i));
Thomas Wouters477c8d52006-05-27 19:21:47 +0000557
558 return mask;
559}
560
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200561#define BLOOM_MEMBER(mask, chr, str) \
562 (BLOOM(mask, chr) \
563 && (PyUnicode_FindChar(str, chr, 0, PyUnicode_GET_LENGTH(str), 1) >= 0))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000564
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200565/* Compilation of templated routines */
566
567#include "stringlib/asciilib.h"
568#include "stringlib/fastsearch.h"
569#include "stringlib/partition.h"
570#include "stringlib/split.h"
571#include "stringlib/count.h"
572#include "stringlib/find.h"
573#include "stringlib/find_max_char.h"
574#include "stringlib/localeutil.h"
575#include "stringlib/undef.h"
576
577#include "stringlib/ucs1lib.h"
578#include "stringlib/fastsearch.h"
579#include "stringlib/partition.h"
580#include "stringlib/split.h"
581#include "stringlib/count.h"
582#include "stringlib/find.h"
583#include "stringlib/find_max_char.h"
584#include "stringlib/localeutil.h"
585#include "stringlib/undef.h"
586
587#include "stringlib/ucs2lib.h"
588#include "stringlib/fastsearch.h"
589#include "stringlib/partition.h"
590#include "stringlib/split.h"
591#include "stringlib/count.h"
592#include "stringlib/find.h"
593#include "stringlib/find_max_char.h"
594#include "stringlib/localeutil.h"
595#include "stringlib/undef.h"
596
597#include "stringlib/ucs4lib.h"
598#include "stringlib/fastsearch.h"
599#include "stringlib/partition.h"
600#include "stringlib/split.h"
601#include "stringlib/count.h"
602#include "stringlib/find.h"
603#include "stringlib/find_max_char.h"
604#include "stringlib/localeutil.h"
605#include "stringlib/undef.h"
606
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200607#include "stringlib/unicodedefs.h"
608#include "stringlib/fastsearch.h"
609#include "stringlib/count.h"
610#include "stringlib/find.h"
Antoine Pitrou0a3229d2011-11-21 20:39:13 +0100611#include "stringlib/undef.h"
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200612
Guido van Rossumd57fd912000-03-10 22:53:23 +0000613/* --- Unicode Object ----------------------------------------------------- */
614
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200615static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +0200616fixup(PyObject *self, Py_UCS4 (*fixfct)(PyObject *s));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200617
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200618Py_LOCAL_INLINE(Py_ssize_t) findchar(void *s, int kind,
619 Py_ssize_t size, Py_UCS4 ch,
620 int direction)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200621{
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200622 int mode = (direction == 1) ? FAST_SEARCH : FAST_RSEARCH;
623
624 switch (kind) {
625 case PyUnicode_1BYTE_KIND:
626 {
627 Py_UCS1 ch1 = (Py_UCS1) ch;
628 if (ch1 == ch)
629 return ucs1lib_fastsearch((Py_UCS1 *) s, size, &ch1, 1, 0, mode);
630 else
631 return -1;
632 }
633 case PyUnicode_2BYTE_KIND:
634 {
635 Py_UCS2 ch2 = (Py_UCS2) ch;
636 if (ch2 == ch)
637 return ucs2lib_fastsearch((Py_UCS2 *) s, size, &ch2, 1, 0, mode);
638 else
639 return -1;
640 }
641 case PyUnicode_4BYTE_KIND:
642 return ucs4lib_fastsearch((Py_UCS4 *) s, size, &ch, 1, 0, mode);
643 default:
644 assert(0);
645 return -1;
Victor Stinner9e7a1bc2011-10-13 00:18:12 +0200646 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200647}
648
Victor Stinnerfe226c02011-10-03 03:52:20 +0200649static PyObject*
650resize_compact(PyObject *unicode, Py_ssize_t length)
651{
652 Py_ssize_t char_size;
653 Py_ssize_t struct_size;
654 Py_ssize_t new_size;
655 int share_wstr;
Victor Stinner84def372011-12-11 20:04:56 +0100656 PyObject *new_unicode;
Victor Stinner79891572012-05-03 13:43:07 +0200657 assert(unicode_modifiable(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200658 assert(PyUnicode_IS_READY(unicode));
Victor Stinner488fa492011-12-12 00:01:39 +0100659 assert(PyUnicode_IS_COMPACT(unicode));
660
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200661 char_size = PyUnicode_KIND(unicode);
Victor Stinner488fa492011-12-12 00:01:39 +0100662 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerfe226c02011-10-03 03:52:20 +0200663 struct_size = sizeof(PyASCIIObject);
664 else
665 struct_size = sizeof(PyCompactUnicodeObject);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200666 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200667
Victor Stinnerfe226c02011-10-03 03:52:20 +0200668 if (length > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1)) {
669 PyErr_NoMemory();
670 return NULL;
671 }
672 new_size = (struct_size + (length + 1) * char_size);
673
Victor Stinner84def372011-12-11 20:04:56 +0100674 _Py_DEC_REFTOTAL;
675 _Py_ForgetReference(unicode);
676
677 new_unicode = (PyObject *)PyObject_REALLOC((char *)unicode, new_size);
678 if (new_unicode == NULL) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +0100679 _Py_NewReference(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200680 PyErr_NoMemory();
681 return NULL;
682 }
Victor Stinner84def372011-12-11 20:04:56 +0100683 unicode = new_unicode;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200684 _Py_NewReference(unicode);
Victor Stinner84def372011-12-11 20:04:56 +0100685
Victor Stinnerfe226c02011-10-03 03:52:20 +0200686 _PyUnicode_LENGTH(unicode) = length;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200687 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200688 _PyUnicode_WSTR(unicode) = PyUnicode_DATA(unicode);
Victor Stinner488fa492011-12-12 00:01:39 +0100689 if (!PyUnicode_IS_ASCII(unicode))
Victor Stinnerc379ead2011-10-03 12:52:27 +0200690 _PyUnicode_WSTR_LENGTH(unicode) = length;
691 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200692 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
693 length, 0);
Victor Stinner79891572012-05-03 13:43:07 +0200694 assert(_PyUnicode_CheckConsistency(unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200695 return unicode;
696}
697
Alexander Belopolsky40018472011-02-26 01:02:56 +0000698static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200699resize_inplace(PyObject *unicode, Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000700{
Victor Stinner95663112011-10-04 01:03:50 +0200701 wchar_t *wstr;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100702 Py_ssize_t new_size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200703 assert(!PyUnicode_IS_COMPACT(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200704 assert(Py_REFCNT(unicode) == 1);
Tim Petersced69f82003-09-16 20:30:58 +0000705
Victor Stinnerfe226c02011-10-03 03:52:20 +0200706 if (PyUnicode_IS_READY(unicode)) {
707 Py_ssize_t char_size;
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200708 int share_wstr, share_utf8;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200709 void *data;
710
711 data = _PyUnicode_DATA_ANY(unicode);
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200712 char_size = PyUnicode_KIND(unicode);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200713 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
714 share_utf8 = _PyUnicode_SHARE_UTF8(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200715
716 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
717 PyErr_NoMemory();
718 return -1;
719 }
720 new_size = (length + 1) * char_size;
721
Victor Stinner7a9105a2011-12-12 00:13:42 +0100722 if (!share_utf8 && _PyUnicode_HAS_UTF8_MEMORY(unicode))
723 {
724 PyObject_DEL(_PyUnicode_UTF8(unicode));
725 _PyUnicode_UTF8(unicode) = NULL;
726 _PyUnicode_UTF8_LENGTH(unicode) = 0;
727 }
728
Victor Stinnerfe226c02011-10-03 03:52:20 +0200729 data = (PyObject *)PyObject_REALLOC(data, new_size);
730 if (data == NULL) {
731 PyErr_NoMemory();
732 return -1;
733 }
734 _PyUnicode_DATA_ANY(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200735 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200736 _PyUnicode_WSTR(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200737 _PyUnicode_WSTR_LENGTH(unicode) = length;
738 }
739 if (share_utf8) {
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200740 _PyUnicode_UTF8(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200741 _PyUnicode_UTF8_LENGTH(unicode) = length;
742 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200743 _PyUnicode_LENGTH(unicode) = length;
744 PyUnicode_WRITE(PyUnicode_KIND(unicode), data, length, 0);
Victor Stinner95663112011-10-04 01:03:50 +0200745 if (share_wstr || _PyUnicode_WSTR(unicode) == NULL) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200746 assert(_PyUnicode_CheckConsistency(unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200747 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200748 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200749 }
Victor Stinner95663112011-10-04 01:03:50 +0200750 assert(_PyUnicode_WSTR(unicode) != NULL);
751
752 /* check for integer overflow */
753 if (length > PY_SSIZE_T_MAX / sizeof(wchar_t) - 1) {
754 PyErr_NoMemory();
755 return -1;
756 }
Victor Stinner7a9105a2011-12-12 00:13:42 +0100757 new_size = sizeof(wchar_t) * (length + 1);
Victor Stinner95663112011-10-04 01:03:50 +0200758 wstr = _PyUnicode_WSTR(unicode);
Victor Stinner7a9105a2011-12-12 00:13:42 +0100759 wstr = PyObject_REALLOC(wstr, new_size);
Victor Stinner95663112011-10-04 01:03:50 +0200760 if (!wstr) {
761 PyErr_NoMemory();
762 return -1;
763 }
764 _PyUnicode_WSTR(unicode) = wstr;
765 _PyUnicode_WSTR(unicode)[length] = 0;
766 _PyUnicode_WSTR_LENGTH(unicode) = length;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200767 assert(_PyUnicode_CheckConsistency(unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +0000768 return 0;
769}
770
Victor Stinnerfe226c02011-10-03 03:52:20 +0200771static PyObject*
772resize_copy(PyObject *unicode, Py_ssize_t length)
773{
774 Py_ssize_t copy_length;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100775 if (_PyUnicode_KIND(unicode) != PyUnicode_WCHAR_KIND) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200776 PyObject *copy;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100777
Benjamin Petersonbac79492012-01-14 13:34:47 -0500778 if (PyUnicode_READY(unicode) == -1)
Victor Stinner7a9105a2011-12-12 00:13:42 +0100779 return NULL;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200780
781 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
782 if (copy == NULL)
783 return NULL;
784
785 copy_length = Py_MIN(length, PyUnicode_GET_LENGTH(unicode));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200786 copy_characters(copy, 0, unicode, 0, copy_length);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200787 return copy;
Victor Stinner8cfcbed2011-10-03 23:19:21 +0200788 }
789 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200790 PyObject *w;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100791
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200792 w = (PyObject*)_PyUnicode_New(length);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200793 if (w == NULL)
794 return NULL;
795 copy_length = _PyUnicode_WSTR_LENGTH(unicode);
796 copy_length = Py_MIN(copy_length, length);
797 Py_UNICODE_COPY(_PyUnicode_WSTR(w), _PyUnicode_WSTR(unicode),
798 copy_length);
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200799 return w;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200800 }
801}
802
Guido van Rossumd57fd912000-03-10 22:53:23 +0000803/* We allocate one more byte to make sure the string is
Martin v. Löwis47383402007-08-15 07:32:56 +0000804 Ux0000 terminated; some code (e.g. new_identifier)
805 relies on that.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000806
807 XXX This allocator could further be enhanced by assuring that the
Benjamin Peterson29060642009-01-31 22:14:21 +0000808 free list never reduces its size below 1.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000809
810*/
811
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200812#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +0200813static int unicode_old_new_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200814#endif
815
Alexander Belopolsky40018472011-02-26 01:02:56 +0000816static PyUnicodeObject *
817_PyUnicode_New(Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000818{
819 register PyUnicodeObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200820 size_t new_size;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000821
Thomas Wouters477c8d52006-05-27 19:21:47 +0000822 /* Optimization for empty strings */
Guido van Rossumd57fd912000-03-10 22:53:23 +0000823 if (length == 0 && unicode_empty != NULL) {
824 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +0200825 return (PyUnicodeObject*)unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000826 }
827
Neal Norwitz3ce5d922008-08-24 07:08:55 +0000828 /* Ensure we won't overflow the size. */
829 if (length > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
830 return (PyUnicodeObject *)PyErr_NoMemory();
831 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200832 if (length < 0) {
833 PyErr_SetString(PyExc_SystemError,
834 "Negative size passed to _PyUnicode_New");
835 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000836 }
837
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200838#ifdef Py_DEBUG
839 ++unicode_old_new_calls;
840#endif
841
842 unicode = PyObject_New(PyUnicodeObject, &PyUnicode_Type);
843 if (unicode == NULL)
844 return NULL;
845 new_size = sizeof(Py_UNICODE) * ((size_t)length + 1);
846 _PyUnicode_WSTR(unicode) = (Py_UNICODE*) PyObject_MALLOC(new_size);
847 if (!_PyUnicode_WSTR(unicode)) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +0100848 Py_DECREF(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +0000849 PyErr_NoMemory();
Victor Stinnerb0a82a62011-12-12 13:08:33 +0100850 return NULL;
Guido van Rossum3c1bb802000-04-27 20:13:50 +0000851 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200852
Jeremy Hyltond8082792003-09-16 19:41:39 +0000853 /* Initialize the first element to guard against cases where
Tim Petersced69f82003-09-16 20:30:58 +0000854 * the caller fails before initializing str -- unicode_resize()
855 * reads str[0], and the Keep-Alive optimization can keep memory
856 * allocated for str alive across a call to unicode_dealloc(unicode).
857 * We don't want unicode_resize to read uninitialized memory in
858 * that case.
859 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200860 _PyUnicode_WSTR(unicode)[0] = 0;
861 _PyUnicode_WSTR(unicode)[length] = 0;
862 _PyUnicode_WSTR_LENGTH(unicode) = length;
863 _PyUnicode_HASH(unicode) = -1;
864 _PyUnicode_STATE(unicode).interned = 0;
865 _PyUnicode_STATE(unicode).kind = 0;
866 _PyUnicode_STATE(unicode).compact = 0;
867 _PyUnicode_STATE(unicode).ready = 0;
868 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +0200869 _PyUnicode_DATA_ANY(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200870 _PyUnicode_LENGTH(unicode) = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200871 _PyUnicode_UTF8(unicode) = NULL;
872 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner7931d9a2011-11-04 00:22:48 +0100873 assert(_PyUnicode_CheckConsistency((PyObject *)unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +0000874 return unicode;
875}
876
Victor Stinnerf42dc442011-10-02 23:33:16 +0200877static const char*
878unicode_kind_name(PyObject *unicode)
879{
Victor Stinner42dfd712011-10-03 14:41:45 +0200880 /* don't check consistency: unicode_kind_name() is called from
881 _PyUnicode_Dump() */
Victor Stinnerf42dc442011-10-02 23:33:16 +0200882 if (!PyUnicode_IS_COMPACT(unicode))
883 {
884 if (!PyUnicode_IS_READY(unicode))
885 return "wstr";
Benjamin Petersonead6b532011-12-20 17:23:42 -0600886 switch (PyUnicode_KIND(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200887 {
888 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200889 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200890 return "legacy ascii";
891 else
892 return "legacy latin1";
893 case PyUnicode_2BYTE_KIND:
894 return "legacy UCS2";
895 case PyUnicode_4BYTE_KIND:
896 return "legacy UCS4";
897 default:
898 return "<legacy invalid kind>";
899 }
900 }
901 assert(PyUnicode_IS_READY(unicode));
Benjamin Petersonead6b532011-12-20 17:23:42 -0600902 switch (PyUnicode_KIND(unicode)) {
Victor Stinnerf42dc442011-10-02 23:33:16 +0200903 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200904 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200905 return "ascii";
906 else
Victor Stinnera3b334d2011-10-03 13:53:37 +0200907 return "latin1";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200908 case PyUnicode_2BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200909 return "UCS2";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200910 case PyUnicode_4BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200911 return "UCS4";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200912 default:
913 return "<invalid compact kind>";
914 }
915}
916
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200917#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +0200918static int unicode_new_new_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200919
920/* Functions wrapping macros for use in debugger */
921char *_PyUnicode_utf8(void *unicode){
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200922 return PyUnicode_UTF8(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200923}
924
925void *_PyUnicode_compact_data(void *unicode) {
926 return _PyUnicode_COMPACT_DATA(unicode);
927}
928void *_PyUnicode_data(void *unicode){
929 printf("obj %p\n", unicode);
930 printf("compact %d\n", PyUnicode_IS_COMPACT(unicode));
931 printf("compact ascii %d\n", PyUnicode_IS_COMPACT_ASCII(unicode));
932 printf("ascii op %p\n", ((void*)((PyASCIIObject*)(unicode) + 1)));
933 printf("compact op %p\n", ((void*)((PyCompactUnicodeObject*)(unicode) + 1)));
934 printf("compact data %p\n", _PyUnicode_COMPACT_DATA(unicode));
935 return PyUnicode_DATA(unicode);
936}
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200937
938void
939_PyUnicode_Dump(PyObject *op)
940{
941 PyASCIIObject *ascii = (PyASCIIObject *)op;
Victor Stinnera849a4b2011-10-03 12:12:11 +0200942 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
943 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
944 void *data;
Victor Stinner0d60e872011-10-23 19:47:19 +0200945
Victor Stinnera849a4b2011-10-03 12:12:11 +0200946 if (ascii->state.compact)
Victor Stinner0d60e872011-10-23 19:47:19 +0200947 {
948 if (ascii->state.ascii)
949 data = (ascii + 1);
950 else
951 data = (compact + 1);
952 }
Victor Stinnera849a4b2011-10-03 12:12:11 +0200953 else
954 data = unicode->data.any;
Victor Stinner0d60e872011-10-23 19:47:19 +0200955 printf("%s: len=%zu, ",unicode_kind_name(op), ascii->length);
956
Victor Stinnera849a4b2011-10-03 12:12:11 +0200957 if (ascii->wstr == data)
958 printf("shared ");
959 printf("wstr=%p", ascii->wstr);
Victor Stinner0d60e872011-10-23 19:47:19 +0200960
Victor Stinnera3b334d2011-10-03 13:53:37 +0200961 if (!(ascii->state.ascii == 1 && ascii->state.compact == 1)) {
Victor Stinnera849a4b2011-10-03 12:12:11 +0200962 printf(" (%zu), ", compact->wstr_length);
963 if (!ascii->state.compact && compact->utf8 == unicode->data.any)
964 printf("shared ");
965 printf("utf8=%p (%zu)", compact->utf8, compact->utf8_length);
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200966 }
Victor Stinnera849a4b2011-10-03 12:12:11 +0200967 printf(", data=%p\n", data);
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200968}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200969#endif
970
971PyObject *
972PyUnicode_New(Py_ssize_t size, Py_UCS4 maxchar)
973{
974 PyObject *obj;
975 PyCompactUnicodeObject *unicode;
976 void *data;
Victor Stinner8f825062012-04-27 13:55:39 +0200977 enum PyUnicode_Kind kind;
Victor Stinner9e9d6892011-10-04 01:02:02 +0200978 int is_sharing, is_ascii;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200979 Py_ssize_t char_size;
980 Py_ssize_t struct_size;
981
982 /* Optimization for empty strings */
983 if (size == 0 && unicode_empty != NULL) {
984 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +0200985 return unicode_empty;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200986 }
987
988#ifdef Py_DEBUG
989 ++unicode_new_new_calls;
990#endif
991
Victor Stinner9e9d6892011-10-04 01:02:02 +0200992 is_ascii = 0;
993 is_sharing = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200994 struct_size = sizeof(PyCompactUnicodeObject);
995 if (maxchar < 128) {
Victor Stinner8f825062012-04-27 13:55:39 +0200996 kind = PyUnicode_1BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200997 char_size = 1;
998 is_ascii = 1;
999 struct_size = sizeof(PyASCIIObject);
1000 }
1001 else if (maxchar < 256) {
Victor Stinner8f825062012-04-27 13:55:39 +02001002 kind = PyUnicode_1BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001003 char_size = 1;
1004 }
1005 else if (maxchar < 65536) {
Victor Stinner8f825062012-04-27 13:55:39 +02001006 kind = PyUnicode_2BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001007 char_size = 2;
1008 if (sizeof(wchar_t) == 2)
1009 is_sharing = 1;
1010 }
1011 else {
Victor Stinnerc9590ad2012-03-04 01:34:37 +01001012 if (maxchar > MAX_UNICODE) {
1013 PyErr_SetString(PyExc_SystemError,
1014 "invalid maximum character passed to PyUnicode_New");
1015 return NULL;
1016 }
Victor Stinner8f825062012-04-27 13:55:39 +02001017 kind = PyUnicode_4BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001018 char_size = 4;
1019 if (sizeof(wchar_t) == 4)
1020 is_sharing = 1;
1021 }
1022
1023 /* Ensure we won't overflow the size. */
1024 if (size < 0) {
1025 PyErr_SetString(PyExc_SystemError,
1026 "Negative size passed to PyUnicode_New");
1027 return NULL;
1028 }
1029 if (size > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1))
1030 return PyErr_NoMemory();
1031
1032 /* Duplicated allocation code from _PyObject_New() instead of a call to
1033 * PyObject_New() so we are able to allocate space for the object and
1034 * it's data buffer.
1035 */
1036 obj = (PyObject *) PyObject_MALLOC(struct_size + (size + 1) * char_size);
1037 if (obj == NULL)
1038 return PyErr_NoMemory();
1039 obj = PyObject_INIT(obj, &PyUnicode_Type);
1040 if (obj == NULL)
1041 return NULL;
1042
1043 unicode = (PyCompactUnicodeObject *)obj;
1044 if (is_ascii)
1045 data = ((PyASCIIObject*)obj) + 1;
1046 else
1047 data = unicode + 1;
1048 _PyUnicode_LENGTH(unicode) = size;
1049 _PyUnicode_HASH(unicode) = -1;
1050 _PyUnicode_STATE(unicode).interned = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001051 _PyUnicode_STATE(unicode).kind = kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001052 _PyUnicode_STATE(unicode).compact = 1;
1053 _PyUnicode_STATE(unicode).ready = 1;
1054 _PyUnicode_STATE(unicode).ascii = is_ascii;
1055 if (is_ascii) {
1056 ((char*)data)[size] = 0;
1057 _PyUnicode_WSTR(unicode) = NULL;
1058 }
Victor Stinner8f825062012-04-27 13:55:39 +02001059 else if (kind == PyUnicode_1BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001060 ((char*)data)[size] = 0;
1061 _PyUnicode_WSTR(unicode) = NULL;
1062 _PyUnicode_WSTR_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001063 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001064 unicode->utf8_length = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001065 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001066 else {
1067 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001068 unicode->utf8_length = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001069 if (kind == PyUnicode_2BYTE_KIND)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001070 ((Py_UCS2*)data)[size] = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001071 else /* kind == PyUnicode_4BYTE_KIND */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001072 ((Py_UCS4*)data)[size] = 0;
1073 if (is_sharing) {
1074 _PyUnicode_WSTR_LENGTH(unicode) = size;
1075 _PyUnicode_WSTR(unicode) = (wchar_t *)data;
1076 }
1077 else {
1078 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1079 _PyUnicode_WSTR(unicode) = NULL;
1080 }
1081 }
Victor Stinner8f825062012-04-27 13:55:39 +02001082#ifdef Py_DEBUG
1083 /* Fill the data with invalid characters to detect bugs earlier.
1084 _PyUnicode_CheckConsistency(str, 1) detects invalid characters,
1085 at least for ASCII and UCS-4 strings. U+00FF is invalid in ASCII
1086 and U+FFFFFFFF is an invalid character in Unicode 6.0. */
1087 memset(data, 0xff, size * kind);
1088#endif
Victor Stinner7931d9a2011-11-04 00:22:48 +01001089 assert(_PyUnicode_CheckConsistency((PyObject*)unicode, 0));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001090 return obj;
1091}
1092
1093#if SIZEOF_WCHAR_T == 2
1094/* Helper function to convert a 16-bits wchar_t representation to UCS4, this
1095 will decode surrogate pairs, the other conversions are implemented as macros
Georg Brandl7597add2011-10-05 16:36:47 +02001096 for efficiency.
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001097
1098 This function assumes that unicode can hold one more code point than wstr
1099 characters for a terminating null character. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001100static void
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001101unicode_convert_wchar_to_ucs4(const wchar_t *begin, const wchar_t *end,
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001102 PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001103{
1104 const wchar_t *iter;
1105 Py_UCS4 *ucs4_out;
1106
Victor Stinner910337b2011-10-03 03:20:16 +02001107 assert(unicode != NULL);
1108 assert(_PyUnicode_CHECK(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001109 assert(_PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
1110 ucs4_out = PyUnicode_4BYTE_DATA(unicode);
1111
1112 for (iter = begin; iter < end; ) {
1113 assert(ucs4_out < (PyUnicode_4BYTE_DATA(unicode) +
1114 _PyUnicode_GET_LENGTH(unicode)));
Victor Stinner551ac952011-11-29 22:58:13 +01001115 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1116 && (iter+1) < end
1117 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001118 {
Victor Stinner551ac952011-11-29 22:58:13 +01001119 *ucs4_out++ = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001120 iter += 2;
1121 }
1122 else {
1123 *ucs4_out++ = *iter;
1124 iter++;
1125 }
1126 }
1127 assert(ucs4_out == (PyUnicode_4BYTE_DATA(unicode) +
1128 _PyUnicode_GET_LENGTH(unicode)));
1129
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001130}
1131#endif
1132
Victor Stinnercd9950f2011-10-02 00:34:53 +02001133static int
Victor Stinner488fa492011-12-12 00:01:39 +01001134unicode_check_modifiable(PyObject *unicode)
Victor Stinnercd9950f2011-10-02 00:34:53 +02001135{
Victor Stinner488fa492011-12-12 00:01:39 +01001136 if (!unicode_modifiable(unicode)) {
Victor Stinner01698042011-10-04 00:04:26 +02001137 PyErr_SetString(PyExc_SystemError,
Victor Stinner488fa492011-12-12 00:01:39 +01001138 "Cannot modify a string currently used");
Victor Stinnercd9950f2011-10-02 00:34:53 +02001139 return -1;
1140 }
Victor Stinnercd9950f2011-10-02 00:34:53 +02001141 return 0;
1142}
1143
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001144static int
1145_copy_characters(PyObject *to, Py_ssize_t to_start,
1146 PyObject *from, Py_ssize_t from_start,
1147 Py_ssize_t how_many, int check_maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001148{
Victor Stinnera0702ab2011-09-29 14:14:38 +02001149 unsigned int from_kind, to_kind;
1150 void *from_data, *to_data;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001151 int fast;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001152
Victor Stinneree4544c2012-05-09 22:24:08 +02001153 assert(0 <= how_many);
1154 assert(0 <= from_start);
1155 assert(0 <= to_start);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001156 assert(PyUnicode_Check(from));
1157 assert(PyUnicode_Check(to));
1158 assert(PyUnicode_IS_READY(from));
1159 assert(PyUnicode_IS_READY(to));
Victor Stinneree4544c2012-05-09 22:24:08 +02001160 assert(from_start + how_many <= PyUnicode_GET_LENGTH(from));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001161 assert(to_start + how_many <= PyUnicode_GET_LENGTH(to));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001162
Victor Stinnerf5ca1a22011-09-28 23:54:59 +02001163 if (how_many == 0)
1164 return 0;
1165
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001166 from_kind = PyUnicode_KIND(from);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001167 from_data = PyUnicode_DATA(from);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001168 to_kind = PyUnicode_KIND(to);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001169 to_data = PyUnicode_DATA(to);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001170
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001171#ifdef Py_DEBUG
1172 if (!check_maxchar
1173 && (from_kind > to_kind
1174 || (!PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to))))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001175 {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001176 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
1177 Py_UCS4 ch;
1178 Py_ssize_t i;
1179 for (i=0; i < how_many; i++) {
1180 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1181 assert(ch <= to_maxchar);
1182 }
1183 }
1184#endif
1185 fast = (from_kind == to_kind);
1186 if (check_maxchar
1187 && (!PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to)))
1188 {
1189 /* deny latin1 => ascii */
1190 fast = 0;
1191 }
1192
1193 if (fast) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +02001194 Py_MEMCPY((char*)to_data + to_kind * to_start,
1195 (char*)from_data + from_kind * from_start,
1196 to_kind * how_many);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001197 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001198 else if (from_kind == PyUnicode_1BYTE_KIND
1199 && to_kind == PyUnicode_2BYTE_KIND)
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001200 {
1201 _PyUnicode_CONVERT_BYTES(
1202 Py_UCS1, Py_UCS2,
1203 PyUnicode_1BYTE_DATA(from) + from_start,
1204 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1205 PyUnicode_2BYTE_DATA(to) + to_start
1206 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001207 }
Victor Stinner157f83f2011-09-28 21:41:31 +02001208 else if (from_kind == PyUnicode_1BYTE_KIND
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001209 && to_kind == PyUnicode_4BYTE_KIND)
1210 {
1211 _PyUnicode_CONVERT_BYTES(
1212 Py_UCS1, Py_UCS4,
1213 PyUnicode_1BYTE_DATA(from) + from_start,
1214 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1215 PyUnicode_4BYTE_DATA(to) + to_start
1216 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001217 }
1218 else if (from_kind == PyUnicode_2BYTE_KIND
1219 && to_kind == PyUnicode_4BYTE_KIND)
1220 {
1221 _PyUnicode_CONVERT_BYTES(
1222 Py_UCS2, Py_UCS4,
1223 PyUnicode_2BYTE_DATA(from) + from_start,
1224 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1225 PyUnicode_4BYTE_DATA(to) + to_start
1226 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001227 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001228 else {
Victor Stinnerf42dc442011-10-02 23:33:16 +02001229 /* check if max_char(from substring) <= max_char(to) */
1230 if (from_kind > to_kind
1231 /* latin1 => ascii */
Victor Stinnerb9275c12011-10-05 14:01:42 +02001232 || (!PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to)))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001233 {
Victor Stinnera0702ab2011-09-29 14:14:38 +02001234 /* slow path to check for character overflow */
1235 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001236 Py_UCS4 ch;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001237 Py_ssize_t i;
1238
Victor Stinner56c161a2011-10-06 02:47:11 +02001239#ifdef Py_DEBUG
Victor Stinnera0702ab2011-09-29 14:14:38 +02001240 for (i=0; i < how_many; i++) {
1241 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
Victor Stinner56c161a2011-10-06 02:47:11 +02001242 assert(ch <= to_maxchar);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001243 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1244 }
Victor Stinner56c161a2011-10-06 02:47:11 +02001245#else
1246 if (!check_maxchar) {
1247 for (i=0; i < how_many; i++) {
1248 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1249 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1250 }
1251 }
1252 else {
1253 for (i=0; i < how_many; i++) {
1254 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1255 if (ch > to_maxchar)
1256 return 1;
1257 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1258 }
1259 }
1260#endif
Victor Stinnera0702ab2011-09-29 14:14:38 +02001261 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001262 else {
Victor Stinner56c161a2011-10-06 02:47:11 +02001263 assert(0 && "inconsistent state");
1264 return 1;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001265 }
1266 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001267 return 0;
1268}
1269
1270static void
1271copy_characters(PyObject *to, Py_ssize_t to_start,
1272 PyObject *from, Py_ssize_t from_start,
1273 Py_ssize_t how_many)
1274{
1275 (void)_copy_characters(to, to_start, from, from_start, how_many, 0);
1276}
1277
1278Py_ssize_t
1279PyUnicode_CopyCharacters(PyObject *to, Py_ssize_t to_start,
1280 PyObject *from, Py_ssize_t from_start,
1281 Py_ssize_t how_many)
1282{
1283 int err;
1284
1285 if (!PyUnicode_Check(from) || !PyUnicode_Check(to)) {
1286 PyErr_BadInternalCall();
1287 return -1;
1288 }
1289
Benjamin Petersonbac79492012-01-14 13:34:47 -05001290 if (PyUnicode_READY(from) == -1)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001291 return -1;
Benjamin Petersonbac79492012-01-14 13:34:47 -05001292 if (PyUnicode_READY(to) == -1)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001293 return -1;
1294
1295 how_many = Py_MIN(PyUnicode_GET_LENGTH(from), how_many);
1296 if (to_start + how_many > PyUnicode_GET_LENGTH(to)) {
1297 PyErr_Format(PyExc_SystemError,
1298 "Cannot write %zi characters at %zi "
1299 "in a string of %zi characters",
1300 how_many, to_start, PyUnicode_GET_LENGTH(to));
1301 return -1;
1302 }
1303
1304 if (how_many == 0)
1305 return 0;
1306
Victor Stinner488fa492011-12-12 00:01:39 +01001307 if (unicode_check_modifiable(to))
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001308 return -1;
1309
1310 err = _copy_characters(to, to_start, from, from_start, how_many, 1);
1311 if (err) {
1312 PyErr_Format(PyExc_SystemError,
1313 "Cannot copy %s characters "
1314 "into a string of %s characters",
1315 unicode_kind_name(from),
1316 unicode_kind_name(to));
1317 return -1;
1318 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001319 return how_many;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001320}
1321
Victor Stinner17222162011-09-28 22:15:37 +02001322/* Find the maximum code point and count the number of surrogate pairs so a
1323 correct string length can be computed before converting a string to UCS4.
1324 This function counts single surrogates as a character and not as a pair.
1325
1326 Return 0 on success, or -1 on error. */
1327static int
1328find_maxchar_surrogates(const wchar_t *begin, const wchar_t *end,
1329 Py_UCS4 *maxchar, Py_ssize_t *num_surrogates)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001330{
1331 const wchar_t *iter;
Victor Stinner8faf8212011-12-08 22:14:11 +01001332 Py_UCS4 ch;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001333
Victor Stinnerc53be962011-10-02 21:33:54 +02001334 assert(num_surrogates != NULL && maxchar != NULL);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001335 *num_surrogates = 0;
1336 *maxchar = 0;
1337
1338 for (iter = begin; iter < end; ) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001339#if SIZEOF_WCHAR_T == 2
Victor Stinnerca4f2072011-11-22 03:38:40 +01001340 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1341 && (iter+1) < end
1342 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001343 {
Victor Stinner8faf8212011-12-08 22:14:11 +01001344 ch = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001345 ++(*num_surrogates);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001346 iter += 2;
1347 }
1348 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001349#endif
Victor Stinner8faf8212011-12-08 22:14:11 +01001350 {
1351 ch = *iter;
1352 iter++;
1353 }
1354 if (ch > *maxchar) {
1355 *maxchar = ch;
1356 if (*maxchar > MAX_UNICODE) {
1357 PyErr_Format(PyExc_ValueError,
1358 "character U+%x is not in range [U+0000; U+10ffff]",
1359 ch);
1360 return -1;
1361 }
1362 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001363 }
1364 return 0;
1365}
1366
1367#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +02001368static int unicode_ready_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001369#endif
1370
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001371int
1372_PyUnicode_Ready(PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001373{
1374 wchar_t *end;
1375 Py_UCS4 maxchar = 0;
1376 Py_ssize_t num_surrogates;
1377#if SIZEOF_WCHAR_T == 2
1378 Py_ssize_t length_wo_surrogates;
1379#endif
1380
Georg Brandl7597add2011-10-05 16:36:47 +02001381 /* _PyUnicode_Ready() is only intended for old-style API usage where
Victor Stinnerd8f65102011-09-29 19:43:17 +02001382 strings were created using _PyObject_New() and where no canonical
1383 representation (the str field) has been set yet aka strings
1384 which are not yet ready. */
Victor Stinner910337b2011-10-03 03:20:16 +02001385 assert(_PyUnicode_CHECK(unicode));
1386 assert(_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001387 assert(_PyUnicode_WSTR(unicode) != NULL);
Victor Stinnerc3c74152011-10-02 20:39:55 +02001388 assert(_PyUnicode_DATA_ANY(unicode) == NULL);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001389 assert(_PyUnicode_UTF8(unicode) == NULL);
Victor Stinnerd8f65102011-09-29 19:43:17 +02001390 /* Actually, it should neither be interned nor be anything else: */
1391 assert(_PyUnicode_STATE(unicode).interned == SSTATE_NOT_INTERNED);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001392
1393#ifdef Py_DEBUG
1394 ++unicode_ready_calls;
1395#endif
1396
1397 end = _PyUnicode_WSTR(unicode) + _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinner17222162011-09-28 22:15:37 +02001398 if (find_maxchar_surrogates(_PyUnicode_WSTR(unicode), end,
Victor Stinnerd8f65102011-09-29 19:43:17 +02001399 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001400 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001401
1402 if (maxchar < 256) {
Victor Stinnerc3c74152011-10-02 20:39:55 +02001403 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(_PyUnicode_WSTR_LENGTH(unicode) + 1);
1404 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001405 PyErr_NoMemory();
1406 return -1;
1407 }
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001408 _PyUnicode_CONVERT_BYTES(wchar_t, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001409 _PyUnicode_WSTR(unicode), end,
1410 PyUnicode_1BYTE_DATA(unicode));
1411 PyUnicode_1BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1412 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1413 _PyUnicode_STATE(unicode).kind = PyUnicode_1BYTE_KIND;
1414 if (maxchar < 128) {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001415 _PyUnicode_STATE(unicode).ascii = 1;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001416 _PyUnicode_UTF8(unicode) = _PyUnicode_DATA_ANY(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001417 _PyUnicode_UTF8_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001418 }
1419 else {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001420 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001421 _PyUnicode_UTF8(unicode) = NULL;
1422 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001423 }
1424 PyObject_FREE(_PyUnicode_WSTR(unicode));
1425 _PyUnicode_WSTR(unicode) = NULL;
1426 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1427 }
1428 /* In this case we might have to convert down from 4-byte native
1429 wchar_t to 2-byte unicode. */
1430 else if (maxchar < 65536) {
1431 assert(num_surrogates == 0 &&
1432 "FindMaxCharAndNumSurrogatePairs() messed up");
1433
Victor Stinner506f5922011-09-28 22:34:18 +02001434#if SIZEOF_WCHAR_T == 2
1435 /* We can share representations and are done. */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001436 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Victor Stinner506f5922011-09-28 22:34:18 +02001437 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1438 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1439 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001440 _PyUnicode_UTF8(unicode) = NULL;
1441 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001442#else
1443 /* sizeof(wchar_t) == 4 */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001444 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(
Victor Stinner506f5922011-09-28 22:34:18 +02001445 2 * (_PyUnicode_WSTR_LENGTH(unicode) + 1));
Victor Stinnerc3c74152011-10-02 20:39:55 +02001446 if (!_PyUnicode_DATA_ANY(unicode)) {
Victor Stinner506f5922011-09-28 22:34:18 +02001447 PyErr_NoMemory();
1448 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001449 }
Victor Stinner506f5922011-09-28 22:34:18 +02001450 _PyUnicode_CONVERT_BYTES(wchar_t, Py_UCS2,
1451 _PyUnicode_WSTR(unicode), end,
1452 PyUnicode_2BYTE_DATA(unicode));
1453 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1454 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1455 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001456 _PyUnicode_UTF8(unicode) = NULL;
1457 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001458 PyObject_FREE(_PyUnicode_WSTR(unicode));
1459 _PyUnicode_WSTR(unicode) = NULL;
1460 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1461#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001462 }
1463 /* maxchar exeeds 16 bit, wee need 4 bytes for unicode characters */
1464 else {
1465#if SIZEOF_WCHAR_T == 2
1466 /* in case the native representation is 2-bytes, we need to allocate a
1467 new normalized 4-byte version. */
1468 length_wo_surrogates = _PyUnicode_WSTR_LENGTH(unicode) - num_surrogates;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001469 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(4 * (length_wo_surrogates + 1));
1470 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001471 PyErr_NoMemory();
1472 return -1;
1473 }
1474 _PyUnicode_LENGTH(unicode) = length_wo_surrogates;
1475 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001476 _PyUnicode_UTF8(unicode) = NULL;
1477 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner126c5592011-10-03 04:17:10 +02001478 /* unicode_convert_wchar_to_ucs4() requires a ready string */
1479 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerc53be962011-10-02 21:33:54 +02001480 unicode_convert_wchar_to_ucs4(_PyUnicode_WSTR(unicode), end, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001481 PyObject_FREE(_PyUnicode_WSTR(unicode));
1482 _PyUnicode_WSTR(unicode) = NULL;
1483 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1484#else
1485 assert(num_surrogates == 0);
1486
Victor Stinnerc3c74152011-10-02 20:39:55 +02001487 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001488 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001489 _PyUnicode_UTF8(unicode) = NULL;
1490 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001491 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
1492#endif
1493 PyUnicode_4BYTE_DATA(unicode)[_PyUnicode_LENGTH(unicode)] = '\0';
1494 }
1495 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001496 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001497 return 0;
1498}
1499
Alexander Belopolsky40018472011-02-26 01:02:56 +00001500static void
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001501unicode_dealloc(register PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001502{
Walter Dörwald16807132007-05-25 13:52:07 +00001503 switch (PyUnicode_CHECK_INTERNED(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001504 case SSTATE_NOT_INTERNED:
1505 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001506
Benjamin Peterson29060642009-01-31 22:14:21 +00001507 case SSTATE_INTERNED_MORTAL:
1508 /* revive dead object temporarily for DelItem */
1509 Py_REFCNT(unicode) = 3;
Victor Stinner7931d9a2011-11-04 00:22:48 +01001510 if (PyDict_DelItem(interned, unicode) != 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00001511 Py_FatalError(
1512 "deletion of interned string failed");
1513 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001514
Benjamin Peterson29060642009-01-31 22:14:21 +00001515 case SSTATE_INTERNED_IMMORTAL:
1516 Py_FatalError("Immortal interned string died.");
Walter Dörwald16807132007-05-25 13:52:07 +00001517
Benjamin Peterson29060642009-01-31 22:14:21 +00001518 default:
1519 Py_FatalError("Inconsistent interned string state.");
Walter Dörwald16807132007-05-25 13:52:07 +00001520 }
1521
Victor Stinner03490912011-10-03 23:45:12 +02001522 if (_PyUnicode_HAS_WSTR_MEMORY(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001523 PyObject_DEL(_PyUnicode_WSTR(unicode));
Victor Stinner829c0ad2011-10-03 01:08:02 +02001524 if (_PyUnicode_HAS_UTF8_MEMORY(unicode))
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001525 PyObject_DEL(_PyUnicode_UTF8(unicode));
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001526 if (!PyUnicode_IS_COMPACT(unicode) && _PyUnicode_DATA_ANY(unicode))
1527 PyObject_DEL(_PyUnicode_DATA_ANY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001528
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001529 Py_TYPE(unicode)->tp_free(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001530}
1531
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001532#ifdef Py_DEBUG
1533static int
1534unicode_is_singleton(PyObject *unicode)
1535{
1536 PyASCIIObject *ascii = (PyASCIIObject *)unicode;
1537 if (unicode == unicode_empty)
1538 return 1;
1539 if (ascii->state.kind != PyUnicode_WCHAR_KIND && ascii->length == 1)
1540 {
1541 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, 0);
1542 if (ch < 256 && unicode_latin1[ch] == unicode)
1543 return 1;
1544 }
1545 return 0;
1546}
1547#endif
1548
Alexander Belopolsky40018472011-02-26 01:02:56 +00001549static int
Victor Stinner488fa492011-12-12 00:01:39 +01001550unicode_modifiable(PyObject *unicode)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001551{
Victor Stinner488fa492011-12-12 00:01:39 +01001552 assert(_PyUnicode_CHECK(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001553 if (Py_REFCNT(unicode) != 1)
1554 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001555 if (_PyUnicode_HASH(unicode) != -1)
1556 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001557 if (PyUnicode_CHECK_INTERNED(unicode))
1558 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001559 if (!PyUnicode_CheckExact(unicode))
1560 return 0;
Victor Stinner77bb47b2011-10-03 20:06:05 +02001561#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001562 /* singleton refcount is greater than 1 */
1563 assert(!unicode_is_singleton(unicode));
Victor Stinner77bb47b2011-10-03 20:06:05 +02001564#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +02001565 return 1;
1566}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001567
Victor Stinnerfe226c02011-10-03 03:52:20 +02001568static int
1569unicode_resize(PyObject **p_unicode, Py_ssize_t length)
1570{
1571 PyObject *unicode;
1572 Py_ssize_t old_length;
1573
1574 assert(p_unicode != NULL);
1575 unicode = *p_unicode;
1576
1577 assert(unicode != NULL);
1578 assert(PyUnicode_Check(unicode));
1579 assert(0 <= length);
1580
Victor Stinner910337b2011-10-03 03:20:16 +02001581 if (_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001582 old_length = PyUnicode_WSTR_LENGTH(unicode);
1583 else
1584 old_length = PyUnicode_GET_LENGTH(unicode);
1585 if (old_length == length)
1586 return 0;
1587
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001588 if (length == 0) {
1589 Py_DECREF(*p_unicode);
1590 *p_unicode = unicode_empty;
1591 Py_INCREF(*p_unicode);
1592 return 0;
1593 }
1594
Victor Stinner488fa492011-12-12 00:01:39 +01001595 if (!unicode_modifiable(unicode)) {
Victor Stinnerfe226c02011-10-03 03:52:20 +02001596 PyObject *copy = resize_copy(unicode, length);
1597 if (copy == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001598 return -1;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001599 Py_DECREF(*p_unicode);
1600 *p_unicode = copy;
Benjamin Peterson29060642009-01-31 22:14:21 +00001601 return 0;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001602 }
1603
Victor Stinnerfe226c02011-10-03 03:52:20 +02001604 if (PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001605 PyObject *new_unicode = resize_compact(unicode, length);
1606 if (new_unicode == NULL)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001607 return -1;
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001608 *p_unicode = new_unicode;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001609 return 0;
Benjamin Peterson4bfce8f2011-10-03 19:35:07 -04001610 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001611 return resize_inplace(unicode, length);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001612}
1613
Alexander Belopolsky40018472011-02-26 01:02:56 +00001614int
Victor Stinnerfe226c02011-10-03 03:52:20 +02001615PyUnicode_Resize(PyObject **p_unicode, Py_ssize_t length)
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001616{
Victor Stinnerfe226c02011-10-03 03:52:20 +02001617 PyObject *unicode;
1618 if (p_unicode == NULL) {
1619 PyErr_BadInternalCall();
1620 return -1;
1621 }
1622 unicode = *p_unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001623 if (unicode == NULL || !PyUnicode_Check(unicode) || length < 0)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001624 {
1625 PyErr_BadInternalCall();
1626 return -1;
1627 }
1628 return unicode_resize(p_unicode, length);
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001629}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001630
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001631static int
Victor Stinner1b487b42012-05-03 12:29:04 +02001632unicode_widen(PyObject **p_unicode, Py_ssize_t length,
1633 unsigned int maxchar)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001634{
1635 PyObject *result;
1636 assert(PyUnicode_IS_READY(*p_unicode));
Victor Stinner1b487b42012-05-03 12:29:04 +02001637 assert(length <= PyUnicode_GET_LENGTH(*p_unicode));
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001638 if (maxchar <= PyUnicode_MAX_CHAR_VALUE(*p_unicode))
1639 return 0;
1640 result = PyUnicode_New(PyUnicode_GET_LENGTH(*p_unicode),
1641 maxchar);
1642 if (result == NULL)
1643 return -1;
Victor Stinner1b487b42012-05-03 12:29:04 +02001644 PyUnicode_CopyCharacters(result, 0, *p_unicode, 0, length);
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001645 Py_DECREF(*p_unicode);
1646 *p_unicode = result;
1647 return 0;
1648}
1649
1650static int
1651unicode_putchar(PyObject **p_unicode, Py_ssize_t *pos,
1652 Py_UCS4 ch)
1653{
Victor Stinner15e9ed22012-02-22 13:36:20 +01001654 assert(ch <= MAX_UNICODE);
Victor Stinner1b487b42012-05-03 12:29:04 +02001655 if (unicode_widen(p_unicode, *pos, ch) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001656 return -1;
1657 PyUnicode_WRITE(PyUnicode_KIND(*p_unicode),
1658 PyUnicode_DATA(*p_unicode),
1659 (*pos)++, ch);
1660 return 0;
1661}
1662
Victor Stinnerc5166102012-02-22 13:55:02 +01001663/* Copy a ASCII or latin1 char* string into a Python Unicode string.
1664 Return the length of the input string.
1665
Victor Stinnerb429d3b2012-02-22 21:22:20 +01001666 WARNING: The function doesn't copy the terminating null character and
1667 doesn't check the maximum character (may write a latin1 character in an
1668 ASCII string). */
Victor Stinnerc5166102012-02-22 13:55:02 +01001669static Py_ssize_t
1670unicode_write_cstr(PyObject *unicode, Py_ssize_t index, const char *str)
1671{
1672 enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
1673 void *data = PyUnicode_DATA(unicode);
1674
1675 switch (kind) {
1676 case PyUnicode_1BYTE_KIND: {
1677 Py_ssize_t len = strlen(str);
1678 assert(index + len <= PyUnicode_GET_LENGTH(unicode));
Antoine Pitrouba6bafc2012-02-22 16:41:50 +01001679 memcpy((char *) data + index, str, len);
Victor Stinnerc5166102012-02-22 13:55:02 +01001680 return len;
1681 }
1682 case PyUnicode_2BYTE_KIND: {
1683 Py_UCS2 *start = (Py_UCS2 *)data + index;
1684 Py_UCS2 *ucs2 = start;
1685 assert(index <= PyUnicode_GET_LENGTH(unicode));
1686
1687 for (; *str; ++ucs2, ++str)
1688 *ucs2 = (Py_UCS2)*str;
1689
1690 assert((ucs2 - start) <= PyUnicode_GET_LENGTH(unicode));
1691 return ucs2 - start;
1692 }
1693 default: {
1694 Py_UCS4 *start = (Py_UCS4 *)data + index;
1695 Py_UCS4 *ucs4 = start;
1696 assert(kind == PyUnicode_4BYTE_KIND);
1697 assert(index <= PyUnicode_GET_LENGTH(unicode));
1698
1699 for (; *str; ++ucs4, ++str)
1700 *ucs4 = (Py_UCS4)*str;
1701
1702 assert((ucs4 - start) <= PyUnicode_GET_LENGTH(unicode));
1703 return ucs4 - start;
1704 }
1705 }
1706}
1707
1708
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001709static PyObject*
1710get_latin1_char(unsigned char ch)
1711{
Victor Stinnera464fc12011-10-02 20:39:30 +02001712 PyObject *unicode = unicode_latin1[ch];
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001713 if (!unicode) {
Victor Stinnera464fc12011-10-02 20:39:30 +02001714 unicode = PyUnicode_New(1, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001715 if (!unicode)
1716 return NULL;
1717 PyUnicode_1BYTE_DATA(unicode)[0] = ch;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001718 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001719 unicode_latin1[ch] = unicode;
1720 }
1721 Py_INCREF(unicode);
Victor Stinnera464fc12011-10-02 20:39:30 +02001722 return unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001723}
1724
Alexander Belopolsky40018472011-02-26 01:02:56 +00001725PyObject *
1726PyUnicode_FromUnicode(const Py_UNICODE *u, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001727{
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001728 PyObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001729 Py_UCS4 maxchar = 0;
1730 Py_ssize_t num_surrogates;
1731
1732 if (u == NULL)
1733 return (PyObject*)_PyUnicode_New(size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001734
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001735 /* If the Unicode data is known at construction time, we can apply
1736 some optimizations which share commonly used objects. */
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001737
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001738 /* Optimization for empty strings */
1739 if (size == 0 && unicode_empty != NULL) {
1740 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001741 return unicode_empty;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001742 }
Tim Petersced69f82003-09-16 20:30:58 +00001743
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001744 /* Single character Unicode objects in the Latin-1 range are
1745 shared when using this constructor */
1746 if (size == 1 && *u < 256)
1747 return get_latin1_char((unsigned char)*u);
1748
1749 /* If not empty and not single character, copy the Unicode data
1750 into the new object */
Victor Stinnerd8f65102011-09-29 19:43:17 +02001751 if (find_maxchar_surrogates(u, u + size,
1752 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001753 return NULL;
1754
Victor Stinner8faf8212011-12-08 22:14:11 +01001755 unicode = PyUnicode_New(size - num_surrogates, maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001756 if (!unicode)
1757 return NULL;
1758
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001759 switch (PyUnicode_KIND(unicode)) {
1760 case PyUnicode_1BYTE_KIND:
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001761 _PyUnicode_CONVERT_BYTES(Py_UNICODE, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001762 u, u + size, PyUnicode_1BYTE_DATA(unicode));
1763 break;
1764 case PyUnicode_2BYTE_KIND:
1765#if Py_UNICODE_SIZE == 2
1766 Py_MEMCPY(PyUnicode_2BYTE_DATA(unicode), u, size * 2);
1767#else
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001768 _PyUnicode_CONVERT_BYTES(Py_UNICODE, Py_UCS2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001769 u, u + size, PyUnicode_2BYTE_DATA(unicode));
1770#endif
1771 break;
1772 case PyUnicode_4BYTE_KIND:
1773#if SIZEOF_WCHAR_T == 2
1774 /* This is the only case which has to process surrogates, thus
1775 a simple copy loop is not enough and we need a function. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001776 unicode_convert_wchar_to_ucs4(u, u + size, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001777#else
1778 assert(num_surrogates == 0);
1779 Py_MEMCPY(PyUnicode_4BYTE_DATA(unicode), u, size * 4);
1780#endif
1781 break;
1782 default:
1783 assert(0 && "Impossible state");
1784 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00001785
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001786 return unicode_result(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001787}
1788
Alexander Belopolsky40018472011-02-26 01:02:56 +00001789PyObject *
1790PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size)
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001791{
Benjamin Peterson14339b62009-01-31 16:36:08 +00001792 if (size < 0) {
1793 PyErr_SetString(PyExc_SystemError,
Benjamin Peterson29060642009-01-31 22:14:21 +00001794 "Negative size passed to PyUnicode_FromStringAndSize");
Benjamin Peterson14339b62009-01-31 16:36:08 +00001795 return NULL;
1796 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01001797 if (u != NULL)
1798 return PyUnicode_DecodeUTF8Stateful(u, size, NULL, NULL);
1799 else
1800 return (PyObject *)_PyUnicode_New(size);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001801}
1802
Alexander Belopolsky40018472011-02-26 01:02:56 +00001803PyObject *
1804PyUnicode_FromString(const char *u)
Walter Dörwaldd2034312007-05-18 16:29:38 +00001805{
1806 size_t size = strlen(u);
1807 if (size > PY_SSIZE_T_MAX) {
1808 PyErr_SetString(PyExc_OverflowError, "input too long");
1809 return NULL;
1810 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01001811 return PyUnicode_DecodeUTF8Stateful(u, (Py_ssize_t)size, NULL, NULL);
Walter Dörwaldd2034312007-05-18 16:29:38 +00001812}
1813
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001814PyObject *
1815_PyUnicode_FromId(_Py_Identifier *id)
1816{
1817 if (!id->object) {
Victor Stinnerd1cd99b2012-02-07 23:05:55 +01001818 id->object = PyUnicode_DecodeUTF8Stateful(id->string,
1819 strlen(id->string),
1820 NULL, NULL);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001821 if (!id->object)
1822 return NULL;
1823 PyUnicode_InternInPlace(&id->object);
1824 assert(!id->next);
1825 id->next = static_strings;
1826 static_strings = id;
1827 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001828 return id->object;
1829}
1830
1831void
1832_PyUnicode_ClearStaticStrings()
1833{
1834 _Py_Identifier *i;
1835 for (i = static_strings; i; i = i->next) {
1836 Py_DECREF(i->object);
1837 i->object = NULL;
1838 i->next = NULL;
1839 }
1840}
1841
Benjamin Peterson0df54292012-03-26 14:50:32 -04001842/* Internal function, doesn't check maximum character */
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001843
Victor Stinnere57b1c02011-09-28 22:20:48 +02001844static PyObject*
Victor Stinner0617b6e2011-10-05 23:26:01 +02001845unicode_fromascii(const unsigned char* s, Py_ssize_t size)
Victor Stinner702c7342011-10-05 13:50:52 +02001846{
Victor Stinner785938e2011-12-11 20:09:03 +01001847 PyObject *unicode;
Victor Stinnere6b2d442011-12-11 21:54:30 +01001848 if (size == 1) {
Victor Stinner0617b6e2011-10-05 23:26:01 +02001849#ifdef Py_DEBUG
Victor Stinnere6b2d442011-12-11 21:54:30 +01001850 assert(s[0] < 128);
Victor Stinner0617b6e2011-10-05 23:26:01 +02001851#endif
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001852 return get_latin1_char(s[0]);
Victor Stinnere6b2d442011-12-11 21:54:30 +01001853 }
Victor Stinner785938e2011-12-11 20:09:03 +01001854 unicode = PyUnicode_New(size, 127);
1855 if (!unicode)
Victor Stinner702c7342011-10-05 13:50:52 +02001856 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01001857 memcpy(PyUnicode_1BYTE_DATA(unicode), s, size);
1858 assert(_PyUnicode_CheckConsistency(unicode, 1));
1859 return unicode;
Victor Stinner702c7342011-10-05 13:50:52 +02001860}
1861
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001862static Py_UCS4
1863kind_maxchar_limit(unsigned int kind)
1864{
Benjamin Petersonead6b532011-12-20 17:23:42 -06001865 switch (kind) {
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001866 case PyUnicode_1BYTE_KIND:
1867 return 0x80;
1868 case PyUnicode_2BYTE_KIND:
1869 return 0x100;
1870 case PyUnicode_4BYTE_KIND:
1871 return 0x10000;
1872 default:
1873 assert(0 && "invalid kind");
Victor Stinner8faf8212011-12-08 22:14:11 +01001874 return MAX_UNICODE;
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001875 }
1876}
1877
Victor Stinnere6abb482012-05-02 01:15:40 +02001878Py_LOCAL_INLINE(Py_UCS4)
1879align_maxchar(Py_UCS4 maxchar)
1880{
1881 if (maxchar <= 127)
1882 return 127;
1883 else if (maxchar <= 255)
1884 return 255;
1885 else if (maxchar <= 65535)
1886 return 65535;
1887 else
1888 return MAX_UNICODE;
1889}
1890
Victor Stinner702c7342011-10-05 13:50:52 +02001891static PyObject*
Victor Stinnere57b1c02011-09-28 22:20:48 +02001892_PyUnicode_FromUCS1(const unsigned char* u, Py_ssize_t size)
Mark Dickinson081dfee2009-03-18 14:47:41 +00001893{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001894 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001895 unsigned char max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001896
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001897 if (size == 0) {
1898 Py_INCREF(unicode_empty);
1899 return unicode_empty;
1900 }
1901 assert(size > 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001902 if (size == 1)
1903 return get_latin1_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001904
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001905 max_char = ucs1lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001906 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001907 if (!res)
1908 return NULL;
1909 memcpy(PyUnicode_1BYTE_DATA(res), u, size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001910 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001911 return res;
Mark Dickinson081dfee2009-03-18 14:47:41 +00001912}
1913
Victor Stinnere57b1c02011-09-28 22:20:48 +02001914static PyObject*
1915_PyUnicode_FromUCS2(const Py_UCS2 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001916{
1917 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001918 Py_UCS2 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001919
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001920 if (size == 0) {
1921 Py_INCREF(unicode_empty);
1922 return unicode_empty;
1923 }
1924 assert(size > 0);
Victor Stinnerb6cd0142012-05-03 02:17:04 +02001925 if (size == 1) {
1926 Py_UCS4 ch = u[0];
1927 if (ch < 256)
1928 return get_latin1_char((unsigned char)ch);
1929
1930 res = PyUnicode_New(1, ch);
1931 if (res == NULL)
1932 return NULL;
1933 PyUnicode_WRITE(PyUnicode_KIND(res), PyUnicode_DATA(res), 0, ch);
1934 assert(_PyUnicode_CheckConsistency(res, 1));
1935 return res;
1936 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001937
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001938 max_char = ucs2lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001939 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001940 if (!res)
1941 return NULL;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001942 if (max_char >= 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001943 memcpy(PyUnicode_2BYTE_DATA(res), u, sizeof(Py_UCS2)*size);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001944 else {
1945 _PyUnicode_CONVERT_BYTES(
1946 Py_UCS2, Py_UCS1, u, u + size, PyUnicode_1BYTE_DATA(res));
1947 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001948 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001949 return res;
1950}
1951
Victor Stinnere57b1c02011-09-28 22:20:48 +02001952static PyObject*
1953_PyUnicode_FromUCS4(const Py_UCS4 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001954{
1955 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001956 Py_UCS4 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001957
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001958 if (size == 0) {
1959 Py_INCREF(unicode_empty);
1960 return unicode_empty;
1961 }
1962 assert(size > 0);
Victor Stinnerb6cd0142012-05-03 02:17:04 +02001963 if (size == 1) {
1964 Py_UCS4 ch = u[0];
1965 if (ch < 256)
1966 return get_latin1_char((unsigned char)ch);
1967
1968 res = PyUnicode_New(1, ch);
1969 if (res == NULL)
1970 return NULL;
1971 PyUnicode_WRITE(PyUnicode_KIND(res), PyUnicode_DATA(res), 0, ch);
1972 assert(_PyUnicode_CheckConsistency(res, 1));
1973 return res;
1974 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001975
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001976 max_char = ucs4lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001977 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001978 if (!res)
1979 return NULL;
Antoine Pitrou950468e2011-10-11 22:45:48 +02001980 if (max_char < 256)
1981 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, u, u + size,
1982 PyUnicode_1BYTE_DATA(res));
1983 else if (max_char < 0x10000)
1984 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, u, u + size,
1985 PyUnicode_2BYTE_DATA(res));
1986 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001987 memcpy(PyUnicode_4BYTE_DATA(res), u, sizeof(Py_UCS4)*size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001988 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001989 return res;
1990}
1991
1992PyObject*
1993PyUnicode_FromKindAndData(int kind, const void *buffer, Py_ssize_t size)
1994{
Victor Stinnercfed46e2011-11-22 01:29:14 +01001995 if (size < 0) {
1996 PyErr_SetString(PyExc_ValueError, "size must be positive");
1997 return NULL;
1998 }
Benjamin Petersonead6b532011-12-20 17:23:42 -06001999 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002000 case PyUnicode_1BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002001 return _PyUnicode_FromUCS1(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002002 case PyUnicode_2BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002003 return _PyUnicode_FromUCS2(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002004 case PyUnicode_4BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002005 return _PyUnicode_FromUCS4(buffer, size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002006 default:
Victor Stinnerb9275c12011-10-05 14:01:42 +02002007 PyErr_SetString(PyExc_SystemError, "invalid kind");
2008 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002009 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002010}
2011
Victor Stinnerece58de2012-04-23 23:36:38 +02002012Py_UCS4
2013_PyUnicode_FindMaxChar(PyObject *unicode, Py_ssize_t start, Py_ssize_t end)
2014{
2015 enum PyUnicode_Kind kind;
2016 void *startptr, *endptr;
2017
2018 assert(PyUnicode_IS_READY(unicode));
2019 assert(0 <= start);
2020 assert(end <= PyUnicode_GET_LENGTH(unicode));
2021 assert(start <= end);
2022
2023 if (start == 0 && end == PyUnicode_GET_LENGTH(unicode))
2024 return PyUnicode_MAX_CHAR_VALUE(unicode);
2025
2026 if (start == end)
2027 return 127;
2028
Victor Stinner94d558b2012-04-27 22:26:58 +02002029 if (PyUnicode_IS_ASCII(unicode))
2030 return 127;
2031
Victor Stinnerece58de2012-04-23 23:36:38 +02002032 kind = PyUnicode_KIND(unicode);
Benjamin Petersonf3b7d862012-04-23 18:07:01 -04002033 startptr = PyUnicode_DATA(unicode);
Benjamin Petersonb9f4c9d2012-04-23 21:45:40 -04002034 endptr = (char *)startptr + end * kind;
2035 startptr = (char *)startptr + start * kind;
Benjamin Peterson2844a7a2012-04-23 18:00:25 -04002036 switch(kind) {
2037 case PyUnicode_1BYTE_KIND:
2038 return ucs1lib_find_max_char(startptr, endptr);
2039 case PyUnicode_2BYTE_KIND:
2040 return ucs2lib_find_max_char(startptr, endptr);
2041 case PyUnicode_4BYTE_KIND:
2042 return ucs4lib_find_max_char(startptr, endptr);
Victor Stinnerece58de2012-04-23 23:36:38 +02002043 default:
Benjamin Peterson2844a7a2012-04-23 18:00:25 -04002044 assert(0);
2045 return 0;
Victor Stinnerece58de2012-04-23 23:36:38 +02002046 }
2047}
2048
Victor Stinner25a4b292011-10-06 12:31:55 +02002049/* Ensure that a string uses the most efficient storage, if it is not the
2050 case: create a new string with of the right kind. Write NULL into *p_unicode
2051 on error. */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02002052static void
Victor Stinner25a4b292011-10-06 12:31:55 +02002053unicode_adjust_maxchar(PyObject **p_unicode)
2054{
2055 PyObject *unicode, *copy;
2056 Py_UCS4 max_char;
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002057 Py_ssize_t len;
Victor Stinner25a4b292011-10-06 12:31:55 +02002058 unsigned int kind;
2059
2060 assert(p_unicode != NULL);
2061 unicode = *p_unicode;
2062 assert(PyUnicode_IS_READY(unicode));
2063 if (PyUnicode_IS_ASCII(unicode))
2064 return;
2065
2066 len = PyUnicode_GET_LENGTH(unicode);
2067 kind = PyUnicode_KIND(unicode);
2068 if (kind == PyUnicode_1BYTE_KIND) {
2069 const Py_UCS1 *u = PyUnicode_1BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002070 max_char = ucs1lib_find_max_char(u, u + len);
2071 if (max_char >= 128)
2072 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002073 }
2074 else if (kind == PyUnicode_2BYTE_KIND) {
2075 const Py_UCS2 *u = PyUnicode_2BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002076 max_char = ucs2lib_find_max_char(u, u + len);
2077 if (max_char >= 256)
2078 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002079 }
2080 else {
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002081 const Py_UCS4 *u = PyUnicode_4BYTE_DATA(unicode);
Victor Stinner25a4b292011-10-06 12:31:55 +02002082 assert(kind == PyUnicode_4BYTE_KIND);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002083 max_char = ucs4lib_find_max_char(u, u + len);
2084 if (max_char >= 0x10000)
2085 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002086 }
Victor Stinner25a4b292011-10-06 12:31:55 +02002087 copy = PyUnicode_New(len, max_char);
2088 copy_characters(copy, 0, unicode, 0, len);
2089 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 {
2733 Py_ssize_t written;
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 Stinnerc5166102012-02-22 13:55:02 +01002740 written = unicode_write_cstr(string, i, numberresult);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002741 /* skip over the separating '\0' */
Victor Stinnerc5166102012-02-22 13:55:02 +01002742 i += written;
2743 numberresult += written;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002744 assert(*numberresult == '\0');
2745 numberresult++;
2746 assert(numberresult <= numberresults + numbersize);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002747 break;
Victor Stinnerc5166102012-02-22 13:55:02 +01002748 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002749 case 's':
2750 {
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002751 /* unused, since we already have the result */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002752 Py_ssize_t size;
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002753 (void) va_arg(vargs, char *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002754 size = PyUnicode_GET_LENGTH(*callresult);
2755 assert(PyUnicode_KIND(*callresult) <= PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002756 copy_characters(string, i, *callresult, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002757 i += size;
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002758 /* We're done with the unicode()/repr() => forget it */
2759 Py_DECREF(*callresult);
2760 /* switch to next unicode()/repr() result */
2761 ++callresult;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002762 break;
2763 }
2764 case 'U':
2765 {
2766 PyObject *obj = va_arg(vargs, PyObject *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002767 Py_ssize_t size;
2768 assert(PyUnicode_KIND(obj) <= PyUnicode_KIND(string));
2769 size = PyUnicode_GET_LENGTH(obj);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002770 copy_characters(string, i, obj, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002771 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002772 break;
2773 }
2774 case 'V':
2775 {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002776 Py_ssize_t size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002777 PyObject *obj = va_arg(vargs, PyObject *);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002778 va_arg(vargs, const char *);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002779 if (obj) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002780 size = PyUnicode_GET_LENGTH(obj);
2781 assert(PyUnicode_KIND(obj) <= PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002782 copy_characters(string, i, obj, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002783 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002784 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002785 size = PyUnicode_GET_LENGTH(*callresult);
2786 assert(PyUnicode_KIND(*callresult) <=
2787 PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002788 copy_characters(string, i, *callresult, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002789 i += size;
Victor Stinner2512a8b2011-03-01 22:46:52 +00002790 Py_DECREF(*callresult);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002791 }
Victor Stinner2512a8b2011-03-01 22:46:52 +00002792 ++callresult;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002793 break;
2794 }
2795 case 'S':
2796 case 'R':
Victor Stinner9a909002010-10-18 20:59:24 +00002797 case 'A':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002798 {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002799 Py_ssize_t size = PyUnicode_GET_LENGTH(*callresult);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002800 /* unused, since we already have the result */
2801 (void) va_arg(vargs, PyObject *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002802 assert(PyUnicode_KIND(*callresult) <= PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002803 copy_characters(string, i, *callresult, 0, size);
2804 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002805 /* We're done with the unicode()/repr() => forget it */
2806 Py_DECREF(*callresult);
2807 /* switch to next unicode()/repr() result */
2808 ++callresult;
2809 break;
2810 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002811 case '%':
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002812 PyUnicode_WRITE(kind, data, i++, '%');
Benjamin Peterson14339b62009-01-31 16:36:08 +00002813 break;
2814 default:
Victor Stinnerc5166102012-02-22 13:55:02 +01002815 i += unicode_write_cstr(string, i, p);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002816 assert(i == PyUnicode_GET_LENGTH(string));
Benjamin Peterson14339b62009-01-31 16:36:08 +00002817 goto end;
2818 }
Victor Stinner1205f272010-09-11 00:54:47 +00002819 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002820 else {
2821 assert(i < PyUnicode_GET_LENGTH(string));
2822 PyUnicode_WRITE(kind, data, i++, *f);
2823 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002824 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002825 assert(i == PyUnicode_GET_LENGTH(string));
Walter Dörwaldd2034312007-05-18 16:29:38 +00002826
Benjamin Peterson29060642009-01-31 22:14:21 +00002827 end:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002828 if (callresults)
2829 PyObject_Free(callresults);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002830 if (numberresults)
2831 PyObject_Free(numberresults);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002832 return unicode_result(string);
Benjamin Peterson29060642009-01-31 22:14:21 +00002833 fail:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002834 if (callresults) {
2835 PyObject **callresult2 = callresults;
2836 while (callresult2 < callresult) {
Victor Stinner2512a8b2011-03-01 22:46:52 +00002837 Py_XDECREF(*callresult2);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002838 ++callresult2;
2839 }
2840 PyObject_Free(callresults);
2841 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002842 if (numberresults)
2843 PyObject_Free(numberresults);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002844 return NULL;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002845}
2846
Walter Dörwaldd2034312007-05-18 16:29:38 +00002847PyObject *
2848PyUnicode_FromFormat(const char *format, ...)
2849{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002850 PyObject* ret;
2851 va_list vargs;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002852
2853#ifdef HAVE_STDARG_PROTOTYPES
Benjamin Peterson14339b62009-01-31 16:36:08 +00002854 va_start(vargs, format);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002855#else
Benjamin Peterson14339b62009-01-31 16:36:08 +00002856 va_start(vargs);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002857#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00002858 ret = PyUnicode_FromFormatV(format, vargs);
2859 va_end(vargs);
2860 return ret;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002861}
2862
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002863#ifdef HAVE_WCHAR_H
2864
Victor Stinner5593d8a2010-10-02 11:11:27 +00002865/* Helper function for PyUnicode_AsWideChar() and PyUnicode_AsWideCharString():
2866 convert a Unicode object to a wide character string.
2867
Victor Stinnerd88d9832011-09-06 02:00:05 +02002868 - If w is NULL: return the number of wide characters (including the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002869 character) required to convert the unicode object. Ignore size argument.
2870
Victor Stinnerd88d9832011-09-06 02:00:05 +02002871 - Otherwise: return the number of wide characters (excluding the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002872 character) written into w. Write at most size wide characters (including
Victor Stinnerd88d9832011-09-06 02:00:05 +02002873 the null character). */
Victor Stinner5593d8a2010-10-02 11:11:27 +00002874static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002875unicode_aswidechar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002876 wchar_t *w,
2877 Py_ssize_t size)
2878{
Victor Stinner5593d8a2010-10-02 11:11:27 +00002879 Py_ssize_t res;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002880 const wchar_t *wstr;
2881
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002882 wstr = PyUnicode_AsUnicodeAndSize(unicode, &res);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002883 if (wstr == NULL)
2884 return -1;
2885
Victor Stinner5593d8a2010-10-02 11:11:27 +00002886 if (w != NULL) {
Victor Stinner5593d8a2010-10-02 11:11:27 +00002887 if (size > res)
2888 size = res + 1;
2889 else
2890 res = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002891 Py_MEMCPY(w, wstr, size * sizeof(wchar_t));
Victor Stinner5593d8a2010-10-02 11:11:27 +00002892 return res;
2893 }
2894 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002895 return res + 1;
Victor Stinner137c34c2010-09-29 10:25:54 +00002896}
2897
2898Py_ssize_t
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002899PyUnicode_AsWideChar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002900 wchar_t *w,
2901 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002902{
2903 if (unicode == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002904 PyErr_BadInternalCall();
2905 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002906 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002907 return unicode_aswidechar(unicode, w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002908}
2909
Victor Stinner137c34c2010-09-29 10:25:54 +00002910wchar_t*
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00002911PyUnicode_AsWideCharString(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002912 Py_ssize_t *size)
2913{
2914 wchar_t* buffer;
2915 Py_ssize_t buflen;
2916
2917 if (unicode == NULL) {
2918 PyErr_BadInternalCall();
2919 return NULL;
2920 }
2921
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002922 buflen = unicode_aswidechar(unicode, NULL, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002923 if (buflen == -1)
2924 return NULL;
Victor Stinner5593d8a2010-10-02 11:11:27 +00002925 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < buflen) {
Victor Stinner137c34c2010-09-29 10:25:54 +00002926 PyErr_NoMemory();
2927 return NULL;
2928 }
2929
Victor Stinner137c34c2010-09-29 10:25:54 +00002930 buffer = PyMem_MALLOC(buflen * sizeof(wchar_t));
2931 if (buffer == NULL) {
2932 PyErr_NoMemory();
2933 return NULL;
2934 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002935 buflen = unicode_aswidechar(unicode, buffer, buflen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002936 if (buflen == -1)
2937 return NULL;
Victor Stinner5593d8a2010-10-02 11:11:27 +00002938 if (size != NULL)
2939 *size = buflen;
Victor Stinner137c34c2010-09-29 10:25:54 +00002940 return buffer;
2941}
2942
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002943#endif /* HAVE_WCHAR_H */
Guido van Rossumd57fd912000-03-10 22:53:23 +00002944
Alexander Belopolsky40018472011-02-26 01:02:56 +00002945PyObject *
2946PyUnicode_FromOrdinal(int ordinal)
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002947{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002948 PyObject *v;
Victor Stinner8faf8212011-12-08 22:14:11 +01002949 if (ordinal < 0 || ordinal > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002950 PyErr_SetString(PyExc_ValueError,
2951 "chr() arg not in range(0x110000)");
2952 return NULL;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002953 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00002954
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002955 if (ordinal < 256)
2956 return get_latin1_char(ordinal);
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002957
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002958 v = PyUnicode_New(1, ordinal);
2959 if (v == NULL)
2960 return NULL;
2961 PyUnicode_WRITE(PyUnicode_KIND(v), PyUnicode_DATA(v), 0, ordinal);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002962 assert(_PyUnicode_CheckConsistency(v, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002963 return v;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002964}
2965
Alexander Belopolsky40018472011-02-26 01:02:56 +00002966PyObject *
2967PyUnicode_FromObject(register PyObject *obj)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002968{
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002969 /* XXX Perhaps we should make this API an alias of
Benjamin Peterson29060642009-01-31 22:14:21 +00002970 PyObject_Str() instead ?! */
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002971 if (PyUnicode_CheckExact(obj)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -05002972 if (PyUnicode_READY(obj) == -1)
Victor Stinnerd3a83d52011-10-01 03:09:33 +02002973 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +00002974 Py_INCREF(obj);
2975 return obj;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002976 }
2977 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002978 /* For a Unicode subtype that's not a Unicode object,
2979 return a true Unicode object with the same data. */
Victor Stinnerbf6e5602011-12-12 01:53:47 +01002980 return _PyUnicode_Copy(obj);
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002981 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00002982 PyErr_Format(PyExc_TypeError,
2983 "Can't convert '%.100s' object to str implicitly",
Christian Heimes90aa7642007-12-19 02:45:37 +00002984 Py_TYPE(obj)->tp_name);
Guido van Rossum98297ee2007-11-06 21:34:58 +00002985 return NULL;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002986}
2987
Alexander Belopolsky40018472011-02-26 01:02:56 +00002988PyObject *
2989PyUnicode_FromEncodedObject(register PyObject *obj,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002990 const char *encoding,
2991 const char *errors)
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002992{
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002993 Py_buffer buffer;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002994 PyObject *v;
Tim Petersced69f82003-09-16 20:30:58 +00002995
Guido van Rossumd57fd912000-03-10 22:53:23 +00002996 if (obj == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002997 PyErr_BadInternalCall();
2998 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002999 }
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003000
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003001 /* Decoding bytes objects is the most common case and should be fast */
3002 if (PyBytes_Check(obj)) {
3003 if (PyBytes_GET_SIZE(obj) == 0) {
3004 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02003005 v = unicode_empty;
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003006 }
3007 else {
3008 v = PyUnicode_Decode(
3009 PyBytes_AS_STRING(obj), PyBytes_GET_SIZE(obj),
3010 encoding, errors);
3011 }
3012 return v;
3013 }
3014
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003015 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003016 PyErr_SetString(PyExc_TypeError,
3017 "decoding str is not supported");
3018 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +00003019 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003020
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003021 /* Retrieve a bytes buffer view through the PEP 3118 buffer interface */
3022 if (PyObject_GetBuffer(obj, &buffer, PyBUF_SIMPLE) < 0) {
3023 PyErr_Format(PyExc_TypeError,
3024 "coercing to str: need bytes, bytearray "
3025 "or buffer-like object, %.80s found",
3026 Py_TYPE(obj)->tp_name);
3027 return NULL;
Marc-André Lemburg6871f6a2001-09-20 12:53:16 +00003028 }
Tim Petersced69f82003-09-16 20:30:58 +00003029
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003030 if (buffer.len == 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003031 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02003032 v = unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003033 }
Tim Petersced69f82003-09-16 20:30:58 +00003034 else
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003035 v = PyUnicode_Decode((char*) buffer.buf, buffer.len, encoding, errors);
Marc-André Lemburgad7c98e2001-01-17 17:09:53 +00003036
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003037 PyBuffer_Release(&buffer);
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003038 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003039}
3040
Victor Stinner600d3be2010-06-10 12:00:55 +00003041/* Convert encoding to lower case and replace '_' with '-' in order to
Victor Stinner37296e82010-06-10 13:36:23 +00003042 catch e.g. UTF_8. Return 0 on error (encoding is longer than lower_len-1),
3043 1 on success. */
3044static int
3045normalize_encoding(const char *encoding,
3046 char *lower,
3047 size_t lower_len)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003048{
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003049 const char *e;
Victor Stinner600d3be2010-06-10 12:00:55 +00003050 char *l;
3051 char *l_end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003052
Benjamin Peterson7a6debe2011-10-15 09:25:28 -04003053 if (encoding == NULL) {
3054 strcpy(lower, "utf-8");
3055 return 1;
3056 }
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003057 e = encoding;
3058 l = lower;
Victor Stinner600d3be2010-06-10 12:00:55 +00003059 l_end = &lower[lower_len - 1];
Victor Stinner37296e82010-06-10 13:36:23 +00003060 while (*e) {
3061 if (l == l_end)
3062 return 0;
David Malcolm96960882010-11-05 17:23:41 +00003063 if (Py_ISUPPER(*e)) {
3064 *l++ = Py_TOLOWER(*e++);
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003065 }
3066 else if (*e == '_') {
3067 *l++ = '-';
3068 e++;
3069 }
3070 else {
3071 *l++ = *e++;
3072 }
3073 }
3074 *l = '\0';
Victor Stinner37296e82010-06-10 13:36:23 +00003075 return 1;
Victor Stinner600d3be2010-06-10 12:00:55 +00003076}
3077
Alexander Belopolsky40018472011-02-26 01:02:56 +00003078PyObject *
3079PyUnicode_Decode(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003080 Py_ssize_t size,
3081 const char *encoding,
3082 const char *errors)
Victor Stinner600d3be2010-06-10 12:00:55 +00003083{
3084 PyObject *buffer = NULL, *unicode;
3085 Py_buffer info;
3086 char lower[11]; /* Enough for any encoding shortcut */
3087
Fred Drakee4315f52000-05-09 19:53:39 +00003088 /* Shortcuts for common default encodings */
Victor Stinner37296e82010-06-10 13:36:23 +00003089 if (normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003090 if ((strcmp(lower, "utf-8") == 0) ||
3091 (strcmp(lower, "utf8") == 0))
Victor Stinnera1d12bb2011-12-11 21:53:09 +01003092 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
Victor Stinner37296e82010-06-10 13:36:23 +00003093 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003094 (strcmp(lower, "latin1") == 0) ||
Victor Stinner37296e82010-06-10 13:36:23 +00003095 (strcmp(lower, "iso-8859-1") == 0))
3096 return PyUnicode_DecodeLatin1(s, size, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02003097#ifdef HAVE_MBCS
Victor Stinner37296e82010-06-10 13:36:23 +00003098 else if (strcmp(lower, "mbcs") == 0)
3099 return PyUnicode_DecodeMBCS(s, size, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003100#endif
Victor Stinner37296e82010-06-10 13:36:23 +00003101 else if (strcmp(lower, "ascii") == 0)
3102 return PyUnicode_DecodeASCII(s, size, errors);
3103 else if (strcmp(lower, "utf-16") == 0)
3104 return PyUnicode_DecodeUTF16(s, size, errors, 0);
3105 else if (strcmp(lower, "utf-32") == 0)
3106 return PyUnicode_DecodeUTF32(s, size, errors, 0);
3107 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003108
3109 /* Decode via the codec registry */
Guido van Rossumbe801ac2007-10-08 03:32:34 +00003110 buffer = NULL;
Antoine Pitrouc3b39242009-01-03 16:59:18 +00003111 if (PyBuffer_FillInfo(&info, NULL, (void *)s, size, 1, PyBUF_FULL_RO) < 0)
Guido van Rossumbe801ac2007-10-08 03:32:34 +00003112 goto onError;
Antoine Pitrouee58fa42008-08-19 18:22:14 +00003113 buffer = PyMemoryView_FromBuffer(&info);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003114 if (buffer == NULL)
3115 goto onError;
3116 unicode = PyCodec_Decode(buffer, encoding, errors);
3117 if (unicode == NULL)
3118 goto onError;
3119 if (!PyUnicode_Check(unicode)) {
3120 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00003121 "decoder did not return a str object (type=%.400s)",
Christian Heimes90aa7642007-12-19 02:45:37 +00003122 Py_TYPE(unicode)->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003123 Py_DECREF(unicode);
3124 goto onError;
3125 }
3126 Py_DECREF(buffer);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003127 return unicode_result(unicode);
Tim Petersced69f82003-09-16 20:30:58 +00003128
Benjamin Peterson29060642009-01-31 22:14:21 +00003129 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003130 Py_XDECREF(buffer);
3131 return NULL;
3132}
3133
Alexander Belopolsky40018472011-02-26 01:02:56 +00003134PyObject *
3135PyUnicode_AsDecodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003136 const char *encoding,
3137 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003138{
3139 PyObject *v;
3140
3141 if (!PyUnicode_Check(unicode)) {
3142 PyErr_BadArgument();
3143 goto onError;
3144 }
3145
3146 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003147 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003148
3149 /* Decode via the codec registry */
3150 v = PyCodec_Decode(unicode, encoding, errors);
3151 if (v == NULL)
3152 goto onError;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003153 return unicode_result(v);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003154
Benjamin Peterson29060642009-01-31 22:14:21 +00003155 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003156 return NULL;
3157}
3158
Alexander Belopolsky40018472011-02-26 01:02:56 +00003159PyObject *
3160PyUnicode_AsDecodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003161 const char *encoding,
3162 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003163{
3164 PyObject *v;
3165
3166 if (!PyUnicode_Check(unicode)) {
3167 PyErr_BadArgument();
3168 goto onError;
3169 }
3170
3171 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003172 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003173
3174 /* Decode via the codec registry */
3175 v = PyCodec_Decode(unicode, encoding, errors);
3176 if (v == NULL)
3177 goto onError;
3178 if (!PyUnicode_Check(v)) {
3179 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00003180 "decoder did not return a str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003181 Py_TYPE(v)->tp_name);
3182 Py_DECREF(v);
3183 goto onError;
3184 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003185 return unicode_result(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003186
Benjamin Peterson29060642009-01-31 22:14:21 +00003187 onError:
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003188 return NULL;
3189}
3190
Alexander Belopolsky40018472011-02-26 01:02:56 +00003191PyObject *
3192PyUnicode_Encode(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003193 Py_ssize_t size,
3194 const char *encoding,
3195 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003196{
3197 PyObject *v, *unicode;
Tim Petersced69f82003-09-16 20:30:58 +00003198
Guido van Rossumd57fd912000-03-10 22:53:23 +00003199 unicode = PyUnicode_FromUnicode(s, size);
3200 if (unicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003201 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003202 v = PyUnicode_AsEncodedString(unicode, encoding, errors);
3203 Py_DECREF(unicode);
3204 return v;
3205}
3206
Alexander Belopolsky40018472011-02-26 01:02:56 +00003207PyObject *
3208PyUnicode_AsEncodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003209 const char *encoding,
3210 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003211{
3212 PyObject *v;
3213
3214 if (!PyUnicode_Check(unicode)) {
3215 PyErr_BadArgument();
3216 goto onError;
3217 }
3218
3219 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003220 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003221
3222 /* Encode via the codec registry */
3223 v = PyCodec_Encode(unicode, encoding, errors);
3224 if (v == NULL)
3225 goto onError;
3226 return v;
3227
Benjamin Peterson29060642009-01-31 22:14:21 +00003228 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003229 return NULL;
3230}
3231
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003232static size_t
3233wcstombs_errorpos(const wchar_t *wstr)
3234{
3235 size_t len;
3236#if SIZEOF_WCHAR_T == 2
3237 wchar_t buf[3];
3238#else
3239 wchar_t buf[2];
3240#endif
3241 char outbuf[MB_LEN_MAX];
3242 const wchar_t *start, *previous;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003243
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003244#if SIZEOF_WCHAR_T == 2
3245 buf[2] = 0;
3246#else
3247 buf[1] = 0;
3248#endif
3249 start = wstr;
3250 while (*wstr != L'\0')
3251 {
3252 previous = wstr;
3253#if SIZEOF_WCHAR_T == 2
3254 if (Py_UNICODE_IS_HIGH_SURROGATE(wstr[0])
3255 && Py_UNICODE_IS_LOW_SURROGATE(wstr[1]))
3256 {
3257 buf[0] = wstr[0];
3258 buf[1] = wstr[1];
3259 wstr += 2;
3260 }
3261 else {
3262 buf[0] = *wstr;
3263 buf[1] = 0;
3264 wstr++;
3265 }
3266#else
3267 buf[0] = *wstr;
3268 wstr++;
3269#endif
3270 len = wcstombs(outbuf, buf, sizeof(outbuf));
Victor Stinner2f197072011-12-17 07:08:30 +01003271 if (len == (size_t)-1)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003272 return previous - start;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003273 }
3274
3275 /* failed to find the unencodable character */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003276 return 0;
3277}
3278
Victor Stinner1b579672011-12-17 05:47:23 +01003279static int
3280locale_error_handler(const char *errors, int *surrogateescape)
3281{
3282 if (errors == NULL) {
3283 *surrogateescape = 0;
3284 return 0;
3285 }
3286
3287 if (strcmp(errors, "strict") == 0) {
3288 *surrogateescape = 0;
3289 return 0;
3290 }
3291 if (strcmp(errors, "surrogateescape") == 0) {
3292 *surrogateescape = 1;
3293 return 0;
3294 }
3295 PyErr_Format(PyExc_ValueError,
3296 "only 'strict' and 'surrogateescape' error handlers "
3297 "are supported, not '%s'",
3298 errors);
3299 return -1;
3300}
3301
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003302PyObject *
Victor Stinner1b579672011-12-17 05:47:23 +01003303PyUnicode_EncodeLocale(PyObject *unicode, const char *errors)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003304{
3305 Py_ssize_t wlen, wlen2;
3306 wchar_t *wstr;
3307 PyObject *bytes = NULL;
3308 char *errmsg;
Victor Stinner1f33f2b2011-12-17 04:45:09 +01003309 PyObject *reason;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003310 PyObject *exc;
3311 size_t error_pos;
Victor Stinner1b579672011-12-17 05:47:23 +01003312 int surrogateescape;
3313
3314 if (locale_error_handler(errors, &surrogateescape) < 0)
3315 return NULL;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003316
3317 wstr = PyUnicode_AsWideCharString(unicode, &wlen);
3318 if (wstr == NULL)
3319 return NULL;
3320
3321 wlen2 = wcslen(wstr);
3322 if (wlen2 != wlen) {
3323 PyMem_Free(wstr);
3324 PyErr_SetString(PyExc_TypeError, "embedded null character");
3325 return NULL;
3326 }
3327
3328 if (surrogateescape) {
3329 /* locale encoding with surrogateescape */
3330 char *str;
3331
3332 str = _Py_wchar2char(wstr, &error_pos);
3333 if (str == NULL) {
3334 if (error_pos == (size_t)-1) {
3335 PyErr_NoMemory();
3336 PyMem_Free(wstr);
3337 return NULL;
3338 }
3339 else {
3340 goto encode_error;
3341 }
3342 }
3343 PyMem_Free(wstr);
3344
3345 bytes = PyBytes_FromString(str);
3346 PyMem_Free(str);
3347 }
3348 else {
3349 size_t len, len2;
3350
3351 len = wcstombs(NULL, wstr, 0);
3352 if (len == (size_t)-1) {
Victor Stinner2f197072011-12-17 07:08:30 +01003353 error_pos = (size_t)-1;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003354 goto encode_error;
3355 }
3356
3357 bytes = PyBytes_FromStringAndSize(NULL, len);
3358 if (bytes == NULL) {
3359 PyMem_Free(wstr);
3360 return NULL;
3361 }
3362
3363 len2 = wcstombs(PyBytes_AS_STRING(bytes), wstr, len+1);
3364 if (len2 == (size_t)-1 || len2 > len) {
Victor Stinner2f197072011-12-17 07:08:30 +01003365 error_pos = (size_t)-1;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003366 goto encode_error;
3367 }
3368 PyMem_Free(wstr);
3369 }
3370 return bytes;
3371
3372encode_error:
3373 errmsg = strerror(errno);
3374 assert(errmsg != NULL);
Victor Stinner2f197072011-12-17 07:08:30 +01003375
3376 if (error_pos == (size_t)-1)
3377 error_pos = wcstombs_errorpos(wstr);
3378
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003379 PyMem_Free(wstr);
3380 Py_XDECREF(bytes);
3381
Victor Stinner2f197072011-12-17 07:08:30 +01003382 if (errmsg != NULL) {
3383 size_t errlen;
3384 wstr = _Py_char2wchar(errmsg, &errlen);
3385 if (wstr != NULL) {
3386 reason = PyUnicode_FromWideChar(wstr, errlen);
3387 PyMem_Free(wstr);
3388 } else
3389 errmsg = NULL;
3390 }
3391 if (errmsg == NULL)
Victor Stinner1f33f2b2011-12-17 04:45:09 +01003392 reason = PyUnicode_FromString(
3393 "wcstombs() encountered an unencodable "
3394 "wide character");
3395 if (reason == NULL)
3396 return NULL;
3397
3398 exc = PyObject_CallFunction(PyExc_UnicodeEncodeError, "sOnnO",
3399 "locale", unicode,
3400 (Py_ssize_t)error_pos,
3401 (Py_ssize_t)(error_pos+1),
3402 reason);
3403 Py_DECREF(reason);
3404 if (exc != NULL) {
3405 PyCodec_StrictErrors(exc);
3406 Py_XDECREF(exc);
3407 }
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003408 return NULL;
3409}
3410
Victor Stinnerad158722010-10-27 00:25:46 +00003411PyObject *
3412PyUnicode_EncodeFSDefault(PyObject *unicode)
Victor Stinnerae6265f2010-05-15 16:27:27 +00003413{
Victor Stinner99b95382011-07-04 14:23:54 +02003414#ifdef HAVE_MBCS
Victor Stinnerac931b12011-11-20 18:27:03 +01003415 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003416#elif defined(__APPLE__)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003417 return _PyUnicode_AsUTF8String(unicode, "surrogateescape");
Victor Stinnerad158722010-10-27 00:25:46 +00003418#else
Victor Stinner793b5312011-04-27 00:24:21 +02003419 PyInterpreterState *interp = PyThreadState_GET()->interp;
3420 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3421 cannot use it to encode and decode filenames before it is loaded. Load
3422 the Python codec requires to encode at least its own filename. Use the C
3423 version of the locale codec until the codec registry is initialized and
3424 the Python codec is loaded.
3425
3426 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3427 cannot only rely on it: check also interp->fscodec_initialized for
3428 subinterpreters. */
3429 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Victor Stinnerae6265f2010-05-15 16:27:27 +00003430 return PyUnicode_AsEncodedString(unicode,
3431 Py_FileSystemDefaultEncoding,
3432 "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00003433 }
3434 else {
Victor Stinner1b579672011-12-17 05:47:23 +01003435 return PyUnicode_EncodeLocale(unicode, "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00003436 }
Victor Stinnerad158722010-10-27 00:25:46 +00003437#endif
Victor Stinnerae6265f2010-05-15 16:27:27 +00003438}
3439
Alexander Belopolsky40018472011-02-26 01:02:56 +00003440PyObject *
3441PyUnicode_AsEncodedString(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003442 const char *encoding,
3443 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003444{
3445 PyObject *v;
Victor Stinner600d3be2010-06-10 12:00:55 +00003446 char lower[11]; /* Enough for any encoding shortcut */
Tim Petersced69f82003-09-16 20:30:58 +00003447
Guido van Rossumd57fd912000-03-10 22:53:23 +00003448 if (!PyUnicode_Check(unicode)) {
3449 PyErr_BadArgument();
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003450 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003451 }
Fred Drakee4315f52000-05-09 19:53:39 +00003452
Fred Drakee4315f52000-05-09 19:53:39 +00003453 /* Shortcuts for common default encodings */
Victor Stinner37296e82010-06-10 13:36:23 +00003454 if (normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003455 if ((strcmp(lower, "utf-8") == 0) ||
3456 (strcmp(lower, "utf8") == 0))
Victor Stinnera5c68c32011-03-02 01:03:14 +00003457 {
Victor Stinner2f283c22011-03-02 01:21:46 +00003458 if (errors == NULL || strcmp(errors, "strict") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003459 return _PyUnicode_AsUTF8String(unicode, NULL);
Victor Stinner2f283c22011-03-02 01:21:46 +00003460 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003461 return _PyUnicode_AsUTF8String(unicode, errors);
Victor Stinnera5c68c32011-03-02 01:03:14 +00003462 }
Victor Stinner37296e82010-06-10 13:36:23 +00003463 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003464 (strcmp(lower, "latin1") == 0) ||
Victor Stinner37296e82010-06-10 13:36:23 +00003465 (strcmp(lower, "iso-8859-1") == 0))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003466 return _PyUnicode_AsLatin1String(unicode, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02003467#ifdef HAVE_MBCS
Victor Stinnerac931b12011-11-20 18:27:03 +01003468 else if (strcmp(lower, "mbcs") == 0)
3469 return PyUnicode_EncodeCodePage(CP_ACP, unicode, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003470#endif
Victor Stinner37296e82010-06-10 13:36:23 +00003471 else if (strcmp(lower, "ascii") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003472 return _PyUnicode_AsASCIIString(unicode, errors);
Victor Stinner37296e82010-06-10 13:36:23 +00003473 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003474
3475 /* Encode via the codec registry */
3476 v = PyCodec_Encode(unicode, encoding, errors);
3477 if (v == NULL)
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003478 return NULL;
3479
3480 /* The normal path */
3481 if (PyBytes_Check(v))
3482 return v;
3483
3484 /* If the codec returns a buffer, raise a warning and convert to bytes */
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003485 if (PyByteArray_Check(v)) {
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003486 int error;
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003487 PyObject *b;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003488
3489 error = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
3490 "encoder %s returned bytearray instead of bytes",
3491 encoding);
3492 if (error) {
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003493 Py_DECREF(v);
3494 return NULL;
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003495 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003496
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003497 b = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(v), Py_SIZE(v));
3498 Py_DECREF(v);
3499 return b;
3500 }
3501
3502 PyErr_Format(PyExc_TypeError,
3503 "encoder did not return a bytes object (type=%.400s)",
3504 Py_TYPE(v)->tp_name);
3505 Py_DECREF(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003506 return NULL;
3507}
3508
Alexander Belopolsky40018472011-02-26 01:02:56 +00003509PyObject *
3510PyUnicode_AsEncodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003511 const char *encoding,
3512 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003513{
3514 PyObject *v;
3515
3516 if (!PyUnicode_Check(unicode)) {
3517 PyErr_BadArgument();
3518 goto onError;
3519 }
3520
3521 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003522 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003523
3524 /* Encode via the codec registry */
3525 v = PyCodec_Encode(unicode, encoding, errors);
3526 if (v == NULL)
3527 goto onError;
3528 if (!PyUnicode_Check(v)) {
3529 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00003530 "encoder did not return an str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003531 Py_TYPE(v)->tp_name);
3532 Py_DECREF(v);
3533 goto onError;
3534 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003535 return v;
Tim Petersced69f82003-09-16 20:30:58 +00003536
Benjamin Peterson29060642009-01-31 22:14:21 +00003537 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003538 return NULL;
3539}
3540
Victor Stinner2f197072011-12-17 07:08:30 +01003541static size_t
3542mbstowcs_errorpos(const char *str, size_t len)
3543{
3544#ifdef HAVE_MBRTOWC
3545 const char *start = str;
3546 mbstate_t mbs;
3547 size_t converted;
3548 wchar_t ch;
3549
3550 memset(&mbs, 0, sizeof mbs);
3551 while (len)
3552 {
3553 converted = mbrtowc(&ch, (char*)str, len, &mbs);
3554 if (converted == 0)
3555 /* Reached end of string */
3556 break;
3557 if (converted == (size_t)-1 || converted == (size_t)-2) {
3558 /* Conversion error or incomplete character */
3559 return str - start;
3560 }
3561 else {
3562 str += converted;
3563 len -= converted;
3564 }
3565 }
3566 /* failed to find the undecodable byte sequence */
3567 return 0;
3568#endif
3569 return 0;
3570}
3571
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003572PyObject*
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003573PyUnicode_DecodeLocaleAndSize(const char *str, Py_ssize_t len,
Victor Stinner1b579672011-12-17 05:47:23 +01003574 const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003575{
3576 wchar_t smallbuf[256];
3577 size_t smallbuf_len = Py_ARRAY_LENGTH(smallbuf);
3578 wchar_t *wstr;
3579 size_t wlen, wlen2;
3580 PyObject *unicode;
Victor Stinner1b579672011-12-17 05:47:23 +01003581 int surrogateescape;
Victor Stinner2f197072011-12-17 07:08:30 +01003582 size_t error_pos;
3583 char *errmsg;
3584 PyObject *reason, *exc;
Victor Stinner1b579672011-12-17 05:47:23 +01003585
3586 if (locale_error_handler(errors, &surrogateescape) < 0)
3587 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003588
3589 if (str[len] != '\0' || len != strlen(str)) {
3590 PyErr_SetString(PyExc_TypeError, "embedded null character");
3591 return NULL;
3592 }
3593
3594 if (surrogateescape)
3595 {
3596 wstr = _Py_char2wchar(str, &wlen);
3597 if (wstr == NULL) {
3598 if (wlen == (size_t)-1)
3599 PyErr_NoMemory();
3600 else
3601 PyErr_SetFromErrno(PyExc_OSError);
3602 return NULL;
3603 }
3604
3605 unicode = PyUnicode_FromWideChar(wstr, wlen);
3606 PyMem_Free(wstr);
3607 }
3608 else {
3609#ifndef HAVE_BROKEN_MBSTOWCS
3610 wlen = mbstowcs(NULL, str, 0);
3611#else
3612 wlen = len;
3613#endif
Victor Stinner2f197072011-12-17 07:08:30 +01003614 if (wlen == (size_t)-1)
3615 goto decode_error;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003616 if (wlen+1 <= smallbuf_len) {
3617 wstr = smallbuf;
3618 }
3619 else {
3620 if (wlen > PY_SSIZE_T_MAX / sizeof(wchar_t) - 1)
3621 return PyErr_NoMemory();
3622
3623 wstr = PyMem_Malloc((wlen+1) * sizeof(wchar_t));
3624 if (!wstr)
3625 return PyErr_NoMemory();
3626 }
3627
3628 /* This shouldn't fail now */
3629 wlen2 = mbstowcs(wstr, str, wlen+1);
3630 if (wlen2 == (size_t)-1) {
3631 if (wstr != smallbuf)
3632 PyMem_Free(wstr);
Victor Stinner2f197072011-12-17 07:08:30 +01003633 goto decode_error;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003634 }
3635#ifdef HAVE_BROKEN_MBSTOWCS
3636 assert(wlen2 == wlen);
3637#endif
3638 unicode = PyUnicode_FromWideChar(wstr, wlen2);
3639 if (wstr != smallbuf)
3640 PyMem_Free(wstr);
3641 }
3642 return unicode;
Victor Stinner2f197072011-12-17 07:08:30 +01003643
3644decode_error:
3645 errmsg = strerror(errno);
3646 assert(errmsg != NULL);
3647
3648 error_pos = mbstowcs_errorpos(str, len);
3649 if (errmsg != NULL) {
3650 size_t errlen;
3651 wstr = _Py_char2wchar(errmsg, &errlen);
3652 if (wstr != NULL) {
3653 reason = PyUnicode_FromWideChar(wstr, errlen);
3654 PyMem_Free(wstr);
3655 } else
3656 errmsg = NULL;
3657 }
3658 if (errmsg == NULL)
3659 reason = PyUnicode_FromString(
3660 "mbstowcs() encountered an invalid multibyte sequence");
3661 if (reason == NULL)
3662 return NULL;
3663
3664 exc = PyObject_CallFunction(PyExc_UnicodeDecodeError, "sy#nnO",
3665 "locale", str, len,
3666 (Py_ssize_t)error_pos,
3667 (Py_ssize_t)(error_pos+1),
3668 reason);
3669 Py_DECREF(reason);
3670 if (exc != NULL) {
3671 PyCodec_StrictErrors(exc);
3672 Py_XDECREF(exc);
3673 }
3674 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003675}
3676
3677PyObject*
Victor Stinner1b579672011-12-17 05:47:23 +01003678PyUnicode_DecodeLocale(const char *str, const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003679{
3680 Py_ssize_t size = (Py_ssize_t)strlen(str);
Victor Stinner1b579672011-12-17 05:47:23 +01003681 return PyUnicode_DecodeLocaleAndSize(str, size, errors);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003682}
3683
3684
3685PyObject*
Christian Heimes5894ba72007-11-04 11:43:14 +00003686PyUnicode_DecodeFSDefault(const char *s) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003687 Py_ssize_t size = (Py_ssize_t)strlen(s);
Christian Heimes5894ba72007-11-04 11:43:14 +00003688 return PyUnicode_DecodeFSDefaultAndSize(s, size);
3689}
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003690
Christian Heimes5894ba72007-11-04 11:43:14 +00003691PyObject*
3692PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
3693{
Victor Stinner99b95382011-07-04 14:23:54 +02003694#ifdef HAVE_MBCS
Victor Stinnerad158722010-10-27 00:25:46 +00003695 return PyUnicode_DecodeMBCS(s, size, NULL);
3696#elif defined(__APPLE__)
Victor Stinnera1d12bb2011-12-11 21:53:09 +01003697 return PyUnicode_DecodeUTF8Stateful(s, size, "surrogateescape", NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003698#else
Victor Stinner793b5312011-04-27 00:24:21 +02003699 PyInterpreterState *interp = PyThreadState_GET()->interp;
3700 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3701 cannot use it to encode and decode filenames before it is loaded. Load
3702 the Python codec requires to encode at least its own filename. Use the C
3703 version of the locale codec until the codec registry is initialized and
3704 the Python codec is loaded.
3705
3706 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3707 cannot only rely on it: check also interp->fscodec_initialized for
3708 subinterpreters. */
3709 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003710 return PyUnicode_Decode(s, size,
3711 Py_FileSystemDefaultEncoding,
Victor Stinnerb9a20ad2010-04-30 16:37:52 +00003712 "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003713 }
3714 else {
Victor Stinner1b579672011-12-17 05:47:23 +01003715 return PyUnicode_DecodeLocaleAndSize(s, size, "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003716 }
Victor Stinnerad158722010-10-27 00:25:46 +00003717#endif
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003718}
3719
Martin v. Löwis011e8422009-05-05 04:43:17 +00003720
3721int
Antoine Pitrou13348842012-01-29 18:36:34 +01003722_PyUnicode_HasNULChars(PyObject* s)
3723{
3724 static PyObject *nul = NULL;
3725
3726 if (nul == NULL)
3727 nul = PyUnicode_FromStringAndSize("\0", 1);
3728 if (nul == NULL)
3729 return -1;
3730 return PyUnicode_Contains(s, nul);
3731}
3732
3733
3734int
Martin v. Löwis011e8422009-05-05 04:43:17 +00003735PyUnicode_FSConverter(PyObject* arg, void* addr)
3736{
3737 PyObject *output = NULL;
3738 Py_ssize_t size;
3739 void *data;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003740 if (arg == NULL) {
3741 Py_DECREF(*(PyObject**)addr);
3742 return 1;
3743 }
Victor Stinnerdcb24032010-04-22 12:08:36 +00003744 if (PyBytes_Check(arg)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00003745 output = arg;
3746 Py_INCREF(output);
3747 }
3748 else {
3749 arg = PyUnicode_FromObject(arg);
3750 if (!arg)
3751 return 0;
Victor Stinnerae6265f2010-05-15 16:27:27 +00003752 output = PyUnicode_EncodeFSDefault(arg);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003753 Py_DECREF(arg);
3754 if (!output)
3755 return 0;
3756 if (!PyBytes_Check(output)) {
3757 Py_DECREF(output);
3758 PyErr_SetString(PyExc_TypeError, "encoder failed to return bytes");
3759 return 0;
3760 }
3761 }
Victor Stinner0ea2a462010-04-30 00:22:08 +00003762 size = PyBytes_GET_SIZE(output);
3763 data = PyBytes_AS_STRING(output);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003764 if (size != strlen(data)) {
Benjamin Peterson7a6b44a2011-08-18 13:51:47 -05003765 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
Martin v. Löwis011e8422009-05-05 04:43:17 +00003766 Py_DECREF(output);
3767 return 0;
3768 }
3769 *(PyObject**)addr = output;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003770 return Py_CLEANUP_SUPPORTED;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003771}
3772
3773
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003774int
3775PyUnicode_FSDecoder(PyObject* arg, void* addr)
3776{
3777 PyObject *output = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003778 if (arg == NULL) {
3779 Py_DECREF(*(PyObject**)addr);
3780 return 1;
3781 }
3782 if (PyUnicode_Check(arg)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -05003783 if (PyUnicode_READY(arg) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003784 return 0;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003785 output = arg;
3786 Py_INCREF(output);
3787 }
3788 else {
3789 arg = PyBytes_FromObject(arg);
3790 if (!arg)
3791 return 0;
3792 output = PyUnicode_DecodeFSDefaultAndSize(PyBytes_AS_STRING(arg),
3793 PyBytes_GET_SIZE(arg));
3794 Py_DECREF(arg);
3795 if (!output)
3796 return 0;
3797 if (!PyUnicode_Check(output)) {
3798 Py_DECREF(output);
3799 PyErr_SetString(PyExc_TypeError, "decoder failed to return unicode");
3800 return 0;
3801 }
3802 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05003803 if (PyUnicode_READY(output) == -1) {
Victor Stinner065836e2011-10-27 01:56:33 +02003804 Py_DECREF(output);
3805 return 0;
3806 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003807 if (findchar(PyUnicode_DATA(output), PyUnicode_KIND(output),
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02003808 PyUnicode_GET_LENGTH(output), 0, 1) >= 0) {
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003809 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
3810 Py_DECREF(output);
3811 return 0;
3812 }
3813 *(PyObject**)addr = output;
3814 return Py_CLEANUP_SUPPORTED;
3815}
3816
3817
Martin v. Löwis5b222132007-06-10 09:51:05 +00003818char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003819PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *psize)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003820{
Christian Heimesf3863112007-11-22 07:46:41 +00003821 PyObject *bytes;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003822
Neal Norwitze0a0a6e2007-08-25 01:04:21 +00003823 if (!PyUnicode_Check(unicode)) {
3824 PyErr_BadArgument();
3825 return NULL;
3826 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003827 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003828 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003829
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003830 if (PyUnicode_UTF8(unicode) == NULL) {
3831 assert(!PyUnicode_IS_COMPACT_ASCII(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003832 bytes = _PyUnicode_AsUTF8String(unicode, "strict");
3833 if (bytes == NULL)
3834 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003835 _PyUnicode_UTF8(unicode) = PyObject_MALLOC(PyBytes_GET_SIZE(bytes) + 1);
3836 if (_PyUnicode_UTF8(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003837 Py_DECREF(bytes);
3838 return NULL;
3839 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003840 _PyUnicode_UTF8_LENGTH(unicode) = PyBytes_GET_SIZE(bytes);
3841 Py_MEMCPY(_PyUnicode_UTF8(unicode),
3842 PyBytes_AS_STRING(bytes),
3843 _PyUnicode_UTF8_LENGTH(unicode) + 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003844 Py_DECREF(bytes);
3845 }
3846
3847 if (psize)
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003848 *psize = PyUnicode_UTF8_LENGTH(unicode);
3849 return PyUnicode_UTF8(unicode);
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003850}
3851
3852char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003853PyUnicode_AsUTF8(PyObject *unicode)
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003854{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003855 return PyUnicode_AsUTF8AndSize(unicode, NULL);
3856}
3857
3858#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +02003859static int unicode_as_unicode_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003860#endif
3861
3862
3863Py_UNICODE *
3864PyUnicode_AsUnicodeAndSize(PyObject *unicode, Py_ssize_t *size)
3865{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003866 const unsigned char *one_byte;
3867#if SIZEOF_WCHAR_T == 4
3868 const Py_UCS2 *two_bytes;
3869#else
3870 const Py_UCS4 *four_bytes;
3871 const Py_UCS4 *ucs4_end;
3872 Py_ssize_t num_surrogates;
3873#endif
3874 wchar_t *w;
3875 wchar_t *wchar_end;
3876
3877 if (!PyUnicode_Check(unicode)) {
3878 PyErr_BadArgument();
3879 return NULL;
3880 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003881 if (_PyUnicode_WSTR(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003882 /* Non-ASCII compact unicode object */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003883 assert(_PyUnicode_KIND(unicode) != 0);
3884 assert(PyUnicode_IS_READY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003885
3886#ifdef Py_DEBUG
3887 ++unicode_as_unicode_calls;
3888#endif
3889
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003890 if (PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003891#if SIZEOF_WCHAR_T == 2
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003892 four_bytes = PyUnicode_4BYTE_DATA(unicode);
3893 ucs4_end = four_bytes + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003894 num_surrogates = 0;
3895
3896 for (; four_bytes < ucs4_end; ++four_bytes) {
3897 if (*four_bytes > 0xFFFF)
3898 ++num_surrogates;
3899 }
3900
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003901 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(
3902 sizeof(wchar_t) * (_PyUnicode_LENGTH(unicode) + 1 + num_surrogates));
3903 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003904 PyErr_NoMemory();
3905 return NULL;
3906 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003907 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode) + num_surrogates;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003908
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003909 w = _PyUnicode_WSTR(unicode);
3910 wchar_end = w + _PyUnicode_WSTR_LENGTH(unicode);
3911 four_bytes = PyUnicode_4BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003912 for (; four_bytes < ucs4_end; ++four_bytes, ++w) {
3913 if (*four_bytes > 0xFFFF) {
Victor Stinner8faf8212011-12-08 22:14:11 +01003914 assert(*four_bytes <= MAX_UNICODE);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003915 /* encode surrogate pair in this case */
Victor Stinner551ac952011-11-29 22:58:13 +01003916 *w++ = Py_UNICODE_HIGH_SURROGATE(*four_bytes);
3917 *w = Py_UNICODE_LOW_SURROGATE(*four_bytes);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003918 }
3919 else
3920 *w = *four_bytes;
3921
3922 if (w > wchar_end) {
3923 assert(0 && "Miscalculated string end");
3924 }
3925 }
3926 *w = 0;
3927#else
3928 /* sizeof(wchar_t) == 4 */
3929 Py_FatalError("Impossible unicode object state, wstr and str "
3930 "should share memory already.");
3931 return NULL;
3932#endif
3933 }
3934 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003935 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(sizeof(wchar_t) *
3936 (_PyUnicode_LENGTH(unicode) + 1));
3937 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003938 PyErr_NoMemory();
3939 return NULL;
3940 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003941 if (!PyUnicode_IS_COMPACT_ASCII(unicode))
3942 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode);
3943 w = _PyUnicode_WSTR(unicode);
3944 wchar_end = w + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003945
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003946 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND) {
3947 one_byte = PyUnicode_1BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003948 for (; w < wchar_end; ++one_byte, ++w)
3949 *w = *one_byte;
3950 /* null-terminate the wstr */
3951 *w = 0;
3952 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003953 else if (PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003954#if SIZEOF_WCHAR_T == 4
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003955 two_bytes = PyUnicode_2BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003956 for (; w < wchar_end; ++two_bytes, ++w)
3957 *w = *two_bytes;
3958 /* null-terminate the wstr */
3959 *w = 0;
3960#else
3961 /* sizeof(wchar_t) == 2 */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003962 PyObject_FREE(_PyUnicode_WSTR(unicode));
3963 _PyUnicode_WSTR(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003964 Py_FatalError("Impossible unicode object state, wstr "
3965 "and str should share memory already.");
3966 return NULL;
3967#endif
3968 }
3969 else {
3970 assert(0 && "This should never happen.");
3971 }
3972 }
3973 }
3974 if (size != NULL)
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003975 *size = PyUnicode_WSTR_LENGTH(unicode);
3976 return _PyUnicode_WSTR(unicode);
Martin v. Löwis5b222132007-06-10 09:51:05 +00003977}
3978
Alexander Belopolsky40018472011-02-26 01:02:56 +00003979Py_UNICODE *
3980PyUnicode_AsUnicode(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003981{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003982 return PyUnicode_AsUnicodeAndSize(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003983}
3984
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003985
Alexander Belopolsky40018472011-02-26 01:02:56 +00003986Py_ssize_t
3987PyUnicode_GetSize(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003988{
3989 if (!PyUnicode_Check(unicode)) {
3990 PyErr_BadArgument();
3991 goto onError;
3992 }
3993 return PyUnicode_GET_SIZE(unicode);
3994
Benjamin Peterson29060642009-01-31 22:14:21 +00003995 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003996 return -1;
3997}
3998
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003999Py_ssize_t
4000PyUnicode_GetLength(PyObject *unicode)
4001{
Victor Stinner5a706cf2011-10-02 00:36:53 +02004002 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004003 PyErr_BadArgument();
4004 return -1;
4005 }
4006
4007 return PyUnicode_GET_LENGTH(unicode);
4008}
4009
4010Py_UCS4
4011PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
4012{
Victor Stinner2fe5ced2011-10-02 00:25:40 +02004013 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
4014 PyErr_BadArgument();
4015 return (Py_UCS4)-1;
4016 }
Victor Stinnerc4b49542011-12-11 22:44:26 +01004017 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinner2fe5ced2011-10-02 00:25:40 +02004018 PyErr_SetString(PyExc_IndexError, "string index out of range");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004019 return (Py_UCS4)-1;
4020 }
4021 return PyUnicode_READ_CHAR(unicode, index);
4022}
4023
4024int
4025PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 ch)
4026{
4027 if (!PyUnicode_Check(unicode) || !PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02004028 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004029 return -1;
4030 }
Victor Stinner488fa492011-12-12 00:01:39 +01004031 assert(PyUnicode_IS_READY(unicode));
Victor Stinnerc4b49542011-12-11 22:44:26 +01004032 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02004033 PyErr_SetString(PyExc_IndexError, "string index out of range");
4034 return -1;
4035 }
Victor Stinner488fa492011-12-12 00:01:39 +01004036 if (unicode_check_modifiable(unicode))
Victor Stinnercd9950f2011-10-02 00:34:53 +02004037 return -1;
Victor Stinnerc9590ad2012-03-04 01:34:37 +01004038 if (ch > PyUnicode_MAX_CHAR_VALUE(unicode)) {
4039 PyErr_SetString(PyExc_ValueError, "character out of range");
4040 return -1;
4041 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004042 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
4043 index, ch);
4044 return 0;
4045}
4046
Alexander Belopolsky40018472011-02-26 01:02:56 +00004047const char *
4048PyUnicode_GetDefaultEncoding(void)
Fred Drakee4315f52000-05-09 19:53:39 +00004049{
Victor Stinner42cb4622010-09-01 19:39:01 +00004050 return "utf-8";
Fred Drakee4315f52000-05-09 19:53:39 +00004051}
4052
Victor Stinner554f3f02010-06-16 23:33:54 +00004053/* create or adjust a UnicodeDecodeError */
4054static void
4055make_decode_exception(PyObject **exceptionObject,
4056 const char *encoding,
4057 const char *input, Py_ssize_t length,
4058 Py_ssize_t startpos, Py_ssize_t endpos,
4059 const char *reason)
4060{
4061 if (*exceptionObject == NULL) {
4062 *exceptionObject = PyUnicodeDecodeError_Create(
4063 encoding, input, length, startpos, endpos, reason);
4064 }
4065 else {
4066 if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
4067 goto onError;
4068 if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
4069 goto onError;
4070 if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
4071 goto onError;
4072 }
4073 return;
4074
4075onError:
4076 Py_DECREF(*exceptionObject);
4077 *exceptionObject = NULL;
4078}
4079
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004080/* error handling callback helper:
4081 build arguments, call the callback and check the arguments,
Fred Drakedb390c12005-10-28 14:39:47 +00004082 if no exception occurred, copy the replacement to the output
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004083 and adjust various state variables.
4084 return 0 on success, -1 on error
4085*/
4086
Alexander Belopolsky40018472011-02-26 01:02:56 +00004087static int
4088unicode_decode_call_errorhandler(const char *errors, PyObject **errorHandler,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004089 const char *encoding, const char *reason,
4090 const char **input, const char **inend, Py_ssize_t *startinpos,
4091 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004092 PyObject **output, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004093{
Benjamin Peterson142957c2008-07-04 19:55:29 +00004094 static char *argparse = "O!n;decoding error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004095
4096 PyObject *restuple = NULL;
4097 PyObject *repunicode = NULL;
Victor Stinner596a6c42011-11-09 00:02:18 +01004098 Py_ssize_t outsize;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004099 Py_ssize_t insize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004100 Py_ssize_t requiredsize;
4101 Py_ssize_t newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004102 PyObject *inputobj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004103 int res = -1;
4104
Victor Stinner596a6c42011-11-09 00:02:18 +01004105 if (_PyUnicode_KIND(*output) != PyUnicode_WCHAR_KIND)
4106 outsize = PyUnicode_GET_LENGTH(*output);
4107 else
4108 outsize = _PyUnicode_WSTR_LENGTH(*output);
4109
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004110 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004111 *errorHandler = PyCodec_LookupError(errors);
4112 if (*errorHandler == NULL)
4113 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004114 }
4115
Victor Stinner554f3f02010-06-16 23:33:54 +00004116 make_decode_exception(exceptionObject,
4117 encoding,
4118 *input, *inend - *input,
4119 *startinpos, *endinpos,
4120 reason);
4121 if (*exceptionObject == NULL)
4122 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004123
4124 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
4125 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004126 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004127 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00004128 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00004129 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004130 }
4131 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00004132 goto onError;
Benjamin Petersonbac79492012-01-14 13:34:47 -05004133 if (PyUnicode_READY(repunicode) == -1)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004134 goto onError;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004135
4136 /* Copy back the bytes variables, which might have been modified by the
4137 callback */
4138 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4139 if (!inputobj)
4140 goto onError;
Christian Heimes72b710a2008-05-26 13:28:38 +00004141 if (!PyBytes_Check(inputobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004142 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
Walter Dörwalde78178e2007-07-30 13:31:40 +00004143 }
Christian Heimes72b710a2008-05-26 13:28:38 +00004144 *input = PyBytes_AS_STRING(inputobj);
4145 insize = PyBytes_GET_SIZE(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004146 *inend = *input + insize;
Walter Dörwald36f938f2007-08-10 10:11:43 +00004147 /* we can DECREF safely, as the exception has another reference,
4148 so the object won't go away. */
4149 Py_DECREF(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004150
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004151 if (newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004152 newpos = insize+newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004153 if (newpos<0 || newpos>insize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004154 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
4155 goto onError;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004156 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004157
Victor Stinner596a6c42011-11-09 00:02:18 +01004158 if (_PyUnicode_KIND(*output) != PyUnicode_WCHAR_KIND) {
4159 /* need more space? (at least enough for what we
4160 have+the replacement+the rest of the string (starting
4161 at the new input position), so we won't have to check space
4162 when there are no errors in the rest of the string) */
4163 Py_ssize_t replen = PyUnicode_GET_LENGTH(repunicode);
4164 requiredsize = *outpos + replen + insize-newpos;
4165 if (requiredsize > outsize) {
4166 if (requiredsize<2*outsize)
4167 requiredsize = 2*outsize;
4168 if (unicode_resize(output, requiredsize) < 0)
4169 goto onError;
4170 }
Victor Stinner1b487b42012-05-03 12:29:04 +02004171 if (unicode_widen(output, *outpos,
4172 PyUnicode_MAX_CHAR_VALUE(repunicode)) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004173 goto onError;
Victor Stinner596a6c42011-11-09 00:02:18 +01004174 copy_characters(*output, *outpos, repunicode, 0, replen);
4175 *outpos += replen;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004176 }
Victor Stinner596a6c42011-11-09 00:02:18 +01004177 else {
4178 wchar_t *repwstr;
4179 Py_ssize_t repwlen;
4180 repwstr = PyUnicode_AsUnicodeAndSize(repunicode, &repwlen);
4181 if (repwstr == NULL)
4182 goto onError;
4183 /* need more space? (at least enough for what we
4184 have+the replacement+the rest of the string (starting
4185 at the new input position), so we won't have to check space
4186 when there are no errors in the rest of the string) */
4187 requiredsize = *outpos + repwlen + insize-newpos;
4188 if (requiredsize > outsize) {
4189 if (requiredsize < 2*outsize)
4190 requiredsize = 2*outsize;
4191 if (unicode_resize(output, requiredsize) < 0)
4192 goto onError;
4193 }
4194 wcsncpy(_PyUnicode_WSTR(*output) + *outpos, repwstr, repwlen);
4195 *outpos += repwlen;
4196 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004197 *endinpos = newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004198 *inptr = *input + newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004199
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004200 /* we made it! */
4201 res = 0;
4202
Benjamin Peterson29060642009-01-31 22:14:21 +00004203 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004204 Py_XDECREF(restuple);
4205 return res;
4206}
4207
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004208/* --- UTF-7 Codec -------------------------------------------------------- */
4209
Antoine Pitrou244651a2009-05-04 18:56:13 +00004210/* See RFC2152 for details. We encode conservatively and decode liberally. */
4211
4212/* Three simple macros defining base-64. */
4213
4214/* Is c a base-64 character? */
4215
4216#define IS_BASE64(c) \
4217 (((c) >= 'A' && (c) <= 'Z') || \
4218 ((c) >= 'a' && (c) <= 'z') || \
4219 ((c) >= '0' && (c) <= '9') || \
4220 (c) == '+' || (c) == '/')
4221
4222/* given that c is a base-64 character, what is its base-64 value? */
4223
4224#define FROM_BASE64(c) \
4225 (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' : \
4226 ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 : \
4227 ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 : \
4228 (c) == '+' ? 62 : 63)
4229
4230/* What is the base-64 character of the bottom 6 bits of n? */
4231
4232#define TO_BASE64(n) \
4233 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
4234
4235/* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
4236 * decoded as itself. We are permissive on decoding; the only ASCII
4237 * byte not decoding to itself is the + which begins a base64
4238 * string. */
4239
4240#define DECODE_DIRECT(c) \
4241 ((c) <= 127 && (c) != '+')
4242
4243/* The UTF-7 encoder treats ASCII characters differently according to
4244 * whether they are Set D, Set O, Whitespace, or special (i.e. none of
4245 * the above). See RFC2152. This array identifies these different
4246 * sets:
4247 * 0 : "Set D"
4248 * alphanumeric and '(),-./:?
4249 * 1 : "Set O"
4250 * !"#$%&*;<=>@[]^_`{|}
4251 * 2 : "whitespace"
4252 * ht nl cr sp
4253 * 3 : special (must be base64 encoded)
4254 * everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
4255 */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004256
Tim Petersced69f82003-09-16 20:30:58 +00004257static
Antoine Pitrou244651a2009-05-04 18:56:13 +00004258char utf7_category[128] = {
4259/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
4260 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
4261/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
4262 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
4263/* sp ! " # $ % & ' ( ) * + , - . / */
4264 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
4265/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
4266 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
4267/* @ A B C D E F G H I J K L M N O */
4268 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4269/* P Q R S T U V W X Y Z [ \ ] ^ _ */
4270 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
4271/* ` a b c d e f g h i j k l m n o */
4272 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4273/* p q r s t u v w x y z { | } ~ del */
4274 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004275};
4276
Antoine Pitrou244651a2009-05-04 18:56:13 +00004277/* ENCODE_DIRECT: this character should be encoded as itself. The
4278 * answer depends on whether we are encoding set O as itself, and also
4279 * on whether we are encoding whitespace as itself. RFC2152 makes it
4280 * clear that the answers to these questions vary between
4281 * applications, so this code needs to be flexible. */
Marc-André Lemburge115ec82005-10-19 22:33:31 +00004282
Antoine Pitrou244651a2009-05-04 18:56:13 +00004283#define ENCODE_DIRECT(c, directO, directWS) \
4284 ((c) < 128 && (c) > 0 && \
4285 ((utf7_category[(c)] == 0) || \
4286 (directWS && (utf7_category[(c)] == 2)) || \
4287 (directO && (utf7_category[(c)] == 1))))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004288
Alexander Belopolsky40018472011-02-26 01:02:56 +00004289PyObject *
4290PyUnicode_DecodeUTF7(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004291 Py_ssize_t size,
4292 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004293{
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004294 return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
4295}
4296
Antoine Pitrou244651a2009-05-04 18:56:13 +00004297/* The decoder. The only state we preserve is our read position,
4298 * i.e. how many characters we have consumed. So if we end in the
4299 * middle of a shift sequence we have to back off the read position
4300 * and the output to the beginning of the sequence, otherwise we lose
4301 * all the shift state (seen bits, number of bits seen, high
4302 * surrogate). */
4303
Alexander Belopolsky40018472011-02-26 01:02:56 +00004304PyObject *
4305PyUnicode_DecodeUTF7Stateful(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004306 Py_ssize_t size,
4307 const char *errors,
4308 Py_ssize_t *consumed)
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004309{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004310 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004311 Py_ssize_t startinpos;
4312 Py_ssize_t endinpos;
4313 Py_ssize_t outpos;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004314 const char *e;
Victor Stinner7931d9a2011-11-04 00:22:48 +01004315 PyObject *unicode;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004316 const char *errmsg = "";
4317 int inShift = 0;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004318 Py_ssize_t shiftOutStart;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004319 unsigned int base64bits = 0;
4320 unsigned long base64buffer = 0;
Victor Stinner24729f32011-11-10 20:31:37 +01004321 Py_UCS4 surrogate = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004322 PyObject *errorHandler = NULL;
4323 PyObject *exc = NULL;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004324
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004325 /* Start off assuming it's all ASCII. Widen later as necessary. */
4326 unicode = PyUnicode_New(size, 127);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004327 if (!unicode)
4328 return NULL;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004329 if (size == 0) {
4330 if (consumed)
4331 *consumed = 0;
Victor Stinner7931d9a2011-11-04 00:22:48 +01004332 return unicode;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004333 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004334
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004335 shiftOutStart = outpos = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004336 e = s + size;
4337
4338 while (s < e) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004339 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00004340 restart:
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00004341 ch = (unsigned char) *s;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004342
Antoine Pitrou244651a2009-05-04 18:56:13 +00004343 if (inShift) { /* in a base-64 section */
4344 if (IS_BASE64(ch)) { /* consume a base-64 character */
4345 base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
4346 base64bits += 6;
4347 s++;
4348 if (base64bits >= 16) {
4349 /* we have enough bits for a UTF-16 value */
Victor Stinner24729f32011-11-10 20:31:37 +01004350 Py_UCS4 outCh = (Py_UCS4)(base64buffer >> (base64bits-16));
Antoine Pitrou244651a2009-05-04 18:56:13 +00004351 base64bits -= 16;
4352 base64buffer &= (1 << base64bits) - 1; /* clear high bits */
4353 if (surrogate) {
4354 /* expecting a second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004355 if (Py_UNICODE_IS_LOW_SURROGATE(outCh)) {
4356 Py_UCS4 ch2 = Py_UNICODE_JOIN_SURROGATES(surrogate, outCh);
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004357 if (unicode_putchar(&unicode, &outpos, ch2) < 0)
4358 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004359 surrogate = 0;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01004360 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004361 }
4362 else {
Antoine Pitrou78edf752011-11-15 01:44:16 +01004363 if (unicode_putchar(&unicode, &outpos, surrogate) < 0)
4364 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004365 surrogate = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004366 }
4367 }
Victor Stinner551ac952011-11-29 22:58:13 +01004368 if (Py_UNICODE_IS_HIGH_SURROGATE(outCh)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004369 /* first surrogate */
4370 surrogate = outCh;
4371 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004372 else {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004373 if (unicode_putchar(&unicode, &outpos, outCh) < 0)
4374 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004375 }
4376 }
4377 }
4378 else { /* now leaving a base-64 section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004379 inShift = 0;
4380 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004381 if (surrogate) {
Antoine Pitrou78edf752011-11-15 01:44:16 +01004382 if (unicode_putchar(&unicode, &outpos, surrogate) < 0)
4383 goto onError;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01004384 surrogate = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004385 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004386 if (base64bits > 0) { /* left-over bits */
4387 if (base64bits >= 6) {
4388 /* We've seen at least one base-64 character */
4389 errmsg = "partial character in shift sequence";
4390 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004391 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004392 else {
4393 /* Some bits remain; they should be zero */
4394 if (base64buffer != 0) {
4395 errmsg = "non-zero padding bits in shift sequence";
4396 goto utf7Error;
4397 }
4398 }
4399 }
4400 if (ch != '-') {
4401 /* '-' is absorbed; other terminating
4402 characters are preserved */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004403 if (unicode_putchar(&unicode, &outpos, ch) < 0)
4404 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004405 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004406 }
4407 }
4408 else if ( ch == '+' ) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004409 startinpos = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004410 s++; /* consume '+' */
4411 if (s < e && *s == '-') { /* '+-' encodes '+' */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004412 s++;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004413 if (unicode_putchar(&unicode, &outpos, '+') < 0)
4414 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004415 }
4416 else { /* begin base64-encoded section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004417 inShift = 1;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004418 shiftOutStart = outpos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004419 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004420 }
4421 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004422 else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004423 if (unicode_putchar(&unicode, &outpos, ch) < 0)
4424 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004425 s++;
4426 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004427 else {
4428 startinpos = s-starts;
4429 s++;
4430 errmsg = "unexpected special character";
4431 goto utf7Error;
4432 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004433 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004434utf7Error:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004435 endinpos = s-starts;
4436 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00004437 errors, &errorHandler,
4438 "utf7", errmsg,
4439 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004440 &unicode, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00004441 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004442 }
4443
Antoine Pitrou244651a2009-05-04 18:56:13 +00004444 /* end of string */
4445
4446 if (inShift && !consumed) { /* in shift sequence, no more to follow */
4447 /* if we're in an inconsistent state, that's an error */
4448 if (surrogate ||
4449 (base64bits >= 6) ||
4450 (base64bits > 0 && base64buffer != 0)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004451 endinpos = size;
4452 if (unicode_decode_call_errorhandler(
4453 errors, &errorHandler,
4454 "utf7", "unterminated shift sequence",
4455 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004456 &unicode, &outpos))
Antoine Pitrou244651a2009-05-04 18:56:13 +00004457 goto onError;
4458 if (s < e)
4459 goto restart;
4460 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004461 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004462
4463 /* return state */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004464 if (consumed) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004465 if (inShift) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004466 outpos = shiftOutStart; /* back off output */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004467 *consumed = startinpos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004468 }
4469 else {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004470 *consumed = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004471 }
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004472 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004473
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004474 if (unicode_resize(&unicode, outpos) < 0)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004475 goto onError;
4476
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004477 Py_XDECREF(errorHandler);
4478 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01004479 return unicode_result(unicode);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004480
Benjamin Peterson29060642009-01-31 22:14:21 +00004481 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004482 Py_XDECREF(errorHandler);
4483 Py_XDECREF(exc);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004484 Py_DECREF(unicode);
4485 return NULL;
4486}
4487
4488
Alexander Belopolsky40018472011-02-26 01:02:56 +00004489PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004490_PyUnicode_EncodeUTF7(PyObject *str,
4491 int base64SetO,
4492 int base64WhiteSpace,
4493 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004494{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004495 int kind;
4496 void *data;
4497 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004498 PyObject *v;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004499 Py_ssize_t allocated;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004500 int inShift = 0;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004501 Py_ssize_t i;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004502 unsigned int base64bits = 0;
4503 unsigned long base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004504 char * out;
4505 char * start;
4506
Benjamin Petersonbac79492012-01-14 13:34:47 -05004507 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004508 return NULL;
4509 kind = PyUnicode_KIND(str);
4510 data = PyUnicode_DATA(str);
4511 len = PyUnicode_GET_LENGTH(str);
4512
4513 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004514 return PyBytes_FromStringAndSize(NULL, 0);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004515
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004516 /* It might be possible to tighten this worst case */
4517 allocated = 8 * len;
4518 if (allocated / 8 != len)
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004519 return PyErr_NoMemory();
4520
Antoine Pitrou244651a2009-05-04 18:56:13 +00004521 v = PyBytes_FromStringAndSize(NULL, allocated);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004522 if (v == NULL)
4523 return NULL;
4524
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004525 start = out = PyBytes_AS_STRING(v);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004526 for (i = 0; i < len; ++i) {
Victor Stinner0e368262011-11-10 20:12:49 +01004527 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004528
Antoine Pitrou244651a2009-05-04 18:56:13 +00004529 if (inShift) {
4530 if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4531 /* shifting out */
4532 if (base64bits) { /* output remaining bits */
4533 *out++ = TO_BASE64(base64buffer << (6-base64bits));
4534 base64buffer = 0;
4535 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004536 }
4537 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004538 /* Characters not in the BASE64 set implicitly unshift the sequence
4539 so no '-' is required, except if the character is itself a '-' */
4540 if (IS_BASE64(ch) || ch == '-') {
4541 *out++ = '-';
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004542 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004543 *out++ = (char) ch;
4544 }
4545 else {
4546 goto encode_char;
Tim Petersced69f82003-09-16 20:30:58 +00004547 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004548 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004549 else { /* not in a shift sequence */
4550 if (ch == '+') {
4551 *out++ = '+';
4552 *out++ = '-';
4553 }
4554 else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4555 *out++ = (char) ch;
4556 }
4557 else {
4558 *out++ = '+';
4559 inShift = 1;
4560 goto encode_char;
4561 }
4562 }
4563 continue;
4564encode_char:
Antoine Pitrou244651a2009-05-04 18:56:13 +00004565 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01004566 assert(ch <= MAX_UNICODE);
Victor Stinner0d3721d2011-11-22 03:27:53 +01004567
Antoine Pitrou244651a2009-05-04 18:56:13 +00004568 /* code first surrogate */
4569 base64bits += 16;
4570 base64buffer = (base64buffer << 16) | 0xd800 | ((ch-0x10000) >> 10);
4571 while (base64bits >= 6) {
4572 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4573 base64bits -= 6;
4574 }
4575 /* prepare second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004576 ch = Py_UNICODE_LOW_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004577 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004578 base64bits += 16;
4579 base64buffer = (base64buffer << 16) | ch;
4580 while (base64bits >= 6) {
4581 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4582 base64bits -= 6;
4583 }
Hye-Shik Chang1bc09b72004-01-03 19:35:43 +00004584 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004585 if (base64bits)
4586 *out++= TO_BASE64(base64buffer << (6-base64bits) );
4587 if (inShift)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004588 *out++ = '-';
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004589 if (_PyBytes_Resize(&v, out - start) < 0)
4590 return NULL;
4591 return v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004592}
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004593PyObject *
4594PyUnicode_EncodeUTF7(const Py_UNICODE *s,
4595 Py_ssize_t size,
4596 int base64SetO,
4597 int base64WhiteSpace,
4598 const char *errors)
4599{
4600 PyObject *result;
4601 PyObject *tmp = PyUnicode_FromUnicode(s, size);
4602 if (tmp == NULL)
4603 return NULL;
Victor Stinner0e368262011-11-10 20:12:49 +01004604 result = _PyUnicode_EncodeUTF7(tmp, base64SetO,
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004605 base64WhiteSpace, errors);
4606 Py_DECREF(tmp);
4607 return result;
4608}
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004609
Antoine Pitrou244651a2009-05-04 18:56:13 +00004610#undef IS_BASE64
4611#undef FROM_BASE64
4612#undef TO_BASE64
4613#undef DECODE_DIRECT
4614#undef ENCODE_DIRECT
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004615
Guido van Rossumd57fd912000-03-10 22:53:23 +00004616/* --- UTF-8 Codec -------------------------------------------------------- */
4617
Alexander Belopolsky40018472011-02-26 01:02:56 +00004618PyObject *
4619PyUnicode_DecodeUTF8(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004620 Py_ssize_t size,
4621 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004622{
Walter Dörwald69652032004-09-07 20:24:22 +00004623 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
4624}
4625
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004626#include "stringlib/asciilib.h"
4627#include "stringlib/codecs.h"
4628#include "stringlib/undef.h"
4629
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004630#include "stringlib/ucs1lib.h"
4631#include "stringlib/codecs.h"
4632#include "stringlib/undef.h"
4633
4634#include "stringlib/ucs2lib.h"
4635#include "stringlib/codecs.h"
4636#include "stringlib/undef.h"
4637
4638#include "stringlib/ucs4lib.h"
4639#include "stringlib/codecs.h"
4640#include "stringlib/undef.h"
4641
Antoine Pitrouab868312009-01-10 15:40:25 +00004642/* Mask to check or force alignment of a pointer to C 'long' boundaries */
4643#define LONG_PTR_MASK (size_t) (SIZEOF_LONG - 1)
4644
4645/* Mask to quickly check whether a C 'long' contains a
4646 non-ASCII, UTF8-encoded char. */
4647#if (SIZEOF_LONG == 8)
4648# define ASCII_CHAR_MASK 0x8080808080808080L
4649#elif (SIZEOF_LONG == 4)
4650# define ASCII_CHAR_MASK 0x80808080L
4651#else
4652# error C 'long' size should be either 4 or 8!
4653#endif
4654
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004655static Py_ssize_t
4656ascii_decode(const char *start, const char *end, Py_UCS1 *dest)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004657{
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004658 const char *p = start;
4659 const char *aligned_end = (const char *) ((size_t) end & ~LONG_PTR_MASK);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004660
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004661#if SIZEOF_LONG <= SIZEOF_VOID_P
4662 assert(!((size_t) dest & LONG_PTR_MASK));
4663 if (!((size_t) p & LONG_PTR_MASK)) {
4664 /* Fast path, see in STRINGLIB(utf8_decode) for
4665 an explanation. */
4666 /* Help register allocation */
4667 register const char *_p = p;
4668 register Py_UCS1 * q = dest;
4669 while (_p < aligned_end) {
4670 unsigned long value = *(const unsigned long *) _p;
4671 if (value & ASCII_CHAR_MASK)
Benjamin Peterson29060642009-01-31 22:14:21 +00004672 break;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004673 *((unsigned long *)q) = value;
4674 _p += SIZEOF_LONG;
4675 q += SIZEOF_LONG;
Benjamin Peterson14339b62009-01-31 16:36:08 +00004676 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004677 p = _p;
4678 while (p < end) {
4679 if ((unsigned char)*p & 0x80)
4680 break;
4681 *q++ = *p++;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004682 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004683 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004684 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004685#endif
4686 while (p < end) {
4687 /* Fast path, see in STRINGLIB(utf8_decode) in stringlib/codecs.h
4688 for an explanation. */
4689 if (!((size_t) p & LONG_PTR_MASK)) {
4690 /* Help register allocation */
4691 register const char *_p = p;
4692 while (_p < aligned_end) {
4693 unsigned long value = *(unsigned long *) _p;
4694 if (value & ASCII_CHAR_MASK)
4695 break;
4696 _p += SIZEOF_LONG;
4697 }
4698 p = _p;
4699 if (_p == end)
4700 break;
4701 }
4702 if ((unsigned char)*p & 0x80)
4703 break;
4704 ++p;
4705 }
4706 memcpy(dest, start, p - start);
4707 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004708}
Antoine Pitrouab868312009-01-10 15:40:25 +00004709
Victor Stinner785938e2011-12-11 20:09:03 +01004710PyObject *
4711PyUnicode_DecodeUTF8Stateful(const char *s,
4712 Py_ssize_t size,
4713 const char *errors,
4714 Py_ssize_t *consumed)
4715{
Victor Stinner785938e2011-12-11 20:09:03 +01004716 PyObject *unicode;
Victor Stinner785938e2011-12-11 20:09:03 +01004717 const char *starts = s;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004718 const char *end = s + size;
4719 Py_ssize_t outpos;
4720
4721 Py_ssize_t startinpos;
4722 Py_ssize_t endinpos;
4723 const char *errmsg = "";
4724 PyObject *errorHandler = NULL;
4725 PyObject *exc = NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01004726
4727 if (size == 0) {
4728 if (consumed)
4729 *consumed = 0;
Victor Stinner382955f2011-12-11 21:44:00 +01004730 Py_INCREF(unicode_empty);
4731 return unicode_empty;
Victor Stinner785938e2011-12-11 20:09:03 +01004732 }
4733
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004734 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
4735 if (size == 1 && (unsigned char)s[0] < 128) {
Victor Stinner785938e2011-12-11 20:09:03 +01004736 if (consumed)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004737 *consumed = 1;
4738 return get_latin1_char((unsigned char)s[0]);
Victor Stinner785938e2011-12-11 20:09:03 +01004739 }
4740
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004741 unicode = PyUnicode_New(size, 127);
Victor Stinner785938e2011-12-11 20:09:03 +01004742 if (!unicode)
4743 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01004744
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004745 outpos = ascii_decode(s, end, PyUnicode_1BYTE_DATA(unicode));
4746 s += outpos;
4747 while (s < end) {
4748 Py_UCS4 ch;
4749 int kind = PyUnicode_KIND(unicode);
4750 if (kind == PyUnicode_1BYTE_KIND) {
4751 if (PyUnicode_IS_ASCII(unicode))
4752 ch = asciilib_utf8_decode(&s, end,
4753 PyUnicode_1BYTE_DATA(unicode), &outpos);
4754 else
4755 ch = ucs1lib_utf8_decode(&s, end,
4756 PyUnicode_1BYTE_DATA(unicode), &outpos);
4757 } else if (kind == PyUnicode_2BYTE_KIND) {
4758 ch = ucs2lib_utf8_decode(&s, end,
4759 PyUnicode_2BYTE_DATA(unicode), &outpos);
4760 } else {
4761 assert(kind == PyUnicode_4BYTE_KIND);
4762 ch = ucs4lib_utf8_decode(&s, end,
4763 PyUnicode_4BYTE_DATA(unicode), &outpos);
4764 }
4765
4766 switch (ch) {
4767 case 0:
4768 if (s == end || consumed)
4769 goto End;
4770 errmsg = "unexpected end of data";
4771 startinpos = s - starts;
4772 endinpos = startinpos + 1;
4773 while (endinpos < size && (starts[endinpos] & 0xC0) == 0x80)
4774 endinpos++;
4775 break;
4776 case 1:
4777 errmsg = "invalid start byte";
4778 startinpos = s - starts;
4779 endinpos = startinpos + 1;
4780 break;
4781 case 2:
4782 errmsg = "invalid continuation byte";
4783 startinpos = s - starts;
4784 endinpos = startinpos + 1;
4785 while (endinpos < size && (starts[endinpos] & 0xC0) == 0x80)
4786 endinpos++;
4787 break;
4788 default:
4789 if (unicode_putchar(&unicode, &outpos, ch) < 0)
4790 goto onError;
4791 continue;
4792 }
4793
4794 if (unicode_decode_call_errorhandler(
4795 errors, &errorHandler,
4796 "utf-8", errmsg,
4797 &starts, &end, &startinpos, &endinpos, &exc, &s,
4798 &unicode, &outpos))
4799 goto onError;
Victor Stinner785938e2011-12-11 20:09:03 +01004800 }
4801
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004802End:
4803 if (unicode_resize(&unicode, outpos) < 0)
4804 goto onError;
4805
4806 if (consumed)
4807 *consumed = s - starts;
4808
4809 Py_XDECREF(errorHandler);
4810 Py_XDECREF(exc);
4811 assert(_PyUnicode_CheckConsistency(unicode, 1));
4812 return unicode;
4813
4814onError:
4815 Py_XDECREF(errorHandler);
4816 Py_XDECREF(exc);
4817 Py_XDECREF(unicode);
4818 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01004819}
4820
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004821#ifdef __APPLE__
4822
4823/* Simplified UTF-8 decoder using surrogateescape error handler,
4824 used to decode the command line arguments on Mac OS X. */
4825
4826wchar_t*
4827_Py_DecodeUTF8_surrogateescape(const char *s, Py_ssize_t size)
4828{
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004829 const char *e;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004830 wchar_t *unicode;
4831 Py_ssize_t outpos;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004832
4833 /* Note: size will always be longer than the resulting Unicode
4834 character count */
4835 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < (size + 1)) {
4836 PyErr_NoMemory();
4837 return NULL;
4838 }
4839 unicode = PyMem_Malloc((size + 1) * sizeof(wchar_t));
4840 if (!unicode)
4841 return NULL;
4842
4843 /* Unpack UTF-8 encoded data */
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004844 e = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004845 outpos = 0;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004846 while (s < e) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004847 Py_UCS4 ch;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004848#if SIZEOF_WCHAR_T == 4
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004849 ch = ucs4lib_utf8_decode(&s, e, (Py_UCS4 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004850#else
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004851 ch = ucs2lib_utf8_decode(&s, e, (Py_UCS2 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004852#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004853 if (ch > 0xFF) {
4854#if SIZEOF_WCHAR_T == 4
4855 assert(0);
4856#else
4857 assert(Py_UNICODE_IS_SURROGATE(ch));
4858 /* compute and append the two surrogates: */
4859 unicode[outpos++] = (wchar_t)Py_UNICODE_HIGH_SURROGATE(ch);
4860 unicode[outpos++] = (wchar_t)Py_UNICODE_LOW_SURROGATE(ch);
4861#endif
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004862 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004863 else {
4864 if (!ch && s == e)
4865 break;
4866 /* surrogateescape */
4867 unicode[outpos++] = 0xDC00 + (unsigned char)*s++;
4868 }
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004869 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004870 unicode[outpos] = L'\0';
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004871 return unicode;
4872}
4873
4874#endif /* __APPLE__ */
Antoine Pitrouab868312009-01-10 15:40:25 +00004875
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004876/* Primary internal function which creates utf8 encoded bytes objects.
4877
4878 Allocation strategy: if the string is short, convert into a stack buffer
Tim Peters602f7402002-04-27 18:03:26 +00004879 and allocate exactly as much space needed at the end. Else allocate the
4880 maximum possible needed (4 result bytes per Unicode character), and return
4881 the excess memory at the end.
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004882*/
Tim Peters7e3d9612002-04-21 03:26:37 +00004883PyObject *
Victor Stinner7931d9a2011-11-04 00:22:48 +01004884_PyUnicode_AsUTF8String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004885{
Victor Stinner6099a032011-12-18 14:22:26 +01004886 enum PyUnicode_Kind kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004887 void *data;
4888 Py_ssize_t size;
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00004889
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004890 if (!PyUnicode_Check(unicode)) {
4891 PyErr_BadArgument();
4892 return NULL;
4893 }
4894
4895 if (PyUnicode_READY(unicode) == -1)
4896 return NULL;
4897
Victor Stinnere90fe6a2011-10-01 16:48:13 +02004898 if (PyUnicode_UTF8(unicode))
4899 return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode),
4900 PyUnicode_UTF8_LENGTH(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004901
4902 kind = PyUnicode_KIND(unicode);
4903 data = PyUnicode_DATA(unicode);
4904 size = PyUnicode_GET_LENGTH(unicode);
4905
Benjamin Petersonead6b532011-12-20 17:23:42 -06004906 switch (kind) {
Victor Stinner6099a032011-12-18 14:22:26 +01004907 default:
4908 assert(0);
4909 case PyUnicode_1BYTE_KIND:
4910 /* the string cannot be ASCII, or PyUnicode_UTF8() would be set */
4911 assert(!PyUnicode_IS_ASCII(unicode));
4912 return ucs1lib_utf8_encoder(unicode, data, size, errors);
4913 case PyUnicode_2BYTE_KIND:
4914 return ucs2lib_utf8_encoder(unicode, data, size, errors);
4915 case PyUnicode_4BYTE_KIND:
4916 return ucs4lib_utf8_encoder(unicode, data, size, errors);
Tim Peters602f7402002-04-27 18:03:26 +00004917 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004918}
4919
Alexander Belopolsky40018472011-02-26 01:02:56 +00004920PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004921PyUnicode_EncodeUTF8(const Py_UNICODE *s,
4922 Py_ssize_t size,
4923 const char *errors)
4924{
4925 PyObject *v, *unicode;
4926
4927 unicode = PyUnicode_FromUnicode(s, size);
4928 if (unicode == NULL)
4929 return NULL;
4930 v = _PyUnicode_AsUTF8String(unicode, errors);
4931 Py_DECREF(unicode);
4932 return v;
4933}
4934
4935PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00004936PyUnicode_AsUTF8String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004937{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004938 return _PyUnicode_AsUTF8String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004939}
4940
Walter Dörwald41980ca2007-08-16 21:55:45 +00004941/* --- UTF-32 Codec ------------------------------------------------------- */
4942
4943PyObject *
4944PyUnicode_DecodeUTF32(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004945 Py_ssize_t size,
4946 const char *errors,
4947 int *byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004948{
4949 return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
4950}
4951
4952PyObject *
4953PyUnicode_DecodeUTF32Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004954 Py_ssize_t size,
4955 const char *errors,
4956 int *byteorder,
4957 Py_ssize_t *consumed)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004958{
4959 const char *starts = s;
4960 Py_ssize_t startinpos;
4961 Py_ssize_t endinpos;
4962 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01004963 PyObject *unicode;
Mark Dickinson7db923c2010-06-12 09:10:14 +00004964 const unsigned char *q, *e;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004965 int bo = 0; /* assume native ordering by default */
4966 const char *errmsg = "";
Walter Dörwald41980ca2007-08-16 21:55:45 +00004967 /* Offsets from q for retrieving bytes in the right order. */
4968#ifdef BYTEORDER_IS_LITTLE_ENDIAN
4969 int iorder[] = {0, 1, 2, 3};
4970#else
4971 int iorder[] = {3, 2, 1, 0};
4972#endif
4973 PyObject *errorHandler = NULL;
4974 PyObject *exc = NULL;
Victor Stinner313a1202010-06-11 23:56:51 +00004975
Walter Dörwald41980ca2007-08-16 21:55:45 +00004976 q = (unsigned char *)s;
4977 e = q + size;
4978
4979 if (byteorder)
4980 bo = *byteorder;
4981
4982 /* Check for BOM marks (U+FEFF) in the input and adjust current
4983 byte order setting accordingly. In native mode, the leading BOM
4984 mark is skipped, in all other modes, it is copied to the output
4985 stream as-is (giving a ZWNBSP character). */
4986 if (bo == 0) {
4987 if (size >= 4) {
4988 const Py_UCS4 bom = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
Benjamin Peterson29060642009-01-31 22:14:21 +00004989 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00004990#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Benjamin Peterson29060642009-01-31 22:14:21 +00004991 if (bom == 0x0000FEFF) {
4992 q += 4;
4993 bo = -1;
4994 }
4995 else if (bom == 0xFFFE0000) {
4996 q += 4;
4997 bo = 1;
4998 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004999#else
Benjamin Peterson29060642009-01-31 22:14:21 +00005000 if (bom == 0x0000FEFF) {
5001 q += 4;
5002 bo = 1;
5003 }
5004 else if (bom == 0xFFFE0000) {
5005 q += 4;
5006 bo = -1;
5007 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00005008#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00005009 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00005010 }
5011
5012 if (bo == -1) {
5013 /* force LE */
5014 iorder[0] = 0;
5015 iorder[1] = 1;
5016 iorder[2] = 2;
5017 iorder[3] = 3;
5018 }
5019 else if (bo == 1) {
5020 /* force BE */
5021 iorder[0] = 3;
5022 iorder[1] = 2;
5023 iorder[2] = 1;
5024 iorder[3] = 0;
5025 }
5026
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005027 /* This might be one to much, because of a BOM */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005028 unicode = PyUnicode_New((size+3)/4, 127);
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005029 if (!unicode)
5030 return NULL;
5031 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01005032 return unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005033 outpos = 0;
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005034
Walter Dörwald41980ca2007-08-16 21:55:45 +00005035 while (q < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005036 Py_UCS4 ch;
5037 /* remaining bytes at the end? (size should be divisible by 4) */
5038 if (e-q<4) {
5039 if (consumed)
5040 break;
5041 errmsg = "truncated data";
5042 startinpos = ((const char *)q)-starts;
5043 endinpos = ((const char *)e)-starts;
5044 goto utf32Error;
5045 /* The remaining input chars are ignored if the callback
5046 chooses to skip the input */
5047 }
5048 ch = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
5049 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00005050
Benjamin Peterson29060642009-01-31 22:14:21 +00005051 if (ch >= 0x110000)
5052 {
5053 errmsg = "codepoint not in range(0x110000)";
5054 startinpos = ((const char *)q)-starts;
5055 endinpos = startinpos+4;
5056 goto utf32Error;
5057 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005058 if (unicode_putchar(&unicode, &outpos, ch) < 0)
5059 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005060 q += 4;
5061 continue;
5062 utf32Error:
Benjamin Peterson29060642009-01-31 22:14:21 +00005063 if (unicode_decode_call_errorhandler(
5064 errors, &errorHandler,
5065 "utf32", errmsg,
5066 &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005067 &unicode, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00005068 goto onError;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005069 }
5070
5071 if (byteorder)
5072 *byteorder = bo;
5073
5074 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005075 *consumed = (const char *)q-starts;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005076
5077 /* Adjust length */
Victor Stinner16e6a802011-12-12 13:24:15 +01005078 if (unicode_resize(&unicode, outpos) < 0)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005079 goto onError;
5080
5081 Py_XDECREF(errorHandler);
5082 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01005083 return unicode_result(unicode);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005084
Benjamin Peterson29060642009-01-31 22:14:21 +00005085 onError:
Walter Dörwald41980ca2007-08-16 21:55:45 +00005086 Py_DECREF(unicode);
5087 Py_XDECREF(errorHandler);
5088 Py_XDECREF(exc);
5089 return NULL;
5090}
5091
5092PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005093_PyUnicode_EncodeUTF32(PyObject *str,
5094 const char *errors,
5095 int byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005096{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005097 int kind;
5098 void *data;
5099 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005100 PyObject *v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005101 unsigned char *p;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005102 Py_ssize_t nsize, bytesize, i;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005103 /* Offsets from p for storing byte pairs in the right order. */
5104#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5105 int iorder[] = {0, 1, 2, 3};
5106#else
5107 int iorder[] = {3, 2, 1, 0};
5108#endif
5109
Benjamin Peterson29060642009-01-31 22:14:21 +00005110#define STORECHAR(CH) \
5111 do { \
5112 p[iorder[3]] = ((CH) >> 24) & 0xff; \
5113 p[iorder[2]] = ((CH) >> 16) & 0xff; \
5114 p[iorder[1]] = ((CH) >> 8) & 0xff; \
5115 p[iorder[0]] = (CH) & 0xff; \
5116 p += 4; \
Walter Dörwald41980ca2007-08-16 21:55:45 +00005117 } while(0)
5118
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005119 if (!PyUnicode_Check(str)) {
5120 PyErr_BadArgument();
5121 return NULL;
5122 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005123 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005124 return NULL;
5125 kind = PyUnicode_KIND(str);
5126 data = PyUnicode_DATA(str);
5127 len = PyUnicode_GET_LENGTH(str);
5128
5129 nsize = len + (byteorder == 0);
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005130 bytesize = nsize * 4;
5131 if (bytesize / 4 != nsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005132 return PyErr_NoMemory();
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005133 v = PyBytes_FromStringAndSize(NULL, bytesize);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005134 if (v == NULL)
5135 return NULL;
5136
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005137 p = (unsigned char *)PyBytes_AS_STRING(v);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005138 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005139 STORECHAR(0xFEFF);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005140 if (len == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005141 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005142
5143 if (byteorder == -1) {
5144 /* force LE */
5145 iorder[0] = 0;
5146 iorder[1] = 1;
5147 iorder[2] = 2;
5148 iorder[3] = 3;
5149 }
5150 else if (byteorder == 1) {
5151 /* force BE */
5152 iorder[0] = 3;
5153 iorder[1] = 2;
5154 iorder[2] = 1;
5155 iorder[3] = 0;
5156 }
5157
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005158 for (i = 0; i < len; i++)
5159 STORECHAR(PyUnicode_READ(kind, data, i));
Guido van Rossum98297ee2007-11-06 21:34:58 +00005160
5161 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005162 return v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005163#undef STORECHAR
5164}
5165
Alexander Belopolsky40018472011-02-26 01:02:56 +00005166PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005167PyUnicode_EncodeUTF32(const Py_UNICODE *s,
5168 Py_ssize_t size,
5169 const char *errors,
5170 int byteorder)
5171{
5172 PyObject *result;
5173 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5174 if (tmp == NULL)
5175 return NULL;
5176 result = _PyUnicode_EncodeUTF32(tmp, errors, byteorder);
5177 Py_DECREF(tmp);
5178 return result;
5179}
5180
5181PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005182PyUnicode_AsUTF32String(PyObject *unicode)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005183{
Victor Stinnerb960b342011-11-20 19:12:52 +01005184 return _PyUnicode_EncodeUTF32(unicode, NULL, 0);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005185}
5186
Guido van Rossumd57fd912000-03-10 22:53:23 +00005187/* --- UTF-16 Codec ------------------------------------------------------- */
5188
Tim Peters772747b2001-08-09 22:21:55 +00005189PyObject *
5190PyUnicode_DecodeUTF16(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005191 Py_ssize_t size,
5192 const char *errors,
5193 int *byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005194{
Walter Dörwald69652032004-09-07 20:24:22 +00005195 return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
5196}
5197
Antoine Pitrouab868312009-01-10 15:40:25 +00005198/* Two masks for fast checking of whether a C 'long' may contain
5199 UTF16-encoded surrogate characters. This is an efficient heuristic,
5200 assuming that non-surrogate characters with a code point >= 0x8000 are
5201 rare in most input.
5202 FAST_CHAR_MASK is used when the input is in native byte ordering,
5203 SWAPPED_FAST_CHAR_MASK when the input is in byteswapped ordering.
Benjamin Peterson29060642009-01-31 22:14:21 +00005204*/
Antoine Pitrouab868312009-01-10 15:40:25 +00005205#if (SIZEOF_LONG == 8)
5206# define FAST_CHAR_MASK 0x8000800080008000L
5207# define SWAPPED_FAST_CHAR_MASK 0x0080008000800080L
Victor Stinnerafb52052012-04-05 22:54:49 +02005208# define STRIPPED_MASK 0x00FF00FF00FF00FFL
Antoine Pitrouab868312009-01-10 15:40:25 +00005209#elif (SIZEOF_LONG == 4)
5210# define FAST_CHAR_MASK 0x80008000L
5211# define SWAPPED_FAST_CHAR_MASK 0x00800080L
Victor Stinnerafb52052012-04-05 22:54:49 +02005212# define STRIPPED_MASK 0x00FF00FFL
Antoine Pitrouab868312009-01-10 15:40:25 +00005213#else
5214# error C 'long' size should be either 4 or 8!
5215#endif
5216
Walter Dörwald69652032004-09-07 20:24:22 +00005217PyObject *
5218PyUnicode_DecodeUTF16Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005219 Py_ssize_t size,
5220 const char *errors,
5221 int *byteorder,
5222 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00005223{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005224 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005225 Py_ssize_t startinpos;
5226 Py_ssize_t endinpos;
5227 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01005228 PyObject *unicode;
Antoine Pitrouab868312009-01-10 15:40:25 +00005229 const unsigned char *q, *e, *aligned_end;
Tim Peters772747b2001-08-09 22:21:55 +00005230 int bo = 0; /* assume native ordering by default */
Antoine Pitrouab868312009-01-10 15:40:25 +00005231 int native_ordering = 0;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00005232 const char *errmsg = "";
Tim Peters772747b2001-08-09 22:21:55 +00005233 /* Offsets from q for retrieving byte pairs in the right order. */
5234#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5235 int ihi = 1, ilo = 0;
5236#else
5237 int ihi = 0, ilo = 1;
5238#endif
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005239 PyObject *errorHandler = NULL;
5240 PyObject *exc = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005241
5242 /* Note: size will always be longer than the resulting Unicode
5243 character count */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005244 unicode = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005245 if (!unicode)
5246 return NULL;
5247 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01005248 return unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005249 outpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005250
Tim Peters772747b2001-08-09 22:21:55 +00005251 q = (unsigned char *)s;
Antoine Pitrouab868312009-01-10 15:40:25 +00005252 e = q + size - 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005253
5254 if (byteorder)
Tim Peters772747b2001-08-09 22:21:55 +00005255 bo = *byteorder;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005256
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005257 /* Check for BOM marks (U+FEFF) in the input and adjust current
5258 byte order setting accordingly. In native mode, the leading BOM
5259 mark is skipped, in all other modes, it is copied to the output
5260 stream as-is (giving a ZWNBSP character). */
5261 if (bo == 0) {
Walter Dörwald69652032004-09-07 20:24:22 +00005262 if (size >= 2) {
Victor Stinner24729f32011-11-10 20:31:37 +01005263 const Py_UCS4 bom = (q[ihi] << 8) | q[ilo];
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005264#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Benjamin Peterson29060642009-01-31 22:14:21 +00005265 if (bom == 0xFEFF) {
5266 q += 2;
5267 bo = -1;
5268 }
5269 else if (bom == 0xFFFE) {
5270 q += 2;
5271 bo = 1;
5272 }
Tim Petersced69f82003-09-16 20:30:58 +00005273#else
Benjamin Peterson29060642009-01-31 22:14:21 +00005274 if (bom == 0xFEFF) {
5275 q += 2;
5276 bo = 1;
5277 }
5278 else if (bom == 0xFFFE) {
5279 q += 2;
5280 bo = -1;
5281 }
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005282#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00005283 }
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005284 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005285
Tim Peters772747b2001-08-09 22:21:55 +00005286 if (bo == -1) {
5287 /* force LE */
5288 ihi = 1;
5289 ilo = 0;
5290 }
5291 else if (bo == 1) {
5292 /* force BE */
5293 ihi = 0;
5294 ilo = 1;
5295 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005296#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5297 native_ordering = ilo < ihi;
5298#else
5299 native_ordering = ilo > ihi;
5300#endif
Tim Peters772747b2001-08-09 22:21:55 +00005301
Antoine Pitrouab868312009-01-10 15:40:25 +00005302 aligned_end = (const unsigned char *) ((size_t) e & ~LONG_PTR_MASK);
Tim Peters772747b2001-08-09 22:21:55 +00005303 while (q < e) {
Victor Stinner24729f32011-11-10 20:31:37 +01005304 Py_UCS4 ch;
Antoine Pitrouab868312009-01-10 15:40:25 +00005305 /* First check for possible aligned read of a C 'long'. Unaligned
5306 reads are more expensive, better to defer to another iteration. */
5307 if (!((size_t) q & LONG_PTR_MASK)) {
5308 /* Fast path for runs of non-surrogate chars. */
5309 register const unsigned char *_q = q;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005310 int kind = PyUnicode_KIND(unicode);
5311 void *data = PyUnicode_DATA(unicode);
5312 while (_q < aligned_end) {
Victor Stinnerafb52052012-04-05 22:54:49 +02005313 unsigned long block = * (unsigned long *) _q;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005314 Py_UCS4 maxch;
5315 if (native_ordering) {
5316 /* Can use buffer directly */
Victor Stinnerafb52052012-04-05 22:54:49 +02005317 if (block & FAST_CHAR_MASK)
Antoine Pitrouab868312009-01-10 15:40:25 +00005318 break;
Antoine Pitrouab868312009-01-10 15:40:25 +00005319 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005320 else {
5321 /* Need to byte-swap */
Victor Stinnerafb52052012-04-05 22:54:49 +02005322 if (block & SWAPPED_FAST_CHAR_MASK)
Antoine Pitrouab868312009-01-10 15:40:25 +00005323 break;
Victor Stinnerafb52052012-04-05 22:54:49 +02005324 block = ((block >> 8) & STRIPPED_MASK) |
5325 ((block & STRIPPED_MASK) << 8);
Antoine Pitrouab868312009-01-10 15:40:25 +00005326 }
Victor Stinnerafb52052012-04-05 22:54:49 +02005327 maxch = (Py_UCS2)(block & 0xFFFF);
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005328#if SIZEOF_LONG == 8
Victor Stinnerafb52052012-04-05 22:54:49 +02005329 ch = (Py_UCS2)((block >> 16) & 0xFFFF);
Victor Stinnere6abb482012-05-02 01:15:40 +02005330 maxch = MAX_MAXCHAR(maxch, ch);
Victor Stinnerafb52052012-04-05 22:54:49 +02005331 ch = (Py_UCS2)((block >> 32) & 0xFFFF);
Victor Stinnere6abb482012-05-02 01:15:40 +02005332 maxch = MAX_MAXCHAR(maxch, ch);
Victor Stinnerafb52052012-04-05 22:54:49 +02005333 ch = (Py_UCS2)(block >> 48);
Victor Stinnere6abb482012-05-02 01:15:40 +02005334 maxch = MAX_MAXCHAR(maxch, ch);
Victor Stinnerafb52052012-04-05 22:54:49 +02005335#else
5336 ch = (Py_UCS2)(block >> 16);
Victor Stinnere6abb482012-05-02 01:15:40 +02005337 maxch = MAX_MAXCHAR(maxch, ch);
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005338#endif
5339 if (maxch > PyUnicode_MAX_CHAR_VALUE(unicode)) {
Victor Stinner1b487b42012-05-03 12:29:04 +02005340 if (unicode_widen(&unicode, outpos, maxch) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005341 goto onError;
5342 kind = PyUnicode_KIND(unicode);
5343 data = PyUnicode_DATA(unicode);
5344 }
Victor Stinnerafb52052012-04-05 22:54:49 +02005345#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5346 PyUnicode_WRITE(kind, data, outpos++, (Py_UCS2)(block & 0xFFFF));
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005347#if SIZEOF_LONG == 8
Victor Stinnerafb52052012-04-05 22:54:49 +02005348 PyUnicode_WRITE(kind, data, outpos++, (Py_UCS2)((block >> 16) & 0xFFFF));
5349 PyUnicode_WRITE(kind, data, outpos++, (Py_UCS2)((block >> 32) & 0xFFFF));
5350 PyUnicode_WRITE(kind, data, outpos++, (Py_UCS2)((block >> 48)));
5351#else
5352 PyUnicode_WRITE(kind, data, outpos++, (Py_UCS2)(block >> 16));
5353#endif
5354#else
5355#if SIZEOF_LONG == 8
5356 PyUnicode_WRITE(kind, data, outpos++, (Py_UCS2)((block >> 48)));
5357 PyUnicode_WRITE(kind, data, outpos++, (Py_UCS2)((block >> 32) & 0xFFFF));
5358 PyUnicode_WRITE(kind, data, outpos++, (Py_UCS2)((block >> 16) & 0xFFFF));
5359#else
5360 PyUnicode_WRITE(kind, data, outpos++, (Py_UCS2)(block >> 16));
5361#endif
5362 PyUnicode_WRITE(kind, data, outpos++, (Py_UCS2)(block & 0xFFFF));
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005363#endif
5364 _q += SIZEOF_LONG;
Antoine Pitrouab868312009-01-10 15:40:25 +00005365 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005366 q = _q;
5367 if (q >= e)
5368 break;
5369 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005370 ch = (q[ihi] << 8) | q[ilo];
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005371
Benjamin Peterson14339b62009-01-31 16:36:08 +00005372 q += 2;
Benjamin Peterson29060642009-01-31 22:14:21 +00005373
Victor Stinner551ac952011-11-29 22:58:13 +01005374 if (!Py_UNICODE_IS_SURROGATE(ch)) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005375 if (unicode_putchar(&unicode, &outpos, ch) < 0)
5376 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005377 continue;
5378 }
5379
5380 /* UTF-16 code pair: */
5381 if (q > e) {
5382 errmsg = "unexpected end of data";
5383 startinpos = (((const char *)q) - 2) - starts;
5384 endinpos = ((const char *)e) + 1 - starts;
5385 goto utf16Error;
5386 }
Victor Stinner2e9cfad2011-11-20 18:40:27 +01005387 if (Py_UNICODE_IS_HIGH_SURROGATE(ch)) {
5388 Py_UCS4 ch2 = (q[ihi] << 8) | q[ilo];
Benjamin Peterson29060642009-01-31 22:14:21 +00005389 q += 2;
Victor Stinner2e9cfad2011-11-20 18:40:27 +01005390 if (Py_UNICODE_IS_LOW_SURROGATE(ch2)) {
Victor Stinner62aa4d02011-11-09 00:03:45 +01005391 if (unicode_putchar(&unicode, &outpos,
Victor Stinner2e9cfad2011-11-20 18:40:27 +01005392 Py_UNICODE_JOIN_SURROGATES(ch, ch2)) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005393 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005394 continue;
5395 }
5396 else {
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005397 errmsg = "illegal UTF-16 surrogate";
Benjamin Peterson29060642009-01-31 22:14:21 +00005398 startinpos = (((const char *)q)-4)-starts;
5399 endinpos = startinpos+2;
5400 goto utf16Error;
5401 }
5402
Benjamin Peterson14339b62009-01-31 16:36:08 +00005403 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005404 errmsg = "illegal encoding";
5405 startinpos = (((const char *)q)-2)-starts;
5406 endinpos = startinpos+2;
5407 /* Fall through to report the error */
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005408
Benjamin Peterson29060642009-01-31 22:14:21 +00005409 utf16Error:
Benjamin Peterson29060642009-01-31 22:14:21 +00005410 if (unicode_decode_call_errorhandler(
Antoine Pitrouab868312009-01-10 15:40:25 +00005411 errors,
5412 &errorHandler,
5413 "utf16", errmsg,
5414 &starts,
5415 (const char **)&e,
5416 &startinpos,
5417 &endinpos,
5418 &exc,
5419 (const char **)&q,
5420 &unicode,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005421 &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00005422 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005423 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005424 /* remaining byte at the end? (size should be even) */
5425 if (e == q) {
5426 if (!consumed) {
5427 errmsg = "truncated data";
5428 startinpos = ((const char *)q) - starts;
5429 endinpos = ((const char *)e) + 1 - starts;
Antoine Pitrouab868312009-01-10 15:40:25 +00005430 if (unicode_decode_call_errorhandler(
5431 errors,
5432 &errorHandler,
5433 "utf16", errmsg,
5434 &starts,
5435 (const char **)&e,
5436 &startinpos,
5437 &endinpos,
5438 &exc,
5439 (const char **)&q,
5440 &unicode,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005441 &outpos))
Antoine Pitrouab868312009-01-10 15:40:25 +00005442 goto onError;
5443 /* The remaining input chars are ignored if the callback
5444 chooses to skip the input */
5445 }
5446 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005447
5448 if (byteorder)
5449 *byteorder = bo;
5450
Walter Dörwald69652032004-09-07 20:24:22 +00005451 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005452 *consumed = (const char *)q-starts;
Walter Dörwald69652032004-09-07 20:24:22 +00005453
Guido van Rossumd57fd912000-03-10 22:53:23 +00005454 /* Adjust length */
Victor Stinner16e6a802011-12-12 13:24:15 +01005455 if (unicode_resize(&unicode, outpos) < 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005456 goto onError;
5457
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005458 Py_XDECREF(errorHandler);
5459 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01005460 return unicode_result(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005461
Benjamin Peterson29060642009-01-31 22:14:21 +00005462 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00005463 Py_DECREF(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005464 Py_XDECREF(errorHandler);
5465 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005466 return NULL;
5467}
5468
Antoine Pitrouab868312009-01-10 15:40:25 +00005469#undef FAST_CHAR_MASK
5470#undef SWAPPED_FAST_CHAR_MASK
5471
Tim Peters772747b2001-08-09 22:21:55 +00005472PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005473_PyUnicode_EncodeUTF16(PyObject *str,
5474 const char *errors,
5475 int byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005476{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005477 int kind;
5478 void *data;
5479 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005480 PyObject *v;
Tim Peters772747b2001-08-09 22:21:55 +00005481 unsigned char *p;
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005482 Py_ssize_t nsize, bytesize;
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005483 Py_ssize_t i, pairs;
Tim Peters772747b2001-08-09 22:21:55 +00005484 /* Offsets from p for storing byte pairs in the right order. */
5485#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5486 int ihi = 1, ilo = 0;
5487#else
5488 int ihi = 0, ilo = 1;
5489#endif
5490
Benjamin Peterson29060642009-01-31 22:14:21 +00005491#define STORECHAR(CH) \
5492 do { \
5493 p[ihi] = ((CH) >> 8) & 0xff; \
5494 p[ilo] = (CH) & 0xff; \
5495 p += 2; \
Tim Peters772747b2001-08-09 22:21:55 +00005496 } while(0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005497
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005498 if (!PyUnicode_Check(str)) {
5499 PyErr_BadArgument();
5500 return NULL;
5501 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005502 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005503 return NULL;
5504 kind = PyUnicode_KIND(str);
5505 data = PyUnicode_DATA(str);
5506 len = PyUnicode_GET_LENGTH(str);
Victor Stinner0e368262011-11-10 20:12:49 +01005507
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005508 pairs = 0;
5509 if (kind == PyUnicode_4BYTE_KIND)
5510 for (i = 0; i < len; i++)
5511 if (PyUnicode_READ(kind, data, i) >= 0x10000)
5512 pairs++;
5513 /* 2 * (len + pairs + (byteorder == 0)) */
5514 if (len > PY_SSIZE_T_MAX - pairs - (byteorder == 0))
Benjamin Peterson29060642009-01-31 22:14:21 +00005515 return PyErr_NoMemory();
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005516 nsize = len + pairs + (byteorder == 0);
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005517 bytesize = nsize * 2;
5518 if (bytesize / 2 != nsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005519 return PyErr_NoMemory();
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005520 v = PyBytes_FromStringAndSize(NULL, bytesize);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005521 if (v == NULL)
5522 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005523
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005524 p = (unsigned char *)PyBytes_AS_STRING(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005525 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005526 STORECHAR(0xFEFF);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005527 if (len == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005528 goto done;
Tim Peters772747b2001-08-09 22:21:55 +00005529
5530 if (byteorder == -1) {
5531 /* force LE */
5532 ihi = 1;
5533 ilo = 0;
5534 }
5535 else if (byteorder == 1) {
5536 /* force BE */
5537 ihi = 0;
5538 ilo = 1;
5539 }
5540
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005541 for (i = 0; i < len; i++) {
5542 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
5543 Py_UCS4 ch2 = 0;
Benjamin Peterson29060642009-01-31 22:14:21 +00005544 if (ch >= 0x10000) {
Victor Stinner551ac952011-11-29 22:58:13 +01005545 ch2 = Py_UNICODE_LOW_SURROGATE(ch);
5546 ch = Py_UNICODE_HIGH_SURROGATE(ch);
Benjamin Peterson29060642009-01-31 22:14:21 +00005547 }
Tim Peters772747b2001-08-09 22:21:55 +00005548 STORECHAR(ch);
5549 if (ch2)
5550 STORECHAR(ch2);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005551 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005552
5553 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005554 return v;
Tim Peters772747b2001-08-09 22:21:55 +00005555#undef STORECHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00005556}
5557
Alexander Belopolsky40018472011-02-26 01:02:56 +00005558PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005559PyUnicode_EncodeUTF16(const Py_UNICODE *s,
5560 Py_ssize_t size,
5561 const char *errors,
5562 int byteorder)
5563{
5564 PyObject *result;
5565 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5566 if (tmp == NULL)
5567 return NULL;
5568 result = _PyUnicode_EncodeUTF16(tmp, errors, byteorder);
5569 Py_DECREF(tmp);
5570 return result;
5571}
5572
5573PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005574PyUnicode_AsUTF16String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005575{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005576 return _PyUnicode_EncodeUTF16(unicode, NULL, 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005577}
5578
5579/* --- Unicode Escape Codec ----------------------------------------------- */
5580
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005581/* Helper function for PyUnicode_DecodeUnicodeEscape, determines
5582 if all the escapes in the string make it still a valid ASCII string.
5583 Returns -1 if any escapes were found which cause the string to
5584 pop out of ASCII range. Otherwise returns the length of the
5585 required buffer to hold the string.
5586 */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02005587static Py_ssize_t
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005588length_of_escaped_ascii_string(const char *s, Py_ssize_t size)
5589{
5590 const unsigned char *p = (const unsigned char *)s;
5591 const unsigned char *end = p + size;
5592 Py_ssize_t length = 0;
5593
5594 if (size < 0)
5595 return -1;
5596
5597 for (; p < end; ++p) {
5598 if (*p > 127) {
5599 /* Non-ASCII */
5600 return -1;
5601 }
5602 else if (*p != '\\') {
5603 /* Normal character */
5604 ++length;
5605 }
5606 else {
5607 /* Backslash-escape, check next char */
5608 ++p;
5609 /* Escape sequence reaches till end of string or
5610 non-ASCII follow-up. */
5611 if (p >= end || *p > 127)
5612 return -1;
5613 switch (*p) {
5614 case '\n':
5615 /* backslash + \n result in zero characters */
5616 break;
5617 case '\\': case '\'': case '\"':
5618 case 'b': case 'f': case 't':
5619 case 'n': case 'r': case 'v': case 'a':
5620 ++length;
5621 break;
5622 case '0': case '1': case '2': case '3':
5623 case '4': case '5': case '6': case '7':
5624 case 'x': case 'u': case 'U': case 'N':
5625 /* these do not guarantee ASCII characters */
5626 return -1;
5627 default:
5628 /* count the backslash + the other character */
5629 length += 2;
5630 }
5631 }
5632 }
5633 return length;
5634}
5635
Fredrik Lundh06d12682001-01-24 07:59:11 +00005636static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
Marc-André Lemburg0f774e32000-06-28 16:43:35 +00005637
Alexander Belopolsky40018472011-02-26 01:02:56 +00005638PyObject *
5639PyUnicode_DecodeUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005640 Py_ssize_t size,
Victor Stinnerc17f5402011-09-29 00:16:58 +02005641 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005642{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005643 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005644 Py_ssize_t startinpos;
5645 Py_ssize_t endinpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005646 int j;
Victor Stinner7931d9a2011-11-04 00:22:48 +01005647 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005648 const char *end;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005649 char* message;
5650 Py_UCS4 chr = 0xffffffff; /* in case 'getcode' messes up */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005651 PyObject *errorHandler = NULL;
5652 PyObject *exc = NULL;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005653 Py_ssize_t len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005654 Py_ssize_t i;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005655
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005656 len = length_of_escaped_ascii_string(s, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005657
5658 /* After length_of_escaped_ascii_string() there are two alternatives,
5659 either the string is pure ASCII with named escapes like \n, etc.
5660 and we determined it's exact size (common case)
5661 or it contains \x, \u, ... escape sequences. then we create a
5662 legacy wchar string and resize it at the end of this function. */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005663 if (len >= 0) {
5664 v = PyUnicode_New(len, 127);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005665 if (!v)
5666 goto onError;
5667 assert(PyUnicode_KIND(v) == PyUnicode_1BYTE_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005668 }
5669 else {
5670 /* Escaped strings will always be longer than the resulting
5671 Unicode string, so we start with size here and then reduce the
5672 length after conversion to the true value.
5673 (but if the error callback returns a long replacement string
5674 we'll have to allocate more space) */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005675 v = PyUnicode_New(size, 127);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005676 if (!v)
5677 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005678 len = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005679 }
5680
Guido van Rossumd57fd912000-03-10 22:53:23 +00005681 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01005682 return v;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005683 i = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005684 end = s + size;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005685
Guido van Rossumd57fd912000-03-10 22:53:23 +00005686 while (s < end) {
5687 unsigned char c;
Victor Stinner24729f32011-11-10 20:31:37 +01005688 Py_UCS4 x;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005689 int digits;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005690
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005691 /* The only case in which i == ascii_length is a backslash
5692 followed by a newline. */
5693 assert(i <= len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005694
Guido van Rossumd57fd912000-03-10 22:53:23 +00005695 /* Non-escape characters are interpreted as Unicode ordinals */
5696 if (*s != '\\') {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005697 if (unicode_putchar(&v, &i, (unsigned char) *s++) < 0)
5698 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005699 continue;
5700 }
5701
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005702 startinpos = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005703 /* \ - Escapes */
5704 s++;
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005705 c = *s++;
5706 if (s > end)
5707 c = '\0'; /* Invalid after \ */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005708
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005709 /* The only case in which i == ascii_length is a backslash
5710 followed by a newline. */
5711 assert(i < len || (i == len && c == '\n'));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005712
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005713 switch (c) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005714
Benjamin Peterson29060642009-01-31 22:14:21 +00005715 /* \x escapes */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005716#define WRITECHAR(ch) \
5717 do { \
5718 if (unicode_putchar(&v, &i, ch) < 0) \
5719 goto onError; \
5720 }while(0)
5721
Guido van Rossumd57fd912000-03-10 22:53:23 +00005722 case '\n': break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005723 case '\\': WRITECHAR('\\'); break;
5724 case '\'': WRITECHAR('\''); break;
5725 case '\"': WRITECHAR('\"'); break;
5726 case 'b': WRITECHAR('\b'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005727 /* FF */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005728 case 'f': WRITECHAR('\014'); break;
5729 case 't': WRITECHAR('\t'); break;
5730 case 'n': WRITECHAR('\n'); break;
5731 case 'r': WRITECHAR('\r'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005732 /* VT */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005733 case 'v': WRITECHAR('\013'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005734 /* BEL, not classic C */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005735 case 'a': WRITECHAR('\007'); break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005736
Benjamin Peterson29060642009-01-31 22:14:21 +00005737 /* \OOO (octal) escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005738 case '0': case '1': case '2': case '3':
5739 case '4': case '5': case '6': case '7':
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005740 x = s[-1] - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005741 if (s < end && '0' <= *s && *s <= '7') {
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005742 x = (x<<3) + *s++ - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005743 if (s < end && '0' <= *s && *s <= '7')
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005744 x = (x<<3) + *s++ - '0';
Guido van Rossumd57fd912000-03-10 22:53:23 +00005745 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005746 WRITECHAR(x);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005747 break;
5748
Benjamin Peterson29060642009-01-31 22:14:21 +00005749 /* hex escapes */
5750 /* \xXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005751 case 'x':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005752 digits = 2;
5753 message = "truncated \\xXX escape";
5754 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005755
Benjamin Peterson29060642009-01-31 22:14:21 +00005756 /* \uXXXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005757 case 'u':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005758 digits = 4;
5759 message = "truncated \\uXXXX escape";
5760 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005761
Benjamin Peterson29060642009-01-31 22:14:21 +00005762 /* \UXXXXXXXX */
Fredrik Lundhdf846752000-09-03 11:29:49 +00005763 case 'U':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005764 digits = 8;
5765 message = "truncated \\UXXXXXXXX escape";
5766 hexescape:
5767 chr = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005768 if (s+digits>end) {
5769 endinpos = size;
5770 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005771 errors, &errorHandler,
5772 "unicodeescape", "end of string in escape sequence",
5773 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005774 &v, &i))
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005775 goto onError;
5776 goto nextByte;
5777 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005778 for (j = 0; j < digits; ++j) {
5779 c = (unsigned char) s[j];
David Malcolm96960882010-11-05 17:23:41 +00005780 if (!Py_ISXDIGIT(c)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005781 endinpos = (s+j+1)-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005782 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005783 errors, &errorHandler,
5784 "unicodeescape", message,
5785 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005786 &v, &i))
Fredrik Lundhdf846752000-09-03 11:29:49 +00005787 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005788 len = PyUnicode_GET_LENGTH(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005789 goto nextByte;
Fredrik Lundhdf846752000-09-03 11:29:49 +00005790 }
5791 chr = (chr<<4) & ~0xF;
5792 if (c >= '0' && c <= '9')
5793 chr += c - '0';
5794 else if (c >= 'a' && c <= 'f')
5795 chr += 10 + c - 'a';
5796 else
5797 chr += 10 + c - 'A';
5798 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005799 s += j;
Jeremy Hylton504de6b2003-10-06 05:08:26 +00005800 if (chr == 0xffffffff && PyErr_Occurred())
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005801 /* _decoding_error will have already written into the
5802 target buffer. */
5803 break;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005804 store:
Fredrik Lundhdf846752000-09-03 11:29:49 +00005805 /* when we get here, chr is a 32-bit unicode character */
Victor Stinner8faf8212011-12-08 22:14:11 +01005806 if (chr <= MAX_UNICODE) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005807 WRITECHAR(chr);
Fredrik Lundhdf846752000-09-03 11:29:49 +00005808 } else {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005809 endinpos = s-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005810 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005811 errors, &errorHandler,
5812 "unicodeescape", "illegal Unicode character",
5813 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005814 &v, &i))
Fredrik Lundhdf846752000-09-03 11:29:49 +00005815 goto onError;
5816 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00005817 break;
5818
Benjamin Peterson29060642009-01-31 22:14:21 +00005819 /* \N{name} */
Fredrik Lundhccc74732001-02-18 22:13:49 +00005820 case 'N':
5821 message = "malformed \\N character escape";
5822 if (ucnhash_CAPI == NULL) {
5823 /* load the unicode data module */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005824 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
5825 PyUnicodeData_CAPSULE_NAME, 1);
Fredrik Lundhccc74732001-02-18 22:13:49 +00005826 if (ucnhash_CAPI == NULL)
5827 goto ucnhashError;
5828 }
5829 if (*s == '{') {
5830 const char *start = s+1;
5831 /* look for the closing brace */
5832 while (*s != '}' && s < end)
5833 s++;
5834 if (s > start && s < end && *s == '}') {
5835 /* found a name. look it up in the unicode database */
5836 message = "unknown Unicode character name";
5837 s++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005838 if (ucnhash_CAPI->getcode(NULL, start, (int)(s-start-1),
Ezio Melotti931b8aa2011-10-21 21:57:36 +03005839 &chr, 0))
Fredrik Lundhccc74732001-02-18 22:13:49 +00005840 goto store;
5841 }
5842 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005843 endinpos = s-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005844 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005845 errors, &errorHandler,
5846 "unicodeescape", message,
5847 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005848 &v, &i))
Fredrik Lundhccc74732001-02-18 22:13:49 +00005849 goto onError;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005850 break;
5851
5852 default:
Walter Dörwald8c077222002-03-25 11:16:18 +00005853 if (s > end) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005854 message = "\\ at end of string";
5855 s--;
5856 endinpos = s-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005857 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005858 errors, &errorHandler,
5859 "unicodeescape", message,
5860 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005861 &v, &i))
Walter Dörwald8c077222002-03-25 11:16:18 +00005862 goto onError;
5863 }
5864 else {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005865 WRITECHAR('\\');
5866 WRITECHAR(s[-1]);
Walter Dörwald8c077222002-03-25 11:16:18 +00005867 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00005868 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005869 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005870 nextByte:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005871 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005872 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005873#undef WRITECHAR
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005874
Victor Stinner16e6a802011-12-12 13:24:15 +01005875 if (unicode_resize(&v, i) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005876 goto onError;
Walter Dörwaldd4ade082003-08-15 15:00:26 +00005877 Py_XDECREF(errorHandler);
5878 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01005879 return unicode_result(v);
Walter Dörwald8c077222002-03-25 11:16:18 +00005880
Benjamin Peterson29060642009-01-31 22:14:21 +00005881 ucnhashError:
Fredrik Lundh06d12682001-01-24 07:59:11 +00005882 PyErr_SetString(
5883 PyExc_UnicodeError,
5884 "\\N escapes not supported (can't load unicodedata module)"
5885 );
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00005886 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005887 Py_XDECREF(errorHandler);
5888 Py_XDECREF(exc);
Fredrik Lundhf6056062001-01-20 11:15:25 +00005889 return NULL;
5890
Benjamin Peterson29060642009-01-31 22:14:21 +00005891 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00005892 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005893 Py_XDECREF(errorHandler);
5894 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005895 return NULL;
5896}
5897
5898/* Return a Unicode-Escape string version of the Unicode object.
5899
5900 If quotes is true, the string is enclosed in u"" or u'' quotes as
5901 appropriate.
5902
5903*/
5904
Alexander Belopolsky40018472011-02-26 01:02:56 +00005905PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005906PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005907{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005908 Py_ssize_t i, len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005909 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005910 char *p;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005911 int kind;
5912 void *data;
5913 Py_ssize_t expandsize = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005914
Thomas Wouters89f507f2006-12-13 04:49:30 +00005915 /* Initial allocation is based on the longest-possible unichr
5916 escape.
5917
5918 In wide (UTF-32) builds '\U00xxxxxx' is 10 chars per source
5919 unichr, so in this case it's the longest unichr escape. In
5920 narrow (UTF-16) builds this is five chars per source unichr
5921 since there are two unichrs in the surrogate pair, so in narrow
5922 (UTF-16) builds it's not the longest unichr escape.
5923
5924 In wide or narrow builds '\uxxxx' is 6 chars per source unichr,
5925 so in the narrow (UTF-16) build case it's the longest unichr
5926 escape.
5927 */
5928
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005929 if (!PyUnicode_Check(unicode)) {
5930 PyErr_BadArgument();
5931 return NULL;
5932 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005933 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005934 return NULL;
5935 len = PyUnicode_GET_LENGTH(unicode);
5936 kind = PyUnicode_KIND(unicode);
5937 data = PyUnicode_DATA(unicode);
Benjamin Petersonead6b532011-12-20 17:23:42 -06005938 switch (kind) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005939 case PyUnicode_1BYTE_KIND: expandsize = 4; break;
5940 case PyUnicode_2BYTE_KIND: expandsize = 6; break;
5941 case PyUnicode_4BYTE_KIND: expandsize = 10; break;
5942 }
5943
5944 if (len == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005945 return PyBytes_FromStringAndSize(NULL, 0);
5946
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005947 if (len > (PY_SSIZE_T_MAX - 2 - 1) / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005948 return PyErr_NoMemory();
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005949
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005950 repr = PyBytes_FromStringAndSize(NULL,
Benjamin Peterson29060642009-01-31 22:14:21 +00005951 2
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005952 + expandsize*len
Benjamin Peterson29060642009-01-31 22:14:21 +00005953 + 1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005954 if (repr == NULL)
5955 return NULL;
5956
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005957 p = PyBytes_AS_STRING(repr);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005958
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005959 for (i = 0; i < len; i++) {
Victor Stinner3326cb62011-11-10 20:15:25 +01005960 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005961
Walter Dörwald79e913e2007-05-12 11:08:06 +00005962 /* Escape backslashes */
5963 if (ch == '\\') {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005964 *p++ = '\\';
5965 *p++ = (char) ch;
Walter Dörwald79e913e2007-05-12 11:08:06 +00005966 continue;
Tim Petersced69f82003-09-16 20:30:58 +00005967 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005968
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005969 /* Map 21-bit characters to '\U00xxxxxx' */
5970 else if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01005971 assert(ch <= MAX_UNICODE);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005972 *p++ = '\\';
5973 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005974 *p++ = Py_hexdigits[(ch >> 28) & 0x0000000F];
5975 *p++ = Py_hexdigits[(ch >> 24) & 0x0000000F];
5976 *p++ = Py_hexdigits[(ch >> 20) & 0x0000000F];
5977 *p++ = Py_hexdigits[(ch >> 16) & 0x0000000F];
5978 *p++ = Py_hexdigits[(ch >> 12) & 0x0000000F];
5979 *p++ = Py_hexdigits[(ch >> 8) & 0x0000000F];
5980 *p++ = Py_hexdigits[(ch >> 4) & 0x0000000F];
5981 *p++ = Py_hexdigits[ch & 0x0000000F];
Benjamin Peterson29060642009-01-31 22:14:21 +00005982 continue;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005983 }
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005984
Guido van Rossumd57fd912000-03-10 22:53:23 +00005985 /* Map 16-bit characters to '\uxxxx' */
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005986 if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005987 *p++ = '\\';
5988 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005989 *p++ = Py_hexdigits[(ch >> 12) & 0x000F];
5990 *p++ = Py_hexdigits[(ch >> 8) & 0x000F];
5991 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
5992 *p++ = Py_hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00005993 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005994
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005995 /* Map special whitespace to '\t', \n', '\r' */
5996 else if (ch == '\t') {
5997 *p++ = '\\';
5998 *p++ = 't';
5999 }
6000 else if (ch == '\n') {
6001 *p++ = '\\';
6002 *p++ = 'n';
6003 }
6004 else if (ch == '\r') {
6005 *p++ = '\\';
6006 *p++ = 'r';
6007 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006008
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006009 /* Map non-printable US ASCII to '\xhh' */
Marc-André Lemburg11326de2001-11-28 12:56:20 +00006010 else if (ch < ' ' || ch >= 0x7F) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006011 *p++ = '\\';
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006012 *p++ = 'x';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006013 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6014 *p++ = Py_hexdigits[ch & 0x000F];
Tim Petersced69f82003-09-16 20:30:58 +00006015 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006016
Guido van Rossumd57fd912000-03-10 22:53:23 +00006017 /* Copy everything else as-is */
6018 else
6019 *p++ = (char) ch;
6020 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006021
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006022 assert(p - PyBytes_AS_STRING(repr) > 0);
6023 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0)
6024 return NULL;
6025 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006026}
6027
Alexander Belopolsky40018472011-02-26 01:02:56 +00006028PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006029PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
6030 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006031{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006032 PyObject *result;
6033 PyObject *tmp = PyUnicode_FromUnicode(s, size);
6034 if (tmp == NULL)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006035 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006036 result = PyUnicode_AsUnicodeEscapeString(tmp);
6037 Py_DECREF(tmp);
6038 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006039}
6040
6041/* --- Raw Unicode Escape Codec ------------------------------------------- */
6042
Alexander Belopolsky40018472011-02-26 01:02:56 +00006043PyObject *
6044PyUnicode_DecodeRawUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006045 Py_ssize_t size,
6046 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006047{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006048 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006049 Py_ssize_t startinpos;
6050 Py_ssize_t endinpos;
6051 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01006052 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006053 const char *end;
6054 const char *bs;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006055 PyObject *errorHandler = NULL;
6056 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006057
Guido van Rossumd57fd912000-03-10 22:53:23 +00006058 /* Escaped strings will always be longer than the resulting
6059 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006060 length after conversion to the true value. (But decoding error
6061 handler might have to resize the string) */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006062 v = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006063 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006064 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006065 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01006066 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006067 outpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006068 end = s + size;
6069 while (s < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006070 unsigned char c;
6071 Py_UCS4 x;
6072 int i;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006073 int count;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006074
Benjamin Peterson29060642009-01-31 22:14:21 +00006075 /* Non-escape characters are interpreted as Unicode ordinals */
6076 if (*s != '\\') {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006077 if (unicode_putchar(&v, &outpos, (unsigned char)*s++) < 0)
6078 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00006079 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006080 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006081 startinpos = s-starts;
6082
6083 /* \u-escapes are only interpreted iff the number of leading
6084 backslashes if odd */
6085 bs = s;
6086 for (;s < end;) {
6087 if (*s != '\\')
6088 break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006089 if (unicode_putchar(&v, &outpos, (unsigned char)*s++) < 0)
6090 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00006091 }
6092 if (((s - bs) & 1) == 0 ||
6093 s >= end ||
6094 (*s != 'u' && *s != 'U')) {
6095 continue;
6096 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006097 outpos--;
Benjamin Peterson29060642009-01-31 22:14:21 +00006098 count = *s=='u' ? 4 : 8;
6099 s++;
6100
6101 /* \uXXXX with 4 hex digits, \Uxxxxxxxx with 8 */
Benjamin Peterson29060642009-01-31 22:14:21 +00006102 for (x = 0, i = 0; i < count; ++i, ++s) {
6103 c = (unsigned char)*s;
David Malcolm96960882010-11-05 17:23:41 +00006104 if (!Py_ISXDIGIT(c)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006105 endinpos = s-starts;
6106 if (unicode_decode_call_errorhandler(
6107 errors, &errorHandler,
6108 "rawunicodeescape", "truncated \\uXXXX",
6109 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006110 &v, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00006111 goto onError;
6112 goto nextByte;
6113 }
6114 x = (x<<4) & ~0xF;
6115 if (c >= '0' && c <= '9')
6116 x += c - '0';
6117 else if (c >= 'a' && c <= 'f')
6118 x += 10 + c - 'a';
6119 else
6120 x += 10 + c - 'A';
6121 }
Victor Stinner8faf8212011-12-08 22:14:11 +01006122 if (x <= MAX_UNICODE) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006123 if (unicode_putchar(&v, &outpos, x) < 0)
6124 goto onError;
Christian Heimesfe337bf2008-03-23 21:54:12 +00006125 } else {
6126 endinpos = s-starts;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006127 if (unicode_decode_call_errorhandler(
6128 errors, &errorHandler,
6129 "rawunicodeescape", "\\Uxxxxxxxx out of range",
Benjamin Peterson29060642009-01-31 22:14:21 +00006130 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006131 &v, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00006132 goto onError;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006133 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006134 nextByte:
6135 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006136 }
Victor Stinner16e6a802011-12-12 13:24:15 +01006137 if (unicode_resize(&v, outpos) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006138 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006139 Py_XDECREF(errorHandler);
6140 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006141 return unicode_result(v);
Tim Petersced69f82003-09-16 20:30:58 +00006142
Benjamin Peterson29060642009-01-31 22:14:21 +00006143 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00006144 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006145 Py_XDECREF(errorHandler);
6146 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006147 return NULL;
6148}
6149
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006150
Alexander Belopolsky40018472011-02-26 01:02:56 +00006151PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006152PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006153{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006154 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006155 char *p;
6156 char *q;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006157 Py_ssize_t expandsize, pos;
6158 int kind;
6159 void *data;
6160 Py_ssize_t len;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006161
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006162 if (!PyUnicode_Check(unicode)) {
6163 PyErr_BadArgument();
6164 return NULL;
6165 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05006166 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006167 return NULL;
6168 kind = PyUnicode_KIND(unicode);
6169 data = PyUnicode_DATA(unicode);
6170 len = PyUnicode_GET_LENGTH(unicode);
Benjamin Peterson1518e872011-11-23 10:44:52 -06006171 /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6
6172 bytes, and 1 byte characters 4. */
6173 expandsize = kind * 2 + 2;
Victor Stinner0e368262011-11-10 20:12:49 +01006174
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006175 if (len > PY_SSIZE_T_MAX / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00006176 return PyErr_NoMemory();
Benjamin Peterson14339b62009-01-31 16:36:08 +00006177
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006178 repr = PyBytes_FromStringAndSize(NULL, expandsize * len);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006179 if (repr == NULL)
6180 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006181 if (len == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006182 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006183
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006184 p = q = PyBytes_AS_STRING(repr);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006185 for (pos = 0; pos < len; pos++) {
6186 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Benjamin Peterson29060642009-01-31 22:14:21 +00006187 /* Map 32-bit characters to '\Uxxxxxxxx' */
6188 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01006189 assert(ch <= MAX_UNICODE);
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006190 *p++ = '\\';
6191 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006192 *p++ = Py_hexdigits[(ch >> 28) & 0xf];
6193 *p++ = Py_hexdigits[(ch >> 24) & 0xf];
6194 *p++ = Py_hexdigits[(ch >> 20) & 0xf];
6195 *p++ = Py_hexdigits[(ch >> 16) & 0xf];
6196 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6197 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6198 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6199 *p++ = Py_hexdigits[ch & 15];
Tim Petersced69f82003-09-16 20:30:58 +00006200 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006201 /* Map 16-bit characters to '\uxxxx' */
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006202 else if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006203 *p++ = '\\';
6204 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006205 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6206 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6207 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6208 *p++ = Py_hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006209 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006210 /* Copy everything else as-is */
6211 else
Guido van Rossumd57fd912000-03-10 22:53:23 +00006212 *p++ = (char) ch;
6213 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00006214
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006215 assert(p > q);
6216 if (_PyBytes_Resize(&repr, p - q) < 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006217 return NULL;
6218 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006219}
6220
Alexander Belopolsky40018472011-02-26 01:02:56 +00006221PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006222PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
6223 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006224{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006225 PyObject *result;
6226 PyObject *tmp = PyUnicode_FromUnicode(s, size);
6227 if (tmp == NULL)
Walter Dörwald711005d2007-05-12 12:03:26 +00006228 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006229 result = PyUnicode_AsRawUnicodeEscapeString(tmp);
6230 Py_DECREF(tmp);
6231 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006232}
6233
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006234/* --- Unicode Internal Codec ------------------------------------------- */
6235
Alexander Belopolsky40018472011-02-26 01:02:56 +00006236PyObject *
6237_PyUnicode_DecodeUnicodeInternal(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006238 Py_ssize_t size,
6239 const char *errors)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006240{
6241 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006242 Py_ssize_t startinpos;
6243 Py_ssize_t endinpos;
6244 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01006245 PyObject *v;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006246 const char *end;
6247 const char *reason;
6248 PyObject *errorHandler = NULL;
6249 PyObject *exc = NULL;
6250
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006251 if (PyErr_WarnEx(PyExc_DeprecationWarning,
Ezio Melotti11060a42011-11-16 09:39:10 +02006252 "unicode_internal codec has been deprecated",
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006253 1))
6254 return NULL;
6255
Thomas Wouters89f507f2006-12-13 04:49:30 +00006256 /* XXX overflow detection missing */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006257 v = PyUnicode_New((size+Py_UNICODE_SIZE-1)/ Py_UNICODE_SIZE, 127);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006258 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006259 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006260 if (PyUnicode_GET_LENGTH(v) == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01006261 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006262 outpos = 0;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006263 end = s + size;
6264
6265 while (s < end) {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006266 Py_UNICODE uch;
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006267 Py_UCS4 ch;
6268 /* We copy the raw representation one byte at a time because the
6269 pointer may be unaligned (see test_codeccallbacks). */
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006270 ((char *) &uch)[0] = s[0];
6271 ((char *) &uch)[1] = s[1];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006272#ifdef Py_UNICODE_WIDE
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006273 ((char *) &uch)[2] = s[2];
6274 ((char *) &uch)[3] = s[3];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006275#endif
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006276 ch = uch;
6277
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006278 /* We have to sanity check the raw data, otherwise doom looms for
6279 some malformed UCS-4 data. */
6280 if (
Benjamin Peterson29060642009-01-31 22:14:21 +00006281#ifdef Py_UNICODE_WIDE
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006282 ch > 0x10ffff ||
Benjamin Peterson29060642009-01-31 22:14:21 +00006283#endif
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006284 end-s < Py_UNICODE_SIZE
6285 )
Benjamin Peterson29060642009-01-31 22:14:21 +00006286 {
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006287 startinpos = s - starts;
6288 if (end-s < Py_UNICODE_SIZE) {
6289 endinpos = end-starts;
6290 reason = "truncated input";
6291 }
6292 else {
6293 endinpos = s - starts + Py_UNICODE_SIZE;
6294 reason = "illegal code point (> 0x10FFFF)";
6295 }
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006296 if (unicode_decode_call_errorhandler(
6297 errors, &errorHandler,
6298 "unicode_internal", reason,
Walter Dörwalde78178e2007-07-30 13:31:40 +00006299 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006300 &v, &outpos))
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006301 goto onError;
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006302 continue;
6303 }
6304
6305 s += Py_UNICODE_SIZE;
6306#ifndef Py_UNICODE_WIDE
Victor Stinner551ac952011-11-29 22:58:13 +01006307 if (Py_UNICODE_IS_HIGH_SURROGATE(ch) && s < end)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006308 {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006309 Py_UNICODE uch2;
6310 ((char *) &uch2)[0] = s[0];
6311 ((char *) &uch2)[1] = s[1];
Victor Stinner551ac952011-11-29 22:58:13 +01006312 if (Py_UNICODE_IS_LOW_SURROGATE(uch2))
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006313 {
Victor Stinner551ac952011-11-29 22:58:13 +01006314 ch = Py_UNICODE_JOIN_SURROGATES(uch, uch2);
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006315 s += Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006316 }
6317 }
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006318#endif
6319
6320 if (unicode_putchar(&v, &outpos, ch) < 0)
6321 goto onError;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006322 }
6323
Victor Stinner16e6a802011-12-12 13:24:15 +01006324 if (unicode_resize(&v, outpos) < 0)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006325 goto onError;
6326 Py_XDECREF(errorHandler);
6327 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006328 return unicode_result(v);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006329
Benjamin Peterson29060642009-01-31 22:14:21 +00006330 onError:
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006331 Py_XDECREF(v);
6332 Py_XDECREF(errorHandler);
6333 Py_XDECREF(exc);
6334 return NULL;
6335}
6336
Guido van Rossumd57fd912000-03-10 22:53:23 +00006337/* --- Latin-1 Codec ------------------------------------------------------ */
6338
Alexander Belopolsky40018472011-02-26 01:02:56 +00006339PyObject *
6340PyUnicode_DecodeLatin1(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006341 Py_ssize_t size,
6342 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006343{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006344 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Victor Stinnere57b1c02011-09-28 22:20:48 +02006345 return _PyUnicode_FromUCS1((unsigned char*)s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006346}
6347
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006348/* create or adjust a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006349static void
6350make_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006351 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006352 PyObject *unicode,
6353 Py_ssize_t startpos, Py_ssize_t endpos,
6354 const char *reason)
6355{
6356 if (*exceptionObject == NULL) {
6357 *exceptionObject = PyObject_CallFunction(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006358 PyExc_UnicodeEncodeError, "sOnns",
Martin v. Löwis9e816682011-11-02 12:45:42 +01006359 encoding, unicode, startpos, endpos, reason);
6360 }
6361 else {
6362 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
6363 goto onError;
6364 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
6365 goto onError;
6366 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
6367 goto onError;
6368 return;
6369 onError:
6370 Py_DECREF(*exceptionObject);
6371 *exceptionObject = NULL;
6372 }
6373}
6374
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006375/* raises a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006376static void
6377raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006378 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006379 PyObject *unicode,
6380 Py_ssize_t startpos, Py_ssize_t endpos,
6381 const char *reason)
6382{
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006383 make_encode_exception(exceptionObject,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006384 encoding, unicode, startpos, endpos, reason);
6385 if (*exceptionObject != NULL)
6386 PyCodec_StrictErrors(*exceptionObject);
6387}
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006388
6389/* error handling callback helper:
6390 build arguments, call the callback and check the arguments,
6391 put the result into newpos and return the replacement string, which
6392 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006393static PyObject *
6394unicode_encode_call_errorhandler(const char *errors,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006395 PyObject **errorHandler,
6396 const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006397 PyObject *unicode, PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006398 Py_ssize_t startpos, Py_ssize_t endpos,
6399 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006400{
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006401 static char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006402 Py_ssize_t len;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006403 PyObject *restuple;
6404 PyObject *resunicode;
6405
6406 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006407 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006408 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006409 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006410 }
6411
Benjamin Petersonbac79492012-01-14 13:34:47 -05006412 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006413 return NULL;
6414 len = PyUnicode_GET_LENGTH(unicode);
6415
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006416 make_encode_exception(exceptionObject,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006417 encoding, unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006418 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006419 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006420
6421 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00006422 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006423 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006424 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006425 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006426 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00006427 Py_DECREF(restuple);
6428 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006429 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006430 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00006431 &resunicode, newpos)) {
6432 Py_DECREF(restuple);
6433 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006434 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006435 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
6436 PyErr_SetString(PyExc_TypeError, &argparse[3]);
6437 Py_DECREF(restuple);
6438 return NULL;
6439 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006440 if (*newpos<0)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006441 *newpos = len + *newpos;
6442 if (*newpos<0 || *newpos>len) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006443 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
6444 Py_DECREF(restuple);
6445 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00006446 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006447 Py_INCREF(resunicode);
6448 Py_DECREF(restuple);
6449 return resunicode;
6450}
6451
Alexander Belopolsky40018472011-02-26 01:02:56 +00006452static PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006453unicode_encode_ucs1(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006454 const char *errors,
Victor Stinnerfcd96532011-11-04 00:28:50 +01006455 unsigned int limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006456{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006457 /* input state */
6458 Py_ssize_t pos=0, size;
6459 int kind;
6460 void *data;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006461 /* output object */
6462 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006463 /* pointer into the output */
6464 char *str;
6465 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00006466 Py_ssize_t ressize;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006467 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
6468 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006469 PyObject *errorHandler = NULL;
6470 PyObject *exc = NULL;
6471 /* the following variable is used for caching string comparisons
6472 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
6473 int known_errorHandler = -1;
6474
Benjamin Petersonbac79492012-01-14 13:34:47 -05006475 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006476 return NULL;
6477 size = PyUnicode_GET_LENGTH(unicode);
6478 kind = PyUnicode_KIND(unicode);
6479 data = PyUnicode_DATA(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006480 /* allocate enough for a simple encoding without
6481 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00006482 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00006483 return PyBytes_FromStringAndSize(NULL, 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006484 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006485 if (res == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00006486 return NULL;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006487 str = PyBytes_AS_STRING(res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006488 ressize = size;
6489
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006490 while (pos < size) {
6491 Py_UCS4 c = PyUnicode_READ(kind, data, pos);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006492
Benjamin Peterson29060642009-01-31 22:14:21 +00006493 /* can we encode this? */
6494 if (c<limit) {
6495 /* no overflow check, because we know that the space is enough */
6496 *str++ = (char)c;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006497 ++pos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006498 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006499 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006500 Py_ssize_t requiredsize;
6501 PyObject *repunicode;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006502 Py_ssize_t repsize, newpos, respos, i;
Benjamin Peterson29060642009-01-31 22:14:21 +00006503 /* startpos for collecting unencodable chars */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006504 Py_ssize_t collstart = pos;
6505 Py_ssize_t collend = pos;
Benjamin Peterson29060642009-01-31 22:14:21 +00006506 /* find all unecodable characters */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006507 while ((collend < size) && (PyUnicode_READ(kind, data, collend)>=limit))
Benjamin Peterson29060642009-01-31 22:14:21 +00006508 ++collend;
6509 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
6510 if (known_errorHandler==-1) {
6511 if ((errors==NULL) || (!strcmp(errors, "strict")))
6512 known_errorHandler = 1;
6513 else if (!strcmp(errors, "replace"))
6514 known_errorHandler = 2;
6515 else if (!strcmp(errors, "ignore"))
6516 known_errorHandler = 3;
6517 else if (!strcmp(errors, "xmlcharrefreplace"))
6518 known_errorHandler = 4;
6519 else
6520 known_errorHandler = 0;
6521 }
6522 switch (known_errorHandler) {
6523 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006524 raise_encode_exception(&exc, encoding, unicode, collstart, collend, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006525 goto onError;
6526 case 2: /* replace */
6527 while (collstart++<collend)
6528 *str++ = '?'; /* fall through */
6529 case 3: /* ignore */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006530 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006531 break;
6532 case 4: /* xmlcharrefreplace */
6533 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006534 /* determine replacement size */
6535 for (i = collstart, repsize = 0; i < collend; ++i) {
6536 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
6537 if (ch < 10)
Benjamin Peterson29060642009-01-31 22:14:21 +00006538 repsize += 2+1+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006539 else if (ch < 100)
Benjamin Peterson29060642009-01-31 22:14:21 +00006540 repsize += 2+2+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006541 else if (ch < 1000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006542 repsize += 2+3+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006543 else if (ch < 10000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006544 repsize += 2+4+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006545 else if (ch < 100000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006546 repsize += 2+5+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006547 else if (ch < 1000000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006548 repsize += 2+6+1;
Victor Stinner0d3721d2011-11-22 03:27:53 +01006549 else {
Victor Stinner8faf8212011-12-08 22:14:11 +01006550 assert(ch <= MAX_UNICODE);
Benjamin Peterson29060642009-01-31 22:14:21 +00006551 repsize += 2+7+1;
Victor Stinner0d3721d2011-11-22 03:27:53 +01006552 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006553 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006554 requiredsize = respos+repsize+(size-collend);
Benjamin Peterson29060642009-01-31 22:14:21 +00006555 if (requiredsize > ressize) {
6556 if (requiredsize<2*ressize)
6557 requiredsize = 2*ressize;
6558 if (_PyBytes_Resize(&res, requiredsize))
6559 goto onError;
6560 str = PyBytes_AS_STRING(res) + respos;
6561 ressize = requiredsize;
6562 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006563 /* generate replacement */
6564 for (i = collstart; i < collend; ++i) {
6565 str += sprintf(str, "&#%d;", PyUnicode_READ(kind, data, i));
Benjamin Peterson29060642009-01-31 22:14:21 +00006566 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006567 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006568 break;
6569 default:
6570 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006571 encoding, reason, unicode, &exc,
6572 collstart, collend, &newpos);
6573 if (repunicode == NULL || (PyUnicode_Check(repunicode) &&
Benjamin Petersonbac79492012-01-14 13:34:47 -05006574 PyUnicode_READY(repunicode) == -1))
Benjamin Peterson29060642009-01-31 22:14:21 +00006575 goto onError;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006576 if (PyBytes_Check(repunicode)) {
6577 /* Directly copy bytes result to output. */
6578 repsize = PyBytes_Size(repunicode);
6579 if (repsize > 1) {
6580 /* Make room for all additional bytes. */
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006581 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006582 if (_PyBytes_Resize(&res, ressize+repsize-1)) {
6583 Py_DECREF(repunicode);
6584 goto onError;
6585 }
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006586 str = PyBytes_AS_STRING(res) + respos;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006587 ressize += repsize-1;
6588 }
6589 memcpy(str, PyBytes_AsString(repunicode), repsize);
6590 str += repsize;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006591 pos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006592 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006593 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006594 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006595 /* need more space? (at least enough for what we
6596 have+the replacement+the rest of the string, so
6597 we won't have to check space for encodable characters) */
6598 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006599 repsize = PyUnicode_GET_LENGTH(repunicode);
6600 requiredsize = respos+repsize+(size-collend);
Benjamin Peterson29060642009-01-31 22:14:21 +00006601 if (requiredsize > ressize) {
6602 if (requiredsize<2*ressize)
6603 requiredsize = 2*ressize;
6604 if (_PyBytes_Resize(&res, requiredsize)) {
6605 Py_DECREF(repunicode);
6606 goto onError;
6607 }
6608 str = PyBytes_AS_STRING(res) + respos;
6609 ressize = requiredsize;
6610 }
6611 /* check if there is anything unencodable in the replacement
6612 and copy it to the output */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006613 for (i = 0; repsize-->0; ++i, ++str) {
6614 c = PyUnicode_READ_CHAR(repunicode, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00006615 if (c >= limit) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006616 raise_encode_exception(&exc, encoding, unicode,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006617 pos, pos+1, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006618 Py_DECREF(repunicode);
6619 goto onError;
6620 }
6621 *str = (char)c;
6622 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006623 pos = newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006624 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006625 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00006626 }
6627 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006628 /* Resize if we allocated to much */
6629 size = str - PyBytes_AS_STRING(res);
6630 if (size < ressize) { /* If this falls res will be NULL */
Alexandre Vassalottibad1b922008-12-27 09:49:09 +00006631 assert(size >= 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006632 if (_PyBytes_Resize(&res, size) < 0)
6633 goto onError;
6634 }
6635
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006636 Py_XDECREF(errorHandler);
6637 Py_XDECREF(exc);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006638 return res;
6639
6640 onError:
6641 Py_XDECREF(res);
6642 Py_XDECREF(errorHandler);
6643 Py_XDECREF(exc);
6644 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006645}
6646
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006647/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006648PyObject *
6649PyUnicode_EncodeLatin1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006650 Py_ssize_t size,
6651 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006652{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006653 PyObject *result;
6654 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6655 if (unicode == NULL)
6656 return NULL;
6657 result = unicode_encode_ucs1(unicode, errors, 256);
6658 Py_DECREF(unicode);
6659 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006660}
6661
Alexander Belopolsky40018472011-02-26 01:02:56 +00006662PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006663_PyUnicode_AsLatin1String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006664{
6665 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006666 PyErr_BadArgument();
6667 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006668 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006669 if (PyUnicode_READY(unicode) == -1)
6670 return NULL;
6671 /* Fast path: if it is a one-byte string, construct
6672 bytes object directly. */
6673 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND)
6674 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6675 PyUnicode_GET_LENGTH(unicode));
6676 /* Non-Latin-1 characters present. Defer to above function to
6677 raise the exception. */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006678 return unicode_encode_ucs1(unicode, errors, 256);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006679}
6680
6681PyObject*
6682PyUnicode_AsLatin1String(PyObject *unicode)
6683{
6684 return _PyUnicode_AsLatin1String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006685}
6686
6687/* --- 7-bit ASCII Codec -------------------------------------------------- */
6688
Alexander Belopolsky40018472011-02-26 01:02:56 +00006689PyObject *
6690PyUnicode_DecodeASCII(const char *s,
6691 Py_ssize_t size,
6692 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006693{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006694 const char *starts = s;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006695 PyObject *unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006696 int kind;
6697 void *data;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006698 Py_ssize_t startinpos;
6699 Py_ssize_t endinpos;
6700 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006701 const char *e;
6702 PyObject *errorHandler = NULL;
6703 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006704
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006705 if (size == 0) {
6706 Py_INCREF(unicode_empty);
6707 return unicode_empty;
6708 }
6709
Guido van Rossumd57fd912000-03-10 22:53:23 +00006710 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Victor Stinner702c7342011-10-05 13:50:52 +02006711 if (size == 1 && (unsigned char)s[0] < 128)
6712 return get_latin1_char((unsigned char)s[0]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006713
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006714 unicode = PyUnicode_New(size, 127);
6715 if (unicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006716 goto onError;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006717
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006718 e = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006719 data = PyUnicode_1BYTE_DATA(unicode);
6720 outpos = ascii_decode(s, e, (Py_UCS1 *)data);
6721 if (outpos == size)
6722 return unicode;
6723
6724 s += outpos;
6725 kind = PyUnicode_1BYTE_KIND;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006726 while (s < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006727 register unsigned char c = (unsigned char)*s;
6728 if (c < 128) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006729 PyUnicode_WRITE(kind, data, outpos++, c);
Benjamin Peterson29060642009-01-31 22:14:21 +00006730 ++s;
6731 }
6732 else {
6733 startinpos = s-starts;
6734 endinpos = startinpos + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00006735 if (unicode_decode_call_errorhandler(
6736 errors, &errorHandler,
6737 "ascii", "ordinal not in range(128)",
6738 &starts, &e, &startinpos, &endinpos, &exc, &s,
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006739 &unicode, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00006740 goto onError;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006741 kind = PyUnicode_KIND(unicode);
6742 data = PyUnicode_DATA(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00006743 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006744 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006745 if (unicode_resize(&unicode, outpos) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006746 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006747 Py_XDECREF(errorHandler);
6748 Py_XDECREF(exc);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006749 assert(_PyUnicode_CheckConsistency(unicode, 1));
6750 return unicode;
Tim Petersced69f82003-09-16 20:30:58 +00006751
Benjamin Peterson29060642009-01-31 22:14:21 +00006752 onError:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006753 Py_XDECREF(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006754 Py_XDECREF(errorHandler);
6755 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006756 return NULL;
6757}
6758
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006759/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006760PyObject *
6761PyUnicode_EncodeASCII(const Py_UNICODE *p,
6762 Py_ssize_t size,
6763 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006764{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006765 PyObject *result;
6766 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6767 if (unicode == NULL)
6768 return NULL;
6769 result = unicode_encode_ucs1(unicode, errors, 128);
6770 Py_DECREF(unicode);
6771 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006772}
6773
Alexander Belopolsky40018472011-02-26 01:02:56 +00006774PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006775_PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006776{
6777 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006778 PyErr_BadArgument();
6779 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006780 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006781 if (PyUnicode_READY(unicode) == -1)
6782 return NULL;
6783 /* Fast path: if it is an ASCII-only string, construct bytes object
6784 directly. Else defer to above function to raise the exception. */
6785 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
6786 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6787 PyUnicode_GET_LENGTH(unicode));
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006788 return unicode_encode_ucs1(unicode, errors, 128);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006789}
6790
6791PyObject *
6792PyUnicode_AsASCIIString(PyObject *unicode)
6793{
6794 return _PyUnicode_AsASCIIString(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006795}
6796
Victor Stinner99b95382011-07-04 14:23:54 +02006797#ifdef HAVE_MBCS
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006798
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006799/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006800
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00006801#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006802#define NEED_RETRY
6803#endif
6804
Victor Stinner3a50e702011-10-18 21:21:00 +02006805#ifndef WC_ERR_INVALID_CHARS
6806# define WC_ERR_INVALID_CHARS 0x0080
6807#endif
6808
6809static char*
6810code_page_name(UINT code_page, PyObject **obj)
6811{
6812 *obj = NULL;
6813 if (code_page == CP_ACP)
6814 return "mbcs";
6815 if (code_page == CP_UTF7)
6816 return "CP_UTF7";
6817 if (code_page == CP_UTF8)
6818 return "CP_UTF8";
6819
6820 *obj = PyBytes_FromFormat("cp%u", code_page);
6821 if (*obj == NULL)
6822 return NULL;
6823 return PyBytes_AS_STRING(*obj);
6824}
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006825
Alexander Belopolsky40018472011-02-26 01:02:56 +00006826static int
Victor Stinner3a50e702011-10-18 21:21:00 +02006827is_dbcs_lead_byte(UINT code_page, const char *s, int offset)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006828{
6829 const char *curr = s + offset;
Victor Stinner3a50e702011-10-18 21:21:00 +02006830 const char *prev;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006831
Victor Stinner3a50e702011-10-18 21:21:00 +02006832 if (!IsDBCSLeadByteEx(code_page, *curr))
6833 return 0;
6834
6835 prev = CharPrevExA(code_page, s, curr, 0);
6836 if (prev == curr)
6837 return 1;
6838 /* FIXME: This code is limited to "true" double-byte encodings,
6839 as it assumes an incomplete character consists of a single
6840 byte. */
6841 if (curr - prev == 2)
6842 return 1;
6843 if (!IsDBCSLeadByteEx(code_page, *prev))
6844 return 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006845 return 0;
6846}
6847
Victor Stinner3a50e702011-10-18 21:21:00 +02006848static DWORD
6849decode_code_page_flags(UINT code_page)
6850{
6851 if (code_page == CP_UTF7) {
6852 /* The CP_UTF7 decoder only supports flags=0 */
6853 return 0;
6854 }
6855 else
6856 return MB_ERR_INVALID_CHARS;
6857}
6858
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006859/*
Victor Stinner3a50e702011-10-18 21:21:00 +02006860 * Decode a byte string from a Windows code page into unicode object in strict
6861 * mode.
6862 *
6863 * Returns consumed size if succeed, returns -2 on decode error, or raise a
6864 * WindowsError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006865 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006866static int
Victor Stinner3a50e702011-10-18 21:21:00 +02006867decode_code_page_strict(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01006868 PyObject **v,
Victor Stinner3a50e702011-10-18 21:21:00 +02006869 const char *in,
6870 int insize)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006871{
Victor Stinner3a50e702011-10-18 21:21:00 +02006872 const DWORD flags = decode_code_page_flags(code_page);
Victor Stinner24729f32011-11-10 20:31:37 +01006873 wchar_t *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02006874 DWORD outsize;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006875
6876 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02006877 assert(insize > 0);
6878 outsize = MultiByteToWideChar(code_page, flags, in, insize, NULL, 0);
6879 if (outsize <= 0)
6880 goto error;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006881
6882 if (*v == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006883 /* Create unicode object */
Victor Stinnerab595942011-12-17 04:59:06 +01006884 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01006885 *v = (PyObject*)_PyUnicode_New(outsize);
Benjamin Peterson29060642009-01-31 22:14:21 +00006886 if (*v == NULL)
6887 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02006888 out = PyUnicode_AS_UNICODE(*v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006889 }
6890 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006891 /* Extend unicode object */
Victor Stinner3a50e702011-10-18 21:21:00 +02006892 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
Victor Stinner16e6a802011-12-12 13:24:15 +01006893 if (unicode_resize(v, n + outsize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006894 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02006895 out = PyUnicode_AS_UNICODE(*v) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006896 }
6897
6898 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02006899 outsize = MultiByteToWideChar(code_page, flags, in, insize, out, outsize);
6900 if (outsize <= 0)
6901 goto error;
6902 return insize;
Victor Stinner554f3f02010-06-16 23:33:54 +00006903
Victor Stinner3a50e702011-10-18 21:21:00 +02006904error:
6905 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
6906 return -2;
6907 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00006908 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006909}
6910
Victor Stinner3a50e702011-10-18 21:21:00 +02006911/*
6912 * Decode a byte string from a code page into unicode object with an error
6913 * handler.
6914 *
6915 * Returns consumed size if succeed, or raise a WindowsError or
6916 * UnicodeDecodeError exception and returns -1 on error.
6917 */
6918static int
6919decode_code_page_errors(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01006920 PyObject **v,
6921 const char *in, const int size,
Victor Stinner3a50e702011-10-18 21:21:00 +02006922 const char *errors)
6923{
6924 const char *startin = in;
6925 const char *endin = in + size;
6926 const DWORD flags = decode_code_page_flags(code_page);
6927 /* Ideally, we should get reason from FormatMessage. This is the Windows
6928 2000 English version of the message. */
6929 const char *reason = "No mapping for the Unicode character exists "
6930 "in the target code page.";
6931 /* each step cannot decode more than 1 character, but a character can be
6932 represented as a surrogate pair */
6933 wchar_t buffer[2], *startout, *out;
6934 int insize, outsize;
6935 PyObject *errorHandler = NULL;
6936 PyObject *exc = NULL;
6937 PyObject *encoding_obj = NULL;
6938 char *encoding;
6939 DWORD err;
6940 int ret = -1;
6941
6942 assert(size > 0);
6943
6944 encoding = code_page_name(code_page, &encoding_obj);
6945 if (encoding == NULL)
6946 return -1;
6947
6948 if (errors == NULL || strcmp(errors, "strict") == 0) {
6949 /* The last error was ERROR_NO_UNICODE_TRANSLATION, then we raise a
6950 UnicodeDecodeError. */
6951 make_decode_exception(&exc, encoding, in, size, 0, 0, reason);
6952 if (exc != NULL) {
6953 PyCodec_StrictErrors(exc);
6954 Py_CLEAR(exc);
6955 }
6956 goto error;
6957 }
6958
6959 if (*v == NULL) {
6960 /* Create unicode object */
6961 if (size > PY_SSIZE_T_MAX / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
6962 PyErr_NoMemory();
6963 goto error;
6964 }
Victor Stinnerab595942011-12-17 04:59:06 +01006965 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01006966 *v = (PyObject*)_PyUnicode_New(size * Py_ARRAY_LENGTH(buffer));
Victor Stinner3a50e702011-10-18 21:21:00 +02006967 if (*v == NULL)
6968 goto error;
6969 startout = PyUnicode_AS_UNICODE(*v);
6970 }
6971 else {
6972 /* Extend unicode object */
6973 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
6974 if (size > (PY_SSIZE_T_MAX - n) / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
6975 PyErr_NoMemory();
6976 goto error;
6977 }
Victor Stinner16e6a802011-12-12 13:24:15 +01006978 if (unicode_resize(v, n + size * Py_ARRAY_LENGTH(buffer)) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02006979 goto error;
6980 startout = PyUnicode_AS_UNICODE(*v) + n;
6981 }
6982
6983 /* Decode the byte string character per character */
6984 out = startout;
6985 while (in < endin)
6986 {
6987 /* Decode a character */
6988 insize = 1;
6989 do
6990 {
6991 outsize = MultiByteToWideChar(code_page, flags,
6992 in, insize,
6993 buffer, Py_ARRAY_LENGTH(buffer));
6994 if (outsize > 0)
6995 break;
6996 err = GetLastError();
6997 if (err != ERROR_NO_UNICODE_TRANSLATION
6998 && err != ERROR_INSUFFICIENT_BUFFER)
6999 {
7000 PyErr_SetFromWindowsErr(0);
7001 goto error;
7002 }
7003 insize++;
7004 }
7005 /* 4=maximum length of a UTF-8 sequence */
7006 while (insize <= 4 && (in + insize) <= endin);
7007
7008 if (outsize <= 0) {
7009 Py_ssize_t startinpos, endinpos, outpos;
7010
7011 startinpos = in - startin;
7012 endinpos = startinpos + 1;
7013 outpos = out - PyUnicode_AS_UNICODE(*v);
7014 if (unicode_decode_call_errorhandler(
7015 errors, &errorHandler,
7016 encoding, reason,
7017 &startin, &endin, &startinpos, &endinpos, &exc, &in,
Victor Stinner596a6c42011-11-09 00:02:18 +01007018 v, &outpos))
Victor Stinner3a50e702011-10-18 21:21:00 +02007019 {
7020 goto error;
7021 }
Victor Stinner596a6c42011-11-09 00:02:18 +01007022 out = PyUnicode_AS_UNICODE(*v) + outpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007023 }
7024 else {
7025 in += insize;
7026 memcpy(out, buffer, outsize * sizeof(wchar_t));
7027 out += outsize;
7028 }
7029 }
7030
7031 /* write a NUL character at the end */
7032 *out = 0;
7033
7034 /* Extend unicode object */
7035 outsize = out - startout;
7036 assert(outsize <= PyUnicode_WSTR_LENGTH(*v));
Victor Stinner16e6a802011-12-12 13:24:15 +01007037 if (unicode_resize(v, outsize) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007038 goto error;
Victor Stinner76a31a62011-11-04 00:05:13 +01007039 ret = size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007040
7041error:
7042 Py_XDECREF(encoding_obj);
7043 Py_XDECREF(errorHandler);
7044 Py_XDECREF(exc);
7045 return ret;
7046}
7047
Victor Stinner3a50e702011-10-18 21:21:00 +02007048static PyObject *
7049decode_code_page_stateful(int code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007050 const char *s, Py_ssize_t size,
7051 const char *errors, Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007052{
Victor Stinner76a31a62011-11-04 00:05:13 +01007053 PyObject *v = NULL;
7054 int chunk_size, final, converted, done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007055
Victor Stinner3a50e702011-10-18 21:21:00 +02007056 if (code_page < 0) {
7057 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7058 return NULL;
7059 }
7060
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007061 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00007062 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007063
Victor Stinner76a31a62011-11-04 00:05:13 +01007064 do
7065 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007066#ifdef NEED_RETRY
Victor Stinner76a31a62011-11-04 00:05:13 +01007067 if (size > INT_MAX) {
7068 chunk_size = INT_MAX;
7069 final = 0;
7070 done = 0;
7071 }
7072 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007073#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007074 {
7075 chunk_size = (int)size;
7076 final = (consumed == NULL);
7077 done = 1;
7078 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007079
Victor Stinner76a31a62011-11-04 00:05:13 +01007080 /* Skip trailing lead-byte unless 'final' is set */
7081 if (!final && is_dbcs_lead_byte(code_page, s, chunk_size - 1))
7082 --chunk_size;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007083
Victor Stinner76a31a62011-11-04 00:05:13 +01007084 if (chunk_size == 0 && done) {
7085 if (v != NULL)
7086 break;
7087 Py_INCREF(unicode_empty);
7088 return unicode_empty;
7089 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007090
Victor Stinner76a31a62011-11-04 00:05:13 +01007091
7092 converted = decode_code_page_strict(code_page, &v,
7093 s, chunk_size);
7094 if (converted == -2)
7095 converted = decode_code_page_errors(code_page, &v,
7096 s, chunk_size,
7097 errors);
7098 assert(converted != 0);
7099
7100 if (converted < 0) {
7101 Py_XDECREF(v);
7102 return NULL;
7103 }
7104
7105 if (consumed)
7106 *consumed += converted;
7107
7108 s += converted;
7109 size -= converted;
7110 } while (!done);
Victor Stinner3a50e702011-10-18 21:21:00 +02007111
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01007112 return unicode_result(v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007113}
7114
Alexander Belopolsky40018472011-02-26 01:02:56 +00007115PyObject *
Victor Stinner3a50e702011-10-18 21:21:00 +02007116PyUnicode_DecodeCodePageStateful(int code_page,
7117 const char *s,
7118 Py_ssize_t size,
7119 const char *errors,
7120 Py_ssize_t *consumed)
7121{
7122 return decode_code_page_stateful(code_page, s, size, errors, consumed);
7123}
7124
7125PyObject *
7126PyUnicode_DecodeMBCSStateful(const char *s,
7127 Py_ssize_t size,
7128 const char *errors,
7129 Py_ssize_t *consumed)
7130{
7131 return decode_code_page_stateful(CP_ACP, s, size, errors, consumed);
7132}
7133
7134PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00007135PyUnicode_DecodeMBCS(const char *s,
7136 Py_ssize_t size,
7137 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007138{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007139 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
7140}
7141
Victor Stinner3a50e702011-10-18 21:21:00 +02007142static DWORD
7143encode_code_page_flags(UINT code_page, const char *errors)
7144{
7145 if (code_page == CP_UTF8) {
7146 if (winver.dwMajorVersion >= 6)
7147 /* CP_UTF8 supports WC_ERR_INVALID_CHARS on Windows Vista
7148 and later */
7149 return WC_ERR_INVALID_CHARS;
7150 else
7151 /* CP_UTF8 only supports flags=0 on Windows older than Vista */
7152 return 0;
7153 }
7154 else if (code_page == CP_UTF7) {
7155 /* CP_UTF7 only supports flags=0 */
7156 return 0;
7157 }
7158 else {
7159 if (errors != NULL && strcmp(errors, "replace") == 0)
7160 return 0;
7161 else
7162 return WC_NO_BEST_FIT_CHARS;
7163 }
7164}
7165
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007166/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007167 * Encode a Unicode string to a Windows code page into a byte string in strict
7168 * mode.
7169 *
7170 * Returns consumed characters if succeed, returns -2 on encode error, or raise
7171 * a WindowsError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007172 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007173static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007174encode_code_page_strict(UINT code_page, PyObject **outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007175 PyObject *unicode, Py_ssize_t offset, int len,
Victor Stinner3a50e702011-10-18 21:21:00 +02007176 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007177{
Victor Stinner554f3f02010-06-16 23:33:54 +00007178 BOOL usedDefaultChar = FALSE;
Victor Stinner3a50e702011-10-18 21:21:00 +02007179 BOOL *pusedDefaultChar = &usedDefaultChar;
7180 int outsize;
Victor Stinner554f3f02010-06-16 23:33:54 +00007181 PyObject *exc = NULL;
Victor Stinner24729f32011-11-10 20:31:37 +01007182 wchar_t *p;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007183 Py_ssize_t size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007184 const DWORD flags = encode_code_page_flags(code_page, NULL);
7185 char *out;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007186 /* Create a substring so that we can get the UTF-16 representation
7187 of just the slice under consideration. */
7188 PyObject *substring;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007189
Martin v. Löwis3d325192011-11-04 18:23:06 +01007190 assert(len > 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007191
Victor Stinner3a50e702011-10-18 21:21:00 +02007192 if (code_page != CP_UTF8 && code_page != CP_UTF7)
Victor Stinner554f3f02010-06-16 23:33:54 +00007193 pusedDefaultChar = &usedDefaultChar;
Victor Stinner3a50e702011-10-18 21:21:00 +02007194 else
Victor Stinner554f3f02010-06-16 23:33:54 +00007195 pusedDefaultChar = NULL;
Victor Stinner554f3f02010-06-16 23:33:54 +00007196
Victor Stinner2fc507f2011-11-04 20:06:39 +01007197 substring = PyUnicode_Substring(unicode, offset, offset+len);
7198 if (substring == NULL)
7199 return -1;
7200 p = PyUnicode_AsUnicodeAndSize(substring, &size);
7201 if (p == NULL) {
7202 Py_DECREF(substring);
7203 return -1;
7204 }
Martin v. Löwis3d325192011-11-04 18:23:06 +01007205
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007206 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007207 outsize = WideCharToMultiByte(code_page, flags,
7208 p, size,
7209 NULL, 0,
7210 NULL, pusedDefaultChar);
7211 if (outsize <= 0)
7212 goto error;
7213 /* If we used a default char, then we failed! */
Victor Stinner2fc507f2011-11-04 20:06:39 +01007214 if (pusedDefaultChar && *pusedDefaultChar) {
7215 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007216 return -2;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007217 }
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007218
Victor Stinner3a50e702011-10-18 21:21:00 +02007219 if (*outbytes == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007220 /* Create string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007221 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007222 if (*outbytes == NULL) {
7223 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007224 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007225 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007226 out = PyBytes_AS_STRING(*outbytes);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007227 }
7228 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007229 /* Extend string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007230 const Py_ssize_t n = PyBytes_Size(*outbytes);
7231 if (outsize > PY_SSIZE_T_MAX - n) {
7232 PyErr_NoMemory();
Victor Stinner2fc507f2011-11-04 20:06:39 +01007233 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007234 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007235 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007236 if (_PyBytes_Resize(outbytes, n + outsize) < 0) {
7237 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007238 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007239 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007240 out = PyBytes_AS_STRING(*outbytes) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007241 }
7242
7243 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007244 outsize = WideCharToMultiByte(code_page, flags,
7245 p, size,
7246 out, outsize,
7247 NULL, pusedDefaultChar);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007248 Py_CLEAR(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007249 if (outsize <= 0)
7250 goto error;
7251 if (pusedDefaultChar && *pusedDefaultChar)
7252 return -2;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007253 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00007254
Victor Stinner3a50e702011-10-18 21:21:00 +02007255error:
Victor Stinner2fc507f2011-11-04 20:06:39 +01007256 Py_XDECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007257 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7258 return -2;
7259 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007260 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007261}
7262
Victor Stinner3a50e702011-10-18 21:21:00 +02007263/*
7264 * Encode a Unicode string to a Windows code page into a byte string using a
7265 * error handler.
7266 *
7267 * Returns consumed characters if succeed, or raise a WindowsError and returns
7268 * -1 on other error.
7269 */
7270static int
7271encode_code_page_errors(UINT code_page, PyObject **outbytes,
Victor Stinner7581cef2011-11-03 22:32:33 +01007272 PyObject *unicode, Py_ssize_t unicode_offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007273 Py_ssize_t insize, const char* errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007274{
Victor Stinner3a50e702011-10-18 21:21:00 +02007275 const DWORD flags = encode_code_page_flags(code_page, errors);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007276 Py_ssize_t pos = unicode_offset;
7277 Py_ssize_t endin = unicode_offset + insize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007278 /* Ideally, we should get reason from FormatMessage. This is the Windows
7279 2000 English version of the message. */
7280 const char *reason = "invalid character";
7281 /* 4=maximum length of a UTF-8 sequence */
7282 char buffer[4];
7283 BOOL usedDefaultChar = FALSE, *pusedDefaultChar;
7284 Py_ssize_t outsize;
7285 char *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007286 PyObject *errorHandler = NULL;
7287 PyObject *exc = NULL;
7288 PyObject *encoding_obj = NULL;
7289 char *encoding;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007290 Py_ssize_t newpos, newoutsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007291 PyObject *rep;
7292 int ret = -1;
7293
7294 assert(insize > 0);
7295
7296 encoding = code_page_name(code_page, &encoding_obj);
7297 if (encoding == NULL)
7298 return -1;
7299
7300 if (errors == NULL || strcmp(errors, "strict") == 0) {
7301 /* The last error was ERROR_NO_UNICODE_TRANSLATION,
7302 then we raise a UnicodeEncodeError. */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007303 make_encode_exception(&exc, encoding, unicode, 0, 0, reason);
Victor Stinner3a50e702011-10-18 21:21:00 +02007304 if (exc != NULL) {
7305 PyCodec_StrictErrors(exc);
7306 Py_DECREF(exc);
7307 }
7308 Py_XDECREF(encoding_obj);
7309 return -1;
7310 }
7311
7312 if (code_page != CP_UTF8 && code_page != CP_UTF7)
7313 pusedDefaultChar = &usedDefaultChar;
7314 else
7315 pusedDefaultChar = NULL;
7316
7317 if (Py_ARRAY_LENGTH(buffer) > PY_SSIZE_T_MAX / insize) {
7318 PyErr_NoMemory();
7319 goto error;
7320 }
7321 outsize = insize * Py_ARRAY_LENGTH(buffer);
7322
7323 if (*outbytes == NULL) {
7324 /* Create string object */
7325 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
7326 if (*outbytes == NULL)
7327 goto error;
7328 out = PyBytes_AS_STRING(*outbytes);
7329 }
7330 else {
7331 /* Extend string object */
7332 Py_ssize_t n = PyBytes_Size(*outbytes);
7333 if (n > PY_SSIZE_T_MAX - outsize) {
7334 PyErr_NoMemory();
7335 goto error;
7336 }
7337 if (_PyBytes_Resize(outbytes, n + outsize) < 0)
7338 goto error;
7339 out = PyBytes_AS_STRING(*outbytes) + n;
7340 }
7341
7342 /* Encode the string character per character */
Martin v. Löwis3d325192011-11-04 18:23:06 +01007343 while (pos < endin)
Victor Stinner3a50e702011-10-18 21:21:00 +02007344 {
Victor Stinner2fc507f2011-11-04 20:06:39 +01007345 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, pos);
7346 wchar_t chars[2];
7347 int charsize;
7348 if (ch < 0x10000) {
7349 chars[0] = (wchar_t)ch;
7350 charsize = 1;
7351 }
7352 else {
7353 ch -= 0x10000;
7354 chars[0] = 0xd800 + (ch >> 10);
7355 chars[1] = 0xdc00 + (ch & 0x3ff);
7356 charsize = 2;
7357 }
7358
Victor Stinner3a50e702011-10-18 21:21:00 +02007359 outsize = WideCharToMultiByte(code_page, flags,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007360 chars, charsize,
Victor Stinner3a50e702011-10-18 21:21:00 +02007361 buffer, Py_ARRAY_LENGTH(buffer),
7362 NULL, pusedDefaultChar);
7363 if (outsize > 0) {
7364 if (pusedDefaultChar == NULL || !(*pusedDefaultChar))
7365 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007366 pos++;
Victor Stinner3a50e702011-10-18 21:21:00 +02007367 memcpy(out, buffer, outsize);
7368 out += outsize;
7369 continue;
7370 }
7371 }
7372 else if (GetLastError() != ERROR_NO_UNICODE_TRANSLATION) {
7373 PyErr_SetFromWindowsErr(0);
7374 goto error;
7375 }
7376
Victor Stinner3a50e702011-10-18 21:21:00 +02007377 rep = unicode_encode_call_errorhandler(
7378 errors, &errorHandler, encoding, reason,
Victor Stinner7581cef2011-11-03 22:32:33 +01007379 unicode, &exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007380 pos, pos + 1, &newpos);
Victor Stinner3a50e702011-10-18 21:21:00 +02007381 if (rep == NULL)
7382 goto error;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007383 pos = newpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007384
7385 if (PyBytes_Check(rep)) {
7386 outsize = PyBytes_GET_SIZE(rep);
7387 if (outsize != 1) {
7388 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7389 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7390 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7391 Py_DECREF(rep);
7392 goto error;
7393 }
7394 out = PyBytes_AS_STRING(*outbytes) + offset;
7395 }
7396 memcpy(out, PyBytes_AS_STRING(rep), outsize);
7397 out += outsize;
7398 }
7399 else {
7400 Py_ssize_t i;
7401 enum PyUnicode_Kind kind;
7402 void *data;
7403
Benjamin Petersonbac79492012-01-14 13:34:47 -05007404 if (PyUnicode_READY(rep) == -1) {
Victor Stinner3a50e702011-10-18 21:21:00 +02007405 Py_DECREF(rep);
7406 goto error;
7407 }
7408
7409 outsize = PyUnicode_GET_LENGTH(rep);
7410 if (outsize != 1) {
7411 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7412 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7413 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7414 Py_DECREF(rep);
7415 goto error;
7416 }
7417 out = PyBytes_AS_STRING(*outbytes) + offset;
7418 }
7419 kind = PyUnicode_KIND(rep);
7420 data = PyUnicode_DATA(rep);
7421 for (i=0; i < outsize; i++) {
7422 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7423 if (ch > 127) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007424 raise_encode_exception(&exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007425 encoding, unicode,
7426 pos, pos + 1,
Victor Stinner3a50e702011-10-18 21:21:00 +02007427 "unable to encode error handler result to ASCII");
7428 Py_DECREF(rep);
7429 goto error;
7430 }
7431 *out = (unsigned char)ch;
7432 out++;
7433 }
7434 }
7435 Py_DECREF(rep);
7436 }
7437 /* write a NUL byte */
7438 *out = 0;
7439 outsize = out - PyBytes_AS_STRING(*outbytes);
7440 assert(outsize <= PyBytes_GET_SIZE(*outbytes));
7441 if (_PyBytes_Resize(outbytes, outsize) < 0)
7442 goto error;
7443 ret = 0;
7444
7445error:
7446 Py_XDECREF(encoding_obj);
7447 Py_XDECREF(errorHandler);
7448 Py_XDECREF(exc);
7449 return ret;
7450}
7451
Victor Stinner3a50e702011-10-18 21:21:00 +02007452static PyObject *
7453encode_code_page(int code_page,
Victor Stinner7581cef2011-11-03 22:32:33 +01007454 PyObject *unicode,
Victor Stinner3a50e702011-10-18 21:21:00 +02007455 const char *errors)
7456{
Martin v. Löwis3d325192011-11-04 18:23:06 +01007457 Py_ssize_t len;
Victor Stinner3a50e702011-10-18 21:21:00 +02007458 PyObject *outbytes = NULL;
Victor Stinner7581cef2011-11-03 22:32:33 +01007459 Py_ssize_t offset;
Victor Stinner76a31a62011-11-04 00:05:13 +01007460 int chunk_len, ret, done;
Victor Stinner7581cef2011-11-03 22:32:33 +01007461
Benjamin Petersonbac79492012-01-14 13:34:47 -05007462 if (PyUnicode_READY(unicode) == -1)
Victor Stinner2fc507f2011-11-04 20:06:39 +01007463 return NULL;
7464 len = PyUnicode_GET_LENGTH(unicode);
Guido van Rossum03e29f12000-05-04 15:52:20 +00007465
Victor Stinner3a50e702011-10-18 21:21:00 +02007466 if (code_page < 0) {
7467 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7468 return NULL;
7469 }
7470
Martin v. Löwis3d325192011-11-04 18:23:06 +01007471 if (len == 0)
Victor Stinner76a31a62011-11-04 00:05:13 +01007472 return PyBytes_FromStringAndSize(NULL, 0);
7473
Victor Stinner7581cef2011-11-03 22:32:33 +01007474 offset = 0;
7475 do
7476 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007477#ifdef NEED_RETRY
Victor Stinner2fc507f2011-11-04 20:06:39 +01007478 /* UTF-16 encoding may double the size, so use only INT_MAX/2
Martin v. Löwis3d325192011-11-04 18:23:06 +01007479 chunks. */
7480 if (len > INT_MAX/2) {
7481 chunk_len = INT_MAX/2;
Victor Stinner76a31a62011-11-04 00:05:13 +01007482 done = 0;
7483 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007484 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007485#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007486 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007487 chunk_len = (int)len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007488 done = 1;
7489 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007490
Victor Stinner76a31a62011-11-04 00:05:13 +01007491 ret = encode_code_page_strict(code_page, &outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007492 unicode, offset, chunk_len,
Victor Stinner76a31a62011-11-04 00:05:13 +01007493 errors);
7494 if (ret == -2)
7495 ret = encode_code_page_errors(code_page, &outbytes,
7496 unicode, offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007497 chunk_len, errors);
Victor Stinner7581cef2011-11-03 22:32:33 +01007498 if (ret < 0) {
7499 Py_XDECREF(outbytes);
7500 return NULL;
7501 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007502
Victor Stinner7581cef2011-11-03 22:32:33 +01007503 offset += chunk_len;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007504 len -= chunk_len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007505 } while (!done);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007506
Victor Stinner3a50e702011-10-18 21:21:00 +02007507 return outbytes;
7508}
7509
7510PyObject *
7511PyUnicode_EncodeMBCS(const Py_UNICODE *p,
7512 Py_ssize_t size,
7513 const char *errors)
7514{
Victor Stinner7581cef2011-11-03 22:32:33 +01007515 PyObject *unicode, *res;
7516 unicode = PyUnicode_FromUnicode(p, size);
7517 if (unicode == NULL)
7518 return NULL;
7519 res = encode_code_page(CP_ACP, unicode, errors);
7520 Py_DECREF(unicode);
7521 return res;
Victor Stinner3a50e702011-10-18 21:21:00 +02007522}
7523
7524PyObject *
7525PyUnicode_EncodeCodePage(int code_page,
7526 PyObject *unicode,
7527 const char *errors)
7528{
Victor Stinner7581cef2011-11-03 22:32:33 +01007529 return encode_code_page(code_page, unicode, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007530}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007531
Alexander Belopolsky40018472011-02-26 01:02:56 +00007532PyObject *
7533PyUnicode_AsMBCSString(PyObject *unicode)
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007534{
7535 if (!PyUnicode_Check(unicode)) {
7536 PyErr_BadArgument();
7537 return NULL;
7538 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007539 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007540}
7541
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007542#undef NEED_RETRY
7543
Victor Stinner99b95382011-07-04 14:23:54 +02007544#endif /* HAVE_MBCS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007545
Guido van Rossumd57fd912000-03-10 22:53:23 +00007546/* --- Character Mapping Codec -------------------------------------------- */
7547
Alexander Belopolsky40018472011-02-26 01:02:56 +00007548PyObject *
7549PyUnicode_DecodeCharmap(const char *s,
7550 Py_ssize_t size,
7551 PyObject *mapping,
7552 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007553{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007554 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007555 Py_ssize_t startinpos;
7556 Py_ssize_t endinpos;
7557 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007558 const char *e;
Victor Stinner7931d9a2011-11-04 00:22:48 +01007559 PyObject *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007560 Py_ssize_t extrachars = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007561 PyObject *errorHandler = NULL;
7562 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00007563
Guido van Rossumd57fd912000-03-10 22:53:23 +00007564 /* Default to Latin-1 */
7565 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007566 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007567
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007568 v = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007569 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007570 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007571 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01007572 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007573 outpos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007574 e = s + size;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007575 if (PyUnicode_CheckExact(mapping)) {
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007576 Py_ssize_t maplen;
7577 enum PyUnicode_Kind kind;
7578 void *data;
7579 Py_UCS4 x;
7580
Benjamin Petersonbac79492012-01-14 13:34:47 -05007581 if (PyUnicode_READY(mapping) == -1)
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007582 return NULL;
7583
7584 maplen = PyUnicode_GET_LENGTH(mapping);
7585 data = PyUnicode_DATA(mapping);
7586 kind = PyUnicode_KIND(mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00007587 while (s < e) {
7588 unsigned char ch = *s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007589
Benjamin Peterson29060642009-01-31 22:14:21 +00007590 if (ch < maplen)
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007591 x = PyUnicode_READ(kind, data, ch);
7592 else
7593 x = 0xfffe; /* invalid value */
Guido van Rossumd57fd912000-03-10 22:53:23 +00007594
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007595 if (x == 0xfffe)
7596 {
Benjamin Peterson29060642009-01-31 22:14:21 +00007597 /* undefined mapping */
Benjamin Peterson29060642009-01-31 22:14:21 +00007598 startinpos = s-starts;
7599 endinpos = startinpos+1;
7600 if (unicode_decode_call_errorhandler(
7601 errors, &errorHandler,
7602 "charmap", "character maps to <undefined>",
7603 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007604 &v, &outpos)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007605 goto onError;
7606 }
7607 continue;
7608 }
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007609
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007610 if (unicode_putchar(&v, &outpos, x) < 0)
7611 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00007612 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007613 }
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007614 }
7615 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007616 while (s < e) {
7617 unsigned char ch = *s;
7618 PyObject *w, *x;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007619
Benjamin Peterson29060642009-01-31 22:14:21 +00007620 /* Get mapping (char ordinal -> integer, Unicode char or None) */
7621 w = PyLong_FromLong((long)ch);
7622 if (w == NULL)
7623 goto onError;
7624 x = PyObject_GetItem(mapping, w);
7625 Py_DECREF(w);
7626 if (x == NULL) {
7627 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7628 /* No mapping found means: mapping is undefined. */
7629 PyErr_Clear();
7630 x = Py_None;
7631 Py_INCREF(x);
7632 } else
7633 goto onError;
7634 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007635
Benjamin Peterson29060642009-01-31 22:14:21 +00007636 /* Apply mapping */
7637 if (PyLong_Check(x)) {
7638 long value = PyLong_AS_LONG(x);
7639 if (value < 0 || value > 65535) {
7640 PyErr_SetString(PyExc_TypeError,
7641 "character mapping must be in range(65536)");
7642 Py_DECREF(x);
7643 goto onError;
7644 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007645 if (unicode_putchar(&v, &outpos, value) < 0)
7646 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00007647 }
7648 else if (x == Py_None) {
7649 /* undefined mapping */
Benjamin Peterson29060642009-01-31 22:14:21 +00007650 startinpos = s-starts;
7651 endinpos = startinpos+1;
7652 if (unicode_decode_call_errorhandler(
7653 errors, &errorHandler,
7654 "charmap", "character maps to <undefined>",
7655 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007656 &v, &outpos)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007657 Py_DECREF(x);
7658 goto onError;
7659 }
7660 Py_DECREF(x);
7661 continue;
7662 }
7663 else if (PyUnicode_Check(x)) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007664 Py_ssize_t targetsize;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007665
Benjamin Petersonbac79492012-01-14 13:34:47 -05007666 if (PyUnicode_READY(x) == -1)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007667 goto onError;
7668 targetsize = PyUnicode_GET_LENGTH(x);
7669
7670 if (targetsize == 1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007671 /* 1-1 mapping */
Victor Stinner62aa4d02011-11-09 00:03:45 +01007672 if (unicode_putchar(&v, &outpos,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007673 PyUnicode_READ_CHAR(x, 0)) < 0)
7674 goto onError;
7675 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007676 else if (targetsize > 1) {
7677 /* 1-n mapping */
7678 if (targetsize > extrachars) {
7679 /* resize first */
Benjamin Peterson29060642009-01-31 22:14:21 +00007680 Py_ssize_t needed = (targetsize - extrachars) + \
7681 (targetsize << 2);
7682 extrachars += needed;
7683 /* XXX overflow detection missing */
Victor Stinner16e6a802011-12-12 13:24:15 +01007684 if (unicode_resize(&v,
7685 PyUnicode_GET_LENGTH(v) + needed) < 0)
7686 {
Benjamin Peterson29060642009-01-31 22:14:21 +00007687 Py_DECREF(x);
7688 goto onError;
7689 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007690 }
Victor Stinner1b487b42012-05-03 12:29:04 +02007691 if (unicode_widen(&v, outpos, PyUnicode_MAX_CHAR_VALUE(x)) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007692 goto onError;
7693 PyUnicode_CopyCharacters(v, outpos, x, 0, targetsize);
7694 outpos += targetsize;
Benjamin Peterson29060642009-01-31 22:14:21 +00007695 extrachars -= targetsize;
7696 }
7697 /* 1-0 mapping: skip the character */
7698 }
7699 else {
7700 /* wrong return value */
7701 PyErr_SetString(PyExc_TypeError,
7702 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00007703 Py_DECREF(x);
7704 goto onError;
7705 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007706 Py_DECREF(x);
7707 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007708 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00007709 }
Victor Stinner16e6a802011-12-12 13:24:15 +01007710 if (unicode_resize(&v, outpos) < 0)
Antoine Pitroua8f63c02011-11-08 18:37:16 +01007711 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007712 Py_XDECREF(errorHandler);
7713 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01007714 return unicode_result(v);
Tim Petersced69f82003-09-16 20:30:58 +00007715
Benjamin Peterson29060642009-01-31 22:14:21 +00007716 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007717 Py_XDECREF(errorHandler);
7718 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007719 Py_XDECREF(v);
7720 return NULL;
7721}
7722
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007723/* Charmap encoding: the lookup table */
7724
Alexander Belopolsky40018472011-02-26 01:02:56 +00007725struct encoding_map {
Benjamin Peterson29060642009-01-31 22:14:21 +00007726 PyObject_HEAD
7727 unsigned char level1[32];
7728 int count2, count3;
7729 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007730};
7731
7732static PyObject*
7733encoding_map_size(PyObject *obj, PyObject* args)
7734{
7735 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007736 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00007737 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007738}
7739
7740static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007741 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00007742 PyDoc_STR("Return the size (in bytes) of this object") },
7743 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007744};
7745
7746static void
7747encoding_map_dealloc(PyObject* o)
7748{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007749 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007750}
7751
7752static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007753 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007754 "EncodingMap", /*tp_name*/
7755 sizeof(struct encoding_map), /*tp_basicsize*/
7756 0, /*tp_itemsize*/
7757 /* methods */
7758 encoding_map_dealloc, /*tp_dealloc*/
7759 0, /*tp_print*/
7760 0, /*tp_getattr*/
7761 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00007762 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00007763 0, /*tp_repr*/
7764 0, /*tp_as_number*/
7765 0, /*tp_as_sequence*/
7766 0, /*tp_as_mapping*/
7767 0, /*tp_hash*/
7768 0, /*tp_call*/
7769 0, /*tp_str*/
7770 0, /*tp_getattro*/
7771 0, /*tp_setattro*/
7772 0, /*tp_as_buffer*/
7773 Py_TPFLAGS_DEFAULT, /*tp_flags*/
7774 0, /*tp_doc*/
7775 0, /*tp_traverse*/
7776 0, /*tp_clear*/
7777 0, /*tp_richcompare*/
7778 0, /*tp_weaklistoffset*/
7779 0, /*tp_iter*/
7780 0, /*tp_iternext*/
7781 encoding_map_methods, /*tp_methods*/
7782 0, /*tp_members*/
7783 0, /*tp_getset*/
7784 0, /*tp_base*/
7785 0, /*tp_dict*/
7786 0, /*tp_descr_get*/
7787 0, /*tp_descr_set*/
7788 0, /*tp_dictoffset*/
7789 0, /*tp_init*/
7790 0, /*tp_alloc*/
7791 0, /*tp_new*/
7792 0, /*tp_free*/
7793 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007794};
7795
7796PyObject*
7797PyUnicode_BuildEncodingMap(PyObject* string)
7798{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007799 PyObject *result;
7800 struct encoding_map *mresult;
7801 int i;
7802 int need_dict = 0;
7803 unsigned char level1[32];
7804 unsigned char level2[512];
7805 unsigned char *mlevel1, *mlevel2, *mlevel3;
7806 int count2 = 0, count3 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007807 int kind;
7808 void *data;
7809 Py_UCS4 ch;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007810
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007811 if (!PyUnicode_Check(string) || PyUnicode_GET_LENGTH(string) != 256) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007812 PyErr_BadArgument();
7813 return NULL;
7814 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007815 kind = PyUnicode_KIND(string);
7816 data = PyUnicode_DATA(string);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007817 memset(level1, 0xFF, sizeof level1);
7818 memset(level2, 0xFF, sizeof level2);
7819
7820 /* If there isn't a one-to-one mapping of NULL to \0,
7821 or if there are non-BMP characters, we need to use
7822 a mapping dictionary. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007823 if (PyUnicode_READ(kind, data, 0) != 0)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007824 need_dict = 1;
7825 for (i = 1; i < 256; i++) {
7826 int l1, l2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007827 ch = PyUnicode_READ(kind, data, i);
7828 if (ch == 0 || ch > 0xFFFF) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007829 need_dict = 1;
7830 break;
7831 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007832 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007833 /* unmapped character */
7834 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007835 l1 = ch >> 11;
7836 l2 = ch >> 7;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007837 if (level1[l1] == 0xFF)
7838 level1[l1] = count2++;
7839 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00007840 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007841 }
7842
7843 if (count2 >= 0xFF || count3 >= 0xFF)
7844 need_dict = 1;
7845
7846 if (need_dict) {
7847 PyObject *result = PyDict_New();
7848 PyObject *key, *value;
7849 if (!result)
7850 return NULL;
7851 for (i = 0; i < 256; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007852 key = PyLong_FromLong(PyUnicode_READ(kind, data, i));
Christian Heimes217cfd12007-12-02 14:31:20 +00007853 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007854 if (!key || !value)
7855 goto failed1;
7856 if (PyDict_SetItem(result, key, value) == -1)
7857 goto failed1;
7858 Py_DECREF(key);
7859 Py_DECREF(value);
7860 }
7861 return result;
7862 failed1:
7863 Py_XDECREF(key);
7864 Py_XDECREF(value);
7865 Py_DECREF(result);
7866 return NULL;
7867 }
7868
7869 /* Create a three-level trie */
7870 result = PyObject_MALLOC(sizeof(struct encoding_map) +
7871 16*count2 + 128*count3 - 1);
7872 if (!result)
7873 return PyErr_NoMemory();
7874 PyObject_Init(result, &EncodingMapType);
7875 mresult = (struct encoding_map*)result;
7876 mresult->count2 = count2;
7877 mresult->count3 = count3;
7878 mlevel1 = mresult->level1;
7879 mlevel2 = mresult->level23;
7880 mlevel3 = mresult->level23 + 16*count2;
7881 memcpy(mlevel1, level1, 32);
7882 memset(mlevel2, 0xFF, 16*count2);
7883 memset(mlevel3, 0, 128*count3);
7884 count3 = 0;
7885 for (i = 1; i < 256; i++) {
7886 int o1, o2, o3, i2, i3;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007887 if (PyUnicode_READ(kind, data, i) == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007888 /* unmapped character */
7889 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007890 o1 = PyUnicode_READ(kind, data, i)>>11;
7891 o2 = (PyUnicode_READ(kind, data, i)>>7) & 0xF;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007892 i2 = 16*mlevel1[o1] + o2;
7893 if (mlevel2[i2] == 0xFF)
7894 mlevel2[i2] = count3++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007895 o3 = PyUnicode_READ(kind, data, i) & 0x7F;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007896 i3 = 128*mlevel2[i2] + o3;
7897 mlevel3[i3] = i;
7898 }
7899 return result;
7900}
7901
7902static int
Victor Stinner22168992011-11-20 17:09:18 +01007903encoding_map_lookup(Py_UCS4 c, PyObject *mapping)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007904{
7905 struct encoding_map *map = (struct encoding_map*)mapping;
7906 int l1 = c>>11;
7907 int l2 = (c>>7) & 0xF;
7908 int l3 = c & 0x7F;
7909 int i;
7910
Victor Stinner22168992011-11-20 17:09:18 +01007911 if (c > 0xFFFF)
Benjamin Peterson29060642009-01-31 22:14:21 +00007912 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007913 if (c == 0)
7914 return 0;
7915 /* level 1*/
7916 i = map->level1[l1];
7917 if (i == 0xFF) {
7918 return -1;
7919 }
7920 /* level 2*/
7921 i = map->level23[16*i+l2];
7922 if (i == 0xFF) {
7923 return -1;
7924 }
7925 /* level 3 */
7926 i = map->level23[16*map->count2 + 128*i + l3];
7927 if (i == 0) {
7928 return -1;
7929 }
7930 return i;
7931}
7932
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007933/* Lookup the character ch in the mapping. If the character
7934 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00007935 error occurred). */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007936static PyObject *
Victor Stinner22168992011-11-20 17:09:18 +01007937charmapencode_lookup(Py_UCS4 c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007938{
Christian Heimes217cfd12007-12-02 14:31:20 +00007939 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007940 PyObject *x;
7941
7942 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007943 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007944 x = PyObject_GetItem(mapping, w);
7945 Py_DECREF(w);
7946 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007947 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7948 /* No mapping found means: mapping is undefined. */
7949 PyErr_Clear();
7950 x = Py_None;
7951 Py_INCREF(x);
7952 return x;
7953 } else
7954 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007955 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00007956 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00007957 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00007958 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007959 long value = PyLong_AS_LONG(x);
7960 if (value < 0 || value > 255) {
7961 PyErr_SetString(PyExc_TypeError,
7962 "character mapping must be in range(256)");
7963 Py_DECREF(x);
7964 return NULL;
7965 }
7966 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007967 }
Christian Heimes72b710a2008-05-26 13:28:38 +00007968 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00007969 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007970 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007971 /* wrong return value */
7972 PyErr_Format(PyExc_TypeError,
7973 "character mapping must return integer, bytes or None, not %.400s",
7974 x->ob_type->tp_name);
7975 Py_DECREF(x);
7976 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007977 }
7978}
7979
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007980static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00007981charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007982{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007983 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
7984 /* exponentially overallocate to minimize reallocations */
7985 if (requiredsize < 2*outsize)
7986 requiredsize = 2*outsize;
7987 if (_PyBytes_Resize(outobj, requiredsize))
7988 return -1;
7989 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007990}
7991
Benjamin Peterson14339b62009-01-31 16:36:08 +00007992typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00007993 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Alexander Belopolsky40018472011-02-26 01:02:56 +00007994} charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007995/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00007996 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007997 space is available. Return a new reference to the object that
7998 was put in the output buffer, or Py_None, if the mapping was undefined
7999 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00008000 reallocation error occurred. The caller must decref the result */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008001static charmapencode_result
Victor Stinner22168992011-11-20 17:09:18 +01008002charmapencode_output(Py_UCS4 c, PyObject *mapping,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008003 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008004{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008005 PyObject *rep;
8006 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00008007 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008008
Christian Heimes90aa7642007-12-19 02:45:37 +00008009 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008010 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008011 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008012 if (res == -1)
8013 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00008014 if (outsize<requiredsize)
8015 if (charmapencode_resize(outobj, outpos, requiredsize))
8016 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00008017 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008018 outstart[(*outpos)++] = (char)res;
8019 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008020 }
8021
8022 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008023 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008024 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008025 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008026 Py_DECREF(rep);
8027 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008028 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008029 if (PyLong_Check(rep)) {
8030 Py_ssize_t requiredsize = *outpos+1;
8031 if (outsize<requiredsize)
8032 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8033 Py_DECREF(rep);
8034 return enc_EXCEPTION;
8035 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008036 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008037 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008038 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008039 else {
8040 const char *repchars = PyBytes_AS_STRING(rep);
8041 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
8042 Py_ssize_t requiredsize = *outpos+repsize;
8043 if (outsize<requiredsize)
8044 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8045 Py_DECREF(rep);
8046 return enc_EXCEPTION;
8047 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008048 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008049 memcpy(outstart + *outpos, repchars, repsize);
8050 *outpos += repsize;
8051 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008052 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008053 Py_DECREF(rep);
8054 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008055}
8056
8057/* handle an error in PyUnicode_EncodeCharmap
8058 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008059static int
8060charmap_encoding_error(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008061 PyObject *unicode, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008062 PyObject **exceptionObject,
Walter Dörwalde5402fb2003-08-14 20:25:29 +00008063 int *known_errorHandler, PyObject **errorHandler, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00008064 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008065{
8066 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008067 Py_ssize_t size, repsize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008068 Py_ssize_t newpos;
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008069 enum PyUnicode_Kind kind;
8070 void *data;
8071 Py_ssize_t index;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008072 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008073 Py_ssize_t collstartpos = *inpos;
8074 Py_ssize_t collendpos = *inpos+1;
8075 Py_ssize_t collpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008076 char *encoding = "charmap";
8077 char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008078 charmapencode_result x;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008079 Py_UCS4 ch;
Brian Curtin2787ea42011-11-02 15:09:37 -05008080 int val;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008081
Benjamin Petersonbac79492012-01-14 13:34:47 -05008082 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008083 return -1;
8084 size = PyUnicode_GET_LENGTH(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008085 /* find all unencodable characters */
8086 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008087 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00008088 if (Py_TYPE(mapping) == &EncodingMapType) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008089 ch = PyUnicode_READ_CHAR(unicode, collendpos);
Brian Curtin2787ea42011-11-02 15:09:37 -05008090 val = encoding_map_lookup(ch, mapping);
8091 if (val != -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008092 break;
8093 ++collendpos;
8094 continue;
8095 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008096
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008097 ch = PyUnicode_READ_CHAR(unicode, collendpos);
8098 rep = charmapencode_lookup(ch, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008099 if (rep==NULL)
8100 return -1;
8101 else if (rep!=Py_None) {
8102 Py_DECREF(rep);
8103 break;
8104 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008105 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00008106 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008107 }
8108 /* cache callback name lookup
8109 * (if not done yet, i.e. it's the first error) */
8110 if (*known_errorHandler==-1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008111 if ((errors==NULL) || (!strcmp(errors, "strict")))
8112 *known_errorHandler = 1;
8113 else if (!strcmp(errors, "replace"))
8114 *known_errorHandler = 2;
8115 else if (!strcmp(errors, "ignore"))
8116 *known_errorHandler = 3;
8117 else if (!strcmp(errors, "xmlcharrefreplace"))
8118 *known_errorHandler = 4;
8119 else
8120 *known_errorHandler = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008121 }
8122 switch (*known_errorHandler) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008123 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008124 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008125 return -1;
8126 case 2: /* replace */
8127 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008128 x = charmapencode_output('?', mapping, res, respos);
8129 if (x==enc_EXCEPTION) {
8130 return -1;
8131 }
8132 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008133 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008134 return -1;
8135 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008136 }
8137 /* fall through */
8138 case 3: /* ignore */
8139 *inpos = collendpos;
8140 break;
8141 case 4: /* xmlcharrefreplace */
8142 /* generate replacement (temporarily (mis)uses p) */
8143 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008144 char buffer[2+29+1+1];
8145 char *cp;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008146 sprintf(buffer, "&#%d;", (int)PyUnicode_READ_CHAR(unicode, collpos));
Benjamin Peterson29060642009-01-31 22:14:21 +00008147 for (cp = buffer; *cp; ++cp) {
8148 x = charmapencode_output(*cp, mapping, res, respos);
8149 if (x==enc_EXCEPTION)
8150 return -1;
8151 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008152 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008153 return -1;
8154 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008155 }
8156 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008157 *inpos = collendpos;
8158 break;
8159 default:
8160 repunicode = unicode_encode_call_errorhandler(errors, errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008161 encoding, reason, unicode, exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00008162 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008163 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008164 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00008165 if (PyBytes_Check(repunicode)) {
8166 /* Directly copy bytes result to output. */
8167 Py_ssize_t outsize = PyBytes_Size(*res);
8168 Py_ssize_t requiredsize;
8169 repsize = PyBytes_Size(repunicode);
8170 requiredsize = *respos + repsize;
8171 if (requiredsize > outsize)
8172 /* Make room for all additional bytes. */
8173 if (charmapencode_resize(res, respos, requiredsize)) {
8174 Py_DECREF(repunicode);
8175 return -1;
8176 }
8177 memcpy(PyBytes_AsString(*res) + *respos,
8178 PyBytes_AsString(repunicode), repsize);
8179 *respos += repsize;
8180 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008181 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00008182 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008183 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008184 /* generate replacement */
Benjamin Petersonbac79492012-01-14 13:34:47 -05008185 if (PyUnicode_READY(repunicode) == -1) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008186 Py_DECREF(repunicode);
8187 return -1;
8188 }
Victor Stinner9e30aa52011-11-21 02:49:52 +01008189 repsize = PyUnicode_GET_LENGTH(repunicode);
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008190 data = PyUnicode_DATA(repunicode);
8191 kind = PyUnicode_KIND(repunicode);
8192 for (index = 0; index < repsize; index++) {
8193 Py_UCS4 repch = PyUnicode_READ(kind, data, index);
8194 x = charmapencode_output(repch, mapping, res, respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008195 if (x==enc_EXCEPTION) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008196 Py_DECREF(repunicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00008197 return -1;
8198 }
8199 else if (x==enc_FAILED) {
8200 Py_DECREF(repunicode);
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008201 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008202 return -1;
8203 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008204 }
8205 *inpos = newpos;
8206 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008207 }
8208 return 0;
8209}
8210
Alexander Belopolsky40018472011-02-26 01:02:56 +00008211PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008212_PyUnicode_EncodeCharmap(PyObject *unicode,
8213 PyObject *mapping,
8214 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008215{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008216 /* output object */
8217 PyObject *res = NULL;
8218 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008219 Py_ssize_t inpos = 0;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008220 Py_ssize_t size;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008221 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008222 Py_ssize_t respos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008223 PyObject *errorHandler = NULL;
8224 PyObject *exc = NULL;
8225 /* the following variable is used for caching string comparisons
8226 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8227 * 3=ignore, 4=xmlcharrefreplace */
8228 int known_errorHandler = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008229
Benjamin Petersonbac79492012-01-14 13:34:47 -05008230 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008231 return NULL;
8232 size = PyUnicode_GET_LENGTH(unicode);
8233
Guido van Rossumd57fd912000-03-10 22:53:23 +00008234 /* Default to Latin-1 */
8235 if (mapping == NULL)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008236 return unicode_encode_ucs1(unicode, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008237
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008238 /* allocate enough for a simple encoding without
8239 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00008240 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008241 if (res == NULL)
8242 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00008243 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008244 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008245
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008246 while (inpos<size) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008247 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, inpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008248 /* try to encode it */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008249 charmapencode_result x = charmapencode_output(ch, mapping, &res, &respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008250 if (x==enc_EXCEPTION) /* error */
8251 goto onError;
8252 if (x==enc_FAILED) { /* unencodable character */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008253 if (charmap_encoding_error(unicode, &inpos, mapping,
Benjamin Peterson29060642009-01-31 22:14:21 +00008254 &exc,
8255 &known_errorHandler, &errorHandler, errors,
8256 &res, &respos)) {
8257 goto onError;
8258 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008259 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008260 else
8261 /* done with this character => adjust input position */
8262 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008263 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008264
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008265 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00008266 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00008267 if (_PyBytes_Resize(&res, respos) < 0)
8268 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00008269
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008270 Py_XDECREF(exc);
8271 Py_XDECREF(errorHandler);
8272 return res;
8273
Benjamin Peterson29060642009-01-31 22:14:21 +00008274 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008275 Py_XDECREF(res);
8276 Py_XDECREF(exc);
8277 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008278 return NULL;
8279}
8280
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008281/* Deprecated */
8282PyObject *
8283PyUnicode_EncodeCharmap(const Py_UNICODE *p,
8284 Py_ssize_t size,
8285 PyObject *mapping,
8286 const char *errors)
8287{
8288 PyObject *result;
8289 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8290 if (unicode == NULL)
8291 return NULL;
8292 result = _PyUnicode_EncodeCharmap(unicode, mapping, errors);
8293 Py_DECREF(unicode);
Victor Stinnerfc026c92011-11-04 00:24:51 +01008294 return result;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008295}
8296
Alexander Belopolsky40018472011-02-26 01:02:56 +00008297PyObject *
8298PyUnicode_AsCharmapString(PyObject *unicode,
8299 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008300{
8301 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008302 PyErr_BadArgument();
8303 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008304 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008305 return _PyUnicode_EncodeCharmap(unicode, mapping, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008306}
8307
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008308/* create or adjust a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008309static void
8310make_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008311 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008312 Py_ssize_t startpos, Py_ssize_t endpos,
8313 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008314{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008315 if (*exceptionObject == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008316 *exceptionObject = _PyUnicodeTranslateError_Create(
8317 unicode, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008318 }
8319 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008320 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
8321 goto onError;
8322 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
8323 goto onError;
8324 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
8325 goto onError;
8326 return;
8327 onError:
8328 Py_DECREF(*exceptionObject);
8329 *exceptionObject = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008330 }
8331}
8332
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008333/* raises a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008334static void
8335raise_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008336 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008337 Py_ssize_t startpos, Py_ssize_t endpos,
8338 const char *reason)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008339{
8340 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008341 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008342 if (*exceptionObject != NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008343 PyCodec_StrictErrors(*exceptionObject);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008344}
8345
8346/* error handling callback helper:
8347 build arguments, call the callback and check the arguments,
8348 put the result into newpos and return the replacement string, which
8349 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008350static PyObject *
8351unicode_translate_call_errorhandler(const char *errors,
8352 PyObject **errorHandler,
8353 const char *reason,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008354 PyObject *unicode, PyObject **exceptionObject,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008355 Py_ssize_t startpos, Py_ssize_t endpos,
8356 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008357{
Benjamin Peterson142957c2008-07-04 19:55:29 +00008358 static char *argparse = "O!n;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008359
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008360 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008361 PyObject *restuple;
8362 PyObject *resunicode;
8363
8364 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008365 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008366 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008367 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008368 }
8369
8370 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008371 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008372 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008373 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008374
8375 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00008376 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008377 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008378 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008379 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00008380 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00008381 Py_DECREF(restuple);
8382 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008383 }
8384 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type,
Benjamin Peterson29060642009-01-31 22:14:21 +00008385 &resunicode, &i_newpos)) {
8386 Py_DECREF(restuple);
8387 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008388 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00008389 if (i_newpos<0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008390 *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008391 else
8392 *newpos = i_newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008393 if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008394 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
8395 Py_DECREF(restuple);
8396 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00008397 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008398 Py_INCREF(resunicode);
8399 Py_DECREF(restuple);
8400 return resunicode;
8401}
8402
8403/* Lookup the character ch in the mapping and put the result in result,
8404 which must be decrefed by the caller.
8405 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008406static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008407charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008408{
Christian Heimes217cfd12007-12-02 14:31:20 +00008409 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008410 PyObject *x;
8411
8412 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008413 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008414 x = PyObject_GetItem(mapping, w);
8415 Py_DECREF(w);
8416 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008417 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8418 /* No mapping found means: use 1:1 mapping. */
8419 PyErr_Clear();
8420 *result = NULL;
8421 return 0;
8422 } else
8423 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008424 }
8425 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008426 *result = x;
8427 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008428 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008429 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008430 long value = PyLong_AS_LONG(x);
8431 long max = PyUnicode_GetMax();
8432 if (value < 0 || value > max) {
8433 PyErr_Format(PyExc_TypeError,
Guido van Rossum5a2f7e602007-10-24 21:13:09 +00008434 "character mapping must be in range(0x%x)", max+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00008435 Py_DECREF(x);
8436 return -1;
8437 }
8438 *result = x;
8439 return 0;
8440 }
8441 else if (PyUnicode_Check(x)) {
8442 *result = x;
8443 return 0;
8444 }
8445 else {
8446 /* wrong return value */
8447 PyErr_SetString(PyExc_TypeError,
8448 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00008449 Py_DECREF(x);
8450 return -1;
8451 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008452}
8453/* ensure that *outobj is at least requiredsize characters long,
Benjamin Peterson29060642009-01-31 22:14:21 +00008454 if not reallocate and adjust various state variables.
8455 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008456static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008457charmaptranslate_makespace(Py_UCS4 **outobj, Py_ssize_t *psize,
Benjamin Peterson29060642009-01-31 22:14:21 +00008458 Py_ssize_t requiredsize)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008459{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008460 Py_ssize_t oldsize = *psize;
Walter Dörwald4894c302003-10-24 14:25:28 +00008461 if (requiredsize > oldsize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008462 /* exponentially overallocate to minimize reallocations */
8463 if (requiredsize < 2 * oldsize)
8464 requiredsize = 2 * oldsize;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008465 *outobj = PyMem_Realloc(*outobj, requiredsize * sizeof(Py_UCS4));
8466 if (*outobj == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008467 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008468 *psize = requiredsize;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008469 }
8470 return 0;
8471}
8472/* lookup the character, put the result in the output string and adjust
8473 various state variables. Return a new reference to the object that
8474 was put in the output buffer in *result, or Py_None, if the mapping was
8475 undefined (in which case no character was written).
8476 The called must decref result.
8477 Return 0 on success, -1 on error. */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008478static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008479charmaptranslate_output(PyObject *input, Py_ssize_t ipos,
8480 PyObject *mapping, Py_UCS4 **output,
8481 Py_ssize_t *osize, Py_ssize_t *opos,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008482 PyObject **res)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008483{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008484 Py_UCS4 curinp = PyUnicode_READ_CHAR(input, ipos);
8485 if (charmaptranslate_lookup(curinp, mapping, res))
Benjamin Peterson29060642009-01-31 22:14:21 +00008486 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008487 if (*res==NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008488 /* not found => default to 1:1 mapping */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008489 (*output)[(*opos)++] = curinp;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008490 }
8491 else if (*res==Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008492 ;
Christian Heimes217cfd12007-12-02 14:31:20 +00008493 else if (PyLong_Check(*res)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008494 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008495 (*output)[(*opos)++] = (Py_UCS4)PyLong_AS_LONG(*res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008496 }
8497 else if (PyUnicode_Check(*res)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008498 Py_ssize_t repsize;
8499 if (PyUnicode_READY(*res) == -1)
8500 return -1;
8501 repsize = PyUnicode_GET_LENGTH(*res);
Benjamin Peterson29060642009-01-31 22:14:21 +00008502 if (repsize==1) {
8503 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008504 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +00008505 }
8506 else if (repsize!=0) {
8507 /* more than one character */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008508 Py_ssize_t requiredsize = *opos +
8509 (PyUnicode_GET_LENGTH(input) - ipos) +
Benjamin Peterson29060642009-01-31 22:14:21 +00008510 repsize - 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008511 Py_ssize_t i;
8512 if (charmaptranslate_makespace(output, osize, requiredsize))
Benjamin Peterson29060642009-01-31 22:14:21 +00008513 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008514 for(i = 0; i < repsize; i++)
8515 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00008516 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008517 }
8518 else
Benjamin Peterson29060642009-01-31 22:14:21 +00008519 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008520 return 0;
8521}
8522
Alexander Belopolsky40018472011-02-26 01:02:56 +00008523PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008524_PyUnicode_TranslateCharmap(PyObject *input,
8525 PyObject *mapping,
8526 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008527{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008528 /* input object */
8529 char *idata;
8530 Py_ssize_t size, i;
8531 int kind;
8532 /* output buffer */
8533 Py_UCS4 *output = NULL;
8534 Py_ssize_t osize;
8535 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008536 /* current output position */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008537 Py_ssize_t opos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008538 char *reason = "character maps to <undefined>";
8539 PyObject *errorHandler = NULL;
8540 PyObject *exc = NULL;
8541 /* the following variable is used for caching string comparisons
8542 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8543 * 3=ignore, 4=xmlcharrefreplace */
8544 int known_errorHandler = -1;
8545
Guido van Rossumd57fd912000-03-10 22:53:23 +00008546 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008547 PyErr_BadArgument();
8548 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008549 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008550
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008551 if (PyUnicode_READY(input) == -1)
8552 return NULL;
8553 idata = (char*)PyUnicode_DATA(input);
8554 kind = PyUnicode_KIND(input);
8555 size = PyUnicode_GET_LENGTH(input);
8556 i = 0;
8557
8558 if (size == 0) {
8559 Py_INCREF(input);
8560 return input;
8561 }
8562
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008563 /* allocate enough for a simple 1:1 translation without
8564 replacements, if we need more, we'll resize */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008565 osize = size;
8566 output = PyMem_Malloc(osize * sizeof(Py_UCS4));
8567 opos = 0;
8568 if (output == NULL) {
8569 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00008570 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008571 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008572
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008573 while (i<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008574 /* try to encode it */
8575 PyObject *x = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008576 if (charmaptranslate_output(input, i, mapping,
8577 &output, &osize, &opos, &x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008578 Py_XDECREF(x);
8579 goto onError;
8580 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008581 Py_XDECREF(x);
Benjamin Peterson29060642009-01-31 22:14:21 +00008582 if (x!=Py_None) /* it worked => adjust input pointer */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008583 ++i;
Benjamin Peterson29060642009-01-31 22:14:21 +00008584 else { /* untranslatable character */
8585 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
8586 Py_ssize_t repsize;
8587 Py_ssize_t newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008588 Py_ssize_t uni2;
Benjamin Peterson29060642009-01-31 22:14:21 +00008589 /* startpos for collecting untranslatable chars */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008590 Py_ssize_t collstart = i;
8591 Py_ssize_t collend = i+1;
8592 Py_ssize_t coll;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008593
Benjamin Peterson29060642009-01-31 22:14:21 +00008594 /* find all untranslatable characters */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008595 while (collend < size) {
8596 if (charmaptranslate_lookup(PyUnicode_READ(kind,idata, collend), mapping, &x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008597 goto onError;
8598 Py_XDECREF(x);
8599 if (x!=Py_None)
8600 break;
8601 ++collend;
8602 }
8603 /* cache callback name lookup
8604 * (if not done yet, i.e. it's the first error) */
8605 if (known_errorHandler==-1) {
8606 if ((errors==NULL) || (!strcmp(errors, "strict")))
8607 known_errorHandler = 1;
8608 else if (!strcmp(errors, "replace"))
8609 known_errorHandler = 2;
8610 else if (!strcmp(errors, "ignore"))
8611 known_errorHandler = 3;
8612 else if (!strcmp(errors, "xmlcharrefreplace"))
8613 known_errorHandler = 4;
8614 else
8615 known_errorHandler = 0;
8616 }
8617 switch (known_errorHandler) {
8618 case 1: /* strict */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008619 raise_translate_exception(&exc, input, collstart,
8620 collend, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008621 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00008622 case 2: /* replace */
8623 /* No need to check for space, this is a 1:1 replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008624 for (coll = collstart; coll<collend; coll++)
8625 output[opos++] = '?';
Benjamin Peterson29060642009-01-31 22:14:21 +00008626 /* fall through */
8627 case 3: /* ignore */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008628 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008629 break;
8630 case 4: /* xmlcharrefreplace */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008631 /* generate replacement (temporarily (mis)uses i) */
8632 for (i = collstart; i < collend; ++i) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008633 char buffer[2+29+1+1];
8634 char *cp;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008635 sprintf(buffer, "&#%d;", PyUnicode_READ(kind, idata, i));
8636 if (charmaptranslate_makespace(&output, &osize,
8637 opos+strlen(buffer)+(size-collend)))
Benjamin Peterson29060642009-01-31 22:14:21 +00008638 goto onError;
8639 for (cp = buffer; *cp; ++cp)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008640 output[opos++] = *cp;
Benjamin Peterson29060642009-01-31 22:14:21 +00008641 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008642 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008643 break;
8644 default:
8645 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008646 reason, input, &exc,
8647 collstart, collend, &newpos);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008648 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008649 goto onError;
Benjamin Peterson9ca3ffa2012-01-01 16:04:29 -06008650 if (PyUnicode_READY(repunicode) == -1) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008651 Py_DECREF(repunicode);
8652 goto onError;
8653 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008654 /* generate replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008655 repsize = PyUnicode_GET_LENGTH(repunicode);
8656 if (charmaptranslate_makespace(&output, &osize,
8657 opos+repsize+(size-collend))) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008658 Py_DECREF(repunicode);
8659 goto onError;
8660 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008661 for (uni2 = 0; repsize-->0; ++uni2)
8662 output[opos++] = PyUnicode_READ_CHAR(repunicode, uni2);
8663 i = newpos;
Benjamin Peterson29060642009-01-31 22:14:21 +00008664 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008665 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008666 }
8667 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008668 res = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND, output, opos);
8669 if (!res)
8670 goto onError;
8671 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008672 Py_XDECREF(exc);
8673 Py_XDECREF(errorHandler);
8674 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008675
Benjamin Peterson29060642009-01-31 22:14:21 +00008676 onError:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008677 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008678 Py_XDECREF(exc);
8679 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008680 return NULL;
8681}
8682
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008683/* Deprecated. Use PyUnicode_Translate instead. */
8684PyObject *
8685PyUnicode_TranslateCharmap(const Py_UNICODE *p,
8686 Py_ssize_t size,
8687 PyObject *mapping,
8688 const char *errors)
8689{
8690 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8691 if (!unicode)
8692 return NULL;
8693 return _PyUnicode_TranslateCharmap(unicode, mapping, errors);
8694}
8695
Alexander Belopolsky40018472011-02-26 01:02:56 +00008696PyObject *
8697PyUnicode_Translate(PyObject *str,
8698 PyObject *mapping,
8699 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008700{
8701 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +00008702
Guido van Rossumd57fd912000-03-10 22:53:23 +00008703 str = PyUnicode_FromObject(str);
8704 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008705 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008706 result = _PyUnicode_TranslateCharmap(str, mapping, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008707 Py_DECREF(str);
8708 return result;
Tim Petersced69f82003-09-16 20:30:58 +00008709
Benjamin Peterson29060642009-01-31 22:14:21 +00008710 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00008711 Py_XDECREF(str);
8712 return NULL;
8713}
Tim Petersced69f82003-09-16 20:30:58 +00008714
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008715static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02008716fix_decimal_and_space_to_ascii(PyObject *self)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008717{
8718 /* No need to call PyUnicode_READY(self) because this function is only
8719 called as a callback from fixup() which does it already. */
8720 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
8721 const int kind = PyUnicode_KIND(self);
8722 void *data = PyUnicode_DATA(self);
Victor Stinnere6abb482012-05-02 01:15:40 +02008723 Py_UCS4 maxchar = 127, ch, fixed;
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008724 int modified = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008725 Py_ssize_t i;
8726
8727 for (i = 0; i < len; ++i) {
8728 ch = PyUnicode_READ(kind, data, i);
8729 fixed = 0;
8730 if (ch > 127) {
8731 if (Py_UNICODE_ISSPACE(ch))
8732 fixed = ' ';
8733 else {
8734 const int decimal = Py_UNICODE_TODECIMAL(ch);
8735 if (decimal >= 0)
8736 fixed = '0' + decimal;
8737 }
8738 if (fixed != 0) {
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008739 modified = 1;
Victor Stinnere6abb482012-05-02 01:15:40 +02008740 maxchar = MAX_MAXCHAR(maxchar, fixed);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008741 PyUnicode_WRITE(kind, data, i, fixed);
8742 }
Victor Stinnere6abb482012-05-02 01:15:40 +02008743 else
8744 maxchar = MAX_MAXCHAR(maxchar, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008745 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008746 }
8747
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008748 return (modified) ? maxchar : 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008749}
8750
8751PyObject *
8752_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
8753{
8754 if (!PyUnicode_Check(unicode)) {
8755 PyErr_BadInternalCall();
8756 return NULL;
8757 }
8758 if (PyUnicode_READY(unicode) == -1)
8759 return NULL;
8760 if (PyUnicode_MAX_CHAR_VALUE(unicode) <= 127) {
8761 /* If the string is already ASCII, just return the same string */
8762 Py_INCREF(unicode);
8763 return unicode;
8764 }
Victor Stinner9310abb2011-10-05 00:59:23 +02008765 return fixup(unicode, fix_decimal_and_space_to_ascii);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008766}
8767
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008768PyObject *
8769PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
8770 Py_ssize_t length)
8771{
Victor Stinnerf0124502011-11-21 23:12:56 +01008772 PyObject *decimal;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008773 Py_ssize_t i;
Victor Stinnerf0124502011-11-21 23:12:56 +01008774 Py_UCS4 maxchar;
8775 enum PyUnicode_Kind kind;
8776 void *data;
8777
Victor Stinner99d7ad02012-02-22 13:37:39 +01008778 maxchar = 127;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008779 for (i = 0; i < length; i++) {
Victor Stinnerf0124502011-11-21 23:12:56 +01008780 Py_UNICODE ch = s[i];
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008781 if (ch > 127) {
8782 int decimal = Py_UNICODE_TODECIMAL(ch);
8783 if (decimal >= 0)
Victor Stinnerf0124502011-11-21 23:12:56 +01008784 ch = '0' + decimal;
Victor Stinnere6abb482012-05-02 01:15:40 +02008785 maxchar = MAX_MAXCHAR(maxchar, ch);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008786 }
8787 }
Victor Stinnerf0124502011-11-21 23:12:56 +01008788
8789 /* Copy to a new string */
8790 decimal = PyUnicode_New(length, maxchar);
8791 if (decimal == NULL)
8792 return decimal;
8793 kind = PyUnicode_KIND(decimal);
8794 data = PyUnicode_DATA(decimal);
8795 /* Iterate over code points */
8796 for (i = 0; i < length; i++) {
8797 Py_UNICODE ch = s[i];
8798 if (ch > 127) {
8799 int decimal = Py_UNICODE_TODECIMAL(ch);
8800 if (decimal >= 0)
8801 ch = '0' + decimal;
8802 }
8803 PyUnicode_WRITE(kind, data, i, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008804 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008805 return unicode_result(decimal);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008806}
Guido van Rossum9e896b32000-04-05 20:11:21 +00008807/* --- Decimal Encoder ---------------------------------------------------- */
8808
Alexander Belopolsky40018472011-02-26 01:02:56 +00008809int
8810PyUnicode_EncodeDecimal(Py_UNICODE *s,
8811 Py_ssize_t length,
8812 char *output,
8813 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00008814{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008815 PyObject *unicode;
Victor Stinner6345be92011-11-25 20:09:01 +01008816 Py_ssize_t i;
Victor Stinner42bf7752011-11-21 22:52:58 +01008817 enum PyUnicode_Kind kind;
8818 void *data;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008819
8820 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008821 PyErr_BadArgument();
8822 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008823 }
8824
Victor Stinner42bf7752011-11-21 22:52:58 +01008825 unicode = PyUnicode_FromUnicode(s, length);
8826 if (unicode == NULL)
8827 return -1;
8828
Benjamin Petersonbac79492012-01-14 13:34:47 -05008829 if (PyUnicode_READY(unicode) == -1) {
Victor Stinner6345be92011-11-25 20:09:01 +01008830 Py_DECREF(unicode);
8831 return -1;
8832 }
Victor Stinner42bf7752011-11-21 22:52:58 +01008833 kind = PyUnicode_KIND(unicode);
8834 data = PyUnicode_DATA(unicode);
8835
Victor Stinnerb84d7232011-11-22 01:50:07 +01008836 for (i=0; i < length; ) {
Victor Stinner6345be92011-11-25 20:09:01 +01008837 PyObject *exc;
8838 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00008839 int decimal;
Victor Stinner6345be92011-11-25 20:09:01 +01008840 Py_ssize_t startpos;
8841
8842 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +00008843
Benjamin Peterson29060642009-01-31 22:14:21 +00008844 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008845 *output++ = ' ';
Victor Stinnerb84d7232011-11-22 01:50:07 +01008846 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00008847 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008848 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008849 decimal = Py_UNICODE_TODECIMAL(ch);
8850 if (decimal >= 0) {
8851 *output++ = '0' + decimal;
Victor Stinnerb84d7232011-11-22 01:50:07 +01008852 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00008853 continue;
8854 }
8855 if (0 < ch && ch < 256) {
8856 *output++ = (char)ch;
Victor Stinnerb84d7232011-11-22 01:50:07 +01008857 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00008858 continue;
8859 }
Victor Stinner6345be92011-11-25 20:09:01 +01008860
Victor Stinner42bf7752011-11-21 22:52:58 +01008861 startpos = i;
Victor Stinner6345be92011-11-25 20:09:01 +01008862 exc = NULL;
8863 raise_encode_exception(&exc, "decimal", unicode,
8864 startpos, startpos+1,
8865 "invalid decimal Unicode string");
8866 Py_XDECREF(exc);
8867 Py_DECREF(unicode);
8868 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008869 }
8870 /* 0-terminate the output string */
8871 *output++ = '\0';
Victor Stinner42bf7752011-11-21 22:52:58 +01008872 Py_DECREF(unicode);
Guido van Rossum9e896b32000-04-05 20:11:21 +00008873 return 0;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008874}
8875
Guido van Rossumd57fd912000-03-10 22:53:23 +00008876/* --- Helpers ------------------------------------------------------------ */
8877
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008878static Py_ssize_t
Victor Stinner794d5672011-10-10 03:21:36 +02008879any_find_slice(int direction, PyObject* s1, PyObject* s2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008880 Py_ssize_t start,
8881 Py_ssize_t end)
8882{
8883 int kind1, kind2, kind;
8884 void *buf1, *buf2;
8885 Py_ssize_t len1, len2, result;
8886
8887 kind1 = PyUnicode_KIND(s1);
8888 kind2 = PyUnicode_KIND(s2);
8889 kind = kind1 > kind2 ? kind1 : kind2;
8890 buf1 = PyUnicode_DATA(s1);
8891 buf2 = PyUnicode_DATA(s2);
8892 if (kind1 != kind)
8893 buf1 = _PyUnicode_AsKind(s1, kind);
8894 if (!buf1)
8895 return -2;
8896 if (kind2 != kind)
8897 buf2 = _PyUnicode_AsKind(s2, kind);
8898 if (!buf2) {
8899 if (kind1 != kind) PyMem_Free(buf1);
8900 return -2;
8901 }
8902 len1 = PyUnicode_GET_LENGTH(s1);
8903 len2 = PyUnicode_GET_LENGTH(s2);
8904
Victor Stinner794d5672011-10-10 03:21:36 +02008905 if (direction > 0) {
Benjamin Petersonead6b532011-12-20 17:23:42 -06008906 switch (kind) {
Victor Stinner794d5672011-10-10 03:21:36 +02008907 case PyUnicode_1BYTE_KIND:
8908 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
8909 result = asciilib_find_slice(buf1, len1, buf2, len2, start, end);
8910 else
8911 result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end);
8912 break;
8913 case PyUnicode_2BYTE_KIND:
8914 result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end);
8915 break;
8916 case PyUnicode_4BYTE_KIND:
8917 result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end);
8918 break;
8919 default:
8920 assert(0); result = -2;
8921 }
8922 }
8923 else {
Benjamin Petersonead6b532011-12-20 17:23:42 -06008924 switch (kind) {
Victor Stinner794d5672011-10-10 03:21:36 +02008925 case PyUnicode_1BYTE_KIND:
8926 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
8927 result = asciilib_rfind_slice(buf1, len1, buf2, len2, start, end);
8928 else
8929 result = ucs1lib_rfind_slice(buf1, len1, buf2, len2, start, end);
8930 break;
8931 case PyUnicode_2BYTE_KIND:
8932 result = ucs2lib_rfind_slice(buf1, len1, buf2, len2, start, end);
8933 break;
8934 case PyUnicode_4BYTE_KIND:
8935 result = ucs4lib_rfind_slice(buf1, len1, buf2, len2, start, end);
8936 break;
8937 default:
8938 assert(0); result = -2;
8939 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008940 }
8941
8942 if (kind1 != kind)
8943 PyMem_Free(buf1);
8944 if (kind2 != kind)
8945 PyMem_Free(buf2);
8946
8947 return result;
8948}
8949
8950Py_ssize_t
Victor Stinner41a863c2012-02-24 00:37:51 +01008951_PyUnicode_InsertThousandsGrouping(
8952 PyObject *unicode, Py_ssize_t index,
8953 Py_ssize_t n_buffer,
8954 void *digits, Py_ssize_t n_digits,
8955 Py_ssize_t min_width,
8956 const char *grouping, PyObject *thousands_sep,
8957 Py_UCS4 *maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008958{
Victor Stinner41a863c2012-02-24 00:37:51 +01008959 unsigned int kind, thousands_sep_kind;
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008960 char *data, *thousands_sep_data;
Victor Stinner41a863c2012-02-24 00:37:51 +01008961 Py_ssize_t thousands_sep_len;
8962 Py_ssize_t len;
8963
8964 if (unicode != NULL) {
8965 kind = PyUnicode_KIND(unicode);
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008966 data = (char *) PyUnicode_DATA(unicode) + index * kind;
Victor Stinner41a863c2012-02-24 00:37:51 +01008967 }
8968 else {
8969 kind = PyUnicode_1BYTE_KIND;
8970 data = NULL;
8971 }
8972 thousands_sep_kind = PyUnicode_KIND(thousands_sep);
8973 thousands_sep_data = PyUnicode_DATA(thousands_sep);
8974 thousands_sep_len = PyUnicode_GET_LENGTH(thousands_sep);
8975 if (unicode != NULL && thousands_sep_kind != kind) {
Victor Stinner90f50d42012-02-24 01:44:47 +01008976 if (thousands_sep_kind < kind) {
8977 thousands_sep_data = _PyUnicode_AsKind(thousands_sep, kind);
8978 if (!thousands_sep_data)
8979 return -1;
8980 }
8981 else {
8982 data = _PyUnicode_AsKind(unicode, thousands_sep_kind);
8983 if (!data)
8984 return -1;
8985 }
Victor Stinner41a863c2012-02-24 00:37:51 +01008986 }
8987
Benjamin Petersonead6b532011-12-20 17:23:42 -06008988 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008989 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02008990 if (unicode != NULL && PyUnicode_IS_ASCII(unicode))
Victor Stinner41a863c2012-02-24 00:37:51 +01008991 len = asciilib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008992 (Py_UCS1 *) data, n_buffer, (Py_UCS1 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01008993 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008994 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinnerc3cec782011-10-05 21:24:08 +02008995 else
Victor Stinner41a863c2012-02-24 00:37:51 +01008996 len = ucs1lib_InsertThousandsGrouping(
Victor Stinnerc3cec782011-10-05 21:24:08 +02008997 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01008998 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008999 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009000 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009001 case PyUnicode_2BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01009002 len = ucs2lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009003 (Py_UCS2 *) data, n_buffer, (Py_UCS2 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009004 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009005 (Py_UCS2 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009006 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009007 case PyUnicode_4BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01009008 len = ucs4lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009009 (Py_UCS4 *) data, n_buffer, (Py_UCS4 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009010 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009011 (Py_UCS4 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009012 break;
9013 default:
9014 assert(0);
9015 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009016 }
Victor Stinner90f50d42012-02-24 01:44:47 +01009017 if (unicode != NULL && thousands_sep_kind != kind) {
9018 if (thousands_sep_kind < kind)
9019 PyMem_Free(thousands_sep_data);
9020 else
9021 PyMem_Free(data);
9022 }
Victor Stinner41a863c2012-02-24 00:37:51 +01009023 if (unicode == NULL) {
9024 *maxchar = 127;
9025 if (len != n_digits) {
Victor Stinnere6abb482012-05-02 01:15:40 +02009026 *maxchar = MAX_MAXCHAR(*maxchar,
9027 PyUnicode_MAX_CHAR_VALUE(thousands_sep));
Victor Stinner41a863c2012-02-24 00:37:51 +01009028 }
9029 }
9030 return len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009031}
9032
9033
Thomas Wouters477c8d52006-05-27 19:21:47 +00009034/* helper macro to fixup start/end slice values */
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009035#define ADJUST_INDICES(start, end, len) \
9036 if (end > len) \
9037 end = len; \
9038 else if (end < 0) { \
9039 end += len; \
9040 if (end < 0) \
9041 end = 0; \
9042 } \
9043 if (start < 0) { \
9044 start += len; \
9045 if (start < 0) \
9046 start = 0; \
9047 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009048
Alexander Belopolsky40018472011-02-26 01:02:56 +00009049Py_ssize_t
9050PyUnicode_Count(PyObject *str,
9051 PyObject *substr,
9052 Py_ssize_t start,
9053 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009054{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009055 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009056 PyObject* str_obj;
9057 PyObject* sub_obj;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009058 int kind1, kind2, kind;
9059 void *buf1 = NULL, *buf2 = NULL;
9060 Py_ssize_t len1, len2;
Tim Petersced69f82003-09-16 20:30:58 +00009061
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009062 str_obj = PyUnicode_FromObject(str);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009063 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +00009064 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009065 sub_obj = PyUnicode_FromObject(substr);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009066 if (!sub_obj) {
9067 Py_DECREF(str_obj);
9068 return -1;
9069 }
Benjamin Peterson4c13a4a2012-01-02 09:07:38 -06009070 if (PyUnicode_READY(sub_obj) == -1 || PyUnicode_READY(str_obj) == -1) {
Benjamin Peterson5e458f52012-01-02 10:12:13 -06009071 Py_DECREF(sub_obj);
Benjamin Peterson29060642009-01-31 22:14:21 +00009072 Py_DECREF(str_obj);
9073 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009074 }
Tim Petersced69f82003-09-16 20:30:58 +00009075
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009076 kind1 = PyUnicode_KIND(str_obj);
9077 kind2 = PyUnicode_KIND(sub_obj);
Antoine Pitroue45c0c52012-05-12 15:49:07 +02009078 kind = kind1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009079 buf1 = PyUnicode_DATA(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009080 buf2 = PyUnicode_DATA(sub_obj);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -05009081 if (kind2 != kind) {
Antoine Pitrou758153b2012-05-12 15:51:51 +02009082 if (kind2 > kind) {
9083 Py_DECREF(sub_obj);
9084 Py_DECREF(str_obj);
Antoine Pitroue45c0c52012-05-12 15:49:07 +02009085 return 0;
Antoine Pitrou758153b2012-05-12 15:51:51 +02009086 }
Victor Stinner7931d9a2011-11-04 00:22:48 +01009087 buf2 = _PyUnicode_AsKind(sub_obj, kind);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -05009088 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009089 if (!buf2)
9090 goto onError;
9091 len1 = PyUnicode_GET_LENGTH(str_obj);
9092 len2 = PyUnicode_GET_LENGTH(sub_obj);
9093
9094 ADJUST_INDICES(start, end, len1);
Benjamin Petersonead6b532011-12-20 17:23:42 -06009095 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009096 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009097 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sub_obj))
9098 result = asciilib_count(
9099 ((Py_UCS1*)buf1) + start, end - start,
9100 buf2, len2, PY_SSIZE_T_MAX
9101 );
9102 else
9103 result = ucs1lib_count(
9104 ((Py_UCS1*)buf1) + start, end - start,
9105 buf2, len2, PY_SSIZE_T_MAX
9106 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009107 break;
9108 case PyUnicode_2BYTE_KIND:
9109 result = ucs2lib_count(
9110 ((Py_UCS2*)buf1) + start, end - start,
9111 buf2, len2, PY_SSIZE_T_MAX
9112 );
9113 break;
9114 case PyUnicode_4BYTE_KIND:
9115 result = ucs4lib_count(
9116 ((Py_UCS4*)buf1) + start, end - start,
9117 buf2, len2, PY_SSIZE_T_MAX
9118 );
9119 break;
9120 default:
9121 assert(0); result = 0;
9122 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009123
9124 Py_DECREF(sub_obj);
9125 Py_DECREF(str_obj);
9126
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009127 if (kind2 != kind)
9128 PyMem_Free(buf2);
9129
Guido van Rossumd57fd912000-03-10 22:53:23 +00009130 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009131 onError:
9132 Py_DECREF(sub_obj);
9133 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009134 if (kind2 != kind && buf2)
9135 PyMem_Free(buf2);
9136 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009137}
9138
Alexander Belopolsky40018472011-02-26 01:02:56 +00009139Py_ssize_t
9140PyUnicode_Find(PyObject *str,
9141 PyObject *sub,
9142 Py_ssize_t start,
9143 Py_ssize_t end,
9144 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009145{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009146 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009147
Guido van Rossumd57fd912000-03-10 22:53:23 +00009148 str = PyUnicode_FromObject(str);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009149 if (!str)
Benjamin Peterson29060642009-01-31 22:14:21 +00009150 return -2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009151 sub = PyUnicode_FromObject(sub);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009152 if (!sub) {
9153 Py_DECREF(str);
9154 return -2;
9155 }
9156 if (PyUnicode_READY(sub) == -1 || PyUnicode_READY(str) == -1) {
9157 Py_DECREF(sub);
Benjamin Peterson29060642009-01-31 22:14:21 +00009158 Py_DECREF(str);
9159 return -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009160 }
Tim Petersced69f82003-09-16 20:30:58 +00009161
Victor Stinner794d5672011-10-10 03:21:36 +02009162 result = any_find_slice(direction,
9163 str, sub, start, end
9164 );
Thomas Wouters477c8d52006-05-27 19:21:47 +00009165
Guido van Rossumd57fd912000-03-10 22:53:23 +00009166 Py_DECREF(str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009167 Py_DECREF(sub);
9168
Guido van Rossumd57fd912000-03-10 22:53:23 +00009169 return result;
9170}
9171
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009172Py_ssize_t
9173PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
9174 Py_ssize_t start, Py_ssize_t end,
9175 int direction)
9176{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009177 int kind;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009178 Py_ssize_t result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009179 if (PyUnicode_READY(str) == -1)
9180 return -2;
Victor Stinner267aa242011-10-02 01:08:37 +02009181 if (start < 0 || end < 0) {
9182 PyErr_SetString(PyExc_IndexError, "string index out of range");
9183 return -2;
9184 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009185 if (end > PyUnicode_GET_LENGTH(str))
9186 end = PyUnicode_GET_LENGTH(str);
9187 kind = PyUnicode_KIND(str);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009188 result = findchar(PyUnicode_1BYTE_DATA(str) + kind*start,
9189 kind, end-start, ch, direction);
9190 if (result == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009191 return -1;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009192 else
9193 return start + result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009194}
9195
Alexander Belopolsky40018472011-02-26 01:02:56 +00009196static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009197tailmatch(PyObject *self,
9198 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009199 Py_ssize_t start,
9200 Py_ssize_t end,
9201 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009202{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009203 int kind_self;
9204 int kind_sub;
9205 void *data_self;
9206 void *data_sub;
9207 Py_ssize_t offset;
9208 Py_ssize_t i;
9209 Py_ssize_t end_sub;
9210
9211 if (PyUnicode_READY(self) == -1 ||
9212 PyUnicode_READY(substring) == -1)
9213 return 0;
9214
9215 if (PyUnicode_GET_LENGTH(substring) == 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009216 return 1;
9217
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009218 ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
9219 end -= PyUnicode_GET_LENGTH(substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009220 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00009221 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009222
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009223 kind_self = PyUnicode_KIND(self);
9224 data_self = PyUnicode_DATA(self);
9225 kind_sub = PyUnicode_KIND(substring);
9226 data_sub = PyUnicode_DATA(substring);
9227 end_sub = PyUnicode_GET_LENGTH(substring) - 1;
9228
9229 if (direction > 0)
9230 offset = end;
9231 else
9232 offset = start;
9233
9234 if (PyUnicode_READ(kind_self, data_self, offset) ==
9235 PyUnicode_READ(kind_sub, data_sub, 0) &&
9236 PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
9237 PyUnicode_READ(kind_sub, data_sub, end_sub)) {
9238 /* If both are of the same kind, memcmp is sufficient */
9239 if (kind_self == kind_sub) {
9240 return ! memcmp((char *)data_self +
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009241 (offset * PyUnicode_KIND(substring)),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009242 data_sub,
9243 PyUnicode_GET_LENGTH(substring) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009244 PyUnicode_KIND(substring));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009245 }
9246 /* otherwise we have to compare each character by first accesing it */
9247 else {
9248 /* We do not need to compare 0 and len(substring)-1 because
9249 the if statement above ensured already that they are equal
9250 when we end up here. */
9251 // TODO: honor direction and do a forward or backwards search
9252 for (i = 1; i < end_sub; ++i) {
9253 if (PyUnicode_READ(kind_self, data_self, offset + i) !=
9254 PyUnicode_READ(kind_sub, data_sub, i))
9255 return 0;
9256 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009257 return 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009258 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009259 }
9260
9261 return 0;
9262}
9263
Alexander Belopolsky40018472011-02-26 01:02:56 +00009264Py_ssize_t
9265PyUnicode_Tailmatch(PyObject *str,
9266 PyObject *substr,
9267 Py_ssize_t start,
9268 Py_ssize_t end,
9269 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009270{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009271 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009272
Guido van Rossumd57fd912000-03-10 22:53:23 +00009273 str = PyUnicode_FromObject(str);
9274 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009275 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009276 substr = PyUnicode_FromObject(substr);
9277 if (substr == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009278 Py_DECREF(str);
9279 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009280 }
Tim Petersced69f82003-09-16 20:30:58 +00009281
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009282 result = tailmatch(str, substr,
Benjamin Peterson29060642009-01-31 22:14:21 +00009283 start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009284 Py_DECREF(str);
9285 Py_DECREF(substr);
9286 return result;
9287}
9288
Guido van Rossumd57fd912000-03-10 22:53:23 +00009289/* Apply fixfct filter to the Unicode object self and return a
9290 reference to the modified object */
9291
Alexander Belopolsky40018472011-02-26 01:02:56 +00009292static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009293fixup(PyObject *self,
9294 Py_UCS4 (*fixfct)(PyObject *s))
Guido van Rossumd57fd912000-03-10 22:53:23 +00009295{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009296 PyObject *u;
9297 Py_UCS4 maxchar_old, maxchar_new = 0;
Victor Stinnereaab6042011-12-11 22:22:39 +01009298 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009299
Victor Stinnerbf6e5602011-12-12 01:53:47 +01009300 u = _PyUnicode_Copy(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009301 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009302 return NULL;
Victor Stinner87af4f22011-11-21 23:03:47 +01009303 maxchar_old = PyUnicode_MAX_CHAR_VALUE(u);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009304
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009305 /* fix functions return the new maximum character in a string,
9306 if the kind of the resulting unicode object does not change,
9307 everything is fine. Otherwise we need to change the string kind
9308 and re-run the fix function. */
Victor Stinner9310abb2011-10-05 00:59:23 +02009309 maxchar_new = fixfct(u);
Victor Stinnereaab6042011-12-11 22:22:39 +01009310
9311 if (maxchar_new == 0) {
9312 /* no changes */;
9313 if (PyUnicode_CheckExact(self)) {
9314 Py_DECREF(u);
9315 Py_INCREF(self);
9316 return self;
9317 }
9318 else
9319 return u;
9320 }
9321
Victor Stinnere6abb482012-05-02 01:15:40 +02009322 maxchar_new = align_maxchar(maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009323
Victor Stinnereaab6042011-12-11 22:22:39 +01009324 if (maxchar_new == maxchar_old)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009325 return u;
Victor Stinnereaab6042011-12-11 22:22:39 +01009326
9327 /* In case the maximum character changed, we need to
9328 convert the string to the new category. */
9329 v = PyUnicode_New(PyUnicode_GET_LENGTH(self), maxchar_new);
9330 if (v == NULL) {
9331 Py_DECREF(u);
9332 return NULL;
9333 }
9334 if (maxchar_new > maxchar_old) {
9335 /* If the maxchar increased so that the kind changed, not all
9336 characters are representable anymore and we need to fix the
9337 string again. This only happens in very few cases. */
9338 copy_characters(v, 0, self, 0, PyUnicode_GET_LENGTH(self));
9339 maxchar_old = fixfct(v);
9340 assert(maxchar_old > 0 && maxchar_old <= maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009341 }
9342 else {
Victor Stinnereaab6042011-12-11 22:22:39 +01009343 copy_characters(v, 0, u, 0, PyUnicode_GET_LENGTH(self));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009344 }
Victor Stinnereaab6042011-12-11 22:22:39 +01009345 Py_DECREF(u);
9346 assert(_PyUnicode_CheckConsistency(v, 1));
9347 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009348}
9349
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009350static PyObject *
9351ascii_upper_or_lower(PyObject *self, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009352{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009353 Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9354 char *resdata, *data = PyUnicode_DATA(self);
9355 PyObject *res;
Tim Petersced69f82003-09-16 20:30:58 +00009356
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009357 res = PyUnicode_New(len, 127);
9358 if (res == NULL)
9359 return NULL;
9360 resdata = PyUnicode_DATA(res);
9361 if (lower)
9362 _Py_bytes_lower(resdata, data, len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009363 else
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009364 _Py_bytes_upper(resdata, data, len);
9365 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009366}
9367
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009368static Py_UCS4
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009369handle_capital_sigma(int kind, void *data, Py_ssize_t length, Py_ssize_t i)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009370{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009371 Py_ssize_t j;
9372 int final_sigma;
9373 Py_UCS4 c;
9374 /* U+03A3 is in the Final_Sigma context when, it is found like this:
Tim Petersced69f82003-09-16 20:30:58 +00009375
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009376 \p{cased}\p{case-ignorable}*U+03A3!(\p{case-ignorable}*\p{cased})
9377
9378 where ! is a negation and \p{xxx} is a character with property xxx.
9379 */
9380 for (j = i - 1; j >= 0; j--) {
9381 c = PyUnicode_READ(kind, data, j);
9382 if (!_PyUnicode_IsCaseIgnorable(c))
9383 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009384 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009385 final_sigma = j >= 0 && _PyUnicode_IsCased(c);
9386 if (final_sigma) {
9387 for (j = i + 1; j < length; j++) {
9388 c = PyUnicode_READ(kind, data, j);
9389 if (!_PyUnicode_IsCaseIgnorable(c))
9390 break;
9391 }
9392 final_sigma = j == length || !_PyUnicode_IsCased(c);
9393 }
9394 return (final_sigma) ? 0x3C2 : 0x3C3;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009395}
9396
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009397static int
9398lower_ucs4(int kind, void *data, Py_ssize_t length, Py_ssize_t i,
9399 Py_UCS4 c, Py_UCS4 *mapped)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009400{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009401 /* Obscure special case. */
9402 if (c == 0x3A3) {
9403 mapped[0] = handle_capital_sigma(kind, data, length, i);
9404 return 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009405 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009406 return _PyUnicode_ToLowerFull(c, mapped);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009407}
9408
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009409static Py_ssize_t
9410do_capitalize(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009411{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009412 Py_ssize_t i, k = 0;
9413 int n_res, j;
9414 Py_UCS4 c, mapped[3];
Tim Petersced69f82003-09-16 20:30:58 +00009415
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009416 c = PyUnicode_READ(kind, data, 0);
9417 n_res = _PyUnicode_ToUpperFull(c, mapped);
9418 for (j = 0; j < n_res; j++) {
Victor Stinnere6abb482012-05-02 01:15:40 +02009419 *maxchar = MAX_MAXCHAR(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009420 res[k++] = mapped[j];
Guido van Rossumd57fd912000-03-10 22:53:23 +00009421 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009422 for (i = 1; i < length; i++) {
9423 c = PyUnicode_READ(kind, data, i);
9424 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9425 for (j = 0; j < n_res; j++) {
Victor Stinnere6abb482012-05-02 01:15:40 +02009426 *maxchar = MAX_MAXCHAR(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009427 res[k++] = mapped[j];
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009428 }
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009429 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009430 return k;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009431}
9432
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009433static Py_ssize_t
9434do_swapcase(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar) {
9435 Py_ssize_t i, k = 0;
9436
9437 for (i = 0; i < length; i++) {
9438 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9439 int n_res, j;
9440 if (Py_UNICODE_ISUPPER(c)) {
9441 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9442 }
9443 else if (Py_UNICODE_ISLOWER(c)) {
9444 n_res = _PyUnicode_ToUpperFull(c, mapped);
9445 }
9446 else {
9447 n_res = 1;
9448 mapped[0] = c;
9449 }
9450 for (j = 0; j < n_res; j++) {
Victor Stinnere6abb482012-05-02 01:15:40 +02009451 *maxchar = MAX_MAXCHAR(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009452 res[k++] = mapped[j];
9453 }
9454 }
9455 return k;
9456}
9457
9458static Py_ssize_t
9459do_upper_or_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res,
9460 Py_UCS4 *maxchar, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009461{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009462 Py_ssize_t i, k = 0;
9463
9464 for (i = 0; i < length; i++) {
9465 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9466 int n_res, j;
9467 if (lower)
9468 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9469 else
9470 n_res = _PyUnicode_ToUpperFull(c, mapped);
9471 for (j = 0; j < n_res; j++) {
Victor Stinnere6abb482012-05-02 01:15:40 +02009472 *maxchar = MAX_MAXCHAR(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009473 res[k++] = mapped[j];
9474 }
9475 }
9476 return k;
9477}
9478
9479static Py_ssize_t
9480do_upper(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9481{
9482 return do_upper_or_lower(kind, data, length, res, maxchar, 0);
9483}
9484
9485static Py_ssize_t
9486do_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9487{
9488 return do_upper_or_lower(kind, data, length, res, maxchar, 1);
9489}
9490
Benjamin Petersone51757f2012-01-12 21:10:29 -05009491static Py_ssize_t
Benjamin Petersond5890c82012-01-14 13:23:30 -05009492do_casefold(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9493{
9494 Py_ssize_t i, k = 0;
9495
9496 for (i = 0; i < length; i++) {
9497 Py_UCS4 c = PyUnicode_READ(kind, data, i);
9498 Py_UCS4 mapped[3];
9499 int j, n_res = _PyUnicode_ToFoldedFull(c, mapped);
9500 for (j = 0; j < n_res; j++) {
Victor Stinnere6abb482012-05-02 01:15:40 +02009501 *maxchar = MAX_MAXCHAR(*maxchar, mapped[j]);
Benjamin Petersond5890c82012-01-14 13:23:30 -05009502 res[k++] = mapped[j];
9503 }
9504 }
9505 return k;
9506}
9507
9508static Py_ssize_t
Benjamin Petersone51757f2012-01-12 21:10:29 -05009509do_title(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9510{
9511 Py_ssize_t i, k = 0;
9512 int previous_is_cased;
9513
9514 previous_is_cased = 0;
9515 for (i = 0; i < length; i++) {
9516 const Py_UCS4 c = PyUnicode_READ(kind, data, i);
9517 Py_UCS4 mapped[3];
9518 int n_res, j;
9519
9520 if (previous_is_cased)
9521 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9522 else
9523 n_res = _PyUnicode_ToTitleFull(c, mapped);
9524
9525 for (j = 0; j < n_res; j++) {
Victor Stinnere6abb482012-05-02 01:15:40 +02009526 *maxchar = MAX_MAXCHAR(*maxchar, mapped[j]);
Benjamin Petersone51757f2012-01-12 21:10:29 -05009527 res[k++] = mapped[j];
9528 }
9529
9530 previous_is_cased = _PyUnicode_IsCased(c);
9531 }
9532 return k;
9533}
9534
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009535static PyObject *
9536case_operation(PyObject *self,
9537 Py_ssize_t (*perform)(int, void *, Py_ssize_t, Py_UCS4 *, Py_UCS4 *))
9538{
9539 PyObject *res = NULL;
9540 Py_ssize_t length, newlength = 0;
9541 int kind, outkind;
9542 void *data, *outdata;
9543 Py_UCS4 maxchar = 0, *tmp, *tmpend;
9544
Benjamin Petersoneea48462012-01-16 14:28:50 -05009545 assert(PyUnicode_IS_READY(self));
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009546
9547 kind = PyUnicode_KIND(self);
9548 data = PyUnicode_DATA(self);
9549 length = PyUnicode_GET_LENGTH(self);
9550 tmp = PyMem_MALLOC(sizeof(Py_UCS4) * 3 * length);
9551 if (tmp == NULL)
9552 return PyErr_NoMemory();
9553 newlength = perform(kind, data, length, tmp, &maxchar);
9554 res = PyUnicode_New(newlength, maxchar);
9555 if (res == NULL)
9556 goto leave;
9557 tmpend = tmp + newlength;
9558 outdata = PyUnicode_DATA(res);
9559 outkind = PyUnicode_KIND(res);
9560 switch (outkind) {
9561 case PyUnicode_1BYTE_KIND:
9562 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, tmp, tmpend, outdata);
9563 break;
9564 case PyUnicode_2BYTE_KIND:
9565 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, tmp, tmpend, outdata);
9566 break;
9567 case PyUnicode_4BYTE_KIND:
9568 memcpy(outdata, tmp, sizeof(Py_UCS4) * newlength);
9569 break;
9570 default:
9571 assert(0);
9572 break;
9573 }
9574 leave:
9575 PyMem_FREE(tmp);
9576 return res;
9577}
9578
Tim Peters8ce9f162004-08-27 01:49:32 +00009579PyObject *
9580PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009581{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009582 PyObject *sep = NULL;
Victor Stinnerdd077322011-10-07 17:02:31 +02009583 Py_ssize_t seplen;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009584 PyObject *res = NULL; /* the result */
Tim Peters05eba1f2004-08-27 21:32:02 +00009585 PyObject *fseq; /* PySequence_Fast(seq) */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009586 Py_ssize_t seqlen; /* len(fseq) -- number of items in sequence */
9587 PyObject **items;
Tim Peters8ce9f162004-08-27 01:49:32 +00009588 PyObject *item;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009589 Py_ssize_t sz, i, res_offset;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009590 Py_UCS4 maxchar;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009591 Py_UCS4 item_maxchar;
Victor Stinnerdd077322011-10-07 17:02:31 +02009592 int use_memcpy;
9593 unsigned char *res_data = NULL, *sep_data = NULL;
9594 PyObject *last_obj;
9595 unsigned int kind = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009596
Tim Peters05eba1f2004-08-27 21:32:02 +00009597 fseq = PySequence_Fast(seq, "");
9598 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009599 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00009600 }
9601
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009602 /* NOTE: the following code can't call back into Python code,
9603 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00009604 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009605
Tim Peters05eba1f2004-08-27 21:32:02 +00009606 seqlen = PySequence_Fast_GET_SIZE(fseq);
9607 /* If empty sequence, return u"". */
9608 if (seqlen == 0) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009609 Py_DECREF(fseq);
9610 Py_INCREF(unicode_empty);
9611 res = unicode_empty;
9612 return res;
Tim Peters05eba1f2004-08-27 21:32:02 +00009613 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009614
Tim Peters05eba1f2004-08-27 21:32:02 +00009615 /* If singleton sequence with an exact Unicode, return that. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009616 last_obj = NULL;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009617 items = PySequence_Fast_ITEMS(fseq);
Victor Stinneracf47b82011-10-06 12:32:37 +02009618 if (seqlen == 1) {
9619 if (PyUnicode_CheckExact(items[0])) {
9620 res = items[0];
9621 Py_INCREF(res);
9622 Py_DECREF(fseq);
9623 return res;
9624 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009625 seplen = 0;
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009626 maxchar = 0;
Tim Peters8ce9f162004-08-27 01:49:32 +00009627 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009628 else {
Victor Stinneracf47b82011-10-06 12:32:37 +02009629 /* Set up sep and seplen */
9630 if (separator == NULL) {
9631 /* fall back to a blank space separator */
9632 sep = PyUnicode_FromOrdinal(' ');
9633 if (!sep)
9634 goto onError;
Victor Stinnerdd077322011-10-07 17:02:31 +02009635 seplen = 1;
Victor Stinneracf47b82011-10-06 12:32:37 +02009636 maxchar = 32;
Tim Peters05eba1f2004-08-27 21:32:02 +00009637 }
Victor Stinneracf47b82011-10-06 12:32:37 +02009638 else {
9639 if (!PyUnicode_Check(separator)) {
9640 PyErr_Format(PyExc_TypeError,
9641 "separator: expected str instance,"
9642 " %.80s found",
9643 Py_TYPE(separator)->tp_name);
9644 goto onError;
9645 }
9646 if (PyUnicode_READY(separator))
9647 goto onError;
9648 sep = separator;
9649 seplen = PyUnicode_GET_LENGTH(separator);
9650 maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
9651 /* inc refcount to keep this code path symmetric with the
9652 above case of a blank separator */
9653 Py_INCREF(sep);
9654 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009655 last_obj = sep;
Tim Peters05eba1f2004-08-27 21:32:02 +00009656 }
9657
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009658 /* There are at least two things to join, or else we have a subclass
9659 * of str in the sequence.
9660 * Do a pre-pass to figure out the total amount of space we'll
9661 * need (sz), and see whether all argument are strings.
9662 */
9663 sz = 0;
Victor Stinnerdd077322011-10-07 17:02:31 +02009664#ifdef Py_DEBUG
9665 use_memcpy = 0;
9666#else
9667 use_memcpy = 1;
9668#endif
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009669 for (i = 0; i < seqlen; i++) {
9670 const Py_ssize_t old_sz = sz;
9671 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009672 if (!PyUnicode_Check(item)) {
9673 PyErr_Format(PyExc_TypeError,
9674 "sequence item %zd: expected str instance,"
9675 " %.80s found",
9676 i, Py_TYPE(item)->tp_name);
9677 goto onError;
9678 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009679 if (PyUnicode_READY(item) == -1)
9680 goto onError;
9681 sz += PyUnicode_GET_LENGTH(item);
9682 item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
Victor Stinnere6abb482012-05-02 01:15:40 +02009683 maxchar = MAX_MAXCHAR(maxchar, item_maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009684 if (i != 0)
9685 sz += seplen;
9686 if (sz < old_sz || sz > PY_SSIZE_T_MAX) {
9687 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009688 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009689 goto onError;
9690 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009691 if (use_memcpy && last_obj != NULL) {
9692 if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
9693 use_memcpy = 0;
9694 }
9695 last_obj = item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009696 }
Tim Petersced69f82003-09-16 20:30:58 +00009697
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009698 res = PyUnicode_New(sz, maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009699 if (res == NULL)
9700 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +00009701
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009702 /* Catenate everything. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009703#ifdef Py_DEBUG
9704 use_memcpy = 0;
9705#else
9706 if (use_memcpy) {
9707 res_data = PyUnicode_1BYTE_DATA(res);
9708 kind = PyUnicode_KIND(res);
9709 if (seplen != 0)
9710 sep_data = PyUnicode_1BYTE_DATA(sep);
9711 }
9712#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009713 for (i = 0, res_offset = 0; i < seqlen; ++i) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009714 Py_ssize_t itemlen;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009715 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009716 /* Copy item, and maybe the separator. */
Victor Stinner9ce5a832011-10-03 23:36:02 +02009717 if (i && seplen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009718 if (use_memcpy) {
9719 Py_MEMCPY(res_data,
9720 sep_data,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009721 kind * seplen);
9722 res_data += kind * seplen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009723 }
9724 else {
9725 copy_characters(res, res_offset, sep, 0, seplen);
9726 res_offset += seplen;
9727 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009728 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009729 itemlen = PyUnicode_GET_LENGTH(item);
9730 if (itemlen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009731 if (use_memcpy) {
9732 Py_MEMCPY(res_data,
9733 PyUnicode_DATA(item),
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009734 kind * itemlen);
9735 res_data += kind * itemlen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009736 }
9737 else {
9738 copy_characters(res, res_offset, item, 0, itemlen);
9739 res_offset += itemlen;
9740 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009741 }
Tim Peters05eba1f2004-08-27 21:32:02 +00009742 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009743 if (use_memcpy)
9744 assert(res_data == PyUnicode_1BYTE_DATA(res)
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009745 + kind * PyUnicode_GET_LENGTH(res));
Victor Stinnerdd077322011-10-07 17:02:31 +02009746 else
9747 assert(res_offset == PyUnicode_GET_LENGTH(res));
Tim Peters8ce9f162004-08-27 01:49:32 +00009748
Tim Peters05eba1f2004-08-27 21:32:02 +00009749 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009750 Py_XDECREF(sep);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009751 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009752 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009753
Benjamin Peterson29060642009-01-31 22:14:21 +00009754 onError:
Tim Peters05eba1f2004-08-27 21:32:02 +00009755 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009756 Py_XDECREF(sep);
Tim Peters8ce9f162004-08-27 01:49:32 +00009757 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009758 return NULL;
9759}
9760
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009761#define FILL(kind, data, value, start, length) \
9762 do { \
9763 Py_ssize_t i_ = 0; \
9764 assert(kind != PyUnicode_WCHAR_KIND); \
9765 switch ((kind)) { \
9766 case PyUnicode_1BYTE_KIND: { \
9767 unsigned char * to_ = (unsigned char *)((data)) + (start); \
Victor Stinnerf2c76aa2012-05-03 13:10:40 +02009768 memset(to_, (unsigned char)value, (length)); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009769 break; \
9770 } \
9771 case PyUnicode_2BYTE_KIND: { \
9772 Py_UCS2 * to_ = (Py_UCS2 *)((data)) + (start); \
9773 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9774 break; \
9775 } \
Benjamin Petersone157cf12012-01-01 15:56:20 -06009776 case PyUnicode_4BYTE_KIND: { \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009777 Py_UCS4 * to_ = (Py_UCS4 *)((data)) + (start); \
9778 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9779 break; \
Benjamin Petersone157cf12012-01-01 15:56:20 -06009780 default: assert(0); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009781 } \
9782 } \
9783 } while (0)
9784
Victor Stinner3fe55312012-01-04 00:33:50 +01009785Py_ssize_t
9786PyUnicode_Fill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
9787 Py_UCS4 fill_char)
9788{
9789 Py_ssize_t maxlen;
9790 enum PyUnicode_Kind kind;
9791 void *data;
9792
9793 if (!PyUnicode_Check(unicode)) {
9794 PyErr_BadInternalCall();
9795 return -1;
9796 }
9797 if (PyUnicode_READY(unicode) == -1)
9798 return -1;
9799 if (unicode_check_modifiable(unicode))
9800 return -1;
9801
9802 if (fill_char > PyUnicode_MAX_CHAR_VALUE(unicode)) {
9803 PyErr_SetString(PyExc_ValueError,
9804 "fill character is bigger than "
9805 "the string maximum character");
9806 return -1;
9807 }
9808
9809 maxlen = PyUnicode_GET_LENGTH(unicode) - start;
9810 length = Py_MIN(maxlen, length);
9811 if (length <= 0)
9812 return 0;
9813
9814 kind = PyUnicode_KIND(unicode);
9815 data = PyUnicode_DATA(unicode);
9816 FILL(kind, data, fill_char, start, length);
9817 return length;
9818}
9819
Victor Stinner9310abb2011-10-05 00:59:23 +02009820static PyObject *
9821pad(PyObject *self,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009822 Py_ssize_t left,
9823 Py_ssize_t right,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009824 Py_UCS4 fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009825{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009826 PyObject *u;
9827 Py_UCS4 maxchar;
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009828 int kind;
9829 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009830
9831 if (left < 0)
9832 left = 0;
9833 if (right < 0)
9834 right = 0;
9835
Victor Stinnerc4b49542011-12-11 22:44:26 +01009836 if (left == 0 && right == 0)
9837 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009838
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009839 if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
9840 right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +00009841 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
9842 return NULL;
9843 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009844 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Victor Stinnere6abb482012-05-02 01:15:40 +02009845 maxchar = MAX_MAXCHAR(maxchar, fill);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009846 u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009847 if (!u)
9848 return NULL;
9849
9850 kind = PyUnicode_KIND(u);
9851 data = PyUnicode_DATA(u);
9852 if (left)
9853 FILL(kind, data, fill, 0, left);
9854 if (right)
9855 FILL(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009856 copy_characters(u, left, self, 0, _PyUnicode_LENGTH(self));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009857 assert(_PyUnicode_CheckConsistency(u, 1));
9858 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009859}
9860
Alexander Belopolsky40018472011-02-26 01:02:56 +00009861PyObject *
9862PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009863{
Guido van Rossumd57fd912000-03-10 22:53:23 +00009864 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009865
9866 string = PyUnicode_FromObject(string);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009867 if (string == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009868 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -06009869 if (PyUnicode_READY(string) == -1) {
9870 Py_DECREF(string);
9871 return NULL;
9872 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009873
Benjamin Petersonead6b532011-12-20 17:23:42 -06009874 switch (PyUnicode_KIND(string)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009875 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009876 if (PyUnicode_IS_ASCII(string))
9877 list = asciilib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009878 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009879 PyUnicode_GET_LENGTH(string), keepends);
9880 else
9881 list = ucs1lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009882 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009883 PyUnicode_GET_LENGTH(string), keepends);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009884 break;
9885 case PyUnicode_2BYTE_KIND:
9886 list = ucs2lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009887 string, PyUnicode_2BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009888 PyUnicode_GET_LENGTH(string), keepends);
9889 break;
9890 case PyUnicode_4BYTE_KIND:
9891 list = ucs4lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009892 string, PyUnicode_4BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009893 PyUnicode_GET_LENGTH(string), keepends);
9894 break;
9895 default:
9896 assert(0);
9897 list = 0;
9898 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009899 Py_DECREF(string);
9900 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009901}
9902
Alexander Belopolsky40018472011-02-26 01:02:56 +00009903static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009904split(PyObject *self,
9905 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009906 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009907{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009908 int kind1, kind2, kind;
9909 void *buf1, *buf2;
9910 Py_ssize_t len1, len2;
9911 PyObject* out;
9912
Guido van Rossumd57fd912000-03-10 22:53:23 +00009913 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00009914 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009915
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009916 if (PyUnicode_READY(self) == -1)
9917 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009918
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009919 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -06009920 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009921 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009922 if (PyUnicode_IS_ASCII(self))
9923 return asciilib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009924 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009925 PyUnicode_GET_LENGTH(self), maxcount
9926 );
9927 else
9928 return ucs1lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009929 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009930 PyUnicode_GET_LENGTH(self), maxcount
9931 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009932 case PyUnicode_2BYTE_KIND:
9933 return ucs2lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009934 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009935 PyUnicode_GET_LENGTH(self), maxcount
9936 );
9937 case PyUnicode_4BYTE_KIND:
9938 return ucs4lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009939 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009940 PyUnicode_GET_LENGTH(self), maxcount
9941 );
9942 default:
9943 assert(0);
9944 return NULL;
9945 }
9946
9947 if (PyUnicode_READY(substring) == -1)
9948 return NULL;
9949
9950 kind1 = PyUnicode_KIND(self);
9951 kind2 = PyUnicode_KIND(substring);
9952 kind = kind1 > kind2 ? kind1 : kind2;
9953 buf1 = PyUnicode_DATA(self);
9954 buf2 = PyUnicode_DATA(substring);
9955 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009956 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009957 if (!buf1)
9958 return NULL;
9959 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009960 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009961 if (!buf2) {
9962 if (kind1 != kind) PyMem_Free(buf1);
9963 return NULL;
9964 }
9965 len1 = PyUnicode_GET_LENGTH(self);
9966 len2 = PyUnicode_GET_LENGTH(substring);
9967
Benjamin Petersonead6b532011-12-20 17:23:42 -06009968 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009969 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009970 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
9971 out = asciilib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009972 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +02009973 else
9974 out = ucs1lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009975 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009976 break;
9977 case PyUnicode_2BYTE_KIND:
9978 out = ucs2lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009979 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009980 break;
9981 case PyUnicode_4BYTE_KIND:
9982 out = ucs4lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009983 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009984 break;
9985 default:
9986 out = NULL;
9987 }
9988 if (kind1 != kind)
9989 PyMem_Free(buf1);
9990 if (kind2 != kind)
9991 PyMem_Free(buf2);
9992 return out;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009993}
9994
Alexander Belopolsky40018472011-02-26 01:02:56 +00009995static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009996rsplit(PyObject *self,
9997 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009998 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009999{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010000 int kind1, kind2, kind;
10001 void *buf1, *buf2;
10002 Py_ssize_t len1, len2;
10003 PyObject* out;
10004
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010005 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010006 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010007
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010008 if (PyUnicode_READY(self) == -1)
10009 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010010
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010011 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010012 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010013 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010014 if (PyUnicode_IS_ASCII(self))
10015 return asciilib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010016 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010017 PyUnicode_GET_LENGTH(self), maxcount
10018 );
10019 else
10020 return ucs1lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010021 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010022 PyUnicode_GET_LENGTH(self), maxcount
10023 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010024 case PyUnicode_2BYTE_KIND:
10025 return ucs2lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010026 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010027 PyUnicode_GET_LENGTH(self), maxcount
10028 );
10029 case PyUnicode_4BYTE_KIND:
10030 return ucs4lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010031 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010032 PyUnicode_GET_LENGTH(self), maxcount
10033 );
10034 default:
10035 assert(0);
10036 return NULL;
10037 }
10038
10039 if (PyUnicode_READY(substring) == -1)
10040 return NULL;
10041
10042 kind1 = PyUnicode_KIND(self);
10043 kind2 = PyUnicode_KIND(substring);
10044 kind = kind1 > kind2 ? kind1 : kind2;
10045 buf1 = PyUnicode_DATA(self);
10046 buf2 = PyUnicode_DATA(substring);
10047 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010048 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010049 if (!buf1)
10050 return NULL;
10051 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010052 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010053 if (!buf2) {
10054 if (kind1 != kind) PyMem_Free(buf1);
10055 return NULL;
10056 }
10057 len1 = PyUnicode_GET_LENGTH(self);
10058 len2 = PyUnicode_GET_LENGTH(substring);
10059
Benjamin Petersonead6b532011-12-20 17:23:42 -060010060 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010061 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010062 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10063 out = asciilib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010064 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010065 else
10066 out = ucs1lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010067 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010068 break;
10069 case PyUnicode_2BYTE_KIND:
10070 out = ucs2lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010071 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010072 break;
10073 case PyUnicode_4BYTE_KIND:
10074 out = ucs4lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010075 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010076 break;
10077 default:
10078 out = NULL;
10079 }
10080 if (kind1 != kind)
10081 PyMem_Free(buf1);
10082 if (kind2 != kind)
10083 PyMem_Free(buf2);
10084 return out;
10085}
10086
10087static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010088anylib_find(int kind, PyObject *str1, void *buf1, Py_ssize_t len1,
10089 PyObject *str2, void *buf2, Py_ssize_t len2, Py_ssize_t offset)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010090{
Benjamin Petersonead6b532011-12-20 17:23:42 -060010091 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010092 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010093 if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
10094 return asciilib_find(buf1, len1, buf2, len2, offset);
10095 else
10096 return ucs1lib_find(buf1, len1, buf2, len2, offset);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010097 case PyUnicode_2BYTE_KIND:
10098 return ucs2lib_find(buf1, len1, buf2, len2, offset);
10099 case PyUnicode_4BYTE_KIND:
10100 return ucs4lib_find(buf1, len1, buf2, len2, offset);
10101 }
10102 assert(0);
10103 return -1;
10104}
10105
10106static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010107anylib_count(int kind, PyObject *sstr, void* sbuf, Py_ssize_t slen,
10108 PyObject *str1, void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010109{
Benjamin Petersonc0b95d12011-12-20 17:24:05 -060010110 switch (kind) {
10111 case PyUnicode_1BYTE_KIND:
10112 if (PyUnicode_IS_ASCII(sstr) && PyUnicode_IS_ASCII(str1))
10113 return asciilib_count(sbuf, slen, buf1, len1, maxcount);
10114 else
10115 return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
10116 case PyUnicode_2BYTE_KIND:
10117 return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
10118 case PyUnicode_4BYTE_KIND:
10119 return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
10120 }
10121 assert(0);
10122 return 0;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010123}
10124
Alexander Belopolsky40018472011-02-26 01:02:56 +000010125static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010126replace(PyObject *self, PyObject *str1,
10127 PyObject *str2, Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010128{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010129 PyObject *u;
10130 char *sbuf = PyUnicode_DATA(self);
10131 char *buf1 = PyUnicode_DATA(str1);
10132 char *buf2 = PyUnicode_DATA(str2);
10133 int srelease = 0, release1 = 0, release2 = 0;
10134 int skind = PyUnicode_KIND(self);
10135 int kind1 = PyUnicode_KIND(str1);
10136 int kind2 = PyUnicode_KIND(str2);
10137 Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
10138 Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
10139 Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010140 int mayshrink;
10141 Py_UCS4 maxchar, maxchar_str2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010142
10143 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010144 maxcount = PY_SSIZE_T_MAX;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010145 else if (maxcount == 0 || slen == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010146 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010147
Victor Stinner59de0ee2011-10-07 10:01:28 +020010148 if (str1 == str2)
10149 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010150 if (skind < kind1)
10151 /* substring too wide to be present */
10152 goto nothing;
10153
Victor Stinner49a0a212011-10-12 23:46:10 +020010154 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
10155 maxchar_str2 = PyUnicode_MAX_CHAR_VALUE(str2);
10156 /* Replacing str1 with str2 may cause a maxchar reduction in the
10157 result string. */
10158 mayshrink = (maxchar_str2 < maxchar);
Victor Stinnere6abb482012-05-02 01:15:40 +020010159 maxchar = MAX_MAXCHAR(maxchar, maxchar_str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010160
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010161 if (len1 == len2) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010162 /* same length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010163 if (len1 == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010164 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010165 if (len1 == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010166 /* replace characters */
Victor Stinner49a0a212011-10-12 23:46:10 +020010167 Py_UCS4 u1, u2;
10168 int rkind;
Victor Stinnerf6441102011-12-18 02:43:08 +010010169 Py_ssize_t index, pos;
10170 char *src;
10171
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010172 u1 = PyUnicode_READ_CHAR(str1, 0);
Victor Stinnerf6441102011-12-18 02:43:08 +010010173 pos = findchar(sbuf, PyUnicode_KIND(self), slen, u1, 1);
10174 if (pos < 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010175 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010176 u2 = PyUnicode_READ_CHAR(str2, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010177 u = PyUnicode_New(slen, maxchar);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010178 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010179 goto error;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020010180 copy_characters(u, 0, self, 0, slen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010181 rkind = PyUnicode_KIND(u);
Victor Stinnerf6441102011-12-18 02:43:08 +010010182
10183 PyUnicode_WRITE(rkind, PyUnicode_DATA(u), pos, u2);
10184 index = 0;
10185 src = sbuf;
10186 while (--maxcount)
10187 {
10188 pos++;
10189 src += pos * PyUnicode_KIND(self);
10190 slen -= pos;
10191 index += pos;
10192 pos = findchar(src, PyUnicode_KIND(self), slen, u1, 1);
10193 if (pos < 0)
10194 break;
10195 PyUnicode_WRITE(rkind, PyUnicode_DATA(u), index + pos, u2);
10196 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010197 }
10198 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010199 int rkind = skind;
10200 char *res;
Victor Stinnerf6441102011-12-18 02:43:08 +010010201 Py_ssize_t i;
Victor Stinner25a4b292011-10-06 12:31:55 +020010202
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010203 if (kind1 < rkind) {
10204 /* widen substring */
10205 buf1 = _PyUnicode_AsKind(str1, rkind);
10206 if (!buf1) goto error;
10207 release1 = 1;
10208 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010209 i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010210 if (i < 0)
10211 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010212 if (rkind > kind2) {
10213 /* widen replacement */
10214 buf2 = _PyUnicode_AsKind(str2, rkind);
10215 if (!buf2) goto error;
10216 release2 = 1;
10217 }
10218 else if (rkind < kind2) {
10219 /* widen self and buf1 */
10220 rkind = kind2;
10221 if (release1) PyMem_Free(buf1);
10222 sbuf = _PyUnicode_AsKind(self, rkind);
10223 if (!sbuf) goto error;
10224 srelease = 1;
10225 buf1 = _PyUnicode_AsKind(str1, rkind);
10226 if (!buf1) goto error;
10227 release1 = 1;
10228 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010229 u = PyUnicode_New(slen, maxchar);
10230 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010231 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010232 assert(PyUnicode_KIND(u) == rkind);
10233 res = PyUnicode_DATA(u);
Victor Stinner25a4b292011-10-06 12:31:55 +020010234
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010235 memcpy(res, sbuf, rkind * slen);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010236 /* change everything in-place, starting with this one */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010237 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010238 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010239 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010240 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010241
10242 while ( --maxcount > 0) {
Victor Stinnerc3cec782011-10-05 21:24:08 +020010243 i = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010244 sbuf+rkind*i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010245 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010246 if (i == -1)
10247 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010248 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010249 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010250 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010251 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010252 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010253 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010254 }
10255 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010256 Py_ssize_t n, i, j, ires;
10257 Py_ssize_t product, new_size;
10258 int rkind = skind;
10259 char *res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010260
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010261 if (kind1 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010262 /* widen substring */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010263 buf1 = _PyUnicode_AsKind(str1, rkind);
10264 if (!buf1) goto error;
10265 release1 = 1;
10266 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010267 n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010268 if (n == 0)
10269 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010270 if (kind2 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010271 /* widen replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010272 buf2 = _PyUnicode_AsKind(str2, rkind);
10273 if (!buf2) goto error;
10274 release2 = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010275 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010276 else if (kind2 > rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010277 /* widen self and buf1 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010278 rkind = kind2;
10279 sbuf = _PyUnicode_AsKind(self, rkind);
10280 if (!sbuf) goto error;
10281 srelease = 1;
10282 if (release1) PyMem_Free(buf1);
10283 buf1 = _PyUnicode_AsKind(str1, rkind);
10284 if (!buf1) goto error;
10285 release1 = 1;
10286 }
10287 /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
10288 PyUnicode_GET_LENGTH(str1))); */
10289 product = n * (len2-len1);
10290 if ((product / (len2-len1)) != n) {
10291 PyErr_SetString(PyExc_OverflowError,
10292 "replace string is too long");
10293 goto error;
10294 }
10295 new_size = slen + product;
Victor Stinner49a0a212011-10-12 23:46:10 +020010296 if (new_size == 0) {
10297 Py_INCREF(unicode_empty);
10298 u = unicode_empty;
10299 goto done;
10300 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010301 if (new_size < 0 || new_size > (PY_SSIZE_T_MAX >> (rkind-1))) {
10302 PyErr_SetString(PyExc_OverflowError,
10303 "replace string is too long");
10304 goto error;
10305 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010306 u = PyUnicode_New(new_size, maxchar);
10307 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010308 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010309 assert(PyUnicode_KIND(u) == rkind);
10310 res = PyUnicode_DATA(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010311 ires = i = 0;
10312 if (len1 > 0) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010313 while (n-- > 0) {
10314 /* look for next match */
Victor Stinnerc3cec782011-10-05 21:24:08 +020010315 j = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010316 sbuf + rkind * i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010317 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010318 if (j == -1)
10319 break;
10320 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010321 /* copy unchanged part [i:j] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010322 memcpy(res + rkind * ires,
10323 sbuf + rkind * i,
10324 rkind * (j-i));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010325 ires += j - i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010326 }
10327 /* copy substitution string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010328 if (len2 > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010329 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010330 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010331 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010332 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010333 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010334 i = j + len1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010335 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010336 if (i < slen)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010337 /* copy tail [i:] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010338 memcpy(res + rkind * ires,
10339 sbuf + rkind * i,
10340 rkind * (slen-i));
Victor Stinner49a0a212011-10-12 23:46:10 +020010341 }
10342 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010343 /* interleave */
10344 while (n > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010345 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010346 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010347 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010348 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010349 if (--n <= 0)
10350 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010351 memcpy(res + rkind * ires,
10352 sbuf + rkind * i,
10353 rkind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010354 ires++;
10355 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010356 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010357 memcpy(res + rkind * ires,
10358 sbuf + rkind * i,
10359 rkind * (slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +000010360 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010361 }
10362
10363 if (mayshrink) {
Victor Stinner25a4b292011-10-06 12:31:55 +020010364 unicode_adjust_maxchar(&u);
10365 if (u == NULL)
10366 goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010367 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010368
10369 done:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010370 if (srelease)
10371 PyMem_FREE(sbuf);
10372 if (release1)
10373 PyMem_FREE(buf1);
10374 if (release2)
10375 PyMem_FREE(buf2);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010376 assert(_PyUnicode_CheckConsistency(u, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010377 return u;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010378
Benjamin Peterson29060642009-01-31 22:14:21 +000010379 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +000010380 /* nothing to replace; return original string (when possible) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010381 if (srelease)
10382 PyMem_FREE(sbuf);
10383 if (release1)
10384 PyMem_FREE(buf1);
10385 if (release2)
10386 PyMem_FREE(buf2);
Victor Stinnerc4b49542011-12-11 22:44:26 +010010387 return unicode_result_unchanged(self);
10388
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010389 error:
10390 if (srelease && sbuf)
10391 PyMem_FREE(sbuf);
10392 if (release1 && buf1)
10393 PyMem_FREE(buf1);
10394 if (release2 && buf2)
10395 PyMem_FREE(buf2);
10396 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010397}
10398
10399/* --- Unicode Object Methods --------------------------------------------- */
10400
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010401PyDoc_STRVAR(title__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010402 "S.title() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010403\n\
10404Return a titlecased version of S, i.e. words start with title case\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010405characters, all remaining cased characters have lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010406
10407static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010408unicode_title(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010409{
Benjamin Petersoneea48462012-01-16 14:28:50 -050010410 if (PyUnicode_READY(self) == -1)
10411 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010412 return case_operation(self, do_title);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010413}
10414
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010415PyDoc_STRVAR(capitalize__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010416 "S.capitalize() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010417\n\
10418Return a capitalized version of S, i.e. make the first character\n\
Senthil Kumarane51ee8a2010-07-05 12:00:56 +000010419have upper case and the rest lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010420
10421static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010422unicode_capitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010423{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050010424 if (PyUnicode_READY(self) == -1)
10425 return NULL;
10426 if (PyUnicode_GET_LENGTH(self) == 0)
10427 return unicode_result_unchanged(self);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010428 return case_operation(self, do_capitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010429}
10430
Benjamin Petersond5890c82012-01-14 13:23:30 -050010431PyDoc_STRVAR(casefold__doc__,
10432 "S.casefold() -> str\n\
10433\n\
10434Return a version of S suitable for caseless comparisons.");
10435
10436static PyObject *
10437unicode_casefold(PyObject *self)
10438{
10439 if (PyUnicode_READY(self) == -1)
10440 return NULL;
10441 if (PyUnicode_IS_ASCII(self))
10442 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010443 return case_operation(self, do_casefold);
Benjamin Petersond5890c82012-01-14 13:23:30 -050010444}
10445
10446
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010447/* Argument converter. Coerces to a single unicode character */
10448
10449static int
10450convert_uc(PyObject *obj, void *addr)
10451{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010452 Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010453 PyObject *uniobj;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010454
Benjamin Peterson14339b62009-01-31 16:36:08 +000010455 uniobj = PyUnicode_FromObject(obj);
10456 if (uniobj == NULL) {
10457 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010458 "The fill character cannot be converted to Unicode");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010459 return 0;
10460 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010461 if (PyUnicode_GET_LENGTH(uniobj) != 1) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010462 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010463 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010464 Py_DECREF(uniobj);
10465 return 0;
10466 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010467 *fillcharloc = PyUnicode_READ_CHAR(uniobj, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010468 Py_DECREF(uniobj);
10469 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010470}
10471
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010472PyDoc_STRVAR(center__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010473 "S.center(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010474\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010475Return S centered in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010476done using the specified fill character (default is a space)");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010477
10478static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010479unicode_center(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010480{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010481 Py_ssize_t marg, left;
10482 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010483 Py_UCS4 fillchar = ' ';
10484
Victor Stinnere9a29352011-10-01 02:14:59 +020010485 if (!PyArg_ParseTuple(args, "n|O&:center", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010486 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010487
Benjamin Petersonbac79492012-01-14 13:34:47 -050010488 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010489 return NULL;
10490
Victor Stinnerc4b49542011-12-11 22:44:26 +010010491 if (PyUnicode_GET_LENGTH(self) >= width)
10492 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010493
Victor Stinnerc4b49542011-12-11 22:44:26 +010010494 marg = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010495 left = marg / 2 + (marg & width & 1);
10496
Victor Stinner9310abb2011-10-05 00:59:23 +020010497 return pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010498}
10499
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010500/* This function assumes that str1 and str2 are readied by the caller. */
10501
Marc-André Lemburge5034372000-08-08 08:04:29 +000010502static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010503unicode_compare(PyObject *str1, PyObject *str2)
Marc-André Lemburge5034372000-08-08 08:04:29 +000010504{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010505 int kind1, kind2;
10506 void *data1, *data2;
10507 Py_ssize_t len1, len2, i;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010508
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010509 kind1 = PyUnicode_KIND(str1);
10510 kind2 = PyUnicode_KIND(str2);
10511 data1 = PyUnicode_DATA(str1);
10512 data2 = PyUnicode_DATA(str2);
10513 len1 = PyUnicode_GET_LENGTH(str1);
10514 len2 = PyUnicode_GET_LENGTH(str2);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010515
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010516 for (i = 0; i < len1 && i < len2; ++i) {
10517 Py_UCS4 c1, c2;
10518 c1 = PyUnicode_READ(kind1, data1, i);
10519 c2 = PyUnicode_READ(kind2, data2, i);
Fredrik Lundh45714e92001-06-26 16:39:36 +000010520
10521 if (c1 != c2)
10522 return (c1 < c2) ? -1 : 1;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010523 }
10524
10525 return (len1 < len2) ? -1 : (len1 != len2);
10526}
10527
Alexander Belopolsky40018472011-02-26 01:02:56 +000010528int
10529PyUnicode_Compare(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010530{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010531 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10532 if (PyUnicode_READY(left) == -1 ||
10533 PyUnicode_READY(right) == -1)
10534 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010535 return unicode_compare(left, right);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010536 }
Guido van Rossum09dc34f2007-05-04 04:17:33 +000010537 PyErr_Format(PyExc_TypeError,
10538 "Can't compare %.100s and %.100s",
10539 left->ob_type->tp_name,
10540 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010541 return -1;
10542}
10543
Martin v. Löwis5b222132007-06-10 09:51:05 +000010544int
10545PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
10546{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010547 Py_ssize_t i;
10548 int kind;
10549 void *data;
10550 Py_UCS4 chr;
10551
Victor Stinner910337b2011-10-03 03:20:16 +020010552 assert(_PyUnicode_CHECK(uni));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010553 if (PyUnicode_READY(uni) == -1)
10554 return -1;
10555 kind = PyUnicode_KIND(uni);
10556 data = PyUnicode_DATA(uni);
Martin v. Löwis5b222132007-06-10 09:51:05 +000010557 /* Compare Unicode string and source character set string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010558 for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
10559 if (chr != str[i])
10560 return (chr < (unsigned char)(str[i])) ? -1 : 1;
Benjamin Peterson8667a9b2010-01-09 21:45:28 +000010561 /* This check keeps Python strings that end in '\0' from comparing equal
10562 to C strings identical up to that point. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010563 if (PyUnicode_GET_LENGTH(uni) != i || chr)
Benjamin Peterson29060642009-01-31 22:14:21 +000010564 return 1; /* uni is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010565 if (str[i])
Benjamin Peterson29060642009-01-31 22:14:21 +000010566 return -1; /* str is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010567 return 0;
10568}
10569
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010570
Benjamin Peterson29060642009-01-31 22:14:21 +000010571#define TEST_COND(cond) \
Benjamin Peterson14339b62009-01-31 16:36:08 +000010572 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010573
Alexander Belopolsky40018472011-02-26 01:02:56 +000010574PyObject *
10575PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010576{
10577 int result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010578
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010579 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10580 PyObject *v;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010581 if (PyUnicode_READY(left) == -1 ||
10582 PyUnicode_READY(right) == -1)
10583 return NULL;
10584 if (PyUnicode_GET_LENGTH(left) != PyUnicode_GET_LENGTH(right) ||
10585 PyUnicode_KIND(left) != PyUnicode_KIND(right)) {
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010586 if (op == Py_EQ) {
10587 Py_INCREF(Py_False);
10588 return Py_False;
10589 }
10590 if (op == Py_NE) {
10591 Py_INCREF(Py_True);
10592 return Py_True;
10593 }
10594 }
10595 if (left == right)
10596 result = 0;
10597 else
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010598 result = unicode_compare(left, right);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010599
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010600 /* Convert the return value to a Boolean */
10601 switch (op) {
10602 case Py_EQ:
10603 v = TEST_COND(result == 0);
10604 break;
10605 case Py_NE:
10606 v = TEST_COND(result != 0);
10607 break;
10608 case Py_LE:
10609 v = TEST_COND(result <= 0);
10610 break;
10611 case Py_GE:
10612 v = TEST_COND(result >= 0);
10613 break;
10614 case Py_LT:
10615 v = TEST_COND(result == -1);
10616 break;
10617 case Py_GT:
10618 v = TEST_COND(result == 1);
10619 break;
10620 default:
10621 PyErr_BadArgument();
10622 return NULL;
10623 }
10624 Py_INCREF(v);
10625 return v;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010626 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000010627
Brian Curtindfc80e32011-08-10 20:28:54 -050010628 Py_RETURN_NOTIMPLEMENTED;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010629}
10630
Alexander Belopolsky40018472011-02-26 01:02:56 +000010631int
10632PyUnicode_Contains(PyObject *container, PyObject *element)
Guido van Rossum403d68b2000-03-13 15:55:09 +000010633{
Thomas Wouters477c8d52006-05-27 19:21:47 +000010634 PyObject *str, *sub;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010635 int kind1, kind2, kind;
10636 void *buf1, *buf2;
10637 Py_ssize_t len1, len2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010638 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010639
10640 /* Coerce the two arguments */
Thomas Wouters477c8d52006-05-27 19:21:47 +000010641 sub = PyUnicode_FromObject(element);
10642 if (!sub) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010643 PyErr_Format(PyExc_TypeError,
10644 "'in <string>' requires string as left operand, not %s",
10645 element->ob_type->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010646 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010647 }
10648
Thomas Wouters477c8d52006-05-27 19:21:47 +000010649 str = PyUnicode_FromObject(container);
Benjamin Peterson22a29702012-01-02 09:00:30 -060010650 if (!str) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010651 Py_DECREF(sub);
10652 return -1;
10653 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060010654 if (PyUnicode_READY(sub) == -1 || PyUnicode_READY(str) == -1) {
10655 Py_DECREF(sub);
10656 Py_DECREF(str);
10657 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000010658
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010659 kind1 = PyUnicode_KIND(str);
10660 kind2 = PyUnicode_KIND(sub);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010661 kind = kind1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010662 buf1 = PyUnicode_DATA(str);
10663 buf2 = PyUnicode_DATA(sub);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010664 if (kind2 != kind) {
Antoine Pitrou758153b2012-05-12 15:51:51 +020010665 if (kind2 > kind) {
10666 Py_DECREF(sub);
10667 Py_DECREF(str);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010668 return 0;
Antoine Pitrou758153b2012-05-12 15:51:51 +020010669 }
Victor Stinner7931d9a2011-11-04 00:22:48 +010010670 buf2 = _PyUnicode_AsKind(sub, kind);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010671 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010672 if (!buf2) {
10673 Py_DECREF(sub);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010674 Py_DECREF(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010675 return -1;
10676 }
10677 len1 = PyUnicode_GET_LENGTH(str);
10678 len2 = PyUnicode_GET_LENGTH(sub);
10679
Benjamin Petersonead6b532011-12-20 17:23:42 -060010680 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010681 case PyUnicode_1BYTE_KIND:
10682 result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
10683 break;
10684 case PyUnicode_2BYTE_KIND:
10685 result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
10686 break;
10687 case PyUnicode_4BYTE_KIND:
10688 result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
10689 break;
10690 default:
10691 result = -1;
10692 assert(0);
10693 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000010694
10695 Py_DECREF(str);
10696 Py_DECREF(sub);
10697
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010698 if (kind2 != kind)
10699 PyMem_Free(buf2);
10700
Guido van Rossum403d68b2000-03-13 15:55:09 +000010701 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010702}
10703
Guido van Rossumd57fd912000-03-10 22:53:23 +000010704/* Concat to string or Unicode object giving a new Unicode object. */
10705
Alexander Belopolsky40018472011-02-26 01:02:56 +000010706PyObject *
10707PyUnicode_Concat(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010708{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010709 PyObject *u = NULL, *v = NULL, *w;
Victor Stinner127226b2011-10-13 01:12:34 +020010710 Py_UCS4 maxchar, maxchar2;
Victor Stinner488fa492011-12-12 00:01:39 +010010711 Py_ssize_t u_len, v_len, new_len;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010712
10713 /* Coerce the two arguments */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010714 u = PyUnicode_FromObject(left);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010715 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010716 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010717 v = PyUnicode_FromObject(right);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010718 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010719 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010720
10721 /* Shortcuts */
Victor Stinnera464fc12011-10-02 20:39:30 +020010722 if (v == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010723 Py_DECREF(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010724 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010725 }
Victor Stinnera464fc12011-10-02 20:39:30 +020010726 if (u == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010727 Py_DECREF(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010728 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010729 }
10730
Victor Stinner488fa492011-12-12 00:01:39 +010010731 u_len = PyUnicode_GET_LENGTH(u);
10732 v_len = PyUnicode_GET_LENGTH(v);
10733 if (u_len > PY_SSIZE_T_MAX - v_len) {
10734 PyErr_SetString(PyExc_OverflowError,
10735 "strings are too large to concat");
10736 goto onError;
10737 }
10738 new_len = u_len + v_len;
10739
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010740 maxchar = PyUnicode_MAX_CHAR_VALUE(u);
Victor Stinner127226b2011-10-13 01:12:34 +020010741 maxchar2 = PyUnicode_MAX_CHAR_VALUE(v);
Victor Stinnere6abb482012-05-02 01:15:40 +020010742 maxchar = MAX_MAXCHAR(maxchar, maxchar2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010743
Guido van Rossumd57fd912000-03-10 22:53:23 +000010744 /* Concat the two Unicode strings */
Victor Stinner488fa492011-12-12 00:01:39 +010010745 w = PyUnicode_New(new_len, maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010746 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010747 goto onError;
Victor Stinner488fa492011-12-12 00:01:39 +010010748 copy_characters(w, 0, u, 0, u_len);
10749 copy_characters(w, u_len, v, 0, v_len);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010750 Py_DECREF(u);
10751 Py_DECREF(v);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010752 assert(_PyUnicode_CheckConsistency(w, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010753 return w;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010754
Benjamin Peterson29060642009-01-31 22:14:21 +000010755 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000010756 Py_XDECREF(u);
10757 Py_XDECREF(v);
10758 return NULL;
10759}
10760
Walter Dörwald1ab83302007-05-18 17:15:44 +000010761void
Victor Stinner23e56682011-10-03 03:54:37 +020010762PyUnicode_Append(PyObject **p_left, PyObject *right)
Walter Dörwald1ab83302007-05-18 17:15:44 +000010763{
Victor Stinner23e56682011-10-03 03:54:37 +020010764 PyObject *left, *res;
Victor Stinner488fa492011-12-12 00:01:39 +010010765 Py_UCS4 maxchar, maxchar2;
10766 Py_ssize_t left_len, right_len, new_len;
Victor Stinner23e56682011-10-03 03:54:37 +020010767
10768 if (p_left == NULL) {
10769 if (!PyErr_Occurred())
10770 PyErr_BadInternalCall();
Benjamin Peterson14339b62009-01-31 16:36:08 +000010771 return;
10772 }
Victor Stinner23e56682011-10-03 03:54:37 +020010773 left = *p_left;
10774 if (right == NULL || !PyUnicode_Check(left)) {
10775 if (!PyErr_Occurred())
10776 PyErr_BadInternalCall();
10777 goto error;
10778 }
10779
Benjamin Petersonbac79492012-01-14 13:34:47 -050010780 if (PyUnicode_READY(left) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020010781 goto error;
Benjamin Petersonbac79492012-01-14 13:34:47 -050010782 if (PyUnicode_READY(right) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020010783 goto error;
10784
Victor Stinner488fa492011-12-12 00:01:39 +010010785 /* Shortcuts */
10786 if (left == unicode_empty) {
10787 Py_DECREF(left);
10788 Py_INCREF(right);
10789 *p_left = right;
10790 return;
10791 }
10792 if (right == unicode_empty)
10793 return;
10794
10795 left_len = PyUnicode_GET_LENGTH(left);
10796 right_len = PyUnicode_GET_LENGTH(right);
10797 if (left_len > PY_SSIZE_T_MAX - right_len) {
10798 PyErr_SetString(PyExc_OverflowError,
10799 "strings are too large to concat");
10800 goto error;
10801 }
10802 new_len = left_len + right_len;
10803
10804 if (unicode_modifiable(left)
10805 && PyUnicode_CheckExact(right)
10806 && PyUnicode_KIND(right) <= PyUnicode_KIND(left)
Victor Stinnerb0923652011-10-04 01:17:31 +020010807 /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
10808 to change the structure size, but characters are stored just after
Georg Brandl7597add2011-10-05 16:36:47 +020010809 the structure, and so it requires to move all characters which is
Victor Stinnerb0923652011-10-04 01:17:31 +020010810 not so different than duplicating the string. */
Victor Stinner488fa492011-12-12 00:01:39 +010010811 && !(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
10812 {
10813 /* append inplace */
10814 if (unicode_resize(p_left, new_len) != 0) {
10815 /* XXX if _PyUnicode_Resize() fails, 'left' has been
10816 * deallocated so it cannot be put back into
10817 * 'variable'. The MemoryError is raised when there
10818 * is no value in 'variable', which might (very
10819 * remotely) be a cause of incompatibilities.
10820 */
10821 goto error;
Victor Stinner23e56682011-10-03 03:54:37 +020010822 }
Victor Stinner488fa492011-12-12 00:01:39 +010010823 /* copy 'right' into the newly allocated area of 'left' */
10824 copy_characters(*p_left, left_len, right, 0, right_len);
Victor Stinner23e56682011-10-03 03:54:37 +020010825 }
Victor Stinner488fa492011-12-12 00:01:39 +010010826 else {
10827 maxchar = PyUnicode_MAX_CHAR_VALUE(left);
10828 maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
Victor Stinnere6abb482012-05-02 01:15:40 +020010829 maxchar = MAX_MAXCHAR(maxchar, maxchar2);
Victor Stinner23e56682011-10-03 03:54:37 +020010830
Victor Stinner488fa492011-12-12 00:01:39 +010010831 /* Concat the two Unicode strings */
10832 res = PyUnicode_New(new_len, maxchar);
10833 if (res == NULL)
10834 goto error;
10835 copy_characters(res, 0, left, 0, left_len);
10836 copy_characters(res, left_len, right, 0, right_len);
10837 Py_DECREF(left);
10838 *p_left = res;
10839 }
10840 assert(_PyUnicode_CheckConsistency(*p_left, 1));
Victor Stinner23e56682011-10-03 03:54:37 +020010841 return;
10842
10843error:
Victor Stinner488fa492011-12-12 00:01:39 +010010844 Py_CLEAR(*p_left);
Walter Dörwald1ab83302007-05-18 17:15:44 +000010845}
10846
10847void
10848PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
10849{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010850 PyUnicode_Append(pleft, right);
10851 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +000010852}
10853
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010854PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010855 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010856\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000010857Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010858string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010859interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010860
10861static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010862unicode_count(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010863{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010864 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010865 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010866 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010867 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010868 int kind1, kind2, kind;
10869 void *buf1, *buf2;
10870 Py_ssize_t len1, len2, iresult;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010871
Jesus Ceaac451502011-04-20 17:09:23 +020010872 if (!stringlib_parse_args_finds_unicode("count", args, &substring,
10873 &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000010874 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000010875
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010876 kind1 = PyUnicode_KIND(self);
10877 kind2 = PyUnicode_KIND(substring);
Benjamin Petersonb63f49f2012-05-03 18:31:07 -040010878 if (kind2 > kind1)
10879 return PyLong_FromLong(0);
10880 kind = kind1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010881 buf1 = PyUnicode_DATA(self);
10882 buf2 = PyUnicode_DATA(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010883 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010884 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010885 if (!buf2) {
10886 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010887 return NULL;
10888 }
10889 len1 = PyUnicode_GET_LENGTH(self);
10890 len2 = PyUnicode_GET_LENGTH(substring);
10891
10892 ADJUST_INDICES(start, end, len1);
Benjamin Petersonead6b532011-12-20 17:23:42 -060010893 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010894 case PyUnicode_1BYTE_KIND:
10895 iresult = ucs1lib_count(
10896 ((Py_UCS1*)buf1) + start, end - start,
10897 buf2, len2, PY_SSIZE_T_MAX
10898 );
10899 break;
10900 case PyUnicode_2BYTE_KIND:
10901 iresult = ucs2lib_count(
10902 ((Py_UCS2*)buf1) + start, end - start,
10903 buf2, len2, PY_SSIZE_T_MAX
10904 );
10905 break;
10906 case PyUnicode_4BYTE_KIND:
10907 iresult = ucs4lib_count(
10908 ((Py_UCS4*)buf1) + start, end - start,
10909 buf2, len2, PY_SSIZE_T_MAX
10910 );
10911 break;
10912 default:
10913 assert(0); iresult = 0;
10914 }
10915
10916 result = PyLong_FromSsize_t(iresult);
10917
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010918 if (kind2 != kind)
10919 PyMem_Free(buf2);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010920
10921 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010922
Guido van Rossumd57fd912000-03-10 22:53:23 +000010923 return result;
10924}
10925
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010926PyDoc_STRVAR(encode__doc__,
Victor Stinnerc911bbf2010-11-07 19:04:46 +000010927 "S.encode(encoding='utf-8', errors='strict') -> bytes\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010928\n\
Victor Stinnere14e2122010-11-07 18:41:46 +000010929Encode S using the codec registered for encoding. Default encoding\n\
10930is 'utf-8'. errors may be given to set a different error\n\
Fred Drakee4315f52000-05-09 19:53:39 +000010931handling scheme. Default is 'strict' meaning that encoding errors raise\n\
Walter Dörwald3aeb6322002-09-02 13:14:32 +000010932a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
10933'xmlcharrefreplace' as well as any other name registered with\n\
10934codecs.register_error that can handle UnicodeEncodeErrors.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010935
10936static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010937unicode_encode(PyObject *self, PyObject *args, PyObject *kwargs)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010938{
Benjamin Peterson308d6372009-09-18 21:42:35 +000010939 static char *kwlist[] = {"encoding", "errors", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000010940 char *encoding = NULL;
10941 char *errors = NULL;
Guido van Rossum35d94282007-08-27 18:20:11 +000010942
Benjamin Peterson308d6372009-09-18 21:42:35 +000010943 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:encode",
10944 kwlist, &encoding, &errors))
Guido van Rossumd57fd912000-03-10 22:53:23 +000010945 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010946 return PyUnicode_AsEncodedString(self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +000010947}
10948
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010949PyDoc_STRVAR(expandtabs__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010950 "S.expandtabs([tabsize]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010951\n\
10952Return a copy of S where all tab characters are expanded using spaces.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010953If tabsize is not given, a tab size of 8 characters is assumed.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010954
10955static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010956unicode_expandtabs(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010957{
Antoine Pitroue71d5742011-10-04 15:55:09 +020010958 Py_ssize_t i, j, line_pos, src_len, incr;
10959 Py_UCS4 ch;
10960 PyObject *u;
10961 void *src_data, *dest_data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010962 int tabsize = 8;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010963 int kind;
Antoine Pitroue19aa382011-10-04 16:04:01 +020010964 int found;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010965
10966 if (!PyArg_ParseTuple(args, "|i:expandtabs", &tabsize))
Benjamin Peterson29060642009-01-31 22:14:21 +000010967 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010968
Antoine Pitrou22425222011-10-04 19:10:51 +020010969 if (PyUnicode_READY(self) == -1)
10970 return NULL;
10971
Thomas Wouters7e474022000-07-16 12:04:32 +000010972 /* First pass: determine size of output string */
Antoine Pitroue71d5742011-10-04 15:55:09 +020010973 src_len = PyUnicode_GET_LENGTH(self);
10974 i = j = line_pos = 0;
10975 kind = PyUnicode_KIND(self);
10976 src_data = PyUnicode_DATA(self);
Antoine Pitroue19aa382011-10-04 16:04:01 +020010977 found = 0;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010978 for (; i < src_len; i++) {
10979 ch = PyUnicode_READ(kind, src_data, i);
10980 if (ch == '\t') {
Antoine Pitroue19aa382011-10-04 16:04:01 +020010981 found = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000010982 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020010983 incr = tabsize - (line_pos % tabsize); /* cannot overflow */
Benjamin Peterson29060642009-01-31 22:14:21 +000010984 if (j > PY_SSIZE_T_MAX - incr)
Antoine Pitroue71d5742011-10-04 15:55:09 +020010985 goto overflow;
10986 line_pos += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000010987 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010988 }
Benjamin Peterson29060642009-01-31 22:14:21 +000010989 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010990 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000010991 if (j > PY_SSIZE_T_MAX - 1)
Antoine Pitroue71d5742011-10-04 15:55:09 +020010992 goto overflow;
10993 line_pos++;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010994 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010995 if (ch == '\n' || ch == '\r')
10996 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010997 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020010998 }
Victor Stinnerc4b49542011-12-11 22:44:26 +010010999 if (!found)
11000 return unicode_result_unchanged(self);
Guido van Rossumcd16bf62007-06-13 18:07:49 +000011001
Guido van Rossumd57fd912000-03-10 22:53:23 +000011002 /* Second pass: create output string and fill it */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011003 u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011004 if (!u)
11005 return NULL;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011006 dest_data = PyUnicode_DATA(u);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011007
Antoine Pitroue71d5742011-10-04 15:55:09 +020011008 i = j = line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011009
Antoine Pitroue71d5742011-10-04 15:55:09 +020011010 for (; i < src_len; i++) {
11011 ch = PyUnicode_READ(kind, src_data, i);
11012 if (ch == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +000011013 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011014 incr = tabsize - (line_pos % tabsize);
11015 line_pos += incr;
Victor Stinnerda79e632012-02-22 13:37:04 +010011016 FILL(kind, dest_data, ' ', j, incr);
11017 j += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011018 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011019 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011020 else {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011021 line_pos++;
11022 PyUnicode_WRITE(kind, dest_data, j, ch);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011023 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011024 if (ch == '\n' || ch == '\r')
11025 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011026 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011027 }
11028 assert (j == PyUnicode_GET_LENGTH(u));
Victor Stinnerd3df8ab2011-11-22 01:22:34 +010011029 return unicode_result(u);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011030
Antoine Pitroue71d5742011-10-04 15:55:09 +020011031 overflow:
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011032 PyErr_SetString(PyExc_OverflowError, "new string is too long");
11033 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011034}
11035
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011036PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011037 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011038\n\
11039Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080011040such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011041arguments start and end are interpreted as in slice notation.\n\
11042\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011043Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011044
11045static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011046unicode_find(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011047{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011048 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011049 Py_ssize_t start;
11050 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011051 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011052
Jesus Ceaac451502011-04-20 17:09:23 +020011053 if (!stringlib_parse_args_finds_unicode("find", args, &substring,
11054 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011055 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011056
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011057 if (PyUnicode_READY(self) == -1)
11058 return NULL;
11059 if (PyUnicode_READY(substring) == -1)
11060 return NULL;
11061
Victor Stinner7931d9a2011-11-04 00:22:48 +010011062 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011063
11064 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011065
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011066 if (result == -2)
11067 return NULL;
11068
Christian Heimes217cfd12007-12-02 14:31:20 +000011069 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011070}
11071
11072static PyObject *
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011073unicode_getitem(PyObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011074{
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011075 void *data;
11076 enum PyUnicode_Kind kind;
11077 Py_UCS4 ch;
11078 PyObject *res;
11079
11080 if (!PyUnicode_Check(self) || PyUnicode_READY(self) == -1) {
11081 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011082 return NULL;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011083 }
11084 if (index < 0 || index >= PyUnicode_GET_LENGTH(self)) {
11085 PyErr_SetString(PyExc_IndexError, "string index out of range");
11086 return NULL;
11087 }
11088 kind = PyUnicode_KIND(self);
11089 data = PyUnicode_DATA(self);
11090 ch = PyUnicode_READ(kind, data, index);
11091 if (ch < 256)
11092 return get_latin1_char(ch);
11093
11094 res = PyUnicode_New(1, ch);
11095 if (res == NULL)
11096 return NULL;
11097 kind = PyUnicode_KIND(res);
11098 data = PyUnicode_DATA(res);
11099 PyUnicode_WRITE(kind, data, 0, ch);
11100 assert(_PyUnicode_CheckConsistency(res, 1));
11101 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011102}
11103
Guido van Rossumc2504932007-09-18 19:42:40 +000011104/* Believe it or not, this produces the same value for ASCII strings
Mark Dickinson57e683e2011-09-24 18:18:40 +010011105 as bytes_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +000011106static Py_hash_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011107unicode_hash(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011108{
Guido van Rossumc2504932007-09-18 19:42:40 +000011109 Py_ssize_t len;
Mark Dickinson57e683e2011-09-24 18:18:40 +010011110 Py_uhash_t x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011111
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011112#ifdef Py_DEBUG
Benjamin Peterson69e97272012-02-21 11:08:50 -050011113 assert(_Py_HashSecret_Initialized);
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011114#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011115 if (_PyUnicode_HASH(self) != -1)
11116 return _PyUnicode_HASH(self);
11117 if (PyUnicode_READY(self) == -1)
11118 return -1;
11119 len = PyUnicode_GET_LENGTH(self);
Georg Brandl16fa2a12012-02-21 00:50:13 +010011120 /*
11121 We make the hash of the empty string be 0, rather than using
11122 (prefix ^ suffix), since this slightly obfuscates the hash secret
11123 */
11124 if (len == 0) {
11125 _PyUnicode_HASH(self) = 0;
11126 return 0;
11127 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011128
11129 /* The hash function as a macro, gets expanded three times below. */
Georg Brandl2fb477c2012-02-21 00:33:36 +010011130#define HASH(P) \
11131 x ^= (Py_uhash_t) *P << 7; \
11132 while (--len >= 0) \
11133 x = (_PyHASH_MULTIPLIER * x) ^ (Py_uhash_t) *P++; \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011134
Georg Brandl2fb477c2012-02-21 00:33:36 +010011135 x = (Py_uhash_t) _Py_HashSecret.prefix;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011136 switch (PyUnicode_KIND(self)) {
11137 case PyUnicode_1BYTE_KIND: {
11138 const unsigned char *c = PyUnicode_1BYTE_DATA(self);
11139 HASH(c);
11140 break;
11141 }
11142 case PyUnicode_2BYTE_KIND: {
11143 const Py_UCS2 *s = PyUnicode_2BYTE_DATA(self);
11144 HASH(s);
11145 break;
11146 }
11147 default: {
11148 Py_UCS4 *l;
11149 assert(PyUnicode_KIND(self) == PyUnicode_4BYTE_KIND &&
11150 "Impossible switch case in unicode_hash");
11151 l = PyUnicode_4BYTE_DATA(self);
11152 HASH(l);
11153 break;
11154 }
11155 }
Georg Brandl2fb477c2012-02-21 00:33:36 +010011156 x ^= (Py_uhash_t) PyUnicode_GET_LENGTH(self);
11157 x ^= (Py_uhash_t) _Py_HashSecret.suffix;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011158
Guido van Rossumc2504932007-09-18 19:42:40 +000011159 if (x == -1)
11160 x = -2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011161 _PyUnicode_HASH(self) = x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011162 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011163}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011164#undef HASH
Guido van Rossumd57fd912000-03-10 22:53:23 +000011165
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011166PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011167 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011168\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011169Like S.find() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011170
11171static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011172unicode_index(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011173{
Martin v. Löwis18e16552006-02-15 17:27:45 +000011174 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011175 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011176 Py_ssize_t start;
11177 Py_ssize_t end;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011178
Jesus Ceaac451502011-04-20 17:09:23 +020011179 if (!stringlib_parse_args_finds_unicode("index", args, &substring,
11180 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011181 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011182
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011183 if (PyUnicode_READY(self) == -1)
11184 return NULL;
11185 if (PyUnicode_READY(substring) == -1)
11186 return NULL;
11187
Victor Stinner7931d9a2011-11-04 00:22:48 +010011188 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011189
11190 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011191
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011192 if (result == -2)
11193 return NULL;
11194
Guido van Rossumd57fd912000-03-10 22:53:23 +000011195 if (result < 0) {
11196 PyErr_SetString(PyExc_ValueError, "substring not found");
11197 return NULL;
11198 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011199
Christian Heimes217cfd12007-12-02 14:31:20 +000011200 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011201}
11202
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011203PyDoc_STRVAR(islower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011204 "S.islower() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011205\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011206Return True if all cased characters in S are lowercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011207at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011208
11209static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011210unicode_islower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011211{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011212 Py_ssize_t i, length;
11213 int kind;
11214 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011215 int cased;
11216
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011217 if (PyUnicode_READY(self) == -1)
11218 return NULL;
11219 length = PyUnicode_GET_LENGTH(self);
11220 kind = PyUnicode_KIND(self);
11221 data = PyUnicode_DATA(self);
11222
Guido van Rossumd57fd912000-03-10 22:53:23 +000011223 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011224 if (length == 1)
11225 return PyBool_FromLong(
11226 Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011227
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011228 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011229 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011230 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011231
Guido van Rossumd57fd912000-03-10 22:53:23 +000011232 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011233 for (i = 0; i < length; i++) {
11234 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011235
Benjamin Peterson29060642009-01-31 22:14:21 +000011236 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
11237 return PyBool_FromLong(0);
11238 else if (!cased && Py_UNICODE_ISLOWER(ch))
11239 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011240 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011241 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011242}
11243
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011244PyDoc_STRVAR(isupper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011245 "S.isupper() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011246\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011247Return True if all cased characters in S are uppercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011248at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011249
11250static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011251unicode_isupper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011252{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011253 Py_ssize_t i, length;
11254 int kind;
11255 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011256 int cased;
11257
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011258 if (PyUnicode_READY(self) == -1)
11259 return NULL;
11260 length = PyUnicode_GET_LENGTH(self);
11261 kind = PyUnicode_KIND(self);
11262 data = PyUnicode_DATA(self);
11263
Guido van Rossumd57fd912000-03-10 22:53:23 +000011264 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011265 if (length == 1)
11266 return PyBool_FromLong(
11267 Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011268
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011269 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011270 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011271 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011272
Guido van Rossumd57fd912000-03-10 22:53:23 +000011273 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011274 for (i = 0; i < length; i++) {
11275 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011276
Benjamin Peterson29060642009-01-31 22:14:21 +000011277 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
11278 return PyBool_FromLong(0);
11279 else if (!cased && Py_UNICODE_ISUPPER(ch))
11280 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011281 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011282 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011283}
11284
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011285PyDoc_STRVAR(istitle__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011286 "S.istitle() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011287\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011288Return True if S is a titlecased string and there is at least one\n\
11289character in S, i.e. upper- and titlecase characters may only\n\
11290follow uncased characters and lowercase characters only cased ones.\n\
11291Return False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011292
11293static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011294unicode_istitle(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011295{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011296 Py_ssize_t i, length;
11297 int kind;
11298 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011299 int cased, previous_is_cased;
11300
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011301 if (PyUnicode_READY(self) == -1)
11302 return NULL;
11303 length = PyUnicode_GET_LENGTH(self);
11304 kind = PyUnicode_KIND(self);
11305 data = PyUnicode_DATA(self);
11306
Guido van Rossumd57fd912000-03-10 22:53:23 +000011307 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011308 if (length == 1) {
11309 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11310 return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
11311 (Py_UNICODE_ISUPPER(ch) != 0));
11312 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011313
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011314 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011315 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011316 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011317
Guido van Rossumd57fd912000-03-10 22:53:23 +000011318 cased = 0;
11319 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011320 for (i = 0; i < length; i++) {
11321 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011322
Benjamin Peterson29060642009-01-31 22:14:21 +000011323 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
11324 if (previous_is_cased)
11325 return PyBool_FromLong(0);
11326 previous_is_cased = 1;
11327 cased = 1;
11328 }
11329 else if (Py_UNICODE_ISLOWER(ch)) {
11330 if (!previous_is_cased)
11331 return PyBool_FromLong(0);
11332 previous_is_cased = 1;
11333 cased = 1;
11334 }
11335 else
11336 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011337 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011338 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011339}
11340
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011341PyDoc_STRVAR(isspace__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011342 "S.isspace() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011343\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011344Return True if all characters in S are whitespace\n\
11345and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011346
11347static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011348unicode_isspace(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011349{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011350 Py_ssize_t i, length;
11351 int kind;
11352 void *data;
11353
11354 if (PyUnicode_READY(self) == -1)
11355 return NULL;
11356 length = PyUnicode_GET_LENGTH(self);
11357 kind = PyUnicode_KIND(self);
11358 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011359
Guido van Rossumd57fd912000-03-10 22:53:23 +000011360 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011361 if (length == 1)
11362 return PyBool_FromLong(
11363 Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011364
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011365 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011366 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011367 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011368
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011369 for (i = 0; i < length; i++) {
11370 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011371 if (!Py_UNICODE_ISSPACE(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011372 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011373 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011374 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011375}
11376
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011377PyDoc_STRVAR(isalpha__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011378 "S.isalpha() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011379\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011380Return True if all characters in S are alphabetic\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011381and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011382
11383static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011384unicode_isalpha(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011385{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011386 Py_ssize_t i, length;
11387 int kind;
11388 void *data;
11389
11390 if (PyUnicode_READY(self) == -1)
11391 return NULL;
11392 length = PyUnicode_GET_LENGTH(self);
11393 kind = PyUnicode_KIND(self);
11394 data = PyUnicode_DATA(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011395
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011396 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011397 if (length == 1)
11398 return PyBool_FromLong(
11399 Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011400
11401 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011402 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011403 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011404
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011405 for (i = 0; i < length; i++) {
11406 if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011407 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011408 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011409 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011410}
11411
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011412PyDoc_STRVAR(isalnum__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011413 "S.isalnum() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011414\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011415Return True if all characters in S are alphanumeric\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011416and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011417
11418static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011419unicode_isalnum(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011420{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011421 int kind;
11422 void *data;
11423 Py_ssize_t len, i;
11424
11425 if (PyUnicode_READY(self) == -1)
11426 return NULL;
11427
11428 kind = PyUnicode_KIND(self);
11429 data = PyUnicode_DATA(self);
11430 len = PyUnicode_GET_LENGTH(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011431
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011432 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011433 if (len == 1) {
11434 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11435 return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
11436 }
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011437
11438 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011439 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011440 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011441
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011442 for (i = 0; i < len; i++) {
11443 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011444 if (!Py_UNICODE_ISALNUM(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011445 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011446 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011447 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011448}
11449
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011450PyDoc_STRVAR(isdecimal__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011451 "S.isdecimal() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011452\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011453Return True if there are only decimal characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011454False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011455
11456static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011457unicode_isdecimal(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011458{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011459 Py_ssize_t i, length;
11460 int kind;
11461 void *data;
11462
11463 if (PyUnicode_READY(self) == -1)
11464 return NULL;
11465 length = PyUnicode_GET_LENGTH(self);
11466 kind = PyUnicode_KIND(self);
11467 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011468
Guido van Rossumd57fd912000-03-10 22:53:23 +000011469 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011470 if (length == 1)
11471 return PyBool_FromLong(
11472 Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011473
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011474 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011475 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011476 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011477
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011478 for (i = 0; i < length; i++) {
11479 if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011480 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011481 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011482 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011483}
11484
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011485PyDoc_STRVAR(isdigit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011486 "S.isdigit() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011487\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011488Return True if all characters in S are digits\n\
11489and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011490
11491static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011492unicode_isdigit(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011493{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011494 Py_ssize_t i, length;
11495 int kind;
11496 void *data;
11497
11498 if (PyUnicode_READY(self) == -1)
11499 return NULL;
11500 length = PyUnicode_GET_LENGTH(self);
11501 kind = PyUnicode_KIND(self);
11502 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011503
Guido van Rossumd57fd912000-03-10 22:53:23 +000011504 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011505 if (length == 1) {
11506 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11507 return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
11508 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011509
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011510 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011511 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011512 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011513
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011514 for (i = 0; i < length; i++) {
11515 if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011516 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011517 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011518 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011519}
11520
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011521PyDoc_STRVAR(isnumeric__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011522 "S.isnumeric() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011523\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011524Return True if there are only numeric characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011525False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011526
11527static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011528unicode_isnumeric(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011529{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011530 Py_ssize_t i, length;
11531 int kind;
11532 void *data;
11533
11534 if (PyUnicode_READY(self) == -1)
11535 return NULL;
11536 length = PyUnicode_GET_LENGTH(self);
11537 kind = PyUnicode_KIND(self);
11538 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011539
Guido van Rossumd57fd912000-03-10 22:53:23 +000011540 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011541 if (length == 1)
11542 return PyBool_FromLong(
11543 Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011544
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011545 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011546 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011547 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011548
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011549 for (i = 0; i < length; i++) {
11550 if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011551 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011552 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011553 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011554}
11555
Martin v. Löwis47383402007-08-15 07:32:56 +000011556int
11557PyUnicode_IsIdentifier(PyObject *self)
11558{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011559 int kind;
11560 void *data;
11561 Py_ssize_t i;
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011562 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +000011563
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011564 if (PyUnicode_READY(self) == -1) {
11565 Py_FatalError("identifier not ready");
Benjamin Peterson29060642009-01-31 22:14:21 +000011566 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011567 }
11568
11569 /* Special case for empty strings */
11570 if (PyUnicode_GET_LENGTH(self) == 0)
11571 return 0;
11572 kind = PyUnicode_KIND(self);
11573 data = PyUnicode_DATA(self);
Martin v. Löwis47383402007-08-15 07:32:56 +000011574
11575 /* PEP 3131 says that the first character must be in
11576 XID_Start and subsequent characters in XID_Continue,
11577 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +000011578 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +000011579 letters, digits, underscore). However, given the current
11580 definition of XID_Start and XID_Continue, it is sufficient
11581 to check just for these, except that _ must be allowed
11582 as starting an identifier. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011583 first = PyUnicode_READ(kind, data, 0);
Benjamin Petersonf413b802011-08-12 22:17:18 -050011584 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +000011585 return 0;
11586
Benjamin Peterson9c6e6a02011-09-28 08:09:05 -040011587 for (i = 1; i < PyUnicode_GET_LENGTH(self); i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011588 if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011589 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +000011590 return 1;
11591}
11592
11593PyDoc_STRVAR(isidentifier__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011594 "S.isidentifier() -> bool\n\
Martin v. Löwis47383402007-08-15 07:32:56 +000011595\n\
11596Return True if S is a valid identifier according\n\
11597to the language definition.");
11598
11599static PyObject*
11600unicode_isidentifier(PyObject *self)
11601{
11602 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
11603}
11604
Georg Brandl559e5d72008-06-11 18:37:52 +000011605PyDoc_STRVAR(isprintable__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011606 "S.isprintable() -> bool\n\
Georg Brandl559e5d72008-06-11 18:37:52 +000011607\n\
11608Return True if all characters in S are considered\n\
11609printable in repr() or S is empty, False otherwise.");
11610
11611static PyObject*
11612unicode_isprintable(PyObject *self)
11613{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011614 Py_ssize_t i, length;
11615 int kind;
11616 void *data;
11617
11618 if (PyUnicode_READY(self) == -1)
11619 return NULL;
11620 length = PyUnicode_GET_LENGTH(self);
11621 kind = PyUnicode_KIND(self);
11622 data = PyUnicode_DATA(self);
Georg Brandl559e5d72008-06-11 18:37:52 +000011623
11624 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011625 if (length == 1)
11626 return PyBool_FromLong(
11627 Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
Georg Brandl559e5d72008-06-11 18:37:52 +000011628
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011629 for (i = 0; i < length; i++) {
11630 if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
Georg Brandl559e5d72008-06-11 18:37:52 +000011631 Py_RETURN_FALSE;
11632 }
11633 }
11634 Py_RETURN_TRUE;
11635}
11636
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011637PyDoc_STRVAR(join__doc__,
Georg Brandl495f7b52009-10-27 15:28:25 +000011638 "S.join(iterable) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011639\n\
11640Return a string which is the concatenation of the strings in the\n\
Georg Brandl495f7b52009-10-27 15:28:25 +000011641iterable. The separator between elements is S.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011642
11643static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011644unicode_join(PyObject *self, PyObject *data)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011645{
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011646 return PyUnicode_Join(self, data);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011647}
11648
Martin v. Löwis18e16552006-02-15 17:27:45 +000011649static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011650unicode_length(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011651{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011652 if (PyUnicode_READY(self) == -1)
11653 return -1;
11654 return PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011655}
11656
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011657PyDoc_STRVAR(ljust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011658 "S.ljust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011659\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000011660Return S left-justified in a Unicode string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011661done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011662
11663static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020011664unicode_ljust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011665{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011666 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011667 Py_UCS4 fillchar = ' ';
11668
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011669 if (!PyArg_ParseTuple(args, "n|O&:ljust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011670 return NULL;
11671
Benjamin Petersonbac79492012-01-14 13:34:47 -050011672 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010011673 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011674
Victor Stinnerc4b49542011-12-11 22:44:26 +010011675 if (PyUnicode_GET_LENGTH(self) >= width)
11676 return unicode_result_unchanged(self);
11677
11678 return pad(self, 0, width - PyUnicode_GET_LENGTH(self), fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011679}
11680
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011681PyDoc_STRVAR(lower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011682 "S.lower() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011683\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011684Return a copy of the string S converted to lowercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011685
11686static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020011687unicode_lower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011688{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050011689 if (PyUnicode_READY(self) == -1)
11690 return NULL;
11691 if (PyUnicode_IS_ASCII(self))
11692 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010011693 return case_operation(self, do_lower);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011694}
11695
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011696#define LEFTSTRIP 0
11697#define RIGHTSTRIP 1
11698#define BOTHSTRIP 2
11699
11700/* Arrays indexed by above */
11701static const char *stripformat[] = {"|O:lstrip", "|O:rstrip", "|O:strip"};
11702
11703#define STRIPNAME(i) (stripformat[i]+3)
11704
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011705/* externally visible for str.strip(unicode) */
11706PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011707_PyUnicode_XStrip(PyObject *self, int striptype, PyObject *sepobj)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011708{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011709 void *data;
11710 int kind;
11711 Py_ssize_t i, j, len;
11712 BLOOM_MASK sepmask;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011713
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011714 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
11715 return NULL;
11716
11717 kind = PyUnicode_KIND(self);
11718 data = PyUnicode_DATA(self);
11719 len = PyUnicode_GET_LENGTH(self);
11720 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
11721 PyUnicode_DATA(sepobj),
11722 PyUnicode_GET_LENGTH(sepobj));
Thomas Wouters477c8d52006-05-27 19:21:47 +000011723
Benjamin Peterson14339b62009-01-31 16:36:08 +000011724 i = 0;
11725 if (striptype != RIGHTSTRIP) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011726 while (i < len &&
11727 BLOOM_MEMBER(sepmask, PyUnicode_READ(kind, data, i), sepobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011728 i++;
11729 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011730 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011731
Benjamin Peterson14339b62009-01-31 16:36:08 +000011732 j = len;
11733 if (striptype != LEFTSTRIP) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011734 do {
11735 j--;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011736 } while (j >= i &&
11737 BLOOM_MEMBER(sepmask, PyUnicode_READ(kind, data, j), sepobj));
Benjamin Peterson29060642009-01-31 22:14:21 +000011738 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011739 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011740
Victor Stinner7931d9a2011-11-04 00:22:48 +010011741 return PyUnicode_Substring(self, i, j);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011742}
11743
11744PyObject*
11745PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
11746{
11747 unsigned char *data;
11748 int kind;
Victor Stinner12bab6d2011-10-01 01:53:49 +020011749 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011750
Victor Stinnerde636f32011-10-01 03:55:54 +020011751 if (PyUnicode_READY(self) == -1)
11752 return NULL;
11753
Victor Stinner684d5fd2012-05-03 02:32:34 +020011754 length = PyUnicode_GET_LENGTH(self);
11755 end = Py_MIN(end, length);
Victor Stinnerde636f32011-10-01 03:55:54 +020011756
Victor Stinner684d5fd2012-05-03 02:32:34 +020011757 if (start == 0 && end == length)
Victor Stinnerc4b49542011-12-11 22:44:26 +010011758 return unicode_result_unchanged(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011759
Victor Stinnerde636f32011-10-01 03:55:54 +020011760 if (start < 0 || end < 0) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020011761 PyErr_SetString(PyExc_IndexError, "string index out of range");
11762 return NULL;
11763 }
Victor Stinner684d5fd2012-05-03 02:32:34 +020011764 if (start >= length || end < start) {
Victor Stinner3a7f79772012-05-03 03:36:40 +020011765 Py_INCREF(unicode_empty);
11766 return unicode_empty;
Victor Stinner684d5fd2012-05-03 02:32:34 +020011767 }
Victor Stinner12bab6d2011-10-01 01:53:49 +020011768
Victor Stinner684d5fd2012-05-03 02:32:34 +020011769 length = end - start;
Victor Stinnerb9275c12011-10-05 14:01:42 +020011770 if (PyUnicode_IS_ASCII(self)) {
Victor Stinnerb9275c12011-10-05 14:01:42 +020011771 data = PyUnicode_1BYTE_DATA(self);
11772 return unicode_fromascii(data + start, length);
11773 }
11774 else {
11775 kind = PyUnicode_KIND(self);
11776 data = PyUnicode_1BYTE_DATA(self);
11777 return PyUnicode_FromKindAndData(kind,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020011778 data + kind * start,
Victor Stinnerb9275c12011-10-05 14:01:42 +020011779 length);
11780 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011781}
Guido van Rossumd57fd912000-03-10 22:53:23 +000011782
11783static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011784do_strip(PyObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011785{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011786 int kind;
11787 void *data;
11788 Py_ssize_t len, i, j;
11789
11790 if (PyUnicode_READY(self) == -1)
11791 return NULL;
11792
11793 kind = PyUnicode_KIND(self);
11794 data = PyUnicode_DATA(self);
11795 len = PyUnicode_GET_LENGTH(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011796
Benjamin Peterson14339b62009-01-31 16:36:08 +000011797 i = 0;
11798 if (striptype != RIGHTSTRIP) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011799 while (i < len && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, i))) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000011800 i++;
11801 }
11802 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011803
Benjamin Peterson14339b62009-01-31 16:36:08 +000011804 j = len;
11805 if (striptype != LEFTSTRIP) {
11806 do {
11807 j--;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011808 } while (j >= i && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, j)));
Benjamin Peterson14339b62009-01-31 16:36:08 +000011809 j++;
11810 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011811
Victor Stinner7931d9a2011-11-04 00:22:48 +010011812 return PyUnicode_Substring(self, i, j);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011813}
11814
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011815
11816static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011817do_argstrip(PyObject *self, int striptype, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011818{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011819 PyObject *sep = NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011820
Benjamin Peterson14339b62009-01-31 16:36:08 +000011821 if (!PyArg_ParseTuple(args, (char *)stripformat[striptype], &sep))
11822 return NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011823
Benjamin Peterson14339b62009-01-31 16:36:08 +000011824 if (sep != NULL && sep != Py_None) {
11825 if (PyUnicode_Check(sep))
11826 return _PyUnicode_XStrip(self, striptype, sep);
11827 else {
11828 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000011829 "%s arg must be None or str",
11830 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +000011831 return NULL;
11832 }
11833 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011834
Benjamin Peterson14339b62009-01-31 16:36:08 +000011835 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011836}
11837
11838
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011839PyDoc_STRVAR(strip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011840 "S.strip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011841\n\
11842Return a copy of the string S with leading and trailing\n\
11843whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011844If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011845
11846static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011847unicode_strip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011848{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011849 if (PyTuple_GET_SIZE(args) == 0)
11850 return do_strip(self, BOTHSTRIP); /* Common case */
11851 else
11852 return do_argstrip(self, BOTHSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011853}
11854
11855
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011856PyDoc_STRVAR(lstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011857 "S.lstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011858\n\
11859Return a copy of the string S with leading whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011860If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011861
11862static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011863unicode_lstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011864{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011865 if (PyTuple_GET_SIZE(args) == 0)
11866 return do_strip(self, LEFTSTRIP); /* Common case */
11867 else
11868 return do_argstrip(self, LEFTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011869}
11870
11871
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011872PyDoc_STRVAR(rstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011873 "S.rstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011874\n\
11875Return a copy of the string S with trailing whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011876If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011877
11878static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011879unicode_rstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011880{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011881 if (PyTuple_GET_SIZE(args) == 0)
11882 return do_strip(self, RIGHTSTRIP); /* Common case */
11883 else
11884 return do_argstrip(self, RIGHTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011885}
11886
11887
Guido van Rossumd57fd912000-03-10 22:53:23 +000011888static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011889unicode_repeat(PyObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011890{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011891 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011892 Py_ssize_t nchars, n;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011893
Georg Brandl222de0f2009-04-12 12:01:50 +000011894 if (len < 1) {
11895 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +020011896 return unicode_empty;
Georg Brandl222de0f2009-04-12 12:01:50 +000011897 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011898
Victor Stinnerc4b49542011-12-11 22:44:26 +010011899 /* no repeat, return original string */
11900 if (len == 1)
11901 return unicode_result_unchanged(str);
Tim Peters8f422462000-09-09 06:13:41 +000011902
Benjamin Petersonbac79492012-01-14 13:34:47 -050011903 if (PyUnicode_READY(str) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011904 return NULL;
11905
Victor Stinnerc759f3e2011-10-01 03:09:58 +020011906 if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
Victor Stinner67ca64c2011-10-01 02:47:29 +020011907 PyErr_SetString(PyExc_OverflowError,
11908 "repeated string is too long");
11909 return NULL;
11910 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011911 nchars = len * PyUnicode_GET_LENGTH(str);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011912
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011913 u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011914 if (!u)
11915 return NULL;
Victor Stinner67ca64c2011-10-01 02:47:29 +020011916 assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011917
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011918 if (PyUnicode_GET_LENGTH(str) == 1) {
11919 const int kind = PyUnicode_KIND(str);
11920 const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
Victor Stinner73f53b52011-12-18 03:26:31 +010011921 if (kind == PyUnicode_1BYTE_KIND) {
11922 void *to = PyUnicode_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011923 memset(to, (unsigned char)fill_char, len);
Victor Stinner73f53b52011-12-18 03:26:31 +010011924 }
11925 else if (kind == PyUnicode_2BYTE_KIND) {
11926 Py_UCS2 *ucs2 = PyUnicode_2BYTE_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011927 for (n = 0; n < len; ++n)
Victor Stinner73f53b52011-12-18 03:26:31 +010011928 ucs2[n] = fill_char;
11929 } else {
11930 Py_UCS4 *ucs4 = PyUnicode_4BYTE_DATA(u);
11931 assert(kind == PyUnicode_4BYTE_KIND);
11932 for (n = 0; n < len; ++n)
11933 ucs4[n] = fill_char;
Victor Stinner67ca64c2011-10-01 02:47:29 +020011934 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011935 }
11936 else {
11937 /* number of characters copied this far */
11938 Py_ssize_t done = PyUnicode_GET_LENGTH(str);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020011939 const Py_ssize_t char_size = PyUnicode_KIND(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011940 char *to = (char *) PyUnicode_DATA(u);
11941 Py_MEMCPY(to, PyUnicode_DATA(str),
11942 PyUnicode_GET_LENGTH(str) * char_size);
Benjamin Peterson29060642009-01-31 22:14:21 +000011943 while (done < nchars) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011944 n = (done <= nchars-done) ? done : nchars-done;
11945 Py_MEMCPY(to + (done * char_size), to, n * char_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011946 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +000011947 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011948 }
11949
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020011950 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011951 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011952}
11953
Alexander Belopolsky40018472011-02-26 01:02:56 +000011954PyObject *
11955PyUnicode_Replace(PyObject *obj,
11956 PyObject *subobj,
11957 PyObject *replobj,
11958 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011959{
11960 PyObject *self;
11961 PyObject *str1;
11962 PyObject *str2;
11963 PyObject *result;
11964
11965 self = PyUnicode_FromObject(obj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060011966 if (self == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000011967 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011968 str1 = PyUnicode_FromObject(subobj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060011969 if (str1 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011970 Py_DECREF(self);
11971 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011972 }
11973 str2 = PyUnicode_FromObject(replobj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060011974 if (str2 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011975 Py_DECREF(self);
11976 Py_DECREF(str1);
11977 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011978 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060011979 if (PyUnicode_READY(self) == -1 ||
11980 PyUnicode_READY(str1) == -1 ||
11981 PyUnicode_READY(str2) == -1)
11982 result = NULL;
11983 else
11984 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011985 Py_DECREF(self);
11986 Py_DECREF(str1);
11987 Py_DECREF(str2);
11988 return result;
11989}
11990
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011991PyDoc_STRVAR(replace__doc__,
Ezio Melottic1897e72010-06-26 18:50:39 +000011992 "S.replace(old, new[, count]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011993\n\
11994Return a copy of S with all occurrences of substring\n\
Georg Brandlf08a9dd2008-06-10 16:57:31 +000011995old replaced by new. If the optional argument count is\n\
11996given, only the first count occurrences are replaced.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011997
11998static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011999unicode_replace(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012000{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012001 PyObject *str1;
12002 PyObject *str2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012003 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012004 PyObject *result;
12005
Martin v. Löwis18e16552006-02-15 17:27:45 +000012006 if (!PyArg_ParseTuple(args, "OO|n:replace", &str1, &str2, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012007 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060012008 if (PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000012009 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012010 str1 = PyUnicode_FromObject(str1);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012011 if (str1 == NULL)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012012 return NULL;
12013 str2 = PyUnicode_FromObject(str2);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012014 if (str2 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012015 Py_DECREF(str1);
12016 return NULL;
Walter Dörwaldf6b56ae2003-02-09 23:42:56 +000012017 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060012018 if (PyUnicode_READY(str1) == -1 || PyUnicode_READY(str2) == -1)
12019 result = NULL;
12020 else
12021 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012022
12023 Py_DECREF(str1);
12024 Py_DECREF(str2);
12025 return result;
12026}
12027
Alexander Belopolsky40018472011-02-26 01:02:56 +000012028static PyObject *
12029unicode_repr(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012030{
Walter Dörwald79e913e2007-05-12 11:08:06 +000012031 PyObject *repr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012032 Py_ssize_t isize;
12033 Py_ssize_t osize, squote, dquote, i, o;
12034 Py_UCS4 max, quote;
12035 int ikind, okind;
12036 void *idata, *odata;
Walter Dörwald79e913e2007-05-12 11:08:06 +000012037
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012038 if (PyUnicode_READY(unicode) == -1)
Walter Dörwald79e913e2007-05-12 11:08:06 +000012039 return NULL;
12040
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012041 isize = PyUnicode_GET_LENGTH(unicode);
12042 idata = PyUnicode_DATA(unicode);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012043
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012044 /* Compute length of output, quote characters, and
12045 maximum character */
12046 osize = 2; /* quotes */
12047 max = 127;
12048 squote = dquote = 0;
12049 ikind = PyUnicode_KIND(unicode);
12050 for (i = 0; i < isize; i++) {
12051 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
12052 switch (ch) {
12053 case '\'': squote++; osize++; break;
12054 case '"': dquote++; osize++; break;
12055 case '\\': case '\t': case '\r': case '\n':
12056 osize += 2; break;
12057 default:
12058 /* Fast-path ASCII */
12059 if (ch < ' ' || ch == 0x7f)
12060 osize += 4; /* \xHH */
12061 else if (ch < 0x7f)
12062 osize++;
12063 else if (Py_UNICODE_ISPRINTABLE(ch)) {
12064 osize++;
12065 max = ch > max ? ch : max;
12066 }
12067 else if (ch < 0x100)
12068 osize += 4; /* \xHH */
12069 else if (ch < 0x10000)
12070 osize += 6; /* \uHHHH */
12071 else
12072 osize += 10; /* \uHHHHHHHH */
12073 }
12074 }
12075
12076 quote = '\'';
12077 if (squote) {
12078 if (dquote)
12079 /* Both squote and dquote present. Use squote,
12080 and escape them */
12081 osize += squote;
12082 else
12083 quote = '"';
12084 }
12085
12086 repr = PyUnicode_New(osize, max);
12087 if (repr == NULL)
12088 return NULL;
12089 okind = PyUnicode_KIND(repr);
12090 odata = PyUnicode_DATA(repr);
12091
12092 PyUnicode_WRITE(okind, odata, 0, quote);
12093 PyUnicode_WRITE(okind, odata, osize-1, quote);
12094
12095 for (i = 0, o = 1; i < isize; i++) {
12096 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012097
12098 /* Escape quotes and backslashes */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012099 if ((ch == quote) || (ch == '\\')) {
12100 PyUnicode_WRITE(okind, odata, o++, '\\');
12101 PyUnicode_WRITE(okind, odata, o++, ch);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012102 continue;
12103 }
12104
Benjamin Peterson29060642009-01-31 22:14:21 +000012105 /* Map special whitespace to '\t', \n', '\r' */
Georg Brandl559e5d72008-06-11 18:37:52 +000012106 if (ch == '\t') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012107 PyUnicode_WRITE(okind, odata, o++, '\\');
12108 PyUnicode_WRITE(okind, odata, o++, 't');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012109 }
12110 else if (ch == '\n') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012111 PyUnicode_WRITE(okind, odata, o++, '\\');
12112 PyUnicode_WRITE(okind, odata, o++, 'n');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012113 }
12114 else if (ch == '\r') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012115 PyUnicode_WRITE(okind, odata, o++, '\\');
12116 PyUnicode_WRITE(okind, odata, o++, 'r');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012117 }
12118
12119 /* Map non-printable US ASCII to '\xhh' */
Georg Brandl559e5d72008-06-11 18:37:52 +000012120 else if (ch < ' ' || ch == 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012121 PyUnicode_WRITE(okind, odata, o++, '\\');
12122 PyUnicode_WRITE(okind, odata, o++, 'x');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012123 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12124 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012125 }
12126
Georg Brandl559e5d72008-06-11 18:37:52 +000012127 /* Copy ASCII characters as-is */
12128 else if (ch < 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012129 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000012130 }
12131
Benjamin Peterson29060642009-01-31 22:14:21 +000012132 /* Non-ASCII characters */
Georg Brandl559e5d72008-06-11 18:37:52 +000012133 else {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012134 /* Map Unicode whitespace and control characters
Georg Brandl559e5d72008-06-11 18:37:52 +000012135 (categories Z* and C* except ASCII space)
12136 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012137 if (!Py_UNICODE_ISPRINTABLE(ch)) {
Georg Brandl559e5d72008-06-11 18:37:52 +000012138 /* Map 8-bit characters to '\xhh' */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012139 if (ch <= 0xff) {
12140 PyUnicode_WRITE(okind, odata, o++, '\\');
12141 PyUnicode_WRITE(okind, odata, o++, 'x');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012142 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12143 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012144 }
12145 /* Map 21-bit characters to '\U00xxxxxx' */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012146 else if (ch >= 0x10000) {
12147 PyUnicode_WRITE(okind, odata, o++, '\\');
12148 PyUnicode_WRITE(okind, odata, o++, 'U');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012149 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 28) & 0xF]);
12150 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 24) & 0xF]);
12151 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 20) & 0xF]);
12152 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 16) & 0xF]);
12153 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12154 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12155 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12156 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012157 }
12158 /* Map 16-bit characters to '\uxxxx' */
12159 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012160 PyUnicode_WRITE(okind, odata, o++, '\\');
12161 PyUnicode_WRITE(okind, odata, o++, 'u');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012162 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12163 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12164 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12165 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012166 }
12167 }
12168 /* Copy characters as-is */
12169 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012170 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000012171 }
12172 }
Walter Dörwald79e913e2007-05-12 11:08:06 +000012173 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012174 /* Closing quote already added at the beginning */
Victor Stinner05d11892011-10-06 01:13:58 +020012175 assert(_PyUnicode_CheckConsistency(repr, 1));
Walter Dörwald79e913e2007-05-12 11:08:06 +000012176 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012177}
12178
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012179PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012180 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012181\n\
12182Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080012183such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012184arguments start and end are interpreted as in slice notation.\n\
12185\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012186Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012187
12188static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012189unicode_rfind(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012190{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012191 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012192 Py_ssize_t start;
12193 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012194 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012195
Jesus Ceaac451502011-04-20 17:09:23 +020012196 if (!stringlib_parse_args_finds_unicode("rfind", args, &substring,
12197 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012198 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012199
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012200 if (PyUnicode_READY(self) == -1)
12201 return NULL;
12202 if (PyUnicode_READY(substring) == -1)
12203 return NULL;
12204
Victor Stinner7931d9a2011-11-04 00:22:48 +010012205 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012206
12207 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012208
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012209 if (result == -2)
12210 return NULL;
12211
Christian Heimes217cfd12007-12-02 14:31:20 +000012212 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012213}
12214
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012215PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012216 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012217\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012218Like S.rfind() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012219
12220static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012221unicode_rindex(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012222{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012223 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012224 Py_ssize_t start;
12225 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012226 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012227
Jesus Ceaac451502011-04-20 17:09:23 +020012228 if (!stringlib_parse_args_finds_unicode("rindex", args, &substring,
12229 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012230 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012231
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012232 if (PyUnicode_READY(self) == -1)
12233 return NULL;
12234 if (PyUnicode_READY(substring) == -1)
12235 return NULL;
12236
Victor Stinner7931d9a2011-11-04 00:22:48 +010012237 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012238
12239 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012240
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012241 if (result == -2)
12242 return NULL;
12243
Guido van Rossumd57fd912000-03-10 22:53:23 +000012244 if (result < 0) {
12245 PyErr_SetString(PyExc_ValueError, "substring not found");
12246 return NULL;
12247 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012248
Christian Heimes217cfd12007-12-02 14:31:20 +000012249 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012250}
12251
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012252PyDoc_STRVAR(rjust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012253 "S.rjust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012254\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012255Return S right-justified in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012256done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012257
12258static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012259unicode_rjust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012260{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012261 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012262 Py_UCS4 fillchar = ' ';
12263
Victor Stinnere9a29352011-10-01 02:14:59 +020012264 if (!PyArg_ParseTuple(args, "n|O&:rjust", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012265 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012266
Benjamin Petersonbac79492012-01-14 13:34:47 -050012267 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012268 return NULL;
12269
Victor Stinnerc4b49542011-12-11 22:44:26 +010012270 if (PyUnicode_GET_LENGTH(self) >= width)
12271 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012272
Victor Stinnerc4b49542011-12-11 22:44:26 +010012273 return pad(self, width - PyUnicode_GET_LENGTH(self), 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012274}
12275
Alexander Belopolsky40018472011-02-26 01:02:56 +000012276PyObject *
12277PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012278{
12279 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +000012280
Guido van Rossumd57fd912000-03-10 22:53:23 +000012281 s = PyUnicode_FromObject(s);
12282 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012283 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012284 if (sep != NULL) {
12285 sep = PyUnicode_FromObject(sep);
12286 if (sep == NULL) {
12287 Py_DECREF(s);
12288 return NULL;
12289 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012290 }
12291
Victor Stinner9310abb2011-10-05 00:59:23 +020012292 result = split(s, sep, maxsplit);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012293
12294 Py_DECREF(s);
12295 Py_XDECREF(sep);
12296 return result;
12297}
12298
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012299PyDoc_STRVAR(split__doc__,
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012300 "S.split(sep=None, maxsplit=-1) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012301\n\
12302Return a list of the words in S, using sep as the\n\
12303delimiter string. If maxsplit is given, at most maxsplit\n\
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000012304splits are done. If sep is not specified or is None, any\n\
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +000012305whitespace string is a separator and empty strings are\n\
12306removed from the result.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012307
12308static PyObject*
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012309unicode_split(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012310{
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012311 static char *kwlist[] = {"sep", "maxsplit", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000012312 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012313 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012314
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012315 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:split",
12316 kwlist, &substring, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012317 return NULL;
12318
12319 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012320 return split(self, NULL, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012321 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012322 return split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012323 else
Victor Stinner7931d9a2011-11-04 00:22:48 +010012324 return PyUnicode_Split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012325}
12326
Thomas Wouters477c8d52006-05-27 19:21:47 +000012327PyObject *
12328PyUnicode_Partition(PyObject *str_in, PyObject *sep_in)
12329{
12330 PyObject* str_obj;
12331 PyObject* sep_obj;
12332 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012333 int kind1, kind2, kind;
12334 void *buf1 = NULL, *buf2 = NULL;
12335 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012336
12337 str_obj = PyUnicode_FromObject(str_in);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012338 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012339 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012340 sep_obj = PyUnicode_FromObject(sep_in);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012341 if (!sep_obj) {
12342 Py_DECREF(str_obj);
12343 return NULL;
12344 }
12345 if (PyUnicode_READY(sep_obj) == -1 || PyUnicode_READY(str_obj) == -1) {
12346 Py_DECREF(sep_obj);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012347 Py_DECREF(str_obj);
12348 return NULL;
12349 }
12350
Victor Stinner14f8f022011-10-05 20:58:25 +020012351 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012352 kind2 = PyUnicode_KIND(sep_obj);
Victor Stinner14f8f022011-10-05 20:58:25 +020012353 kind = Py_MAX(kind1, kind2);
12354 buf1 = PyUnicode_DATA(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012355 if (kind1 != kind)
Victor Stinner14f8f022011-10-05 20:58:25 +020012356 buf1 = _PyUnicode_AsKind(str_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012357 if (!buf1)
12358 goto onError;
12359 buf2 = PyUnicode_DATA(sep_obj);
12360 if (kind2 != kind)
12361 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12362 if (!buf2)
12363 goto onError;
12364 len1 = PyUnicode_GET_LENGTH(str_obj);
12365 len2 = PyUnicode_GET_LENGTH(sep_obj);
12366
Benjamin Petersonead6b532011-12-20 17:23:42 -060012367 switch (PyUnicode_KIND(str_obj)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012368 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012369 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12370 out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12371 else
12372 out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012373 break;
12374 case PyUnicode_2BYTE_KIND:
12375 out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12376 break;
12377 case PyUnicode_4BYTE_KIND:
12378 out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12379 break;
12380 default:
12381 assert(0);
12382 out = 0;
12383 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012384
12385 Py_DECREF(sep_obj);
12386 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012387 if (kind1 != kind)
12388 PyMem_Free(buf1);
12389 if (kind2 != kind)
12390 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012391
12392 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012393 onError:
12394 Py_DECREF(sep_obj);
12395 Py_DECREF(str_obj);
12396 if (kind1 != kind && buf1)
12397 PyMem_Free(buf1);
12398 if (kind2 != kind && buf2)
12399 PyMem_Free(buf2);
12400 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012401}
12402
12403
12404PyObject *
12405PyUnicode_RPartition(PyObject *str_in, PyObject *sep_in)
12406{
12407 PyObject* str_obj;
12408 PyObject* sep_obj;
12409 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012410 int kind1, kind2, kind;
12411 void *buf1 = NULL, *buf2 = NULL;
12412 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012413
12414 str_obj = PyUnicode_FromObject(str_in);
12415 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012416 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012417 sep_obj = PyUnicode_FromObject(sep_in);
12418 if (!sep_obj) {
12419 Py_DECREF(str_obj);
12420 return NULL;
12421 }
12422
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012423 kind1 = PyUnicode_KIND(str_in);
12424 kind2 = PyUnicode_KIND(sep_obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +020012425 kind = Py_MAX(kind1, kind2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012426 buf1 = PyUnicode_DATA(str_in);
12427 if (kind1 != kind)
12428 buf1 = _PyUnicode_AsKind(str_in, kind);
12429 if (!buf1)
12430 goto onError;
12431 buf2 = PyUnicode_DATA(sep_obj);
12432 if (kind2 != kind)
12433 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12434 if (!buf2)
12435 goto onError;
12436 len1 = PyUnicode_GET_LENGTH(str_obj);
12437 len2 = PyUnicode_GET_LENGTH(sep_obj);
12438
Benjamin Petersonead6b532011-12-20 17:23:42 -060012439 switch (PyUnicode_KIND(str_in)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012440 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012441 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12442 out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12443 else
12444 out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012445 break;
12446 case PyUnicode_2BYTE_KIND:
12447 out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12448 break;
12449 case PyUnicode_4BYTE_KIND:
12450 out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12451 break;
12452 default:
12453 assert(0);
12454 out = 0;
12455 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012456
12457 Py_DECREF(sep_obj);
12458 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012459 if (kind1 != kind)
12460 PyMem_Free(buf1);
12461 if (kind2 != kind)
12462 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012463
12464 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012465 onError:
12466 Py_DECREF(sep_obj);
12467 Py_DECREF(str_obj);
12468 if (kind1 != kind && buf1)
12469 PyMem_Free(buf1);
12470 if (kind2 != kind && buf2)
12471 PyMem_Free(buf2);
12472 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012473}
12474
12475PyDoc_STRVAR(partition__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012476 "S.partition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012477\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012478Search for the separator sep in S, and return the part before it,\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012479the separator itself, and the part after it. If the separator is not\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012480found, return S and two empty strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012481
12482static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012483unicode_partition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012484{
Victor Stinner9310abb2011-10-05 00:59:23 +020012485 return PyUnicode_Partition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012486}
12487
12488PyDoc_STRVAR(rpartition__doc__,
Ezio Melotti5b2b2422010-01-25 11:58:28 +000012489 "S.rpartition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012490\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012491Search for the separator sep in S, starting at the end of S, and return\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012492the part before it, the separator itself, and the part after it. If the\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012493separator is not found, return two empty strings and S.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012494
12495static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012496unicode_rpartition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012497{
Victor Stinner9310abb2011-10-05 00:59:23 +020012498 return PyUnicode_RPartition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012499}
12500
Alexander Belopolsky40018472011-02-26 01:02:56 +000012501PyObject *
12502PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012503{
12504 PyObject *result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012505
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012506 s = PyUnicode_FromObject(s);
12507 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012508 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012509 if (sep != NULL) {
12510 sep = PyUnicode_FromObject(sep);
12511 if (sep == NULL) {
12512 Py_DECREF(s);
12513 return NULL;
12514 }
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012515 }
12516
Victor Stinner9310abb2011-10-05 00:59:23 +020012517 result = rsplit(s, sep, maxsplit);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012518
12519 Py_DECREF(s);
12520 Py_XDECREF(sep);
12521 return result;
12522}
12523
12524PyDoc_STRVAR(rsplit__doc__,
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012525 "S.rsplit(sep=None, maxsplit=-1) -> list of strings\n\
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012526\n\
12527Return a list of the words in S, using sep as the\n\
12528delimiter string, starting at the end of the string and\n\
12529working to the front. If maxsplit is given, at most maxsplit\n\
12530splits are done. If sep is not specified, any whitespace string\n\
12531is a separator.");
12532
12533static PyObject*
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012534unicode_rsplit(PyObject *self, PyObject *args, PyObject *kwds)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012535{
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012536 static char *kwlist[] = {"sep", "maxsplit", 0};
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012537 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012538 Py_ssize_t maxcount = -1;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012539
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012540 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:rsplit",
12541 kwlist, &substring, &maxcount))
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012542 return NULL;
12543
12544 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012545 return rsplit(self, NULL, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012546 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012547 return rsplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012548 else
Victor Stinner9310abb2011-10-05 00:59:23 +020012549 return PyUnicode_RSplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012550}
12551
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012552PyDoc_STRVAR(splitlines__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012553 "S.splitlines([keepends]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012554\n\
12555Return a list of the lines in S, breaking at line boundaries.\n\
Guido van Rossum86662912000-04-11 15:38:46 +000012556Line breaks are not included in the resulting list unless keepends\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012557is given and true.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012558
12559static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012560unicode_splitlines(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012561{
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012562 static char *kwlist[] = {"keepends", 0};
Guido van Rossum86662912000-04-11 15:38:46 +000012563 int keepends = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012564
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012565 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:splitlines",
12566 kwlist, &keepends))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012567 return NULL;
12568
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012569 return PyUnicode_Splitlines(self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012570}
12571
12572static
Guido van Rossumf15a29f2007-05-04 00:41:39 +000012573PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012574{
Victor Stinnerc4b49542011-12-11 22:44:26 +010012575 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012576}
12577
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012578PyDoc_STRVAR(swapcase__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012579 "S.swapcase() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012580\n\
12581Return a copy of S with uppercase characters converted to lowercase\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012582and vice versa.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012583
12584static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012585unicode_swapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012586{
Benjamin Petersoneea48462012-01-16 14:28:50 -050012587 if (PyUnicode_READY(self) == -1)
12588 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010012589 return case_operation(self, do_swapcase);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012590}
12591
Georg Brandlceee0772007-11-27 23:48:05 +000012592PyDoc_STRVAR(maketrans__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012593 "str.maketrans(x[, y[, z]]) -> dict (static method)\n\
Georg Brandlceee0772007-11-27 23:48:05 +000012594\n\
12595Return a translation table usable for str.translate().\n\
12596If there is only one argument, it must be a dictionary mapping Unicode\n\
12597ordinals (integers) or characters to Unicode ordinals, strings or None.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012598Character keys will be then converted to ordinals.\n\
Georg Brandlceee0772007-11-27 23:48:05 +000012599If there are two arguments, they must be strings of equal length, and\n\
12600in the resulting dictionary, each character in x will be mapped to the\n\
12601character at the same position in y. If there is a third argument, it\n\
12602must be a string, whose characters will be mapped to None in the result.");
12603
12604static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012605unicode_maketrans(PyObject *null, PyObject *args)
Georg Brandlceee0772007-11-27 23:48:05 +000012606{
12607 PyObject *x, *y = NULL, *z = NULL;
12608 PyObject *new = NULL, *key, *value;
12609 Py_ssize_t i = 0;
12610 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012611
Georg Brandlceee0772007-11-27 23:48:05 +000012612 if (!PyArg_ParseTuple(args, "O|UU:maketrans", &x, &y, &z))
12613 return NULL;
12614 new = PyDict_New();
12615 if (!new)
12616 return NULL;
12617 if (y != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012618 int x_kind, y_kind, z_kind;
12619 void *x_data, *y_data, *z_data;
12620
Georg Brandlceee0772007-11-27 23:48:05 +000012621 /* x must be a string too, of equal length */
Georg Brandlceee0772007-11-27 23:48:05 +000012622 if (!PyUnicode_Check(x)) {
12623 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
12624 "be a string if there is a second argument");
12625 goto err;
12626 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012627 if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012628 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
12629 "arguments must have equal length");
12630 goto err;
12631 }
12632 /* create entries for translating chars in x to those in y */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012633 x_kind = PyUnicode_KIND(x);
12634 y_kind = PyUnicode_KIND(y);
12635 x_data = PyUnicode_DATA(x);
12636 y_data = PyUnicode_DATA(y);
12637 for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
12638 key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060012639 if (!key)
Georg Brandlceee0772007-11-27 23:48:05 +000012640 goto err;
Benjamin Peterson822c7902011-12-20 13:32:50 -060012641 value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060012642 if (!value) {
12643 Py_DECREF(key);
12644 goto err;
12645 }
Georg Brandlceee0772007-11-27 23:48:05 +000012646 res = PyDict_SetItem(new, key, value);
12647 Py_DECREF(key);
12648 Py_DECREF(value);
12649 if (res < 0)
12650 goto err;
12651 }
12652 /* create entries for deleting chars in z */
12653 if (z != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012654 z_kind = PyUnicode_KIND(z);
12655 z_data = PyUnicode_DATA(z);
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012656 for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012657 key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000012658 if (!key)
12659 goto err;
12660 res = PyDict_SetItem(new, key, Py_None);
12661 Py_DECREF(key);
12662 if (res < 0)
12663 goto err;
12664 }
12665 }
12666 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012667 int kind;
12668 void *data;
12669
Georg Brandlceee0772007-11-27 23:48:05 +000012670 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +000012671 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012672 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
12673 "to maketrans it must be a dict");
12674 goto err;
12675 }
12676 /* copy entries into the new dict, converting string keys to int keys */
12677 while (PyDict_Next(x, &i, &key, &value)) {
12678 if (PyUnicode_Check(key)) {
12679 /* convert string keys to integer keys */
12680 PyObject *newkey;
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012681 if (PyUnicode_GET_LENGTH(key) != 1) {
Georg Brandlceee0772007-11-27 23:48:05 +000012682 PyErr_SetString(PyExc_ValueError, "string keys in translate "
12683 "table must be of length 1");
12684 goto err;
12685 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012686 kind = PyUnicode_KIND(key);
12687 data = PyUnicode_DATA(key);
12688 newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
Georg Brandlceee0772007-11-27 23:48:05 +000012689 if (!newkey)
12690 goto err;
12691 res = PyDict_SetItem(new, newkey, value);
12692 Py_DECREF(newkey);
12693 if (res < 0)
12694 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +000012695 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012696 /* just keep integer keys */
12697 if (PyDict_SetItem(new, key, value) < 0)
12698 goto err;
12699 } else {
12700 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
12701 "be strings or integers");
12702 goto err;
12703 }
12704 }
12705 }
12706 return new;
12707 err:
12708 Py_DECREF(new);
12709 return NULL;
12710}
12711
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012712PyDoc_STRVAR(translate__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012713 "S.translate(table) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012714\n\
12715Return a copy of the string S, where all characters have been mapped\n\
12716through the given translation table, which must be a mapping of\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012717Unicode ordinals to Unicode ordinals, strings, or None.\n\
Walter Dörwald5c1ee172002-09-04 20:31:32 +000012718Unmapped characters are left untouched. Characters mapped to None\n\
12719are deleted.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012720
12721static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012722unicode_translate(PyObject *self, PyObject *table)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012723{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012724 return _PyUnicode_TranslateCharmap(self, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012725}
12726
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012727PyDoc_STRVAR(upper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012728 "S.upper() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012729\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012730Return a copy of S converted to uppercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012731
12732static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012733unicode_upper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012734{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050012735 if (PyUnicode_READY(self) == -1)
12736 return NULL;
12737 if (PyUnicode_IS_ASCII(self))
12738 return ascii_upper_or_lower(self, 0);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010012739 return case_operation(self, do_upper);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012740}
12741
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012742PyDoc_STRVAR(zfill__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012743 "S.zfill(width) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012744\n\
Benjamin Peterson9aa42992008-09-10 21:57:34 +000012745Pad a numeric string S with zeros on the left, to fill a field\n\
12746of the specified width. The string S is never truncated.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012747
12748static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012749unicode_zfill(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012750{
Martin v. Löwis18e16552006-02-15 17:27:45 +000012751 Py_ssize_t fill;
Victor Stinner9310abb2011-10-05 00:59:23 +020012752 PyObject *u;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012753 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012754 int kind;
12755 void *data;
12756 Py_UCS4 chr;
12757
Martin v. Löwis18e16552006-02-15 17:27:45 +000012758 if (!PyArg_ParseTuple(args, "n:zfill", &width))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012759 return NULL;
12760
Benjamin Petersonbac79492012-01-14 13:34:47 -050012761 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010012762 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012763
Victor Stinnerc4b49542011-12-11 22:44:26 +010012764 if (PyUnicode_GET_LENGTH(self) >= width)
12765 return unicode_result_unchanged(self);
12766
12767 fill = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012768
12769 u = pad(self, fill, 0, '0');
12770
Walter Dörwald068325e2002-04-15 13:36:47 +000012771 if (u == NULL)
12772 return NULL;
12773
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012774 kind = PyUnicode_KIND(u);
12775 data = PyUnicode_DATA(u);
12776 chr = PyUnicode_READ(kind, data, fill);
12777
12778 if (chr == '+' || chr == '-') {
Guido van Rossumd57fd912000-03-10 22:53:23 +000012779 /* move sign to beginning of string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012780 PyUnicode_WRITE(kind, data, 0, chr);
12781 PyUnicode_WRITE(kind, data, fill, '0');
Guido van Rossumd57fd912000-03-10 22:53:23 +000012782 }
12783
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012784 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +010012785 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012786}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012787
12788#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012789static PyObject *
12790unicode__decimal2ascii(PyObject *self)
12791{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012792 return PyUnicode_TransformDecimalAndSpaceToASCII(self);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012793}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012794#endif
12795
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012796PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012797 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012798\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000012799Return True if S starts with the specified prefix, False otherwise.\n\
12800With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012801With optional end, stop comparing S at that position.\n\
12802prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012803
12804static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012805unicode_startswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000012806 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012807{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012808 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012809 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012810 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012811 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012812 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012813
Jesus Ceaac451502011-04-20 17:09:23 +020012814 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000012815 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012816 if (PyTuple_Check(subobj)) {
12817 Py_ssize_t i;
12818 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012819 substring = PyUnicode_FromObject(PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012820 if (substring == NULL)
12821 return NULL;
12822 result = tailmatch(self, substring, start, end, -1);
12823 Py_DECREF(substring);
12824 if (result) {
12825 Py_RETURN_TRUE;
12826 }
12827 }
12828 /* nothing matched */
12829 Py_RETURN_FALSE;
12830 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012831 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030012832 if (substring == NULL) {
12833 if (PyErr_ExceptionMatches(PyExc_TypeError))
12834 PyErr_Format(PyExc_TypeError, "startswith first arg must be str or "
12835 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000012836 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030012837 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012838 result = tailmatch(self, substring, start, end, -1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012839 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012840 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012841}
12842
12843
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012844PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012845 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012846\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000012847Return True if S ends with the specified suffix, False otherwise.\n\
12848With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012849With optional end, stop comparing S at that position.\n\
12850suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012851
12852static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012853unicode_endswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000012854 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012855{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012856 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012857 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012858 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012859 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012860 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012861
Jesus Ceaac451502011-04-20 17:09:23 +020012862 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000012863 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012864 if (PyTuple_Check(subobj)) {
12865 Py_ssize_t i;
12866 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012867 substring = PyUnicode_FromObject(
Benjamin Peterson29060642009-01-31 22:14:21 +000012868 PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012869 if (substring == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000012870 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012871 result = tailmatch(self, substring, start, end, +1);
12872 Py_DECREF(substring);
12873 if (result) {
12874 Py_RETURN_TRUE;
12875 }
12876 }
12877 Py_RETURN_FALSE;
12878 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012879 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030012880 if (substring == NULL) {
12881 if (PyErr_ExceptionMatches(PyExc_TypeError))
12882 PyErr_Format(PyExc_TypeError, "endswith first arg must be str or "
12883 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000012884 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030012885 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012886 result = tailmatch(self, substring, start, end, +1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012887 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012888 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012889}
12890
Victor Stinner202fdca2012-05-07 12:47:02 +020012891typedef struct {
12892 PyObject *buffer;
12893 void *data;
12894 enum PyUnicode_Kind kind;
12895 Py_UCS4 maxchar;
12896 Py_ssize_t pos;
Victor Stinner3b1a74a2012-05-09 22:25:00 +020012897} _PyUnicodeWriter ;
Victor Stinner202fdca2012-05-07 12:47:02 +020012898
12899Py_LOCAL_INLINE(void)
Victor Stinner3b1a74a2012-05-09 22:25:00 +020012900_PyUnicodeWriter_Update(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020012901{
12902 writer->maxchar = PyUnicode_MAX_CHAR_VALUE(writer->buffer);
12903 writer->data = PyUnicode_DATA(writer->buffer);
12904 writer->kind = PyUnicode_KIND(writer->buffer);
12905}
12906
12907Py_LOCAL(int)
Victor Stinner3b1a74a2012-05-09 22:25:00 +020012908_PyUnicodeWriter_Init(_PyUnicodeWriter *writer,
Victor Stinner202fdca2012-05-07 12:47:02 +020012909 Py_ssize_t length, Py_UCS4 maxchar)
12910{
12911 writer->pos = 0;
12912 writer->buffer = PyUnicode_New(length, maxchar);
12913 if (writer->buffer == NULL)
12914 return -1;
Victor Stinner3b1a74a2012-05-09 22:25:00 +020012915 _PyUnicodeWriter_Update(writer);
Victor Stinner202fdca2012-05-07 12:47:02 +020012916 return 0;
12917}
12918
12919Py_LOCAL_INLINE(int)
Victor Stinner3b1a74a2012-05-09 22:25:00 +020012920_PyUnicodeWriter_Prepare(_PyUnicodeWriter *writer,
Victor Stinner202fdca2012-05-07 12:47:02 +020012921 Py_ssize_t length, Py_UCS4 maxchar)
12922{
12923 Py_ssize_t newlen;
12924 PyObject *newbuffer;
12925
12926 if (length > PY_SSIZE_T_MAX - writer->pos) {
12927 PyErr_NoMemory();
12928 return -1;
12929 }
12930 newlen = writer->pos + length;
12931
12932 if (newlen > PyUnicode_GET_LENGTH(writer->buffer)) {
Victor Stinner10680252012-05-07 23:50:05 +020012933 /* overallocate 25% to limit the number of resize */
12934 if (newlen <= (PY_SSIZE_T_MAX - newlen / 4))
Victor Stinner202fdca2012-05-07 12:47:02 +020012935 newlen += newlen / 4;
12936
12937 if (maxchar > writer->maxchar) {
12938 /* resize + widen */
12939 newbuffer = PyUnicode_New(newlen, maxchar);
12940 if (newbuffer == NULL)
12941 return -1;
12942 PyUnicode_CopyCharacters(newbuffer, 0,
12943 writer->buffer, 0, writer->pos);
12944 Py_DECREF(writer->buffer);
12945 }
12946 else {
12947 newbuffer = resize_compact(writer->buffer, newlen);
12948 if (newbuffer == NULL)
12949 return -1;
12950 }
12951 writer->buffer = newbuffer;
Victor Stinner3b1a74a2012-05-09 22:25:00 +020012952 _PyUnicodeWriter_Update(writer);
Victor Stinner202fdca2012-05-07 12:47:02 +020012953 }
12954 else if (maxchar > writer->maxchar) {
12955 if (unicode_widen(&writer->buffer, writer->pos, maxchar) < 0)
12956 return -1;
Victor Stinner3b1a74a2012-05-09 22:25:00 +020012957 _PyUnicodeWriter_Update(writer);
Victor Stinner202fdca2012-05-07 12:47:02 +020012958 }
12959 return 0;
12960}
12961
Victor Stinner202fdca2012-05-07 12:47:02 +020012962Py_LOCAL(PyObject *)
Victor Stinner3b1a74a2012-05-09 22:25:00 +020012963_PyUnicodeWriter_Finish(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020012964{
12965 if (PyUnicode_Resize(&writer->buffer, writer->pos) < 0) {
12966 Py_DECREF(writer->buffer);
12967 return NULL;
12968 }
Victor Stinnerf59c28c2012-05-09 03:24:14 +020012969 assert(_PyUnicode_CheckConsistency(writer->buffer, 1));
Victor Stinner202fdca2012-05-07 12:47:02 +020012970 return writer->buffer;
12971}
12972
12973Py_LOCAL(void)
Victor Stinner3b1a74a2012-05-09 22:25:00 +020012974_PyUnicodeWriter_Dealloc(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020012975{
12976 Py_CLEAR(writer->buffer);
12977}
12978
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012979#include "stringlib/unicode_format.h"
Eric Smith8c663262007-08-25 02:26:07 +000012980
12981PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012982 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000012983\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012984Return a formatted version of S, using substitutions from args and kwargs.\n\
12985The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +000012986
Eric Smith27bbca62010-11-04 17:06:58 +000012987PyDoc_STRVAR(format_map__doc__,
12988 "S.format_map(mapping) -> str\n\
12989\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012990Return a formatted version of S, using substitutions from mapping.\n\
12991The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +000012992
Eric Smith4a7d76d2008-05-30 18:10:19 +000012993static PyObject *
12994unicode__format__(PyObject* self, PyObject* args)
12995{
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012996 PyObject *format_spec, *out;
Eric Smith4a7d76d2008-05-30 18:10:19 +000012997
12998 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
12999 return NULL;
13000
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013001 out = _PyUnicode_FormatAdvanced(self, format_spec, 0,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013002 PyUnicode_GET_LENGTH(format_spec));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013003 return out;
Eric Smith4a7d76d2008-05-30 18:10:19 +000013004}
13005
Eric Smith8c663262007-08-25 02:26:07 +000013006PyDoc_STRVAR(p_format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013007 "S.__format__(format_spec) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000013008\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013009Return a formatted version of S as described by format_spec.");
Eric Smith8c663262007-08-25 02:26:07 +000013010
13011static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013012unicode__sizeof__(PyObject *v)
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013013{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013014 Py_ssize_t size;
13015
13016 /* If it's a compact object, account for base structure +
13017 character data. */
13018 if (PyUnicode_IS_COMPACT_ASCII(v))
13019 size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(v) + 1;
13020 else if (PyUnicode_IS_COMPACT(v))
13021 size = sizeof(PyCompactUnicodeObject) +
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013022 (PyUnicode_GET_LENGTH(v) + 1) * PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013023 else {
13024 /* If it is a two-block object, account for base object, and
13025 for character block if present. */
13026 size = sizeof(PyUnicodeObject);
Victor Stinnerc3c74152011-10-02 20:39:55 +020013027 if (_PyUnicode_DATA_ANY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013028 size += (PyUnicode_GET_LENGTH(v) + 1) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013029 PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013030 }
13031 /* If the wstr pointer is present, account for it unless it is shared
Victor Stinnera3be6132011-10-03 02:16:37 +020013032 with the data pointer. Check if the data is not shared. */
Victor Stinner03490912011-10-03 23:45:12 +020013033 if (_PyUnicode_HAS_WSTR_MEMORY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013034 size += (PyUnicode_WSTR_LENGTH(v) + 1) * sizeof(wchar_t);
Victor Stinner829c0ad2011-10-03 01:08:02 +020013035 if (_PyUnicode_HAS_UTF8_MEMORY(v))
Victor Stinnere90fe6a2011-10-01 16:48:13 +020013036 size += PyUnicode_UTF8_LENGTH(v) + 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013037
13038 return PyLong_FromSsize_t(size);
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013039}
13040
13041PyDoc_STRVAR(sizeof__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013042 "S.__sizeof__() -> size of S in memory, in bytes");
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013043
13044static PyObject *
Victor Stinner034f6cf2011-09-30 02:26:44 +020013045unicode_getnewargs(PyObject *v)
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013046{
Victor Stinnerbf6e5602011-12-12 01:53:47 +010013047 PyObject *copy = _PyUnicode_Copy(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013048 if (!copy)
13049 return NULL;
13050 return Py_BuildValue("(N)", copy);
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013051}
13052
Guido van Rossumd57fd912000-03-10 22:53:23 +000013053static PyMethodDef unicode_methods[] = {
Benjamin Peterson28a4dce2010-12-12 01:33:04 +000013054 {"encode", (PyCFunction) unicode_encode, METH_VARARGS | METH_KEYWORDS, encode__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013055 {"replace", (PyCFunction) unicode_replace, METH_VARARGS, replace__doc__},
Ezio Melotticda6b6d2012-02-26 09:39:55 +020013056 {"split", (PyCFunction) unicode_split, METH_VARARGS | METH_KEYWORDS, split__doc__},
13057 {"rsplit", (PyCFunction) unicode_rsplit, METH_VARARGS | METH_KEYWORDS, rsplit__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013058 {"join", (PyCFunction) unicode_join, METH_O, join__doc__},
13059 {"capitalize", (PyCFunction) unicode_capitalize, METH_NOARGS, capitalize__doc__},
Benjamin Petersond5890c82012-01-14 13:23:30 -050013060 {"casefold", (PyCFunction) unicode_casefold, METH_NOARGS, casefold__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013061 {"title", (PyCFunction) unicode_title, METH_NOARGS, title__doc__},
13062 {"center", (PyCFunction) unicode_center, METH_VARARGS, center__doc__},
13063 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
13064 {"expandtabs", (PyCFunction) unicode_expandtabs, METH_VARARGS, expandtabs__doc__},
13065 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013066 {"partition", (PyCFunction) unicode_partition, METH_O, partition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013067 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
13068 {"ljust", (PyCFunction) unicode_ljust, METH_VARARGS, ljust__doc__},
13069 {"lower", (PyCFunction) unicode_lower, METH_NOARGS, lower__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013070 {"lstrip", (PyCFunction) unicode_lstrip, METH_VARARGS, lstrip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013071 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
13072 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
13073 {"rjust", (PyCFunction) unicode_rjust, METH_VARARGS, rjust__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013074 {"rstrip", (PyCFunction) unicode_rstrip, METH_VARARGS, rstrip__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013075 {"rpartition", (PyCFunction) unicode_rpartition, METH_O, rpartition__doc__},
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010013076 {"splitlines", (PyCFunction) unicode_splitlines, METH_VARARGS | METH_KEYWORDS, splitlines__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013077 {"strip", (PyCFunction) unicode_strip, METH_VARARGS, strip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013078 {"swapcase", (PyCFunction) unicode_swapcase, METH_NOARGS, swapcase__doc__},
13079 {"translate", (PyCFunction) unicode_translate, METH_O, translate__doc__},
13080 {"upper", (PyCFunction) unicode_upper, METH_NOARGS, upper__doc__},
13081 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
13082 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
13083 {"islower", (PyCFunction) unicode_islower, METH_NOARGS, islower__doc__},
13084 {"isupper", (PyCFunction) unicode_isupper, METH_NOARGS, isupper__doc__},
13085 {"istitle", (PyCFunction) unicode_istitle, METH_NOARGS, istitle__doc__},
13086 {"isspace", (PyCFunction) unicode_isspace, METH_NOARGS, isspace__doc__},
13087 {"isdecimal", (PyCFunction) unicode_isdecimal, METH_NOARGS, isdecimal__doc__},
13088 {"isdigit", (PyCFunction) unicode_isdigit, METH_NOARGS, isdigit__doc__},
13089 {"isnumeric", (PyCFunction) unicode_isnumeric, METH_NOARGS, isnumeric__doc__},
13090 {"isalpha", (PyCFunction) unicode_isalpha, METH_NOARGS, isalpha__doc__},
13091 {"isalnum", (PyCFunction) unicode_isalnum, METH_NOARGS, isalnum__doc__},
Martin v. Löwis47383402007-08-15 07:32:56 +000013092 {"isidentifier", (PyCFunction) unicode_isidentifier, METH_NOARGS, isidentifier__doc__},
Georg Brandl559e5d72008-06-11 18:37:52 +000013093 {"isprintable", (PyCFunction) unicode_isprintable, METH_NOARGS, isprintable__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013094 {"zfill", (PyCFunction) unicode_zfill, METH_VARARGS, zfill__doc__},
Eric Smith9cd1e092007-08-31 18:39:38 +000013095 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +000013096 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
Eric Smith4a7d76d2008-05-30 18:10:19 +000013097 {"__format__", (PyCFunction) unicode__format__, METH_VARARGS, p_format__doc__},
Georg Brandlceee0772007-11-27 23:48:05 +000013098 {"maketrans", (PyCFunction) unicode_maketrans,
13099 METH_VARARGS | METH_STATIC, maketrans__doc__},
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013100 {"__sizeof__", (PyCFunction) unicode__sizeof__, METH_NOARGS, sizeof__doc__},
Walter Dörwald068325e2002-04-15 13:36:47 +000013101#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013102 /* These methods are just used for debugging the implementation. */
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013103 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013104#endif
13105
Benjamin Peterson14339b62009-01-31 16:36:08 +000013106 {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013107 {NULL, NULL}
13108};
13109
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013110static PyObject *
13111unicode_mod(PyObject *v, PyObject *w)
13112{
Brian Curtindfc80e32011-08-10 20:28:54 -050013113 if (!PyUnicode_Check(v))
13114 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson29060642009-01-31 22:14:21 +000013115 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013116}
13117
13118static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013119 0, /*nb_add*/
13120 0, /*nb_subtract*/
13121 0, /*nb_multiply*/
13122 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013123};
13124
Guido van Rossumd57fd912000-03-10 22:53:23 +000013125static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013126 (lenfunc) unicode_length, /* sq_length */
13127 PyUnicode_Concat, /* sq_concat */
13128 (ssizeargfunc) unicode_repeat, /* sq_repeat */
13129 (ssizeargfunc) unicode_getitem, /* sq_item */
13130 0, /* sq_slice */
13131 0, /* sq_ass_item */
13132 0, /* sq_ass_slice */
13133 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013134};
13135
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013136static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013137unicode_subscript(PyObject* self, PyObject* item)
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013138{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013139 if (PyUnicode_READY(self) == -1)
13140 return NULL;
13141
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000013142 if (PyIndex_Check(item)) {
13143 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013144 if (i == -1 && PyErr_Occurred())
13145 return NULL;
13146 if (i < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013147 i += PyUnicode_GET_LENGTH(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013148 return unicode_getitem(self, i);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013149 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000013150 Py_ssize_t start, stop, step, slicelength, cur, i;
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013151 PyObject *result;
13152 void *src_data, *dest_data;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013153 int src_kind, dest_kind;
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013154 Py_UCS4 ch, max_char, kind_limit;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013155
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013156 if (PySlice_GetIndicesEx(item, PyUnicode_GET_LENGTH(self),
Benjamin Peterson29060642009-01-31 22:14:21 +000013157 &start, &stop, &step, &slicelength) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013158 return NULL;
13159 }
13160
13161 if (slicelength <= 0) {
Victor Stinner382955f2011-12-11 21:44:00 +010013162 Py_INCREF(unicode_empty);
13163 return unicode_empty;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013164 } else if (start == 0 && step == 1 &&
Victor Stinnerc4b49542011-12-11 22:44:26 +010013165 slicelength == PyUnicode_GET_LENGTH(self)) {
13166 return unicode_result_unchanged(self);
Thomas Woutersed03b412007-08-28 21:37:11 +000013167 } else if (step == 1) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013168 return PyUnicode_Substring(self,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013169 start, start + slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013170 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013171 /* General case */
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013172 src_kind = PyUnicode_KIND(self);
13173 src_data = PyUnicode_DATA(self);
Victor Stinner55c99112011-10-13 01:17:06 +020013174 if (!PyUnicode_IS_ASCII(self)) {
13175 kind_limit = kind_maxchar_limit(src_kind);
13176 max_char = 0;
13177 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
13178 ch = PyUnicode_READ(src_kind, src_data, cur);
13179 if (ch > max_char) {
13180 max_char = ch;
13181 if (max_char >= kind_limit)
13182 break;
13183 }
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013184 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013185 }
Victor Stinner55c99112011-10-13 01:17:06 +020013186 else
13187 max_char = 127;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013188 result = PyUnicode_New(slicelength, max_char);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013189 if (result == NULL)
13190 return NULL;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013191 dest_kind = PyUnicode_KIND(result);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013192 dest_data = PyUnicode_DATA(result);
13193
13194 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013195 Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
13196 PyUnicode_WRITE(dest_kind, dest_data, i, ch);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013197 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013198 assert(_PyUnicode_CheckConsistency(result, 1));
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013199 return result;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013200 } else {
13201 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
13202 return NULL;
13203 }
13204}
13205
13206static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013207 (lenfunc)unicode_length, /* mp_length */
13208 (binaryfunc)unicode_subscript, /* mp_subscript */
13209 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013210};
13211
Guido van Rossumd57fd912000-03-10 22:53:23 +000013212
Guido van Rossumd57fd912000-03-10 22:53:23 +000013213/* Helpers for PyUnicode_Format() */
13214
13215static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +000013216getnextarg(PyObject *args, Py_ssize_t arglen, Py_ssize_t *p_argidx)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013217{
Martin v. Löwis18e16552006-02-15 17:27:45 +000013218 Py_ssize_t argidx = *p_argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013219 if (argidx < arglen) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013220 (*p_argidx)++;
13221 if (arglen < 0)
13222 return args;
13223 else
13224 return PyTuple_GetItem(args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013225 }
13226 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013227 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013228 return NULL;
13229}
13230
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013231/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013232
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013233static PyObject *
13234formatfloat(PyObject *v, int flags, int prec, int type)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013235{
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013236 char *p;
13237 PyObject *result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013238 double x;
Tim Petersced69f82003-09-16 20:30:58 +000013239
Guido van Rossumd57fd912000-03-10 22:53:23 +000013240 x = PyFloat_AsDouble(v);
13241 if (x == -1.0 && PyErr_Occurred())
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013242 return NULL;
13243
Guido van Rossumd57fd912000-03-10 22:53:23 +000013244 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000013245 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +000013246
Eric Smith0923d1d2009-04-16 20:16:10 +000013247 p = PyOS_double_to_string(x, type, prec,
13248 (flags & F_ALT) ? Py_DTSF_ALT : 0, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013249 if (p == NULL)
13250 return NULL;
Victor Stinnerb5c3ea32012-05-02 00:29:36 +020013251 result = unicode_fromascii((unsigned char*)p, strlen(p));
Eric Smith0923d1d2009-04-16 20:16:10 +000013252 PyMem_Free(p);
13253 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013254}
13255
Victor Stinnerd0880d52012-04-27 23:40:13 +020013256/* formatlong() emulates the format codes d, u, o, x and X, and
13257 * the F_ALT flag, for Python's long (unbounded) ints. It's not used for
13258 * Python's regular ints.
13259 * Return value: a new PyUnicodeObject*, or NULL if error.
13260 * The output string is of the form
13261 * "-"? ("0x" | "0X")? digit+
13262 * "0x"/"0X" are present only for x and X conversions, with F_ALT
13263 * set in flags. The case of hex digits will be correct,
13264 * There will be at least prec digits, zero-filled on the left if
13265 * necessary to get that many.
13266 * val object to be converted
13267 * flags bitmask of format flags; only F_ALT is looked at
13268 * prec minimum number of digits; 0-fill on left if needed
13269 * type a character in [duoxX]; u acts the same as d
13270 *
13271 * CAUTION: o, x and X conversions on regular ints can never
13272 * produce a '-' sign, but can for Python's unbounded ints.
13273 */
Tim Peters38fd5b62000-09-21 05:43:11 +000013274static PyObject*
13275formatlong(PyObject *val, int flags, int prec, int type)
13276{
Victor Stinnerd0880d52012-04-27 23:40:13 +020013277 PyObject *result = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013278 char *buf;
Victor Stinnerd0880d52012-04-27 23:40:13 +020013279 Py_ssize_t i;
13280 int sign; /* 1 if '-', else 0 */
13281 int len; /* number of characters */
13282 Py_ssize_t llen;
13283 int numdigits; /* len == numnondigits + numdigits */
13284 int numnondigits = 0;
Tim Peters38fd5b62000-09-21 05:43:11 +000013285
Victor Stinnerd0880d52012-04-27 23:40:13 +020013286 /* Avoid exceeding SSIZE_T_MAX */
13287 if (prec > INT_MAX-3) {
13288 PyErr_SetString(PyExc_OverflowError,
13289 "precision too large");
Benjamin Peterson14339b62009-01-31 16:36:08 +000013290 return NULL;
Victor Stinnerd0880d52012-04-27 23:40:13 +020013291 }
13292
13293 assert(PyLong_Check(val));
13294
13295 switch (type) {
13296 case 'd':
13297 case 'u':
13298 /* Special-case boolean: we want 0/1 */
Victor Stinnerb11d91d2012-04-28 00:25:34 +020013299 if (PyBool_Check(val))
13300 result = PyNumber_ToBase(val, 10);
13301 else
13302 result = Py_TYPE(val)->tp_str(val);
Victor Stinnerd0880d52012-04-27 23:40:13 +020013303 break;
13304 case 'o':
13305 numnondigits = 2;
13306 result = PyNumber_ToBase(val, 8);
13307 break;
13308 case 'x':
13309 case 'X':
13310 numnondigits = 2;
13311 result = PyNumber_ToBase(val, 16);
13312 break;
13313 default:
13314 assert(!"'type' not in [duoxX]");
13315 }
13316 if (!result)
13317 return NULL;
13318
13319 assert(unicode_modifiable(result));
13320 assert(PyUnicode_IS_READY(result));
13321 assert(PyUnicode_IS_ASCII(result));
13322
13323 /* To modify the string in-place, there can only be one reference. */
13324 if (Py_REFCNT(result) != 1) {
13325 PyErr_BadInternalCall();
13326 return NULL;
13327 }
13328 buf = PyUnicode_DATA(result);
13329 llen = PyUnicode_GET_LENGTH(result);
13330 if (llen > INT_MAX) {
13331 PyErr_SetString(PyExc_ValueError,
13332 "string too large in _PyBytes_FormatLong");
13333 return NULL;
13334 }
13335 len = (int)llen;
13336 sign = buf[0] == '-';
13337 numnondigits += sign;
13338 numdigits = len - numnondigits;
13339 assert(numdigits > 0);
13340
13341 /* Get rid of base marker unless F_ALT */
13342 if (((flags & F_ALT) == 0 &&
13343 (type == 'o' || type == 'x' || type == 'X'))) {
13344 assert(buf[sign] == '0');
13345 assert(buf[sign+1] == 'x' || buf[sign+1] == 'X' ||
13346 buf[sign+1] == 'o');
13347 numnondigits -= 2;
13348 buf += 2;
13349 len -= 2;
13350 if (sign)
13351 buf[0] = '-';
13352 assert(len == numnondigits + numdigits);
13353 assert(numdigits > 0);
13354 }
13355
13356 /* Fill with leading zeroes to meet minimum width. */
13357 if (prec > numdigits) {
13358 PyObject *r1 = PyBytes_FromStringAndSize(NULL,
13359 numnondigits + prec);
13360 char *b1;
13361 if (!r1) {
13362 Py_DECREF(result);
13363 return NULL;
13364 }
13365 b1 = PyBytes_AS_STRING(r1);
13366 for (i = 0; i < numnondigits; ++i)
13367 *b1++ = *buf++;
13368 for (i = 0; i < prec - numdigits; i++)
13369 *b1++ = '0';
13370 for (i = 0; i < numdigits; i++)
13371 *b1++ = *buf++;
13372 *b1 = '\0';
13373 Py_DECREF(result);
13374 result = r1;
13375 buf = PyBytes_AS_STRING(result);
13376 len = numnondigits + prec;
13377 }
13378
13379 /* Fix up case for hex conversions. */
13380 if (type == 'X') {
13381 /* Need to convert all lower case letters to upper case.
13382 and need to convert 0x to 0X (and -0x to -0X). */
13383 for (i = 0; i < len; i++)
13384 if (buf[i] >= 'a' && buf[i] <= 'x')
13385 buf[i] -= 'a'-'A';
13386 }
13387 if (!PyUnicode_Check(result) || len != PyUnicode_GET_LENGTH(result)) {
13388 PyObject *unicode;
13389 unicode = unicode_fromascii((unsigned char *)buf, len);
13390 Py_DECREF(result);
13391 result = unicode;
13392 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000013393 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +000013394}
13395
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013396static Py_UCS4
13397formatchar(PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013398{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000013399 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000013400 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013401 if (PyUnicode_GET_LENGTH(v) == 1) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013402 return PyUnicode_READ_CHAR(v, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +000013403 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013404 goto onError;
13405 }
13406 else {
13407 /* Integer input truncated to a character */
13408 long x;
13409 x = PyLong_AsLong(v);
13410 if (x == -1 && PyErr_Occurred())
13411 goto onError;
13412
Victor Stinner8faf8212011-12-08 22:14:11 +010013413 if (x < 0 || x > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013414 PyErr_SetString(PyExc_OverflowError,
13415 "%c arg not in range(0x110000)");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013416 return (Py_UCS4) -1;
Benjamin Peterson29060642009-01-31 22:14:21 +000013417 }
13418
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013419 return (Py_UCS4) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013420 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000013421
Benjamin Peterson29060642009-01-31 22:14:21 +000013422 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000013423 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013424 "%c requires int or char");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013425 return (Py_UCS4) -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013426}
13427
Alexander Belopolsky40018472011-02-26 01:02:56 +000013428PyObject *
13429PyUnicode_Format(PyObject *format, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013430{
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013431 Py_ssize_t fmtcnt, fmtpos, arglen, argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013432 int args_owned = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013433 PyObject *dict = NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013434 PyObject *temp = NULL;
13435 PyObject *second = NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013436 PyObject *uformat;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013437 void *fmt;
13438 enum PyUnicode_Kind kind, fmtkind;
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013439 _PyUnicodeWriter writer;
Victor Stinneree4544c2012-05-09 22:24:08 +020013440 Py_ssize_t sublen;
13441 Py_UCS4 maxchar;
Tim Petersced69f82003-09-16 20:30:58 +000013442
Guido van Rossumd57fd912000-03-10 22:53:23 +000013443 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013444 PyErr_BadInternalCall();
13445 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013446 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013447 uformat = PyUnicode_FromObject(format);
Benjamin Peterson22a29702012-01-02 09:00:30 -060013448 if (uformat == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000013449 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060013450 if (PyUnicode_READY(uformat) == -1)
13451 Py_DECREF(uformat);
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013452
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013453 fmt = PyUnicode_DATA(uformat);
13454 fmtkind = PyUnicode_KIND(uformat);
13455 fmtcnt = PyUnicode_GET_LENGTH(uformat);
13456 fmtpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013457
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013458 if (_PyUnicodeWriter_Init(&writer, fmtcnt + 100, 127) < 0)
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013459 goto onError;
13460
Guido van Rossumd57fd912000-03-10 22:53:23 +000013461 if (PyTuple_Check(args)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013462 arglen = PyTuple_Size(args);
13463 argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013464 }
13465 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013466 arglen = -1;
13467 argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013468 }
Christian Heimes90aa7642007-12-19 02:45:37 +000013469 if (Py_TYPE(args)->tp_as_mapping && !PyTuple_Check(args) &&
Christian Heimesf3863112007-11-22 07:46:41 +000013470 !PyUnicode_Check(args))
Benjamin Peterson29060642009-01-31 22:14:21 +000013471 dict = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013472
13473 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013474 if (PyUnicode_READ(fmtkind, fmt, fmtpos) != '%') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013475 Py_ssize_t nonfmtpos;
13476 nonfmtpos = fmtpos++;
13477 while (fmtcnt >= 0 &&
13478 PyUnicode_READ(fmtkind, fmt, fmtpos) != '%') {
13479 fmtpos++;
13480 fmtcnt--;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013481 }
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013482 if (fmtcnt < 0)
13483 fmtpos--;
Victor Stinneree4544c2012-05-09 22:24:08 +020013484 sublen = fmtpos - nonfmtpos;
13485 maxchar = _PyUnicode_FindMaxChar(uformat,
13486 nonfmtpos, nonfmtpos + sublen);
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013487 if (_PyUnicodeWriter_Prepare(&writer, sublen, maxchar) == -1)
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013488 goto onError;
Victor Stinneree4544c2012-05-09 22:24:08 +020013489
13490 copy_characters(writer.buffer, writer.pos,
13491 uformat, nonfmtpos, sublen);
13492 writer.pos += sublen;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013493 }
13494 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013495 /* Got a format specifier */
13496 int flags = 0;
13497 Py_ssize_t width = -1;
13498 int prec = -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013499 Py_UCS4 c = '\0';
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013500 Py_UCS4 fill;
13501 int sign;
13502 Py_UCS4 signchar;
Benjamin Peterson29060642009-01-31 22:14:21 +000013503 int isnumok;
13504 PyObject *v = NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013505 void *pbuf = NULL;
13506 Py_ssize_t pindex, len;
Victor Stinneree4544c2012-05-09 22:24:08 +020013507 Py_UCS4 bufmaxchar;
13508 Py_ssize_t buflen;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013509
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013510 fmtpos++;
Victor Stinner438106b2012-05-02 00:41:57 +020013511 c = PyUnicode_READ(fmtkind, fmt, fmtpos);
13512 if (c == '(') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013513 Py_ssize_t keystart;
Benjamin Peterson29060642009-01-31 22:14:21 +000013514 Py_ssize_t keylen;
13515 PyObject *key;
13516 int pcount = 1;
Christian Heimesa612dc02008-02-24 13:08:18 +000013517
Benjamin Peterson29060642009-01-31 22:14:21 +000013518 if (dict == NULL) {
13519 PyErr_SetString(PyExc_TypeError,
13520 "format requires a mapping");
13521 goto onError;
13522 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013523 ++fmtpos;
Benjamin Peterson29060642009-01-31 22:14:21 +000013524 --fmtcnt;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013525 keystart = fmtpos;
Benjamin Peterson29060642009-01-31 22:14:21 +000013526 /* Skip over balanced parentheses */
13527 while (pcount > 0 && --fmtcnt >= 0) {
Victor Stinnerbff7c962012-05-03 01:44:59 +020013528 c = PyUnicode_READ(fmtkind, fmt, fmtpos);
13529 if (c == ')')
Benjamin Peterson29060642009-01-31 22:14:21 +000013530 --pcount;
Victor Stinnerbff7c962012-05-03 01:44:59 +020013531 else if (c == '(')
Benjamin Peterson29060642009-01-31 22:14:21 +000013532 ++pcount;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013533 fmtpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +000013534 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013535 keylen = fmtpos - keystart - 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000013536 if (fmtcnt < 0 || pcount > 0) {
13537 PyErr_SetString(PyExc_ValueError,
13538 "incomplete format key");
13539 goto onError;
13540 }
Victor Stinner7931d9a2011-11-04 00:22:48 +010013541 key = PyUnicode_Substring(uformat,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013542 keystart, keystart + keylen);
Benjamin Peterson29060642009-01-31 22:14:21 +000013543 if (key == NULL)
13544 goto onError;
13545 if (args_owned) {
13546 Py_DECREF(args);
13547 args_owned = 0;
13548 }
13549 args = PyObject_GetItem(dict, key);
13550 Py_DECREF(key);
13551 if (args == NULL) {
13552 goto onError;
13553 }
13554 args_owned = 1;
13555 arglen = -1;
13556 argidx = -2;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013557 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013558 while (--fmtcnt >= 0) {
Victor Stinner438106b2012-05-02 00:41:57 +020013559 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
13560 switch (c) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013561 case '-': flags |= F_LJUST; continue;
13562 case '+': flags |= F_SIGN; continue;
13563 case ' ': flags |= F_BLANK; continue;
13564 case '#': flags |= F_ALT; continue;
13565 case '0': flags |= F_ZERO; continue;
13566 }
13567 break;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013568 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013569 if (c == '*') {
13570 v = getnextarg(args, arglen, &argidx);
13571 if (v == NULL)
13572 goto onError;
13573 if (!PyLong_Check(v)) {
13574 PyErr_SetString(PyExc_TypeError,
13575 "* wants int");
13576 goto onError;
13577 }
13578 width = PyLong_AsLong(v);
13579 if (width == -1 && PyErr_Occurred())
13580 goto onError;
13581 if (width < 0) {
13582 flags |= F_LJUST;
13583 width = -width;
13584 }
13585 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013586 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013587 }
13588 else if (c >= '0' && c <= '9') {
13589 width = c - '0';
13590 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013591 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013592 if (c < '0' || c > '9')
13593 break;
Mark Dickinson99e2e552012-05-07 11:20:50 +010013594 if (width > (PY_SSIZE_T_MAX - (c - '0')) / 10) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013595 PyErr_SetString(PyExc_ValueError,
13596 "width too big");
Benjamin Peterson14339b62009-01-31 16:36:08 +000013597 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +000013598 }
13599 width = width*10 + (c - '0');
13600 }
13601 }
13602 if (c == '.') {
13603 prec = 0;
13604 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013605 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013606 if (c == '*') {
13607 v = getnextarg(args, arglen, &argidx);
13608 if (v == NULL)
13609 goto onError;
13610 if (!PyLong_Check(v)) {
13611 PyErr_SetString(PyExc_TypeError,
13612 "* wants int");
13613 goto onError;
13614 }
13615 prec = PyLong_AsLong(v);
13616 if (prec == -1 && PyErr_Occurred())
13617 goto onError;
13618 if (prec < 0)
13619 prec = 0;
13620 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013621 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013622 }
13623 else if (c >= '0' && c <= '9') {
13624 prec = c - '0';
13625 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013626 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013627 if (c < '0' || c > '9')
13628 break;
Mark Dickinson99e2e552012-05-07 11:20:50 +010013629 if (prec > (INT_MAX - (c - '0')) / 10) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013630 PyErr_SetString(PyExc_ValueError,
13631 "prec too big");
13632 goto onError;
13633 }
13634 prec = prec*10 + (c - '0');
13635 }
13636 }
13637 } /* prec */
13638 if (fmtcnt >= 0) {
13639 if (c == 'h' || c == 'l' || c == 'L') {
13640 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013641 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013642 }
13643 }
13644 if (fmtcnt < 0) {
13645 PyErr_SetString(PyExc_ValueError,
13646 "incomplete format");
13647 goto onError;
13648 }
Victor Stinneraff3cc62012-04-30 05:19:21 +020013649
13650 if (c == '%') {
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013651 if (_PyUnicodeWriter_Prepare(&writer, 1, '%') == -1)
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013652 goto onError;
Victor Stinneree4544c2012-05-09 22:24:08 +020013653 PyUnicode_WRITE(writer.kind, writer.data, writer.pos, '%');
13654 writer.pos += 1;
Victor Stinneraff3cc62012-04-30 05:19:21 +020013655 continue;
Benjamin Peterson29060642009-01-31 22:14:21 +000013656 }
Victor Stinneraff3cc62012-04-30 05:19:21 +020013657
13658
13659 v = getnextarg(args, arglen, &argidx);
13660 if (v == NULL)
13661 goto onError;
13662
Benjamin Peterson29060642009-01-31 22:14:21 +000013663 sign = 0;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013664 signchar = '\0';
Benjamin Peterson29060642009-01-31 22:14:21 +000013665 fill = ' ';
13666 switch (c) {
13667
Benjamin Peterson29060642009-01-31 22:14:21 +000013668 case 's':
13669 case 'r':
13670 case 'a':
Victor Stinner808fc0a2010-03-22 12:50:40 +000013671 if (PyUnicode_CheckExact(v) && c == 's') {
Benjamin Peterson29060642009-01-31 22:14:21 +000013672 temp = v;
13673 Py_INCREF(temp);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013674 }
13675 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013676 if (c == 's')
13677 temp = PyObject_Str(v);
13678 else if (c == 'r')
13679 temp = PyObject_Repr(v);
13680 else
13681 temp = PyObject_ASCII(v);
Benjamin Peterson29060642009-01-31 22:14:21 +000013682 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013683 break;
13684
13685 case 'i':
13686 case 'd':
13687 case 'u':
13688 case 'o':
13689 case 'x':
13690 case 'X':
Benjamin Peterson29060642009-01-31 22:14:21 +000013691 isnumok = 0;
13692 if (PyNumber_Check(v)) {
13693 PyObject *iobj=NULL;
13694
13695 if (PyLong_Check(v)) {
13696 iobj = v;
13697 Py_INCREF(iobj);
13698 }
13699 else {
13700 iobj = PyNumber_Long(v);
13701 }
13702 if (iobj!=NULL) {
13703 if (PyLong_Check(iobj)) {
13704 isnumok = 1;
Victor Stinneraff3cc62012-04-30 05:19:21 +020013705 sign = 1;
Senthil Kumaran9ebe08d2011-07-03 21:03:16 -070013706 temp = formatlong(iobj, flags, prec, (c == 'i'? 'd': c));
Benjamin Peterson29060642009-01-31 22:14:21 +000013707 Py_DECREF(iobj);
Benjamin Peterson29060642009-01-31 22:14:21 +000013708 }
13709 else {
13710 Py_DECREF(iobj);
13711 }
13712 }
13713 }
13714 if (!isnumok) {
13715 PyErr_Format(PyExc_TypeError,
13716 "%%%c format: a number is required, "
13717 "not %.200s", (char)c, Py_TYPE(v)->tp_name);
13718 goto onError;
13719 }
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013720 if (flags & F_ZERO)
Benjamin Peterson29060642009-01-31 22:14:21 +000013721 fill = '0';
13722 break;
13723
13724 case 'e':
13725 case 'E':
13726 case 'f':
13727 case 'F':
13728 case 'g':
13729 case 'G':
Benjamin Peterson29060642009-01-31 22:14:21 +000013730 sign = 1;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013731 if (flags & F_ZERO)
Benjamin Peterson29060642009-01-31 22:14:21 +000013732 fill = '0';
Victor Stinneraff3cc62012-04-30 05:19:21 +020013733 temp = formatfloat(v, flags, prec, c);
Benjamin Peterson29060642009-01-31 22:14:21 +000013734 break;
13735
13736 case 'c':
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013737 {
13738 Py_UCS4 ch = formatchar(v);
13739 if (ch == (Py_UCS4) -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000013740 goto onError;
Victor Stinnerb5c3ea32012-05-02 00:29:36 +020013741 temp = PyUnicode_FromOrdinal(ch);
Benjamin Peterson29060642009-01-31 22:14:21 +000013742 break;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013743 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013744
13745 default:
13746 PyErr_Format(PyExc_ValueError,
13747 "unsupported format character '%c' (0x%x) "
13748 "at index %zd",
13749 (31<=c && c<=126) ? (char)c : '?',
13750 (int)c,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013751 fmtpos - 1);
Benjamin Peterson29060642009-01-31 22:14:21 +000013752 goto onError;
13753 }
Victor Stinneraff3cc62012-04-30 05:19:21 +020013754 if (temp == NULL)
13755 goto onError;
13756 assert (PyUnicode_Check(temp));
13757 if (PyUnicode_READY(temp) == -1) {
13758 Py_CLEAR(temp);
13759 goto onError;
13760 }
13761 kind = PyUnicode_KIND(temp);
13762 pbuf = PyUnicode_DATA(temp);
13763 len = PyUnicode_GET_LENGTH(temp);
13764
13765 if (c == 's' || c == 'r' || c == 'a') {
13766 if (prec >= 0 && len > prec)
13767 len = prec;
13768 }
13769
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013770 /* pbuf is initialized here. */
13771 pindex = 0;
Benjamin Peterson29060642009-01-31 22:14:21 +000013772 if (sign) {
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013773 Py_UCS4 ch = PyUnicode_READ(kind, pbuf, pindex);
13774 if (ch == '-' || ch == '+') {
13775 signchar = ch;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013776 len--;
13777 pindex++;
Benjamin Peterson29060642009-01-31 22:14:21 +000013778 }
13779 else if (flags & F_SIGN)
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013780 signchar = '+';
Benjamin Peterson29060642009-01-31 22:14:21 +000013781 else if (flags & F_BLANK)
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013782 signchar = ' ';
Benjamin Peterson29060642009-01-31 22:14:21 +000013783 else
13784 sign = 0;
13785 }
13786 if (width < len)
13787 width = len;
Victor Stinneree4544c2012-05-09 22:24:08 +020013788
13789 /* Compute the length and maximum character of the
13790 written characters */
13791 bufmaxchar = 127;
13792 if (!(flags & F_LJUST)) {
13793 if (sign) {
13794 if ((width-1) > len)
13795 bufmaxchar = Py_MAX(bufmaxchar, fill);
13796 }
13797 else {
13798 if (width > len)
13799 bufmaxchar = Py_MAX(bufmaxchar, fill);
13800 }
13801 }
13802 maxchar = _PyUnicode_FindMaxChar(temp, 0, pindex+len);
13803 bufmaxchar = Py_MAX(bufmaxchar, maxchar);
13804
13805 buflen = width;
13806 if (sign && len == width)
13807 buflen++;
13808
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013809 if (_PyUnicodeWriter_Prepare(&writer, buflen, bufmaxchar) == -1)
Victor Stinneree4544c2012-05-09 22:24:08 +020013810 goto onError;
13811
13812 /* Write characters */
Benjamin Peterson29060642009-01-31 22:14:21 +000013813 if (sign) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013814 if (fill != ' ') {
Victor Stinneree4544c2012-05-09 22:24:08 +020013815 PyUnicode_WRITE(writer.kind, writer.data, writer.pos, signchar);
13816 writer.pos += 1;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013817 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013818 if (width > len)
13819 width--;
13820 }
13821 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013822 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013823 assert(PyUnicode_READ(kind, pbuf, pindex + 1) == c);
Benjamin Peterson29060642009-01-31 22:14:21 +000013824 if (fill != ' ') {
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013825 PyUnicode_WRITE(writer.kind, writer.data, writer.pos, '0');
13826 PyUnicode_WRITE(writer.kind, writer.data, writer.pos+1, c);
13827 writer.pos += 2;
13828 pindex += 2;
Benjamin Peterson29060642009-01-31 22:14:21 +000013829 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013830 width -= 2;
13831 if (width < 0)
13832 width = 0;
13833 len -= 2;
13834 }
13835 if (width > len && !(flags & F_LJUST)) {
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013836 sublen = width - len;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013837 FILL(writer.kind, writer.data, fill, writer.pos, sublen);
13838 writer.pos += sublen;
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013839 width = len;
Benjamin Peterson29060642009-01-31 22:14:21 +000013840 }
13841 if (fill == ' ') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013842 if (sign) {
Victor Stinneree4544c2012-05-09 22:24:08 +020013843 PyUnicode_WRITE(writer.kind, writer.data, writer.pos, signchar);
13844 writer.pos += 1;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013845 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013846 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013847 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
13848 assert(PyUnicode_READ(kind, pbuf, pindex+1) == c);
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013849 PyUnicode_WRITE(writer.kind, writer.data, writer.pos, '0');
13850 PyUnicode_WRITE(writer.kind, writer.data, writer.pos+1, c);
13851 writer.pos += 2;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013852 pindex += 2;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013853 }
13854 }
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013855
Victor Stinneree4544c2012-05-09 22:24:08 +020013856 copy_characters(writer.buffer, writer.pos,
13857 temp, pindex, len);
13858 writer.pos += len;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013859 if (width > len) {
Victor Stinneree4544c2012-05-09 22:24:08 +020013860 sublen = width - len;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013861 FILL(writer.kind, writer.data, ' ', writer.pos, sublen);
13862 writer.pos += sublen;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013863 }
Victor Stinneree4544c2012-05-09 22:24:08 +020013864
Benjamin Peterson29060642009-01-31 22:14:21 +000013865 if (dict && (argidx < arglen) && c != '%') {
13866 PyErr_SetString(PyExc_TypeError,
13867 "not all arguments converted during string formatting");
Benjamin Peterson29060642009-01-31 22:14:21 +000013868 goto onError;
13869 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013870 Py_CLEAR(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013871 } /* '%' */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013872 } /* until end */
13873 if (argidx < arglen && !dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013874 PyErr_SetString(PyExc_TypeError,
13875 "not all arguments converted during string formatting");
13876 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013877 }
13878
13879 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013880 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013881 }
13882 Py_DECREF(uformat);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013883 Py_XDECREF(temp);
13884 Py_XDECREF(second);
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013885 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013886
Benjamin Peterson29060642009-01-31 22:14:21 +000013887 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000013888 Py_DECREF(uformat);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013889 Py_XDECREF(temp);
13890 Py_XDECREF(second);
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013891 _PyUnicodeWriter_Dealloc(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013892 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013893 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013894 }
13895 return NULL;
13896}
13897
Jeremy Hylton938ace62002-07-17 16:30:39 +000013898static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +000013899unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
13900
Tim Peters6d6c1a32001-08-02 04:15:00 +000013901static PyObject *
13902unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
13903{
Benjamin Peterson29060642009-01-31 22:14:21 +000013904 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013905 static char *kwlist[] = {"object", "encoding", "errors", 0};
13906 char *encoding = NULL;
13907 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000013908
Benjamin Peterson14339b62009-01-31 16:36:08 +000013909 if (type != &PyUnicode_Type)
13910 return unicode_subtype_new(type, args, kwds);
13911 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +000013912 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +000013913 return NULL;
Victor Stinner382955f2011-12-11 21:44:00 +010013914 if (x == NULL) {
13915 Py_INCREF(unicode_empty);
13916 return unicode_empty;
13917 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000013918 if (encoding == NULL && errors == NULL)
13919 return PyObject_Str(x);
13920 else
Benjamin Peterson29060642009-01-31 22:14:21 +000013921 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +000013922}
13923
Guido van Rossume023fe02001-08-30 03:12:59 +000013924static PyObject *
13925unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
13926{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013927 PyObject *unicode, *self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013928 Py_ssize_t length, char_size;
13929 int share_wstr, share_utf8;
13930 unsigned int kind;
13931 void *data;
Guido van Rossume023fe02001-08-30 03:12:59 +000013932
Benjamin Peterson14339b62009-01-31 16:36:08 +000013933 assert(PyType_IsSubtype(type, &PyUnicode_Type));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013934
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013935 unicode = unicode_new(&PyUnicode_Type, args, kwds);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013936 if (unicode == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000013937 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020013938 assert(_PyUnicode_CHECK(unicode));
Benjamin Petersonbac79492012-01-14 13:34:47 -050013939 if (PyUnicode_READY(unicode) == -1) {
Benjamin Peterson22a29702012-01-02 09:00:30 -060013940 Py_DECREF(unicode);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013941 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060013942 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013943
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013944 self = type->tp_alloc(type, 0);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013945 if (self == NULL) {
13946 Py_DECREF(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013947 return NULL;
13948 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013949 kind = PyUnicode_KIND(unicode);
13950 length = PyUnicode_GET_LENGTH(unicode);
13951
13952 _PyUnicode_LENGTH(self) = length;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020013953#ifdef Py_DEBUG
13954 _PyUnicode_HASH(self) = -1;
13955#else
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013956 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020013957#endif
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013958 _PyUnicode_STATE(self).interned = 0;
13959 _PyUnicode_STATE(self).kind = kind;
13960 _PyUnicode_STATE(self).compact = 0;
Victor Stinner3cf46372011-10-03 14:42:15 +020013961 _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013962 _PyUnicode_STATE(self).ready = 1;
13963 _PyUnicode_WSTR(self) = NULL;
13964 _PyUnicode_UTF8_LENGTH(self) = 0;
13965 _PyUnicode_UTF8(self) = NULL;
13966 _PyUnicode_WSTR_LENGTH(self) = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +020013967 _PyUnicode_DATA_ANY(self) = NULL;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013968
13969 share_utf8 = 0;
13970 share_wstr = 0;
13971 if (kind == PyUnicode_1BYTE_KIND) {
13972 char_size = 1;
13973 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
13974 share_utf8 = 1;
13975 }
13976 else if (kind == PyUnicode_2BYTE_KIND) {
13977 char_size = 2;
13978 if (sizeof(wchar_t) == 2)
13979 share_wstr = 1;
13980 }
13981 else {
13982 assert(kind == PyUnicode_4BYTE_KIND);
13983 char_size = 4;
13984 if (sizeof(wchar_t) == 4)
13985 share_wstr = 1;
13986 }
13987
13988 /* Ensure we won't overflow the length. */
13989 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
13990 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013991 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013992 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013993 data = PyObject_MALLOC((length + 1) * char_size);
13994 if (data == NULL) {
13995 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013996 goto onError;
13997 }
13998
Victor Stinnerc3c74152011-10-02 20:39:55 +020013999 _PyUnicode_DATA_ANY(self) = data;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014000 if (share_utf8) {
14001 _PyUnicode_UTF8_LENGTH(self) = length;
14002 _PyUnicode_UTF8(self) = data;
14003 }
14004 if (share_wstr) {
14005 _PyUnicode_WSTR_LENGTH(self) = length;
14006 _PyUnicode_WSTR(self) = (wchar_t *)data;
14007 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014008
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014009 Py_MEMCPY(data, PyUnicode_DATA(unicode),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020014010 kind * (length + 1));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020014011 assert(_PyUnicode_CheckConsistency(self, 1));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014012#ifdef Py_DEBUG
14013 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
14014#endif
Victor Stinnerdd18d3a2011-10-22 11:08:10 +020014015 Py_DECREF(unicode);
Victor Stinner7931d9a2011-11-04 00:22:48 +010014016 return self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014017
14018onError:
14019 Py_DECREF(unicode);
14020 Py_DECREF(self);
14021 return NULL;
Guido van Rossume023fe02001-08-30 03:12:59 +000014022}
14023
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000014024PyDoc_STRVAR(unicode_doc,
Benjamin Peterson29060642009-01-31 22:14:21 +000014025 "str(string[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +000014026\n\
Collin Winterd474ce82007-08-07 19:42:11 +000014027Create a new string object from the given encoded string.\n\
Skip Montanaro35b37a52002-07-26 16:22:46 +000014028encoding defaults to the current default string encoding.\n\
14029errors can be 'strict', 'replace' or 'ignore' and defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +000014030
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014031static PyObject *unicode_iter(PyObject *seq);
14032
Guido van Rossumd57fd912000-03-10 22:53:23 +000014033PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000014034 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Benjamin Peterson14339b62009-01-31 16:36:08 +000014035 "str", /* tp_name */
14036 sizeof(PyUnicodeObject), /* tp_size */
14037 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014038 /* Slots */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014039 (destructor)unicode_dealloc, /* tp_dealloc */
14040 0, /* tp_print */
14041 0, /* tp_getattr */
14042 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000014043 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014044 unicode_repr, /* tp_repr */
14045 &unicode_as_number, /* tp_as_number */
14046 &unicode_as_sequence, /* tp_as_sequence */
14047 &unicode_as_mapping, /* tp_as_mapping */
14048 (hashfunc) unicode_hash, /* tp_hash*/
14049 0, /* tp_call*/
14050 (reprfunc) unicode_str, /* tp_str */
14051 PyObject_GenericGetAttr, /* tp_getattro */
14052 0, /* tp_setattro */
14053 0, /* tp_as_buffer */
14054 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Benjamin Peterson29060642009-01-31 22:14:21 +000014055 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014056 unicode_doc, /* tp_doc */
14057 0, /* tp_traverse */
14058 0, /* tp_clear */
14059 PyUnicode_RichCompare, /* tp_richcompare */
14060 0, /* tp_weaklistoffset */
14061 unicode_iter, /* tp_iter */
14062 0, /* tp_iternext */
14063 unicode_methods, /* tp_methods */
14064 0, /* tp_members */
14065 0, /* tp_getset */
14066 &PyBaseObject_Type, /* tp_base */
14067 0, /* tp_dict */
14068 0, /* tp_descr_get */
14069 0, /* tp_descr_set */
14070 0, /* tp_dictoffset */
14071 0, /* tp_init */
14072 0, /* tp_alloc */
14073 unicode_new, /* tp_new */
14074 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014075};
14076
14077/* Initialize the Unicode implementation */
14078
Victor Stinner3a50e702011-10-18 21:21:00 +020014079int _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014080{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014081 int i;
14082
Thomas Wouters477c8d52006-05-27 19:21:47 +000014083 /* XXX - move this array to unicodectype.c ? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014084 Py_UCS2 linebreak[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +000014085 0x000A, /* LINE FEED */
14086 0x000D, /* CARRIAGE RETURN */
14087 0x001C, /* FILE SEPARATOR */
14088 0x001D, /* GROUP SEPARATOR */
14089 0x001E, /* RECORD SEPARATOR */
14090 0x0085, /* NEXT LINE */
14091 0x2028, /* LINE SEPARATOR */
14092 0x2029, /* PARAGRAPH SEPARATOR */
14093 };
14094
Fred Drakee4315f52000-05-09 19:53:39 +000014095 /* Init the implementation */
Victor Stinnera464fc12011-10-02 20:39:30 +020014096 unicode_empty = PyUnicode_New(0, 0);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014097 if (!unicode_empty)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014098 Py_FatalError("Can't create empty string");
Victor Stinnerd3df8ab2011-11-22 01:22:34 +010014099 assert(_PyUnicode_CheckConsistency(unicode_empty, 1));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014100
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014101 for (i = 0; i < 256; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +000014102 unicode_latin1[i] = NULL;
Guido van Rossumcacfc072002-05-24 19:01:59 +000014103 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000014104 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +000014105
14106 /* initialize the linebreak bloom filter */
14107 bloom_linebreak = make_bloom_mask(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014108 PyUnicode_2BYTE_KIND, linebreak,
Victor Stinner63941882011-09-29 00:42:28 +020014109 Py_ARRAY_LENGTH(linebreak));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014110
14111 PyType_Ready(&EncodingMapType);
Victor Stinner3a50e702011-10-18 21:21:00 +020014112
14113#ifdef HAVE_MBCS
14114 winver.dwOSVersionInfoSize = sizeof(winver);
14115 if (!GetVersionEx((OSVERSIONINFO*)&winver)) {
14116 PyErr_SetFromWindowsErr(0);
14117 return -1;
14118 }
14119#endif
14120 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014121}
14122
14123/* Finalize the Unicode implementation */
14124
Christian Heimesa156e092008-02-16 07:38:31 +000014125int
14126PyUnicode_ClearFreeList(void)
14127{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014128 return 0;
Christian Heimesa156e092008-02-16 07:38:31 +000014129}
14130
Guido van Rossumd57fd912000-03-10 22:53:23 +000014131void
Thomas Wouters78890102000-07-22 19:25:51 +000014132_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014133{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014134 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014135
Guido van Rossum4ae8ef82000-10-03 18:09:04 +000014136 Py_XDECREF(unicode_empty);
14137 unicode_empty = NULL;
Barry Warsaw5b4c2282000-10-03 20:45:26 +000014138
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014139 for (i = 0; i < 256; i++) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014140 if (unicode_latin1[i]) {
14141 Py_DECREF(unicode_latin1[i]);
14142 unicode_latin1[i] = NULL;
14143 }
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014144 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020014145 _PyUnicode_ClearStaticStrings();
Christian Heimesa156e092008-02-16 07:38:31 +000014146 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +000014147}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000014148
Walter Dörwald16807132007-05-25 13:52:07 +000014149void
14150PyUnicode_InternInPlace(PyObject **p)
14151{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014152 register PyObject *s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014153 PyObject *t;
Victor Stinner4fae54c2011-10-03 02:01:52 +020014154#ifdef Py_DEBUG
14155 assert(s != NULL);
14156 assert(_PyUnicode_CHECK(s));
14157#else
Benjamin Peterson14339b62009-01-31 16:36:08 +000014158 if (s == NULL || !PyUnicode_Check(s))
Victor Stinner4fae54c2011-10-03 02:01:52 +020014159 return;
14160#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000014161 /* If it's a subclass, we don't really know what putting
14162 it in the interned dict might do. */
14163 if (!PyUnicode_CheckExact(s))
14164 return;
14165 if (PyUnicode_CHECK_INTERNED(s))
14166 return;
14167 if (interned == NULL) {
14168 interned = PyDict_New();
14169 if (interned == NULL) {
14170 PyErr_Clear(); /* Don't leave an exception */
14171 return;
14172 }
14173 }
14174 /* It might be that the GetItem call fails even
14175 though the key is present in the dictionary,
14176 namely when this happens during a stack overflow. */
14177 Py_ALLOW_RECURSION
Victor Stinner7931d9a2011-11-04 00:22:48 +010014178 t = PyDict_GetItem(interned, s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014179 Py_END_ALLOW_RECURSION
Martin v. Löwis5b222132007-06-10 09:51:05 +000014180
Benjamin Peterson29060642009-01-31 22:14:21 +000014181 if (t) {
14182 Py_INCREF(t);
14183 Py_DECREF(*p);
14184 *p = t;
14185 return;
14186 }
Walter Dörwald16807132007-05-25 13:52:07 +000014187
Benjamin Peterson14339b62009-01-31 16:36:08 +000014188 PyThreadState_GET()->recursion_critical = 1;
Victor Stinner7931d9a2011-11-04 00:22:48 +010014189 if (PyDict_SetItem(interned, s, s) < 0) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014190 PyErr_Clear();
14191 PyThreadState_GET()->recursion_critical = 0;
14192 return;
14193 }
14194 PyThreadState_GET()->recursion_critical = 0;
14195 /* The two references in interned are not counted by refcnt.
14196 The deallocator will take care of this */
14197 Py_REFCNT(s) -= 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014198 _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000014199}
14200
14201void
14202PyUnicode_InternImmortal(PyObject **p)
14203{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014204 PyUnicode_InternInPlace(p);
14205 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
Victor Stinneraf9e4b82011-10-23 20:07:00 +020014206 _PyUnicode_STATE(*p).interned = SSTATE_INTERNED_IMMORTAL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014207 Py_INCREF(*p);
14208 }
Walter Dörwald16807132007-05-25 13:52:07 +000014209}
14210
14211PyObject *
14212PyUnicode_InternFromString(const char *cp)
14213{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014214 PyObject *s = PyUnicode_FromString(cp);
14215 if (s == NULL)
14216 return NULL;
14217 PyUnicode_InternInPlace(&s);
14218 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000014219}
14220
Alexander Belopolsky40018472011-02-26 01:02:56 +000014221void
14222_Py_ReleaseInternedUnicodeStrings(void)
Walter Dörwald16807132007-05-25 13:52:07 +000014223{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014224 PyObject *keys;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014225 PyObject *s;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014226 Py_ssize_t i, n;
14227 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000014228
Benjamin Peterson14339b62009-01-31 16:36:08 +000014229 if (interned == NULL || !PyDict_Check(interned))
14230 return;
14231 keys = PyDict_Keys(interned);
14232 if (keys == NULL || !PyList_Check(keys)) {
14233 PyErr_Clear();
14234 return;
14235 }
Walter Dörwald16807132007-05-25 13:52:07 +000014236
Benjamin Peterson14339b62009-01-31 16:36:08 +000014237 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
14238 detector, interned unicode strings are not forcibly deallocated;
14239 rather, we give them their stolen references back, and then clear
14240 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000014241
Benjamin Peterson14339b62009-01-31 16:36:08 +000014242 n = PyList_GET_SIZE(keys);
14243 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000014244 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014245 for (i = 0; i < n; i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014246 s = PyList_GET_ITEM(keys, i);
Victor Stinner6b56a7f2011-10-04 20:04:52 +020014247 if (PyUnicode_READY(s) == -1) {
14248 assert(0 && "could not ready string");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014249 fprintf(stderr, "could not ready string\n");
Victor Stinner6b56a7f2011-10-04 20:04:52 +020014250 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014251 switch (PyUnicode_CHECK_INTERNED(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014252 case SSTATE_NOT_INTERNED:
14253 /* XXX Shouldn't happen */
14254 break;
14255 case SSTATE_INTERNED_IMMORTAL:
14256 Py_REFCNT(s) += 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014257 immortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014258 break;
14259 case SSTATE_INTERNED_MORTAL:
14260 Py_REFCNT(s) += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014261 mortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014262 break;
14263 default:
14264 Py_FatalError("Inconsistent interned string state.");
14265 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014266 _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014267 }
14268 fprintf(stderr, "total size of all interned strings: "
14269 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
14270 "mortal/immortal\n", mortal_size, immortal_size);
14271 Py_DECREF(keys);
14272 PyDict_Clear(interned);
14273 Py_DECREF(interned);
14274 interned = NULL;
Walter Dörwald16807132007-05-25 13:52:07 +000014275}
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014276
14277
14278/********************* Unicode Iterator **************************/
14279
14280typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014281 PyObject_HEAD
14282 Py_ssize_t it_index;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014283 PyObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014284} unicodeiterobject;
14285
14286static void
14287unicodeiter_dealloc(unicodeiterobject *it)
14288{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014289 _PyObject_GC_UNTRACK(it);
14290 Py_XDECREF(it->it_seq);
14291 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014292}
14293
14294static int
14295unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
14296{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014297 Py_VISIT(it->it_seq);
14298 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014299}
14300
14301static PyObject *
14302unicodeiter_next(unicodeiterobject *it)
14303{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014304 PyObject *seq, *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014305
Benjamin Peterson14339b62009-01-31 16:36:08 +000014306 assert(it != NULL);
14307 seq = it->it_seq;
14308 if (seq == NULL)
14309 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020014310 assert(_PyUnicode_CHECK(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014311
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014312 if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
14313 int kind = PyUnicode_KIND(seq);
14314 void *data = PyUnicode_DATA(seq);
14315 Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
14316 item = PyUnicode_FromOrdinal(chr);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014317 if (item != NULL)
14318 ++it->it_index;
14319 return item;
14320 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014321
Benjamin Peterson14339b62009-01-31 16:36:08 +000014322 Py_DECREF(seq);
14323 it->it_seq = NULL;
14324 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014325}
14326
14327static PyObject *
14328unicodeiter_len(unicodeiterobject *it)
14329{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014330 Py_ssize_t len = 0;
14331 if (it->it_seq)
Victor Stinnerc4f281e2011-10-11 22:11:42 +020014332 len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014333 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014334}
14335
14336PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
14337
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000014338static PyObject *
14339unicodeiter_reduce(unicodeiterobject *it)
14340{
14341 if (it->it_seq != NULL) {
Antoine Pitroua7013882012-04-05 00:04:20 +020014342 return Py_BuildValue("N(O)n", _PyObject_GetBuiltin("iter"),
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000014343 it->it_seq, it->it_index);
14344 } else {
14345 PyObject *u = PyUnicode_FromUnicode(NULL, 0);
14346 if (u == NULL)
14347 return NULL;
Antoine Pitroua7013882012-04-05 00:04:20 +020014348 return Py_BuildValue("N(N)", _PyObject_GetBuiltin("iter"), u);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000014349 }
14350}
14351
14352PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
14353
14354static PyObject *
14355unicodeiter_setstate(unicodeiterobject *it, PyObject *state)
14356{
14357 Py_ssize_t index = PyLong_AsSsize_t(state);
14358 if (index == -1 && PyErr_Occurred())
14359 return NULL;
14360 if (index < 0)
14361 index = 0;
14362 it->it_index = index;
14363 Py_RETURN_NONE;
14364}
14365
14366PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
14367
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014368static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014369 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000014370 length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000014371 {"__reduce__", (PyCFunction)unicodeiter_reduce, METH_NOARGS,
14372 reduce_doc},
14373 {"__setstate__", (PyCFunction)unicodeiter_setstate, METH_O,
14374 setstate_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000014375 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014376};
14377
14378PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014379 PyVarObject_HEAD_INIT(&PyType_Type, 0)
14380 "str_iterator", /* tp_name */
14381 sizeof(unicodeiterobject), /* tp_basicsize */
14382 0, /* tp_itemsize */
14383 /* methods */
14384 (destructor)unicodeiter_dealloc, /* tp_dealloc */
14385 0, /* tp_print */
14386 0, /* tp_getattr */
14387 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000014388 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014389 0, /* tp_repr */
14390 0, /* tp_as_number */
14391 0, /* tp_as_sequence */
14392 0, /* tp_as_mapping */
14393 0, /* tp_hash */
14394 0, /* tp_call */
14395 0, /* tp_str */
14396 PyObject_GenericGetAttr, /* tp_getattro */
14397 0, /* tp_setattro */
14398 0, /* tp_as_buffer */
14399 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
14400 0, /* tp_doc */
14401 (traverseproc)unicodeiter_traverse, /* tp_traverse */
14402 0, /* tp_clear */
14403 0, /* tp_richcompare */
14404 0, /* tp_weaklistoffset */
14405 PyObject_SelfIter, /* tp_iter */
14406 (iternextfunc)unicodeiter_next, /* tp_iternext */
14407 unicodeiter_methods, /* tp_methods */
14408 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014409};
14410
14411static PyObject *
14412unicode_iter(PyObject *seq)
14413{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014414 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014415
Benjamin Peterson14339b62009-01-31 16:36:08 +000014416 if (!PyUnicode_Check(seq)) {
14417 PyErr_BadInternalCall();
14418 return NULL;
14419 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014420 if (PyUnicode_READY(seq) == -1)
14421 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014422 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
14423 if (it == NULL)
14424 return NULL;
14425 it->it_index = 0;
14426 Py_INCREF(seq);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014427 it->it_seq = seq;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014428 _PyObject_GC_TRACK(it);
14429 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014430}
14431
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010014432
14433size_t
14434Py_UNICODE_strlen(const Py_UNICODE *u)
14435{
14436 int res = 0;
14437 while(*u++)
14438 res++;
14439 return res;
14440}
14441
14442Py_UNICODE*
14443Py_UNICODE_strcpy(Py_UNICODE *s1, const Py_UNICODE *s2)
14444{
14445 Py_UNICODE *u = s1;
14446 while ((*u++ = *s2++));
14447 return s1;
14448}
14449
14450Py_UNICODE*
14451Py_UNICODE_strncpy(Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
14452{
14453 Py_UNICODE *u = s1;
14454 while ((*u++ = *s2++))
14455 if (n-- == 0)
14456 break;
14457 return s1;
14458}
14459
14460Py_UNICODE*
14461Py_UNICODE_strcat(Py_UNICODE *s1, const Py_UNICODE *s2)
14462{
14463 Py_UNICODE *u1 = s1;
14464 u1 += Py_UNICODE_strlen(u1);
14465 Py_UNICODE_strcpy(u1, s2);
14466 return s1;
14467}
14468
14469int
14470Py_UNICODE_strcmp(const Py_UNICODE *s1, const Py_UNICODE *s2)
14471{
14472 while (*s1 && *s2 && *s1 == *s2)
14473 s1++, s2++;
14474 if (*s1 && *s2)
14475 return (*s1 < *s2) ? -1 : +1;
14476 if (*s1)
14477 return 1;
14478 if (*s2)
14479 return -1;
14480 return 0;
14481}
14482
14483int
14484Py_UNICODE_strncmp(const Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
14485{
14486 register Py_UNICODE u1, u2;
14487 for (; n != 0; n--) {
14488 u1 = *s1;
14489 u2 = *s2;
14490 if (u1 != u2)
14491 return (u1 < u2) ? -1 : +1;
14492 if (u1 == '\0')
14493 return 0;
14494 s1++;
14495 s2++;
14496 }
14497 return 0;
14498}
14499
14500Py_UNICODE*
14501Py_UNICODE_strchr(const Py_UNICODE *s, Py_UNICODE c)
14502{
14503 const Py_UNICODE *p;
14504 for (p = s; *p; p++)
14505 if (*p == c)
14506 return (Py_UNICODE*)p;
14507 return NULL;
14508}
14509
14510Py_UNICODE*
14511Py_UNICODE_strrchr(const Py_UNICODE *s, Py_UNICODE c)
14512{
14513 const Py_UNICODE *p;
14514 p = s + Py_UNICODE_strlen(s);
14515 while (p != s) {
14516 p--;
14517 if (*p == c)
14518 return (Py_UNICODE*)p;
14519 }
14520 return NULL;
14521}
Victor Stinner331ea922010-08-10 16:37:20 +000014522
Victor Stinner71133ff2010-09-01 23:43:53 +000014523Py_UNICODE*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014524PyUnicode_AsUnicodeCopy(PyObject *unicode)
Victor Stinner71133ff2010-09-01 23:43:53 +000014525{
Victor Stinner577db2c2011-10-11 22:12:48 +020014526 Py_UNICODE *u, *copy;
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014527 Py_ssize_t len, size;
Victor Stinner71133ff2010-09-01 23:43:53 +000014528
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014529 if (!PyUnicode_Check(unicode)) {
14530 PyErr_BadArgument();
14531 return NULL;
14532 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014533 u = PyUnicode_AsUnicodeAndSize(unicode, &len);
Victor Stinner577db2c2011-10-11 22:12:48 +020014534 if (u == NULL)
14535 return NULL;
Victor Stinner71133ff2010-09-01 23:43:53 +000014536 /* Ensure we won't overflow the size. */
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014537 if (len > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
Victor Stinner71133ff2010-09-01 23:43:53 +000014538 PyErr_NoMemory();
14539 return NULL;
14540 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014541 size = len + 1; /* copy the null character */
Victor Stinner71133ff2010-09-01 23:43:53 +000014542 size *= sizeof(Py_UNICODE);
14543 copy = PyMem_Malloc(size);
14544 if (copy == NULL) {
14545 PyErr_NoMemory();
14546 return NULL;
14547 }
Victor Stinner577db2c2011-10-11 22:12:48 +020014548 memcpy(copy, u, size);
Victor Stinner71133ff2010-09-01 23:43:53 +000014549 return copy;
14550}
Martin v. Löwis5b222132007-06-10 09:51:05 +000014551
Georg Brandl66c221e2010-10-14 07:04:07 +000014552/* A _string module, to export formatter_parser and formatter_field_name_split
14553 to the string.Formatter class implemented in Python. */
14554
14555static PyMethodDef _string_methods[] = {
14556 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
14557 METH_O, PyDoc_STR("split the argument as a field name")},
14558 {"formatter_parser", (PyCFunction) formatter_parser,
14559 METH_O, PyDoc_STR("parse the argument as a format string")},
14560 {NULL, NULL}
14561};
14562
14563static struct PyModuleDef _string_module = {
14564 PyModuleDef_HEAD_INIT,
14565 "_string",
14566 PyDoc_STR("string helper module"),
14567 0,
14568 _string_methods,
14569 NULL,
14570 NULL,
14571 NULL,
14572 NULL
14573};
14574
14575PyMODINIT_FUNC
14576PyInit__string(void)
14577{
14578 return PyModule_Create(&_string_module);
14579}
14580
14581
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000014582#ifdef __cplusplus
14583}
14584#endif