blob: e6fe1fba4e2a9c5ba9ffe91287a2fe2d33c8b8e0 [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 = \
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +0200162 _iter + _Py_SIZE_ROUND_DOWN(n, 4); \
Antoine Pitroue459a082011-10-11 20:58:41 +0200163 while (_iter < (_unrolled_end)) { \
164 _to[0] = (to_type) _iter[0]; \
165 _to[1] = (to_type) _iter[1]; \
166 _to[2] = (to_type) _iter[2]; \
167 _to[3] = (to_type) _iter[3]; \
168 _iter += 4; _to += 4; \
Victor Stinner910337b2011-10-03 03:20:16 +0200169 } \
Antoine Pitroue459a082011-10-11 20:58:41 +0200170 while (_iter < (_end)) \
171 *_to++ = (to_type) *_iter++; \
Victor Stinner910337b2011-10-03 03:20:16 +0200172 } while (0)
Victor Stinner829c0ad2011-10-03 01:08:02 +0200173
Walter Dörwald16807132007-05-25 13:52:07 +0000174/* This dictionary holds all interned unicode strings. Note that references
175 to strings in this dictionary are *not* counted in the string's ob_refcnt.
176 When the interned string reaches a refcnt of 0 the string deallocation
177 function will delete the reference from this dictionary.
178
179 Another way to look at this is that to say that the actual reference
Guido van Rossum98297ee2007-11-06 21:34:58 +0000180 count of a string is: s->ob_refcnt + (s->state ? 2 : 0)
Walter Dörwald16807132007-05-25 13:52:07 +0000181*/
182static PyObject *interned;
183
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000184/* The empty Unicode object is shared to improve performance. */
Victor Stinnera464fc12011-10-02 20:39:30 +0200185static PyObject *unicode_empty;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000186
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200187/* List of static strings. */
188static _Py_Identifier *static_strings;
189
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000190/* Single character Unicode strings in the Latin-1 range are being
191 shared as well. */
Victor Stinnera464fc12011-10-02 20:39:30 +0200192static PyObject *unicode_latin1[256];
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000193
Christian Heimes190d79e2008-01-30 11:58:22 +0000194/* Fast detection of the most frequent whitespace characters */
195const unsigned char _Py_ascii_whitespace[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000196 0, 0, 0, 0, 0, 0, 0, 0,
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000197/* case 0x0009: * CHARACTER TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000198/* case 0x000A: * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000199/* case 0x000B: * LINE TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000200/* case 0x000C: * FORM FEED */
201/* case 0x000D: * CARRIAGE RETURN */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000202 0, 1, 1, 1, 1, 1, 0, 0,
203 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000204/* case 0x001C: * FILE SEPARATOR */
205/* case 0x001D: * GROUP SEPARATOR */
206/* case 0x001E: * RECORD SEPARATOR */
207/* case 0x001F: * UNIT SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000208 0, 0, 0, 0, 1, 1, 1, 1,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000209/* case 0x0020: * SPACE */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000210 1, 0, 0, 0, 0, 0, 0, 0,
211 0, 0, 0, 0, 0, 0, 0, 0,
212 0, 0, 0, 0, 0, 0, 0, 0,
213 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes190d79e2008-01-30 11:58:22 +0000214
Benjamin Peterson14339b62009-01-31 16:36:08 +0000215 0, 0, 0, 0, 0, 0, 0, 0,
216 0, 0, 0, 0, 0, 0, 0, 0,
217 0, 0, 0, 0, 0, 0, 0, 0,
218 0, 0, 0, 0, 0, 0, 0, 0,
219 0, 0, 0, 0, 0, 0, 0, 0,
220 0, 0, 0, 0, 0, 0, 0, 0,
221 0, 0, 0, 0, 0, 0, 0, 0,
222 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000223};
224
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200225/* forward */
Victor Stinnerfe226c02011-10-03 03:52:20 +0200226static PyUnicodeObject *_PyUnicode_New(Py_ssize_t length);
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200227static PyObject* get_latin1_char(unsigned char ch);
Victor Stinner488fa492011-12-12 00:01:39 +0100228static int unicode_modifiable(PyObject *unicode);
229
Victor Stinnerfe226c02011-10-03 03:52:20 +0200230
Alexander Belopolsky40018472011-02-26 01:02:56 +0000231static PyObject *
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200232_PyUnicode_FromUCS1(const unsigned char *s, Py_ssize_t size);
233static PyObject *
234_PyUnicode_FromUCS2(const Py_UCS2 *s, Py_ssize_t size);
235static PyObject *
236_PyUnicode_FromUCS4(const Py_UCS4 *s, Py_ssize_t size);
237
238static PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +0000239unicode_encode_call_errorhandler(const char *errors,
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000240 PyObject **errorHandler,const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +0100241 PyObject *unicode, PyObject **exceptionObject,
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000242 Py_ssize_t startpos, Py_ssize_t endpos, Py_ssize_t *newpos);
243
Alexander Belopolsky40018472011-02-26 01:02:56 +0000244static void
245raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +0300246 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +0100247 PyObject *unicode,
248 Py_ssize_t startpos, Py_ssize_t endpos,
249 const char *reason);
Victor Stinner31be90b2010-04-22 19:38:16 +0000250
Christian Heimes190d79e2008-01-30 11:58:22 +0000251/* Same for linebreaks */
252static unsigned char ascii_linebreak[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000253 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000254/* 0x000A, * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000255/* 0x000B, * LINE TABULATION */
256/* 0x000C, * FORM FEED */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000257/* 0x000D, * CARRIAGE RETURN */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000258 0, 0, 1, 1, 1, 1, 0, 0,
Benjamin Peterson14339b62009-01-31 16:36:08 +0000259 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000260/* 0x001C, * FILE SEPARATOR */
261/* 0x001D, * GROUP SEPARATOR */
262/* 0x001E, * RECORD SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000263 0, 0, 0, 0, 1, 1, 1, 0,
264 0, 0, 0, 0, 0, 0, 0, 0,
265 0, 0, 0, 0, 0, 0, 0, 0,
266 0, 0, 0, 0, 0, 0, 0, 0,
267 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes190d79e2008-01-30 11:58:22 +0000268
Benjamin Peterson14339b62009-01-31 16:36:08 +0000269 0, 0, 0, 0, 0, 0, 0, 0,
270 0, 0, 0, 0, 0, 0, 0, 0,
271 0, 0, 0, 0, 0, 0, 0, 0,
272 0, 0, 0, 0, 0, 0, 0, 0,
273 0, 0, 0, 0, 0, 0, 0, 0,
274 0, 0, 0, 0, 0, 0, 0, 0,
275 0, 0, 0, 0, 0, 0, 0, 0,
276 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000277};
278
Ezio Melotti48a2f8f2011-09-29 00:18:19 +0300279/* The max unicode value is always 0x10FFFF while using the PEP-393 API.
280 This function is kept for backward compatibility with the old API. */
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000281Py_UNICODE
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +0000282PyUnicode_GetMax(void)
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000283{
Fredrik Lundh8f455852001-06-27 18:59:43 +0000284#ifdef Py_UNICODE_WIDE
Benjamin Peterson14339b62009-01-31 16:36:08 +0000285 return 0x10FFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000286#else
Benjamin Peterson14339b62009-01-31 16:36:08 +0000287 /* This is actually an illegal character, so it should
288 not be passed to unichr. */
289 return 0xFFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000290#endif
291}
292
Victor Stinner910337b2011-10-03 03:20:16 +0200293#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200294int
Victor Stinner7931d9a2011-11-04 00:22:48 +0100295_PyUnicode_CheckConsistency(PyObject *op, int check_content)
Victor Stinner910337b2011-10-03 03:20:16 +0200296{
297 PyASCIIObject *ascii;
298 unsigned int kind;
299
300 assert(PyUnicode_Check(op));
301
302 ascii = (PyASCIIObject *)op;
303 kind = ascii->state.kind;
304
Victor Stinnera3b334d2011-10-03 13:53:37 +0200305 if (ascii->state.ascii == 1 && ascii->state.compact == 1) {
Victor Stinner910337b2011-10-03 03:20:16 +0200306 assert(kind == PyUnicode_1BYTE_KIND);
Victor Stinner910337b2011-10-03 03:20:16 +0200307 assert(ascii->state.ready == 1);
308 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200309 else {
Victor Stinner85041a52011-10-03 14:42:39 +0200310 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
Victor Stinner7f11ad42011-10-04 00:00:20 +0200311 void *data;
Victor Stinner910337b2011-10-03 03:20:16 +0200312
Victor Stinnera41463c2011-10-04 01:05:08 +0200313 if (ascii->state.compact == 1) {
314 data = compact + 1;
Victor Stinner910337b2011-10-03 03:20:16 +0200315 assert(kind == PyUnicode_1BYTE_KIND
316 || kind == PyUnicode_2BYTE_KIND
317 || kind == PyUnicode_4BYTE_KIND);
Victor Stinnera41463c2011-10-04 01:05:08 +0200318 assert(ascii->state.ascii == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200319 assert(ascii->state.ready == 1);
Victor Stinnera41463c2011-10-04 01:05:08 +0200320 assert (compact->utf8 != data);
Victor Stinnere30c0a12011-11-04 20:54:05 +0100321 }
322 else {
Victor Stinnera41463c2011-10-04 01:05:08 +0200323 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
324
325 data = unicode->data.any;
326 if (kind == PyUnicode_WCHAR_KIND) {
Victor Stinnere30c0a12011-11-04 20:54:05 +0100327 assert(ascii->length == 0);
328 assert(ascii->hash == -1);
Victor Stinnera41463c2011-10-04 01:05:08 +0200329 assert(ascii->state.compact == 0);
330 assert(ascii->state.ascii == 0);
331 assert(ascii->state.ready == 0);
Victor Stinnere30c0a12011-11-04 20:54:05 +0100332 assert(ascii->state.interned == SSTATE_NOT_INTERNED);
Victor Stinnera41463c2011-10-04 01:05:08 +0200333 assert(ascii->wstr != NULL);
334 assert(data == NULL);
335 assert(compact->utf8 == NULL);
Victor Stinnera41463c2011-10-04 01:05:08 +0200336 }
337 else {
338 assert(kind == PyUnicode_1BYTE_KIND
339 || kind == PyUnicode_2BYTE_KIND
340 || kind == PyUnicode_4BYTE_KIND);
341 assert(ascii->state.compact == 0);
342 assert(ascii->state.ready == 1);
343 assert(data != NULL);
344 if (ascii->state.ascii) {
345 assert (compact->utf8 == data);
346 assert (compact->utf8_length == ascii->length);
347 }
348 else
349 assert (compact->utf8 != data);
350 }
351 }
352 if (kind != PyUnicode_WCHAR_KIND) {
Victor Stinner7f11ad42011-10-04 00:00:20 +0200353 if (
354#if SIZEOF_WCHAR_T == 2
355 kind == PyUnicode_2BYTE_KIND
356#else
357 kind == PyUnicode_4BYTE_KIND
358#endif
359 )
Victor Stinnera41463c2011-10-04 01:05:08 +0200360 {
361 assert(ascii->wstr == data);
362 assert(compact->wstr_length == ascii->length);
363 } else
364 assert(ascii->wstr != data);
Victor Stinner910337b2011-10-03 03:20:16 +0200365 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200366
367 if (compact->utf8 == NULL)
368 assert(compact->utf8_length == 0);
369 if (ascii->wstr == NULL)
370 assert(compact->wstr_length == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200371 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200372 /* check that the best kind is used */
373 if (check_content && kind != PyUnicode_WCHAR_KIND)
374 {
375 Py_ssize_t i;
376 Py_UCS4 maxchar = 0;
Victor Stinner718fbf02012-04-26 00:39:37 +0200377 void *data;
378 Py_UCS4 ch;
379
380 data = PyUnicode_DATA(ascii);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200381 for (i=0; i < ascii->length; i++)
382 {
Victor Stinner718fbf02012-04-26 00:39:37 +0200383 ch = PyUnicode_READ(kind, data, i);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200384 if (ch > maxchar)
385 maxchar = ch;
386 }
387 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinner77faf692011-11-20 18:56:05 +0100388 if (ascii->state.ascii == 0) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200389 assert(maxchar >= 128);
Victor Stinner77faf692011-11-20 18:56:05 +0100390 assert(maxchar <= 255);
391 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200392 else
393 assert(maxchar < 128);
394 }
Victor Stinner77faf692011-11-20 18:56:05 +0100395 else if (kind == PyUnicode_2BYTE_KIND) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200396 assert(maxchar >= 0x100);
Victor Stinner77faf692011-11-20 18:56:05 +0100397 assert(maxchar <= 0xFFFF);
398 }
399 else {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200400 assert(maxchar >= 0x10000);
Victor Stinner8faf8212011-12-08 22:14:11 +0100401 assert(maxchar <= MAX_UNICODE);
Victor Stinner77faf692011-11-20 18:56:05 +0100402 }
Victor Stinner718fbf02012-04-26 00:39:37 +0200403 assert(PyUnicode_READ(kind, data, ascii->length) == 0);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200404 }
Benjamin Petersonccc51c12011-10-03 19:34:12 -0400405 return 1;
406}
Victor Stinner910337b2011-10-03 03:20:16 +0200407#endif
408
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100409static PyObject*
410unicode_result_wchar(PyObject *unicode)
411{
412#ifndef Py_DEBUG
413 Py_ssize_t len;
414
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100415 len = _PyUnicode_WSTR_LENGTH(unicode);
416 if (len == 0) {
417 Py_INCREF(unicode_empty);
418 Py_DECREF(unicode);
419 return unicode_empty;
420 }
421
422 if (len == 1) {
423 wchar_t ch = _PyUnicode_WSTR(unicode)[0];
424 if (ch < 256) {
425 PyObject *latin1_char = get_latin1_char((unsigned char)ch);
426 Py_DECREF(unicode);
427 return latin1_char;
428 }
429 }
430
431 if (_PyUnicode_Ready(unicode) < 0) {
Victor Stinneraa771272012-10-04 02:32:58 +0200432 Py_DECREF(unicode);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100433 return NULL;
434 }
435#else
Victor Stinneraa771272012-10-04 02:32:58 +0200436 assert(Py_REFCNT(unicode) == 1);
437
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100438 /* don't make the result ready in debug mode to ensure that the caller
439 makes the string ready before using it */
440 assert(_PyUnicode_CheckConsistency(unicode, 1));
441#endif
442 return unicode;
443}
444
445static PyObject*
446unicode_result_ready(PyObject *unicode)
447{
448 Py_ssize_t length;
449
450 length = PyUnicode_GET_LENGTH(unicode);
451 if (length == 0) {
452 if (unicode != unicode_empty) {
453 Py_INCREF(unicode_empty);
454 Py_DECREF(unicode);
455 }
456 return unicode_empty;
457 }
458
459 if (length == 1) {
460 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, 0);
461 if (ch < 256) {
462 PyObject *latin1_char = unicode_latin1[ch];
463 if (latin1_char != NULL) {
464 if (unicode != latin1_char) {
465 Py_INCREF(latin1_char);
466 Py_DECREF(unicode);
467 }
468 return latin1_char;
469 }
470 else {
471 assert(_PyUnicode_CheckConsistency(unicode, 1));
472 Py_INCREF(unicode);
473 unicode_latin1[ch] = unicode;
474 return unicode;
475 }
476 }
477 }
478
479 assert(_PyUnicode_CheckConsistency(unicode, 1));
480 return unicode;
481}
482
483static PyObject*
484unicode_result(PyObject *unicode)
485{
486 assert(_PyUnicode_CHECK(unicode));
487 if (PyUnicode_IS_READY(unicode))
488 return unicode_result_ready(unicode);
489 else
490 return unicode_result_wchar(unicode);
491}
492
Victor Stinnerc4b49542011-12-11 22:44:26 +0100493static PyObject*
494unicode_result_unchanged(PyObject *unicode)
495{
496 if (PyUnicode_CheckExact(unicode)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -0500497 if (PyUnicode_READY(unicode) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +0100498 return NULL;
499 Py_INCREF(unicode);
500 return unicode;
501 }
502 else
503 /* Subtype -- return genuine unicode string with the same value. */
Victor Stinnerbf6e5602011-12-12 01:53:47 +0100504 return _PyUnicode_Copy(unicode);
Victor Stinnerc4b49542011-12-11 22:44:26 +0100505}
506
Victor Stinner3a50e702011-10-18 21:21:00 +0200507#ifdef HAVE_MBCS
508static OSVERSIONINFOEX winver;
509#endif
510
Thomas Wouters477c8d52006-05-27 19:21:47 +0000511/* --- Bloom Filters ----------------------------------------------------- */
512
513/* stuff to implement simple "bloom filters" for Unicode characters.
514 to keep things simple, we use a single bitmask, using the least 5
515 bits from each unicode characters as the bit index. */
516
517/* the linebreak mask is set up by Unicode_Init below */
518
Antoine Pitrouf068f942010-01-13 14:19:12 +0000519#if LONG_BIT >= 128
520#define BLOOM_WIDTH 128
521#elif LONG_BIT >= 64
522#define BLOOM_WIDTH 64
523#elif LONG_BIT >= 32
524#define BLOOM_WIDTH 32
525#else
526#error "LONG_BIT is smaller than 32"
527#endif
528
Thomas Wouters477c8d52006-05-27 19:21:47 +0000529#define BLOOM_MASK unsigned long
530
531static BLOOM_MASK bloom_linebreak;
532
Antoine Pitrouf068f942010-01-13 14:19:12 +0000533#define BLOOM_ADD(mask, ch) ((mask |= (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
534#define BLOOM(mask, ch) ((mask & (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000535
Benjamin Peterson29060642009-01-31 22:14:21 +0000536#define BLOOM_LINEBREAK(ch) \
537 ((ch) < 128U ? ascii_linebreak[(ch)] : \
538 (BLOOM(bloom_linebreak, (ch)) && Py_UNICODE_ISLINEBREAK(ch)))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000539
Alexander Belopolsky40018472011-02-26 01:02:56 +0000540Py_LOCAL_INLINE(BLOOM_MASK)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200541make_bloom_mask(int kind, void* ptr, Py_ssize_t len)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000542{
543 /* calculate simple bloom-style bitmask for a given unicode string */
544
Antoine Pitrouf068f942010-01-13 14:19:12 +0000545 BLOOM_MASK mask;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000546 Py_ssize_t i;
547
548 mask = 0;
549 for (i = 0; i < len; i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200550 BLOOM_ADD(mask, PyUnicode_READ(kind, ptr, i));
Thomas Wouters477c8d52006-05-27 19:21:47 +0000551
552 return mask;
553}
554
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200555#define BLOOM_MEMBER(mask, chr, str) \
556 (BLOOM(mask, chr) \
557 && (PyUnicode_FindChar(str, chr, 0, PyUnicode_GET_LENGTH(str), 1) >= 0))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000558
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200559/* Compilation of templated routines */
560
561#include "stringlib/asciilib.h"
562#include "stringlib/fastsearch.h"
563#include "stringlib/partition.h"
564#include "stringlib/split.h"
565#include "stringlib/count.h"
566#include "stringlib/find.h"
567#include "stringlib/find_max_char.h"
568#include "stringlib/localeutil.h"
569#include "stringlib/undef.h"
570
571#include "stringlib/ucs1lib.h"
572#include "stringlib/fastsearch.h"
573#include "stringlib/partition.h"
574#include "stringlib/split.h"
575#include "stringlib/count.h"
576#include "stringlib/find.h"
577#include "stringlib/find_max_char.h"
578#include "stringlib/localeutil.h"
579#include "stringlib/undef.h"
580
581#include "stringlib/ucs2lib.h"
582#include "stringlib/fastsearch.h"
583#include "stringlib/partition.h"
584#include "stringlib/split.h"
585#include "stringlib/count.h"
586#include "stringlib/find.h"
587#include "stringlib/find_max_char.h"
588#include "stringlib/localeutil.h"
589#include "stringlib/undef.h"
590
591#include "stringlib/ucs4lib.h"
592#include "stringlib/fastsearch.h"
593#include "stringlib/partition.h"
594#include "stringlib/split.h"
595#include "stringlib/count.h"
596#include "stringlib/find.h"
597#include "stringlib/find_max_char.h"
598#include "stringlib/localeutil.h"
599#include "stringlib/undef.h"
600
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200601#include "stringlib/unicodedefs.h"
602#include "stringlib/fastsearch.h"
603#include "stringlib/count.h"
604#include "stringlib/find.h"
Antoine Pitrou0a3229d2011-11-21 20:39:13 +0100605#include "stringlib/undef.h"
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200606
Guido van Rossumd57fd912000-03-10 22:53:23 +0000607/* --- Unicode Object ----------------------------------------------------- */
608
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200609static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +0200610fixup(PyObject *self, Py_UCS4 (*fixfct)(PyObject *s));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200611
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200612Py_LOCAL_INLINE(Py_ssize_t) findchar(void *s, int kind,
613 Py_ssize_t size, Py_UCS4 ch,
614 int direction)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200615{
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200616 int mode = (direction == 1) ? FAST_SEARCH : FAST_RSEARCH;
617
618 switch (kind) {
619 case PyUnicode_1BYTE_KIND:
620 {
621 Py_UCS1 ch1 = (Py_UCS1) ch;
622 if (ch1 == ch)
623 return ucs1lib_fastsearch((Py_UCS1 *) s, size, &ch1, 1, 0, mode);
624 else
625 return -1;
626 }
627 case PyUnicode_2BYTE_KIND:
628 {
629 Py_UCS2 ch2 = (Py_UCS2) ch;
630 if (ch2 == ch)
631 return ucs2lib_fastsearch((Py_UCS2 *) s, size, &ch2, 1, 0, mode);
632 else
633 return -1;
634 }
635 case PyUnicode_4BYTE_KIND:
636 return ucs4lib_fastsearch((Py_UCS4 *) s, size, &ch, 1, 0, mode);
637 default:
638 assert(0);
639 return -1;
Victor Stinner9e7a1bc2011-10-13 00:18:12 +0200640 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200641}
642
Victor Stinnerafffce42012-10-03 23:03:17 +0200643#ifdef Py_DEBUG
644/* Fill the data of an Unicode string with invalid characters to detect bugs
645 earlier.
646
647 _PyUnicode_CheckConsistency(str, 1) detects invalid characters, at least for
648 ASCII and UCS-4 strings. U+00FF is invalid in ASCII and U+FFFFFFFF is an
649 invalid character in Unicode 6.0. */
650static void
651unicode_fill_invalid(PyObject *unicode, Py_ssize_t old_length)
652{
653 int kind = PyUnicode_KIND(unicode);
654 Py_UCS1 *data = PyUnicode_1BYTE_DATA(unicode);
655 Py_ssize_t length = _PyUnicode_LENGTH(unicode);
656 if (length <= old_length)
657 return;
658 memset(data + old_length * kind, 0xff, (length - old_length) * kind);
659}
660#endif
661
Victor Stinnerfe226c02011-10-03 03:52:20 +0200662static PyObject*
663resize_compact(PyObject *unicode, Py_ssize_t length)
664{
665 Py_ssize_t char_size;
666 Py_ssize_t struct_size;
667 Py_ssize_t new_size;
668 int share_wstr;
Victor Stinner84def372011-12-11 20:04:56 +0100669 PyObject *new_unicode;
Victor Stinnerafffce42012-10-03 23:03:17 +0200670#ifdef Py_DEBUG
671 Py_ssize_t old_length = _PyUnicode_LENGTH(unicode);
672#endif
673
Victor Stinner79891572012-05-03 13:43:07 +0200674 assert(unicode_modifiable(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200675 assert(PyUnicode_IS_READY(unicode));
Victor Stinner488fa492011-12-12 00:01:39 +0100676 assert(PyUnicode_IS_COMPACT(unicode));
677
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200678 char_size = PyUnicode_KIND(unicode);
Victor Stinner488fa492011-12-12 00:01:39 +0100679 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerfe226c02011-10-03 03:52:20 +0200680 struct_size = sizeof(PyASCIIObject);
681 else
682 struct_size = sizeof(PyCompactUnicodeObject);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200683 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200684
Victor Stinnerfe226c02011-10-03 03:52:20 +0200685 if (length > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1)) {
686 PyErr_NoMemory();
687 return NULL;
688 }
689 new_size = (struct_size + (length + 1) * char_size);
690
Victor Stinner84def372011-12-11 20:04:56 +0100691 _Py_DEC_REFTOTAL;
692 _Py_ForgetReference(unicode);
693
694 new_unicode = (PyObject *)PyObject_REALLOC((char *)unicode, new_size);
695 if (new_unicode == NULL) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +0100696 _Py_NewReference(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200697 PyErr_NoMemory();
698 return NULL;
699 }
Victor Stinner84def372011-12-11 20:04:56 +0100700 unicode = new_unicode;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200701 _Py_NewReference(unicode);
Victor Stinner84def372011-12-11 20:04:56 +0100702
Victor Stinnerfe226c02011-10-03 03:52:20 +0200703 _PyUnicode_LENGTH(unicode) = length;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200704 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200705 _PyUnicode_WSTR(unicode) = PyUnicode_DATA(unicode);
Victor Stinner488fa492011-12-12 00:01:39 +0100706 if (!PyUnicode_IS_ASCII(unicode))
Victor Stinnerc379ead2011-10-03 12:52:27 +0200707 _PyUnicode_WSTR_LENGTH(unicode) = length;
708 }
Victor Stinnerafffce42012-10-03 23:03:17 +0200709#ifdef Py_DEBUG
710 unicode_fill_invalid(unicode, old_length);
711#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +0200712 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
713 length, 0);
Victor Stinner79891572012-05-03 13:43:07 +0200714 assert(_PyUnicode_CheckConsistency(unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200715 return unicode;
716}
717
Alexander Belopolsky40018472011-02-26 01:02:56 +0000718static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200719resize_inplace(PyObject *unicode, Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000720{
Victor Stinner95663112011-10-04 01:03:50 +0200721 wchar_t *wstr;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100722 Py_ssize_t new_size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200723 assert(!PyUnicode_IS_COMPACT(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200724 assert(Py_REFCNT(unicode) == 1);
Tim Petersced69f82003-09-16 20:30:58 +0000725
Victor Stinnerfe226c02011-10-03 03:52:20 +0200726 if (PyUnicode_IS_READY(unicode)) {
727 Py_ssize_t char_size;
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200728 int share_wstr, share_utf8;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200729 void *data;
Victor Stinnerafffce42012-10-03 23:03:17 +0200730#ifdef Py_DEBUG
731 Py_ssize_t old_length = _PyUnicode_LENGTH(unicode);
732#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +0200733
734 data = _PyUnicode_DATA_ANY(unicode);
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200735 char_size = PyUnicode_KIND(unicode);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200736 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
737 share_utf8 = _PyUnicode_SHARE_UTF8(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200738
739 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
740 PyErr_NoMemory();
741 return -1;
742 }
743 new_size = (length + 1) * char_size;
744
Victor Stinner7a9105a2011-12-12 00:13:42 +0100745 if (!share_utf8 && _PyUnicode_HAS_UTF8_MEMORY(unicode))
746 {
747 PyObject_DEL(_PyUnicode_UTF8(unicode));
748 _PyUnicode_UTF8(unicode) = NULL;
749 _PyUnicode_UTF8_LENGTH(unicode) = 0;
750 }
751
Victor Stinnerfe226c02011-10-03 03:52:20 +0200752 data = (PyObject *)PyObject_REALLOC(data, new_size);
753 if (data == NULL) {
754 PyErr_NoMemory();
755 return -1;
756 }
757 _PyUnicode_DATA_ANY(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200758 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200759 _PyUnicode_WSTR(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200760 _PyUnicode_WSTR_LENGTH(unicode) = length;
761 }
762 if (share_utf8) {
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200763 _PyUnicode_UTF8(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200764 _PyUnicode_UTF8_LENGTH(unicode) = length;
765 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200766 _PyUnicode_LENGTH(unicode) = length;
767 PyUnicode_WRITE(PyUnicode_KIND(unicode), data, length, 0);
Victor Stinnerafffce42012-10-03 23:03:17 +0200768#ifdef Py_DEBUG
769 unicode_fill_invalid(unicode, old_length);
770#endif
Victor Stinner95663112011-10-04 01:03:50 +0200771 if (share_wstr || _PyUnicode_WSTR(unicode) == NULL) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200772 assert(_PyUnicode_CheckConsistency(unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200773 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200774 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200775 }
Victor Stinner95663112011-10-04 01:03:50 +0200776 assert(_PyUnicode_WSTR(unicode) != NULL);
777
778 /* check for integer overflow */
779 if (length > PY_SSIZE_T_MAX / sizeof(wchar_t) - 1) {
780 PyErr_NoMemory();
781 return -1;
782 }
Victor Stinner7a9105a2011-12-12 00:13:42 +0100783 new_size = sizeof(wchar_t) * (length + 1);
Victor Stinner95663112011-10-04 01:03:50 +0200784 wstr = _PyUnicode_WSTR(unicode);
Victor Stinner7a9105a2011-12-12 00:13:42 +0100785 wstr = PyObject_REALLOC(wstr, new_size);
Victor Stinner95663112011-10-04 01:03:50 +0200786 if (!wstr) {
787 PyErr_NoMemory();
788 return -1;
789 }
790 _PyUnicode_WSTR(unicode) = wstr;
791 _PyUnicode_WSTR(unicode)[length] = 0;
792 _PyUnicode_WSTR_LENGTH(unicode) = length;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200793 assert(_PyUnicode_CheckConsistency(unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +0000794 return 0;
795}
796
Victor Stinnerfe226c02011-10-03 03:52:20 +0200797static PyObject*
798resize_copy(PyObject *unicode, Py_ssize_t length)
799{
800 Py_ssize_t copy_length;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100801 if (_PyUnicode_KIND(unicode) != PyUnicode_WCHAR_KIND) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200802 PyObject *copy;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100803
Benjamin Petersonbac79492012-01-14 13:34:47 -0500804 if (PyUnicode_READY(unicode) == -1)
Victor Stinner7a9105a2011-12-12 00:13:42 +0100805 return NULL;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200806
807 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
808 if (copy == NULL)
809 return NULL;
810
811 copy_length = Py_MIN(length, PyUnicode_GET_LENGTH(unicode));
Victor Stinnerd3f08822012-05-29 12:57:52 +0200812 _PyUnicode_FastCopyCharacters(copy, 0, unicode, 0, copy_length);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200813 return copy;
Victor Stinner8cfcbed2011-10-03 23:19:21 +0200814 }
815 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200816 PyObject *w;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100817
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200818 w = (PyObject*)_PyUnicode_New(length);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200819 if (w == NULL)
820 return NULL;
821 copy_length = _PyUnicode_WSTR_LENGTH(unicode);
822 copy_length = Py_MIN(copy_length, length);
823 Py_UNICODE_COPY(_PyUnicode_WSTR(w), _PyUnicode_WSTR(unicode),
824 copy_length);
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200825 return w;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200826 }
827}
828
Guido van Rossumd57fd912000-03-10 22:53:23 +0000829/* We allocate one more byte to make sure the string is
Martin v. Löwis47383402007-08-15 07:32:56 +0000830 Ux0000 terminated; some code (e.g. new_identifier)
831 relies on that.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000832
833 XXX This allocator could further be enhanced by assuring that the
Benjamin Peterson29060642009-01-31 22:14:21 +0000834 free list never reduces its size below 1.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000835
836*/
837
Alexander Belopolsky40018472011-02-26 01:02:56 +0000838static PyUnicodeObject *
839_PyUnicode_New(Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000840{
841 register PyUnicodeObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200842 size_t new_size;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000843
Thomas Wouters477c8d52006-05-27 19:21:47 +0000844 /* Optimization for empty strings */
Guido van Rossumd57fd912000-03-10 22:53:23 +0000845 if (length == 0 && unicode_empty != NULL) {
846 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +0200847 return (PyUnicodeObject*)unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000848 }
849
Neal Norwitz3ce5d922008-08-24 07:08:55 +0000850 /* Ensure we won't overflow the size. */
851 if (length > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
852 return (PyUnicodeObject *)PyErr_NoMemory();
853 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200854 if (length < 0) {
855 PyErr_SetString(PyExc_SystemError,
856 "Negative size passed to _PyUnicode_New");
857 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000858 }
859
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200860 unicode = PyObject_New(PyUnicodeObject, &PyUnicode_Type);
861 if (unicode == NULL)
862 return NULL;
863 new_size = sizeof(Py_UNICODE) * ((size_t)length + 1);
864 _PyUnicode_WSTR(unicode) = (Py_UNICODE*) PyObject_MALLOC(new_size);
865 if (!_PyUnicode_WSTR(unicode)) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +0100866 Py_DECREF(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +0000867 PyErr_NoMemory();
Victor Stinnerb0a82a62011-12-12 13:08:33 +0100868 return NULL;
Guido van Rossum3c1bb802000-04-27 20:13:50 +0000869 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200870
Jeremy Hyltond8082792003-09-16 19:41:39 +0000871 /* Initialize the first element to guard against cases where
Tim Petersced69f82003-09-16 20:30:58 +0000872 * the caller fails before initializing str -- unicode_resize()
873 * reads str[0], and the Keep-Alive optimization can keep memory
874 * allocated for str alive across a call to unicode_dealloc(unicode).
875 * We don't want unicode_resize to read uninitialized memory in
876 * that case.
877 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200878 _PyUnicode_WSTR(unicode)[0] = 0;
879 _PyUnicode_WSTR(unicode)[length] = 0;
880 _PyUnicode_WSTR_LENGTH(unicode) = length;
881 _PyUnicode_HASH(unicode) = -1;
882 _PyUnicode_STATE(unicode).interned = 0;
883 _PyUnicode_STATE(unicode).kind = 0;
884 _PyUnicode_STATE(unicode).compact = 0;
885 _PyUnicode_STATE(unicode).ready = 0;
886 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +0200887 _PyUnicode_DATA_ANY(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200888 _PyUnicode_LENGTH(unicode) = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200889 _PyUnicode_UTF8(unicode) = NULL;
890 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner7931d9a2011-11-04 00:22:48 +0100891 assert(_PyUnicode_CheckConsistency((PyObject *)unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +0000892 return unicode;
893}
894
Victor Stinnerf42dc442011-10-02 23:33:16 +0200895static const char*
896unicode_kind_name(PyObject *unicode)
897{
Victor Stinner42dfd712011-10-03 14:41:45 +0200898 /* don't check consistency: unicode_kind_name() is called from
899 _PyUnicode_Dump() */
Victor Stinnerf42dc442011-10-02 23:33:16 +0200900 if (!PyUnicode_IS_COMPACT(unicode))
901 {
902 if (!PyUnicode_IS_READY(unicode))
903 return "wstr";
Benjamin Petersonead6b532011-12-20 17:23:42 -0600904 switch (PyUnicode_KIND(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200905 {
906 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200907 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200908 return "legacy ascii";
909 else
910 return "legacy latin1";
911 case PyUnicode_2BYTE_KIND:
912 return "legacy UCS2";
913 case PyUnicode_4BYTE_KIND:
914 return "legacy UCS4";
915 default:
916 return "<legacy invalid kind>";
917 }
918 }
919 assert(PyUnicode_IS_READY(unicode));
Benjamin Petersonead6b532011-12-20 17:23:42 -0600920 switch (PyUnicode_KIND(unicode)) {
Victor Stinnerf42dc442011-10-02 23:33:16 +0200921 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200922 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200923 return "ascii";
924 else
Victor Stinnera3b334d2011-10-03 13:53:37 +0200925 return "latin1";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200926 case PyUnicode_2BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200927 return "UCS2";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200928 case PyUnicode_4BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200929 return "UCS4";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200930 default:
931 return "<invalid compact kind>";
932 }
933}
934
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200935#ifdef Py_DEBUG
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200936/* Functions wrapping macros for use in debugger */
937char *_PyUnicode_utf8(void *unicode){
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200938 return PyUnicode_UTF8(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200939}
940
941void *_PyUnicode_compact_data(void *unicode) {
942 return _PyUnicode_COMPACT_DATA(unicode);
943}
944void *_PyUnicode_data(void *unicode){
945 printf("obj %p\n", unicode);
946 printf("compact %d\n", PyUnicode_IS_COMPACT(unicode));
947 printf("compact ascii %d\n", PyUnicode_IS_COMPACT_ASCII(unicode));
948 printf("ascii op %p\n", ((void*)((PyASCIIObject*)(unicode) + 1)));
949 printf("compact op %p\n", ((void*)((PyCompactUnicodeObject*)(unicode) + 1)));
950 printf("compact data %p\n", _PyUnicode_COMPACT_DATA(unicode));
951 return PyUnicode_DATA(unicode);
952}
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200953
954void
955_PyUnicode_Dump(PyObject *op)
956{
957 PyASCIIObject *ascii = (PyASCIIObject *)op;
Victor Stinnera849a4b2011-10-03 12:12:11 +0200958 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
959 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
960 void *data;
Victor Stinner0d60e872011-10-23 19:47:19 +0200961
Victor Stinnera849a4b2011-10-03 12:12:11 +0200962 if (ascii->state.compact)
Victor Stinner0d60e872011-10-23 19:47:19 +0200963 {
964 if (ascii->state.ascii)
965 data = (ascii + 1);
966 else
967 data = (compact + 1);
968 }
Victor Stinnera849a4b2011-10-03 12:12:11 +0200969 else
970 data = unicode->data.any;
Victor Stinner0d60e872011-10-23 19:47:19 +0200971 printf("%s: len=%zu, ",unicode_kind_name(op), ascii->length);
972
Victor Stinnera849a4b2011-10-03 12:12:11 +0200973 if (ascii->wstr == data)
974 printf("shared ");
975 printf("wstr=%p", ascii->wstr);
Victor Stinner0d60e872011-10-23 19:47:19 +0200976
Victor Stinnera3b334d2011-10-03 13:53:37 +0200977 if (!(ascii->state.ascii == 1 && ascii->state.compact == 1)) {
Victor Stinnera849a4b2011-10-03 12:12:11 +0200978 printf(" (%zu), ", compact->wstr_length);
979 if (!ascii->state.compact && compact->utf8 == unicode->data.any)
980 printf("shared ");
981 printf("utf8=%p (%zu)", compact->utf8, compact->utf8_length);
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200982 }
Victor Stinnera849a4b2011-10-03 12:12:11 +0200983 printf(", data=%p\n", data);
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200984}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200985#endif
986
987PyObject *
988PyUnicode_New(Py_ssize_t size, Py_UCS4 maxchar)
989{
990 PyObject *obj;
991 PyCompactUnicodeObject *unicode;
992 void *data;
Victor Stinner8f825062012-04-27 13:55:39 +0200993 enum PyUnicode_Kind kind;
Victor Stinner9e9d6892011-10-04 01:02:02 +0200994 int is_sharing, is_ascii;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200995 Py_ssize_t char_size;
996 Py_ssize_t struct_size;
997
998 /* Optimization for empty strings */
999 if (size == 0 && unicode_empty != NULL) {
1000 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001001 return unicode_empty;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001002 }
1003
Victor Stinner9e9d6892011-10-04 01:02:02 +02001004 is_ascii = 0;
1005 is_sharing = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001006 struct_size = sizeof(PyCompactUnicodeObject);
1007 if (maxchar < 128) {
Victor Stinner8f825062012-04-27 13:55:39 +02001008 kind = PyUnicode_1BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001009 char_size = 1;
1010 is_ascii = 1;
1011 struct_size = sizeof(PyASCIIObject);
1012 }
1013 else if (maxchar < 256) {
Victor Stinner8f825062012-04-27 13:55:39 +02001014 kind = PyUnicode_1BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001015 char_size = 1;
1016 }
1017 else if (maxchar < 65536) {
Victor Stinner8f825062012-04-27 13:55:39 +02001018 kind = PyUnicode_2BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001019 char_size = 2;
1020 if (sizeof(wchar_t) == 2)
1021 is_sharing = 1;
1022 }
1023 else {
Victor Stinnerc9590ad2012-03-04 01:34:37 +01001024 if (maxchar > MAX_UNICODE) {
1025 PyErr_SetString(PyExc_SystemError,
1026 "invalid maximum character passed to PyUnicode_New");
1027 return NULL;
1028 }
Victor Stinner8f825062012-04-27 13:55:39 +02001029 kind = PyUnicode_4BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001030 char_size = 4;
1031 if (sizeof(wchar_t) == 4)
1032 is_sharing = 1;
1033 }
1034
1035 /* Ensure we won't overflow the size. */
1036 if (size < 0) {
1037 PyErr_SetString(PyExc_SystemError,
1038 "Negative size passed to PyUnicode_New");
1039 return NULL;
1040 }
1041 if (size > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1))
1042 return PyErr_NoMemory();
1043
1044 /* Duplicated allocation code from _PyObject_New() instead of a call to
1045 * PyObject_New() so we are able to allocate space for the object and
1046 * it's data buffer.
1047 */
1048 obj = (PyObject *) PyObject_MALLOC(struct_size + (size + 1) * char_size);
1049 if (obj == NULL)
1050 return PyErr_NoMemory();
1051 obj = PyObject_INIT(obj, &PyUnicode_Type);
1052 if (obj == NULL)
1053 return NULL;
1054
1055 unicode = (PyCompactUnicodeObject *)obj;
1056 if (is_ascii)
1057 data = ((PyASCIIObject*)obj) + 1;
1058 else
1059 data = unicode + 1;
1060 _PyUnicode_LENGTH(unicode) = size;
1061 _PyUnicode_HASH(unicode) = -1;
1062 _PyUnicode_STATE(unicode).interned = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001063 _PyUnicode_STATE(unicode).kind = kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001064 _PyUnicode_STATE(unicode).compact = 1;
1065 _PyUnicode_STATE(unicode).ready = 1;
1066 _PyUnicode_STATE(unicode).ascii = is_ascii;
1067 if (is_ascii) {
1068 ((char*)data)[size] = 0;
1069 _PyUnicode_WSTR(unicode) = NULL;
1070 }
Victor Stinner8f825062012-04-27 13:55:39 +02001071 else if (kind == PyUnicode_1BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001072 ((char*)data)[size] = 0;
1073 _PyUnicode_WSTR(unicode) = NULL;
1074 _PyUnicode_WSTR_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001075 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001076 unicode->utf8_length = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001077 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001078 else {
1079 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001080 unicode->utf8_length = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001081 if (kind == PyUnicode_2BYTE_KIND)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001082 ((Py_UCS2*)data)[size] = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001083 else /* kind == PyUnicode_4BYTE_KIND */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001084 ((Py_UCS4*)data)[size] = 0;
1085 if (is_sharing) {
1086 _PyUnicode_WSTR_LENGTH(unicode) = size;
1087 _PyUnicode_WSTR(unicode) = (wchar_t *)data;
1088 }
1089 else {
1090 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1091 _PyUnicode_WSTR(unicode) = NULL;
1092 }
1093 }
Victor Stinner8f825062012-04-27 13:55:39 +02001094#ifdef Py_DEBUG
Victor Stinnerafffce42012-10-03 23:03:17 +02001095 unicode_fill_invalid((PyObject*)unicode, 0);
Victor Stinner8f825062012-04-27 13:55:39 +02001096#endif
Victor Stinner7931d9a2011-11-04 00:22:48 +01001097 assert(_PyUnicode_CheckConsistency((PyObject*)unicode, 0));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001098 return obj;
1099}
1100
1101#if SIZEOF_WCHAR_T == 2
1102/* Helper function to convert a 16-bits wchar_t representation to UCS4, this
1103 will decode surrogate pairs, the other conversions are implemented as macros
Georg Brandl7597add2011-10-05 16:36:47 +02001104 for efficiency.
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001105
1106 This function assumes that unicode can hold one more code point than wstr
1107 characters for a terminating null character. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001108static void
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001109unicode_convert_wchar_to_ucs4(const wchar_t *begin, const wchar_t *end,
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001110 PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001111{
1112 const wchar_t *iter;
1113 Py_UCS4 *ucs4_out;
1114
Victor Stinner910337b2011-10-03 03:20:16 +02001115 assert(unicode != NULL);
1116 assert(_PyUnicode_CHECK(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001117 assert(_PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
1118 ucs4_out = PyUnicode_4BYTE_DATA(unicode);
1119
1120 for (iter = begin; iter < end; ) {
1121 assert(ucs4_out < (PyUnicode_4BYTE_DATA(unicode) +
1122 _PyUnicode_GET_LENGTH(unicode)));
Victor Stinner551ac952011-11-29 22:58:13 +01001123 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1124 && (iter+1) < end
1125 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001126 {
Victor Stinner551ac952011-11-29 22:58:13 +01001127 *ucs4_out++ = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001128 iter += 2;
1129 }
1130 else {
1131 *ucs4_out++ = *iter;
1132 iter++;
1133 }
1134 }
1135 assert(ucs4_out == (PyUnicode_4BYTE_DATA(unicode) +
1136 _PyUnicode_GET_LENGTH(unicode)));
1137
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001138}
1139#endif
1140
Victor Stinnercd9950f2011-10-02 00:34:53 +02001141static int
Victor Stinner488fa492011-12-12 00:01:39 +01001142unicode_check_modifiable(PyObject *unicode)
Victor Stinnercd9950f2011-10-02 00:34:53 +02001143{
Victor Stinner488fa492011-12-12 00:01:39 +01001144 if (!unicode_modifiable(unicode)) {
Victor Stinner01698042011-10-04 00:04:26 +02001145 PyErr_SetString(PyExc_SystemError,
Victor Stinner488fa492011-12-12 00:01:39 +01001146 "Cannot modify a string currently used");
Victor Stinnercd9950f2011-10-02 00:34:53 +02001147 return -1;
1148 }
Victor Stinnercd9950f2011-10-02 00:34:53 +02001149 return 0;
1150}
1151
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001152static int
1153_copy_characters(PyObject *to, Py_ssize_t to_start,
1154 PyObject *from, Py_ssize_t from_start,
1155 Py_ssize_t how_many, int check_maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001156{
Victor Stinnera0702ab2011-09-29 14:14:38 +02001157 unsigned int from_kind, to_kind;
1158 void *from_data, *to_data;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001159
Victor Stinneree4544c2012-05-09 22:24:08 +02001160 assert(0 <= how_many);
1161 assert(0 <= from_start);
1162 assert(0 <= to_start);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001163 assert(PyUnicode_Check(from));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001164 assert(PyUnicode_IS_READY(from));
Victor Stinneree4544c2012-05-09 22:24:08 +02001165 assert(from_start + how_many <= PyUnicode_GET_LENGTH(from));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001166
Victor Stinnerd3f08822012-05-29 12:57:52 +02001167 assert(PyUnicode_Check(to));
1168 assert(PyUnicode_IS_READY(to));
1169 assert(to_start + how_many <= PyUnicode_GET_LENGTH(to));
1170
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001171 if (how_many == 0)
1172 return 0;
1173
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001174 from_kind = PyUnicode_KIND(from);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001175 from_data = PyUnicode_DATA(from);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001176 to_kind = PyUnicode_KIND(to);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001177 to_data = PyUnicode_DATA(to);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001178
Victor Stinnerf1852262012-06-16 16:38:26 +02001179#ifdef Py_DEBUG
1180 if (!check_maxchar
1181 && PyUnicode_MAX_CHAR_VALUE(from) > PyUnicode_MAX_CHAR_VALUE(to))
1182 {
1183 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
1184 Py_UCS4 ch;
1185 Py_ssize_t i;
1186 for (i=0; i < how_many; i++) {
1187 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1188 assert(ch <= to_maxchar);
1189 }
1190 }
1191#endif
1192
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001193 if (from_kind == to_kind) {
Victor Stinnerf1852262012-06-16 16:38:26 +02001194 if (check_maxchar
1195 && !PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to))
1196 {
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001197 /* Writing Latin-1 characters into an ASCII string requires to
1198 check that all written characters are pure ASCII */
Victor Stinnerf1852262012-06-16 16:38:26 +02001199 Py_UCS4 max_char;
1200 max_char = ucs1lib_find_max_char(from_data,
1201 (Py_UCS1*)from_data + how_many);
1202 if (max_char >= 128)
1203 return -1;
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001204 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +02001205 Py_MEMCPY((char*)to_data + to_kind * to_start,
1206 (char*)from_data + from_kind * from_start,
1207 to_kind * how_many);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001208 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001209 else if (from_kind == PyUnicode_1BYTE_KIND
1210 && to_kind == PyUnicode_2BYTE_KIND)
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001211 {
1212 _PyUnicode_CONVERT_BYTES(
1213 Py_UCS1, Py_UCS2,
1214 PyUnicode_1BYTE_DATA(from) + from_start,
1215 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1216 PyUnicode_2BYTE_DATA(to) + to_start
1217 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001218 }
Victor Stinner157f83f2011-09-28 21:41:31 +02001219 else if (from_kind == PyUnicode_1BYTE_KIND
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001220 && to_kind == PyUnicode_4BYTE_KIND)
1221 {
1222 _PyUnicode_CONVERT_BYTES(
1223 Py_UCS1, Py_UCS4,
1224 PyUnicode_1BYTE_DATA(from) + from_start,
1225 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1226 PyUnicode_4BYTE_DATA(to) + to_start
1227 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001228 }
1229 else if (from_kind == PyUnicode_2BYTE_KIND
1230 && to_kind == PyUnicode_4BYTE_KIND)
1231 {
1232 _PyUnicode_CONVERT_BYTES(
1233 Py_UCS2, Py_UCS4,
1234 PyUnicode_2BYTE_DATA(from) + from_start,
1235 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1236 PyUnicode_4BYTE_DATA(to) + to_start
1237 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001238 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001239 else {
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001240 assert (PyUnicode_MAX_CHAR_VALUE(from) > PyUnicode_MAX_CHAR_VALUE(to));
1241
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001242 if (!check_maxchar) {
1243 if (from_kind == PyUnicode_2BYTE_KIND
1244 && to_kind == PyUnicode_1BYTE_KIND)
1245 {
1246 _PyUnicode_CONVERT_BYTES(
1247 Py_UCS2, Py_UCS1,
1248 PyUnicode_2BYTE_DATA(from) + from_start,
1249 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1250 PyUnicode_1BYTE_DATA(to) + to_start
1251 );
1252 }
1253 else if (from_kind == PyUnicode_4BYTE_KIND
1254 && to_kind == PyUnicode_1BYTE_KIND)
1255 {
1256 _PyUnicode_CONVERT_BYTES(
1257 Py_UCS4, Py_UCS1,
1258 PyUnicode_4BYTE_DATA(from) + from_start,
1259 PyUnicode_4BYTE_DATA(from) + from_start + how_many,
1260 PyUnicode_1BYTE_DATA(to) + to_start
1261 );
1262 }
1263 else if (from_kind == PyUnicode_4BYTE_KIND
1264 && to_kind == PyUnicode_2BYTE_KIND)
1265 {
1266 _PyUnicode_CONVERT_BYTES(
1267 Py_UCS4, Py_UCS2,
1268 PyUnicode_4BYTE_DATA(from) + from_start,
1269 PyUnicode_4BYTE_DATA(from) + from_start + how_many,
1270 PyUnicode_2BYTE_DATA(to) + to_start
1271 );
1272 }
1273 else {
1274 assert(0);
1275 return -1;
1276 }
1277 }
Victor Stinnerf1852262012-06-16 16:38:26 +02001278 else {
Victor Stinnera0702ab2011-09-29 14:14:38 +02001279 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001280 Py_UCS4 ch;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001281 Py_ssize_t i;
1282
Victor Stinnera0702ab2011-09-29 14:14:38 +02001283 for (i=0; i < how_many; i++) {
1284 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001285 if (ch > to_maxchar)
1286 return -1;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001287 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1288 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001289 }
1290 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001291 return 0;
1292}
1293
Victor Stinnerd3f08822012-05-29 12:57:52 +02001294void
1295_PyUnicode_FastCopyCharacters(
1296 PyObject *to, Py_ssize_t to_start,
1297 PyObject *from, Py_ssize_t from_start, Py_ssize_t how_many)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001298{
1299 (void)_copy_characters(to, to_start, from, from_start, how_many, 0);
1300}
1301
1302Py_ssize_t
1303PyUnicode_CopyCharacters(PyObject *to, Py_ssize_t to_start,
1304 PyObject *from, Py_ssize_t from_start,
1305 Py_ssize_t how_many)
1306{
1307 int err;
1308
1309 if (!PyUnicode_Check(from) || !PyUnicode_Check(to)) {
1310 PyErr_BadInternalCall();
1311 return -1;
1312 }
1313
Benjamin Petersonbac79492012-01-14 13:34:47 -05001314 if (PyUnicode_READY(from) == -1)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001315 return -1;
Benjamin Petersonbac79492012-01-14 13:34:47 -05001316 if (PyUnicode_READY(to) == -1)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001317 return -1;
1318
Victor Stinnerd3f08822012-05-29 12:57:52 +02001319 if (from_start < 0) {
1320 PyErr_SetString(PyExc_IndexError, "string index out of range");
1321 return -1;
1322 }
1323 if (to_start < 0) {
1324 PyErr_SetString(PyExc_IndexError, "string index out of range");
1325 return -1;
1326 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001327 how_many = Py_MIN(PyUnicode_GET_LENGTH(from), how_many);
1328 if (to_start + how_many > PyUnicode_GET_LENGTH(to)) {
1329 PyErr_Format(PyExc_SystemError,
1330 "Cannot write %zi characters at %zi "
1331 "in a string of %zi characters",
1332 how_many, to_start, PyUnicode_GET_LENGTH(to));
1333 return -1;
1334 }
1335
1336 if (how_many == 0)
1337 return 0;
1338
Victor Stinner488fa492011-12-12 00:01:39 +01001339 if (unicode_check_modifiable(to))
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001340 return -1;
1341
1342 err = _copy_characters(to, to_start, from, from_start, how_many, 1);
1343 if (err) {
1344 PyErr_Format(PyExc_SystemError,
1345 "Cannot copy %s characters "
1346 "into a string of %s characters",
1347 unicode_kind_name(from),
1348 unicode_kind_name(to));
1349 return -1;
1350 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001351 return how_many;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001352}
1353
Victor Stinner17222162011-09-28 22:15:37 +02001354/* Find the maximum code point and count the number of surrogate pairs so a
1355 correct string length can be computed before converting a string to UCS4.
1356 This function counts single surrogates as a character and not as a pair.
1357
1358 Return 0 on success, or -1 on error. */
1359static int
1360find_maxchar_surrogates(const wchar_t *begin, const wchar_t *end,
1361 Py_UCS4 *maxchar, Py_ssize_t *num_surrogates)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001362{
1363 const wchar_t *iter;
Victor Stinner8faf8212011-12-08 22:14:11 +01001364 Py_UCS4 ch;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001365
Victor Stinnerc53be962011-10-02 21:33:54 +02001366 assert(num_surrogates != NULL && maxchar != NULL);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001367 *num_surrogates = 0;
1368 *maxchar = 0;
1369
1370 for (iter = begin; iter < end; ) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001371#if SIZEOF_WCHAR_T == 2
Victor Stinnerca4f2072011-11-22 03:38:40 +01001372 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1373 && (iter+1) < end
1374 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001375 {
Victor Stinner8faf8212011-12-08 22:14:11 +01001376 ch = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001377 ++(*num_surrogates);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001378 iter += 2;
1379 }
1380 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001381#endif
Victor Stinner8faf8212011-12-08 22:14:11 +01001382 {
1383 ch = *iter;
1384 iter++;
1385 }
1386 if (ch > *maxchar) {
1387 *maxchar = ch;
1388 if (*maxchar > MAX_UNICODE) {
1389 PyErr_Format(PyExc_ValueError,
1390 "character U+%x is not in range [U+0000; U+10ffff]",
1391 ch);
1392 return -1;
1393 }
1394 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001395 }
1396 return 0;
1397}
1398
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001399int
1400_PyUnicode_Ready(PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001401{
1402 wchar_t *end;
1403 Py_UCS4 maxchar = 0;
1404 Py_ssize_t num_surrogates;
1405#if SIZEOF_WCHAR_T == 2
1406 Py_ssize_t length_wo_surrogates;
1407#endif
1408
Georg Brandl7597add2011-10-05 16:36:47 +02001409 /* _PyUnicode_Ready() is only intended for old-style API usage where
Victor Stinnerd8f65102011-09-29 19:43:17 +02001410 strings were created using _PyObject_New() and where no canonical
1411 representation (the str field) has been set yet aka strings
1412 which are not yet ready. */
Victor Stinner910337b2011-10-03 03:20:16 +02001413 assert(_PyUnicode_CHECK(unicode));
1414 assert(_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001415 assert(_PyUnicode_WSTR(unicode) != NULL);
Victor Stinnerc3c74152011-10-02 20:39:55 +02001416 assert(_PyUnicode_DATA_ANY(unicode) == NULL);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001417 assert(_PyUnicode_UTF8(unicode) == NULL);
Victor Stinnerd8f65102011-09-29 19:43:17 +02001418 /* Actually, it should neither be interned nor be anything else: */
1419 assert(_PyUnicode_STATE(unicode).interned == SSTATE_NOT_INTERNED);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001420
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001421 end = _PyUnicode_WSTR(unicode) + _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinner17222162011-09-28 22:15:37 +02001422 if (find_maxchar_surrogates(_PyUnicode_WSTR(unicode), end,
Victor Stinnerd8f65102011-09-29 19:43:17 +02001423 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001424 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001425
1426 if (maxchar < 256) {
Victor Stinnerc3c74152011-10-02 20:39:55 +02001427 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(_PyUnicode_WSTR_LENGTH(unicode) + 1);
1428 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001429 PyErr_NoMemory();
1430 return -1;
1431 }
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001432 _PyUnicode_CONVERT_BYTES(wchar_t, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001433 _PyUnicode_WSTR(unicode), end,
1434 PyUnicode_1BYTE_DATA(unicode));
1435 PyUnicode_1BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1436 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1437 _PyUnicode_STATE(unicode).kind = PyUnicode_1BYTE_KIND;
1438 if (maxchar < 128) {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001439 _PyUnicode_STATE(unicode).ascii = 1;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001440 _PyUnicode_UTF8(unicode) = _PyUnicode_DATA_ANY(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001441 _PyUnicode_UTF8_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001442 }
1443 else {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001444 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001445 _PyUnicode_UTF8(unicode) = NULL;
1446 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001447 }
1448 PyObject_FREE(_PyUnicode_WSTR(unicode));
1449 _PyUnicode_WSTR(unicode) = NULL;
1450 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1451 }
1452 /* In this case we might have to convert down from 4-byte native
1453 wchar_t to 2-byte unicode. */
1454 else if (maxchar < 65536) {
1455 assert(num_surrogates == 0 &&
1456 "FindMaxCharAndNumSurrogatePairs() messed up");
1457
Victor Stinner506f5922011-09-28 22:34:18 +02001458#if SIZEOF_WCHAR_T == 2
1459 /* We can share representations and are done. */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001460 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Victor Stinner506f5922011-09-28 22:34:18 +02001461 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1462 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1463 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001464 _PyUnicode_UTF8(unicode) = NULL;
1465 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001466#else
1467 /* sizeof(wchar_t) == 4 */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001468 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(
Victor Stinner506f5922011-09-28 22:34:18 +02001469 2 * (_PyUnicode_WSTR_LENGTH(unicode) + 1));
Victor Stinnerc3c74152011-10-02 20:39:55 +02001470 if (!_PyUnicode_DATA_ANY(unicode)) {
Victor Stinner506f5922011-09-28 22:34:18 +02001471 PyErr_NoMemory();
1472 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001473 }
Victor Stinner506f5922011-09-28 22:34:18 +02001474 _PyUnicode_CONVERT_BYTES(wchar_t, Py_UCS2,
1475 _PyUnicode_WSTR(unicode), end,
1476 PyUnicode_2BYTE_DATA(unicode));
1477 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1478 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1479 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001480 _PyUnicode_UTF8(unicode) = NULL;
1481 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001482 PyObject_FREE(_PyUnicode_WSTR(unicode));
1483 _PyUnicode_WSTR(unicode) = NULL;
1484 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1485#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001486 }
1487 /* maxchar exeeds 16 bit, wee need 4 bytes for unicode characters */
1488 else {
1489#if SIZEOF_WCHAR_T == 2
1490 /* in case the native representation is 2-bytes, we need to allocate a
1491 new normalized 4-byte version. */
1492 length_wo_surrogates = _PyUnicode_WSTR_LENGTH(unicode) - num_surrogates;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001493 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(4 * (length_wo_surrogates + 1));
1494 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001495 PyErr_NoMemory();
1496 return -1;
1497 }
1498 _PyUnicode_LENGTH(unicode) = length_wo_surrogates;
1499 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001500 _PyUnicode_UTF8(unicode) = NULL;
1501 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner126c5592011-10-03 04:17:10 +02001502 /* unicode_convert_wchar_to_ucs4() requires a ready string */
1503 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerc53be962011-10-02 21:33:54 +02001504 unicode_convert_wchar_to_ucs4(_PyUnicode_WSTR(unicode), end, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001505 PyObject_FREE(_PyUnicode_WSTR(unicode));
1506 _PyUnicode_WSTR(unicode) = NULL;
1507 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1508#else
1509 assert(num_surrogates == 0);
1510
Victor Stinnerc3c74152011-10-02 20:39:55 +02001511 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001512 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001513 _PyUnicode_UTF8(unicode) = NULL;
1514 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001515 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
1516#endif
1517 PyUnicode_4BYTE_DATA(unicode)[_PyUnicode_LENGTH(unicode)] = '\0';
1518 }
1519 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001520 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001521 return 0;
1522}
1523
Alexander Belopolsky40018472011-02-26 01:02:56 +00001524static void
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001525unicode_dealloc(register PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001526{
Walter Dörwald16807132007-05-25 13:52:07 +00001527 switch (PyUnicode_CHECK_INTERNED(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001528 case SSTATE_NOT_INTERNED:
1529 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001530
Benjamin Peterson29060642009-01-31 22:14:21 +00001531 case SSTATE_INTERNED_MORTAL:
1532 /* revive dead object temporarily for DelItem */
1533 Py_REFCNT(unicode) = 3;
Victor Stinner7931d9a2011-11-04 00:22:48 +01001534 if (PyDict_DelItem(interned, unicode) != 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00001535 Py_FatalError(
1536 "deletion of interned string failed");
1537 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001538
Benjamin Peterson29060642009-01-31 22:14:21 +00001539 case SSTATE_INTERNED_IMMORTAL:
1540 Py_FatalError("Immortal interned string died.");
Walter Dörwald16807132007-05-25 13:52:07 +00001541
Benjamin Peterson29060642009-01-31 22:14:21 +00001542 default:
1543 Py_FatalError("Inconsistent interned string state.");
Walter Dörwald16807132007-05-25 13:52:07 +00001544 }
1545
Victor Stinner03490912011-10-03 23:45:12 +02001546 if (_PyUnicode_HAS_WSTR_MEMORY(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001547 PyObject_DEL(_PyUnicode_WSTR(unicode));
Victor Stinner829c0ad2011-10-03 01:08:02 +02001548 if (_PyUnicode_HAS_UTF8_MEMORY(unicode))
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001549 PyObject_DEL(_PyUnicode_UTF8(unicode));
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001550 if (!PyUnicode_IS_COMPACT(unicode) && _PyUnicode_DATA_ANY(unicode))
1551 PyObject_DEL(_PyUnicode_DATA_ANY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001552
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001553 Py_TYPE(unicode)->tp_free(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001554}
1555
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001556#ifdef Py_DEBUG
1557static int
1558unicode_is_singleton(PyObject *unicode)
1559{
1560 PyASCIIObject *ascii = (PyASCIIObject *)unicode;
1561 if (unicode == unicode_empty)
1562 return 1;
1563 if (ascii->state.kind != PyUnicode_WCHAR_KIND && ascii->length == 1)
1564 {
1565 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, 0);
1566 if (ch < 256 && unicode_latin1[ch] == unicode)
1567 return 1;
1568 }
1569 return 0;
1570}
1571#endif
1572
Alexander Belopolsky40018472011-02-26 01:02:56 +00001573static int
Victor Stinner488fa492011-12-12 00:01:39 +01001574unicode_modifiable(PyObject *unicode)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001575{
Victor Stinner488fa492011-12-12 00:01:39 +01001576 assert(_PyUnicode_CHECK(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001577 if (Py_REFCNT(unicode) != 1)
1578 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001579 if (_PyUnicode_HASH(unicode) != -1)
1580 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001581 if (PyUnicode_CHECK_INTERNED(unicode))
1582 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001583 if (!PyUnicode_CheckExact(unicode))
1584 return 0;
Victor Stinner77bb47b2011-10-03 20:06:05 +02001585#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001586 /* singleton refcount is greater than 1 */
1587 assert(!unicode_is_singleton(unicode));
Victor Stinner77bb47b2011-10-03 20:06:05 +02001588#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +02001589 return 1;
1590}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001591
Victor Stinnerfe226c02011-10-03 03:52:20 +02001592static int
1593unicode_resize(PyObject **p_unicode, Py_ssize_t length)
1594{
1595 PyObject *unicode;
1596 Py_ssize_t old_length;
1597
1598 assert(p_unicode != NULL);
1599 unicode = *p_unicode;
1600
1601 assert(unicode != NULL);
1602 assert(PyUnicode_Check(unicode));
1603 assert(0 <= length);
1604
Victor Stinner910337b2011-10-03 03:20:16 +02001605 if (_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001606 old_length = PyUnicode_WSTR_LENGTH(unicode);
1607 else
1608 old_length = PyUnicode_GET_LENGTH(unicode);
1609 if (old_length == length)
1610 return 0;
1611
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001612 if (length == 0) {
1613 Py_DECREF(*p_unicode);
1614 *p_unicode = unicode_empty;
1615 Py_INCREF(*p_unicode);
1616 return 0;
1617 }
1618
Victor Stinner488fa492011-12-12 00:01:39 +01001619 if (!unicode_modifiable(unicode)) {
Victor Stinnerfe226c02011-10-03 03:52:20 +02001620 PyObject *copy = resize_copy(unicode, length);
1621 if (copy == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001622 return -1;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001623 Py_DECREF(*p_unicode);
1624 *p_unicode = copy;
Benjamin Peterson29060642009-01-31 22:14:21 +00001625 return 0;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001626 }
1627
Victor Stinnerfe226c02011-10-03 03:52:20 +02001628 if (PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001629 PyObject *new_unicode = resize_compact(unicode, length);
1630 if (new_unicode == NULL)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001631 return -1;
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001632 *p_unicode = new_unicode;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001633 return 0;
Benjamin Peterson4bfce8f2011-10-03 19:35:07 -04001634 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001635 return resize_inplace(unicode, length);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001636}
1637
Alexander Belopolsky40018472011-02-26 01:02:56 +00001638int
Victor Stinnerfe226c02011-10-03 03:52:20 +02001639PyUnicode_Resize(PyObject **p_unicode, Py_ssize_t length)
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001640{
Victor Stinnerfe226c02011-10-03 03:52:20 +02001641 PyObject *unicode;
1642 if (p_unicode == NULL) {
1643 PyErr_BadInternalCall();
1644 return -1;
1645 }
1646 unicode = *p_unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001647 if (unicode == NULL || !PyUnicode_Check(unicode) || length < 0)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001648 {
1649 PyErr_BadInternalCall();
1650 return -1;
1651 }
1652 return unicode_resize(p_unicode, length);
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001653}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001654
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001655static int
Victor Stinner1b487b42012-05-03 12:29:04 +02001656unicode_widen(PyObject **p_unicode, Py_ssize_t length,
1657 unsigned int maxchar)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001658{
1659 PyObject *result;
1660 assert(PyUnicode_IS_READY(*p_unicode));
Victor Stinner1b487b42012-05-03 12:29:04 +02001661 assert(length <= PyUnicode_GET_LENGTH(*p_unicode));
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001662 if (maxchar <= PyUnicode_MAX_CHAR_VALUE(*p_unicode))
1663 return 0;
1664 result = PyUnicode_New(PyUnicode_GET_LENGTH(*p_unicode),
1665 maxchar);
1666 if (result == NULL)
1667 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +02001668 _PyUnicode_FastCopyCharacters(result, 0, *p_unicode, 0, length);
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001669 Py_DECREF(*p_unicode);
1670 *p_unicode = result;
1671 return 0;
1672}
1673
1674static int
1675unicode_putchar(PyObject **p_unicode, Py_ssize_t *pos,
1676 Py_UCS4 ch)
1677{
Victor Stinner15e9ed22012-02-22 13:36:20 +01001678 assert(ch <= MAX_UNICODE);
Victor Stinner1b487b42012-05-03 12:29:04 +02001679 if (unicode_widen(p_unicode, *pos, ch) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001680 return -1;
1681 PyUnicode_WRITE(PyUnicode_KIND(*p_unicode),
1682 PyUnicode_DATA(*p_unicode),
1683 (*pos)++, ch);
1684 return 0;
1685}
1686
Victor Stinnerc5166102012-02-22 13:55:02 +01001687/* Copy a ASCII or latin1 char* string into a Python Unicode string.
Victor Stinnerc5166102012-02-22 13:55:02 +01001688
Victor Stinnerb429d3b2012-02-22 21:22:20 +01001689 WARNING: The function doesn't copy the terminating null character and
1690 doesn't check the maximum character (may write a latin1 character in an
1691 ASCII string). */
Victor Stinner184252a2012-06-16 02:57:41 +02001692static void
1693unicode_write_cstr(PyObject *unicode, Py_ssize_t index,
1694 const char *str, Py_ssize_t len)
Victor Stinnerc5166102012-02-22 13:55:02 +01001695{
1696 enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
1697 void *data = PyUnicode_DATA(unicode);
Victor Stinner184252a2012-06-16 02:57:41 +02001698 const char *end = str + len;
Victor Stinnerc5166102012-02-22 13:55:02 +01001699
1700 switch (kind) {
1701 case PyUnicode_1BYTE_KIND: {
Victor Stinnerc5166102012-02-22 13:55:02 +01001702 assert(index + len <= PyUnicode_GET_LENGTH(unicode));
Victor Stinner8c6db452012-10-06 00:40:45 +02001703#ifdef Py_DEBUG
1704 if (PyUnicode_IS_ASCII(unicode)) {
1705 Py_UCS4 maxchar = ucs1lib_find_max_char(
1706 (const Py_UCS1*)str,
1707 (const Py_UCS1*)str + len);
1708 assert(maxchar < 128);
1709 }
1710#endif
Antoine Pitrouba6bafc2012-02-22 16:41:50 +01001711 memcpy((char *) data + index, str, len);
Victor Stinner184252a2012-06-16 02:57:41 +02001712 break;
Victor Stinnerc5166102012-02-22 13:55:02 +01001713 }
1714 case PyUnicode_2BYTE_KIND: {
1715 Py_UCS2 *start = (Py_UCS2 *)data + index;
1716 Py_UCS2 *ucs2 = start;
1717 assert(index <= PyUnicode_GET_LENGTH(unicode));
1718
Victor Stinner184252a2012-06-16 02:57:41 +02001719 for (; str < end; ++ucs2, ++str)
Victor Stinnerc5166102012-02-22 13:55:02 +01001720 *ucs2 = (Py_UCS2)*str;
1721
1722 assert((ucs2 - start) <= PyUnicode_GET_LENGTH(unicode));
Victor Stinner184252a2012-06-16 02:57:41 +02001723 break;
Victor Stinnerc5166102012-02-22 13:55:02 +01001724 }
1725 default: {
1726 Py_UCS4 *start = (Py_UCS4 *)data + index;
1727 Py_UCS4 *ucs4 = start;
1728 assert(kind == PyUnicode_4BYTE_KIND);
1729 assert(index <= PyUnicode_GET_LENGTH(unicode));
1730
Victor Stinner184252a2012-06-16 02:57:41 +02001731 for (; str < end; ++ucs4, ++str)
Victor Stinnerc5166102012-02-22 13:55:02 +01001732 *ucs4 = (Py_UCS4)*str;
1733
1734 assert((ucs4 - start) <= PyUnicode_GET_LENGTH(unicode));
Victor Stinnerc5166102012-02-22 13:55:02 +01001735 }
1736 }
1737}
1738
1739
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001740static PyObject*
1741get_latin1_char(unsigned char ch)
1742{
Victor Stinnera464fc12011-10-02 20:39:30 +02001743 PyObject *unicode = unicode_latin1[ch];
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001744 if (!unicode) {
Victor Stinnera464fc12011-10-02 20:39:30 +02001745 unicode = PyUnicode_New(1, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001746 if (!unicode)
1747 return NULL;
1748 PyUnicode_1BYTE_DATA(unicode)[0] = ch;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001749 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001750 unicode_latin1[ch] = unicode;
1751 }
1752 Py_INCREF(unicode);
Victor Stinnera464fc12011-10-02 20:39:30 +02001753 return unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001754}
1755
Alexander Belopolsky40018472011-02-26 01:02:56 +00001756PyObject *
1757PyUnicode_FromUnicode(const Py_UNICODE *u, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001758{
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001759 PyObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001760 Py_UCS4 maxchar = 0;
1761 Py_ssize_t num_surrogates;
1762
1763 if (u == NULL)
1764 return (PyObject*)_PyUnicode_New(size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001765
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001766 /* If the Unicode data is known at construction time, we can apply
1767 some optimizations which share commonly used objects. */
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001768
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001769 /* Optimization for empty strings */
1770 if (size == 0 && unicode_empty != NULL) {
1771 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001772 return unicode_empty;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001773 }
Tim Petersced69f82003-09-16 20:30:58 +00001774
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001775 /* Single character Unicode objects in the Latin-1 range are
1776 shared when using this constructor */
1777 if (size == 1 && *u < 256)
1778 return get_latin1_char((unsigned char)*u);
1779
1780 /* If not empty and not single character, copy the Unicode data
1781 into the new object */
Victor Stinnerd8f65102011-09-29 19:43:17 +02001782 if (find_maxchar_surrogates(u, u + size,
1783 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001784 return NULL;
1785
Victor Stinner8faf8212011-12-08 22:14:11 +01001786 unicode = PyUnicode_New(size - num_surrogates, maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001787 if (!unicode)
1788 return NULL;
1789
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001790 switch (PyUnicode_KIND(unicode)) {
1791 case PyUnicode_1BYTE_KIND:
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001792 _PyUnicode_CONVERT_BYTES(Py_UNICODE, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001793 u, u + size, PyUnicode_1BYTE_DATA(unicode));
1794 break;
1795 case PyUnicode_2BYTE_KIND:
1796#if Py_UNICODE_SIZE == 2
1797 Py_MEMCPY(PyUnicode_2BYTE_DATA(unicode), u, size * 2);
1798#else
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001799 _PyUnicode_CONVERT_BYTES(Py_UNICODE, Py_UCS2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001800 u, u + size, PyUnicode_2BYTE_DATA(unicode));
1801#endif
1802 break;
1803 case PyUnicode_4BYTE_KIND:
1804#if SIZEOF_WCHAR_T == 2
1805 /* This is the only case which has to process surrogates, thus
1806 a simple copy loop is not enough and we need a function. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001807 unicode_convert_wchar_to_ucs4(u, u + size, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001808#else
1809 assert(num_surrogates == 0);
1810 Py_MEMCPY(PyUnicode_4BYTE_DATA(unicode), u, size * 4);
1811#endif
1812 break;
1813 default:
1814 assert(0 && "Impossible state");
1815 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00001816
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001817 return unicode_result(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001818}
1819
Alexander Belopolsky40018472011-02-26 01:02:56 +00001820PyObject *
1821PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size)
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001822{
Benjamin Peterson14339b62009-01-31 16:36:08 +00001823 if (size < 0) {
1824 PyErr_SetString(PyExc_SystemError,
Benjamin Peterson29060642009-01-31 22:14:21 +00001825 "Negative size passed to PyUnicode_FromStringAndSize");
Benjamin Peterson14339b62009-01-31 16:36:08 +00001826 return NULL;
1827 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01001828 if (u != NULL)
1829 return PyUnicode_DecodeUTF8Stateful(u, size, NULL, NULL);
1830 else
1831 return (PyObject *)_PyUnicode_New(size);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001832}
1833
Alexander Belopolsky40018472011-02-26 01:02:56 +00001834PyObject *
1835PyUnicode_FromString(const char *u)
Walter Dörwaldd2034312007-05-18 16:29:38 +00001836{
1837 size_t size = strlen(u);
1838 if (size > PY_SSIZE_T_MAX) {
1839 PyErr_SetString(PyExc_OverflowError, "input too long");
1840 return NULL;
1841 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01001842 return PyUnicode_DecodeUTF8Stateful(u, (Py_ssize_t)size, NULL, NULL);
Walter Dörwaldd2034312007-05-18 16:29:38 +00001843}
1844
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001845PyObject *
1846_PyUnicode_FromId(_Py_Identifier *id)
1847{
1848 if (!id->object) {
Victor Stinnerd1cd99b2012-02-07 23:05:55 +01001849 id->object = PyUnicode_DecodeUTF8Stateful(id->string,
1850 strlen(id->string),
1851 NULL, NULL);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001852 if (!id->object)
1853 return NULL;
1854 PyUnicode_InternInPlace(&id->object);
1855 assert(!id->next);
1856 id->next = static_strings;
1857 static_strings = id;
1858 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001859 return id->object;
1860}
1861
1862void
1863_PyUnicode_ClearStaticStrings()
1864{
1865 _Py_Identifier *i;
1866 for (i = static_strings; i; i = i->next) {
1867 Py_DECREF(i->object);
1868 i->object = NULL;
1869 i->next = NULL;
1870 }
1871}
1872
Benjamin Peterson0df54292012-03-26 14:50:32 -04001873/* Internal function, doesn't check maximum character */
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001874
Victor Stinnerd3f08822012-05-29 12:57:52 +02001875PyObject*
1876_PyUnicode_FromASCII(const char *buffer, Py_ssize_t size)
Victor Stinner702c7342011-10-05 13:50:52 +02001877{
Victor Stinnerd3f08822012-05-29 12:57:52 +02001878 const unsigned char *s = (const unsigned char *)buffer;
Victor Stinner785938e2011-12-11 20:09:03 +01001879 PyObject *unicode;
Victor Stinnere6b2d442011-12-11 21:54:30 +01001880 if (size == 1) {
Victor Stinner0617b6e2011-10-05 23:26:01 +02001881#ifdef Py_DEBUG
Victor Stinnere6b2d442011-12-11 21:54:30 +01001882 assert(s[0] < 128);
Victor Stinner0617b6e2011-10-05 23:26:01 +02001883#endif
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001884 return get_latin1_char(s[0]);
Victor Stinnere6b2d442011-12-11 21:54:30 +01001885 }
Victor Stinner785938e2011-12-11 20:09:03 +01001886 unicode = PyUnicode_New(size, 127);
1887 if (!unicode)
Victor Stinner702c7342011-10-05 13:50:52 +02001888 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01001889 memcpy(PyUnicode_1BYTE_DATA(unicode), s, size);
1890 assert(_PyUnicode_CheckConsistency(unicode, 1));
1891 return unicode;
Victor Stinner702c7342011-10-05 13:50:52 +02001892}
1893
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001894static Py_UCS4
1895kind_maxchar_limit(unsigned int kind)
1896{
Benjamin Petersonead6b532011-12-20 17:23:42 -06001897 switch (kind) {
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001898 case PyUnicode_1BYTE_KIND:
1899 return 0x80;
1900 case PyUnicode_2BYTE_KIND:
1901 return 0x100;
1902 case PyUnicode_4BYTE_KIND:
1903 return 0x10000;
1904 default:
1905 assert(0 && "invalid kind");
Victor Stinner8faf8212011-12-08 22:14:11 +01001906 return MAX_UNICODE;
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001907 }
1908}
1909
Victor Stinnere6abb482012-05-02 01:15:40 +02001910Py_LOCAL_INLINE(Py_UCS4)
1911align_maxchar(Py_UCS4 maxchar)
1912{
1913 if (maxchar <= 127)
1914 return 127;
1915 else if (maxchar <= 255)
1916 return 255;
1917 else if (maxchar <= 65535)
1918 return 65535;
1919 else
1920 return MAX_UNICODE;
1921}
1922
Victor Stinner702c7342011-10-05 13:50:52 +02001923static PyObject*
Victor Stinnere57b1c02011-09-28 22:20:48 +02001924_PyUnicode_FromUCS1(const unsigned char* u, Py_ssize_t size)
Mark Dickinson081dfee2009-03-18 14:47:41 +00001925{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001926 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001927 unsigned char max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001928
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001929 if (size == 0) {
1930 Py_INCREF(unicode_empty);
1931 return unicode_empty;
1932 }
1933 assert(size > 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001934 if (size == 1)
1935 return get_latin1_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001936
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001937 max_char = ucs1lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001938 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001939 if (!res)
1940 return NULL;
1941 memcpy(PyUnicode_1BYTE_DATA(res), u, size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001942 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001943 return res;
Mark Dickinson081dfee2009-03-18 14:47:41 +00001944}
1945
Victor Stinnere57b1c02011-09-28 22:20:48 +02001946static PyObject*
1947_PyUnicode_FromUCS2(const Py_UCS2 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001948{
1949 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001950 Py_UCS2 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001951
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001952 if (size == 0) {
1953 Py_INCREF(unicode_empty);
1954 return unicode_empty;
1955 }
1956 assert(size > 0);
Victor Stinnerb6cd0142012-05-03 02:17:04 +02001957 if (size == 1) {
1958 Py_UCS4 ch = u[0];
1959 if (ch < 256)
1960 return get_latin1_char((unsigned char)ch);
1961
1962 res = PyUnicode_New(1, ch);
1963 if (res == NULL)
1964 return NULL;
1965 PyUnicode_WRITE(PyUnicode_KIND(res), PyUnicode_DATA(res), 0, ch);
1966 assert(_PyUnicode_CheckConsistency(res, 1));
1967 return res;
1968 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001969
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001970 max_char = ucs2lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001971 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001972 if (!res)
1973 return NULL;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001974 if (max_char >= 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001975 memcpy(PyUnicode_2BYTE_DATA(res), u, sizeof(Py_UCS2)*size);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001976 else {
1977 _PyUnicode_CONVERT_BYTES(
1978 Py_UCS2, Py_UCS1, u, u + size, PyUnicode_1BYTE_DATA(res));
1979 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001980 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001981 return res;
1982}
1983
Victor Stinnere57b1c02011-09-28 22:20:48 +02001984static PyObject*
1985_PyUnicode_FromUCS4(const Py_UCS4 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001986{
1987 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001988 Py_UCS4 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001989
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001990 if (size == 0) {
1991 Py_INCREF(unicode_empty);
1992 return unicode_empty;
1993 }
1994 assert(size > 0);
Victor Stinnerb6cd0142012-05-03 02:17:04 +02001995 if (size == 1) {
1996 Py_UCS4 ch = u[0];
1997 if (ch < 256)
1998 return get_latin1_char((unsigned char)ch);
1999
2000 res = PyUnicode_New(1, ch);
2001 if (res == NULL)
2002 return NULL;
2003 PyUnicode_WRITE(PyUnicode_KIND(res), PyUnicode_DATA(res), 0, ch);
2004 assert(_PyUnicode_CheckConsistency(res, 1));
2005 return res;
2006 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002007
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002008 max_char = ucs4lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002009 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002010 if (!res)
2011 return NULL;
Antoine Pitrou950468e2011-10-11 22:45:48 +02002012 if (max_char < 256)
2013 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, u, u + size,
2014 PyUnicode_1BYTE_DATA(res));
2015 else if (max_char < 0x10000)
2016 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, u, u + size,
2017 PyUnicode_2BYTE_DATA(res));
2018 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002019 memcpy(PyUnicode_4BYTE_DATA(res), u, sizeof(Py_UCS4)*size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002020 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002021 return res;
2022}
2023
2024PyObject*
2025PyUnicode_FromKindAndData(int kind, const void *buffer, Py_ssize_t size)
2026{
Victor Stinnercfed46e2011-11-22 01:29:14 +01002027 if (size < 0) {
2028 PyErr_SetString(PyExc_ValueError, "size must be positive");
2029 return NULL;
2030 }
Benjamin Petersonead6b532011-12-20 17:23:42 -06002031 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002032 case PyUnicode_1BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002033 return _PyUnicode_FromUCS1(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002034 case PyUnicode_2BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002035 return _PyUnicode_FromUCS2(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002036 case PyUnicode_4BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002037 return _PyUnicode_FromUCS4(buffer, size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002038 default:
Victor Stinnerb9275c12011-10-05 14:01:42 +02002039 PyErr_SetString(PyExc_SystemError, "invalid kind");
2040 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002041 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002042}
2043
Victor Stinnerece58de2012-04-23 23:36:38 +02002044Py_UCS4
2045_PyUnicode_FindMaxChar(PyObject *unicode, Py_ssize_t start, Py_ssize_t end)
2046{
2047 enum PyUnicode_Kind kind;
2048 void *startptr, *endptr;
2049
2050 assert(PyUnicode_IS_READY(unicode));
2051 assert(0 <= start);
2052 assert(end <= PyUnicode_GET_LENGTH(unicode));
2053 assert(start <= end);
2054
2055 if (start == 0 && end == PyUnicode_GET_LENGTH(unicode))
2056 return PyUnicode_MAX_CHAR_VALUE(unicode);
2057
2058 if (start == end)
2059 return 127;
2060
Victor Stinner94d558b2012-04-27 22:26:58 +02002061 if (PyUnicode_IS_ASCII(unicode))
2062 return 127;
2063
Victor Stinnerece58de2012-04-23 23:36:38 +02002064 kind = PyUnicode_KIND(unicode);
Benjamin Petersonf3b7d862012-04-23 18:07:01 -04002065 startptr = PyUnicode_DATA(unicode);
Benjamin Petersonb9f4c9d2012-04-23 21:45:40 -04002066 endptr = (char *)startptr + end * kind;
2067 startptr = (char *)startptr + start * kind;
Benjamin Peterson2844a7a2012-04-23 18:00:25 -04002068 switch(kind) {
2069 case PyUnicode_1BYTE_KIND:
2070 return ucs1lib_find_max_char(startptr, endptr);
2071 case PyUnicode_2BYTE_KIND:
2072 return ucs2lib_find_max_char(startptr, endptr);
2073 case PyUnicode_4BYTE_KIND:
2074 return ucs4lib_find_max_char(startptr, endptr);
Victor Stinnerece58de2012-04-23 23:36:38 +02002075 default:
Benjamin Peterson2844a7a2012-04-23 18:00:25 -04002076 assert(0);
2077 return 0;
Victor Stinnerece58de2012-04-23 23:36:38 +02002078 }
2079}
2080
Victor Stinner25a4b292011-10-06 12:31:55 +02002081/* Ensure that a string uses the most efficient storage, if it is not the
2082 case: create a new string with of the right kind. Write NULL into *p_unicode
2083 on error. */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02002084static void
Victor Stinner25a4b292011-10-06 12:31:55 +02002085unicode_adjust_maxchar(PyObject **p_unicode)
2086{
2087 PyObject *unicode, *copy;
2088 Py_UCS4 max_char;
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002089 Py_ssize_t len;
Victor Stinner25a4b292011-10-06 12:31:55 +02002090 unsigned int kind;
2091
2092 assert(p_unicode != NULL);
2093 unicode = *p_unicode;
2094 assert(PyUnicode_IS_READY(unicode));
2095 if (PyUnicode_IS_ASCII(unicode))
2096 return;
2097
2098 len = PyUnicode_GET_LENGTH(unicode);
2099 kind = PyUnicode_KIND(unicode);
2100 if (kind == PyUnicode_1BYTE_KIND) {
2101 const Py_UCS1 *u = PyUnicode_1BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002102 max_char = ucs1lib_find_max_char(u, u + len);
2103 if (max_char >= 128)
2104 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002105 }
2106 else if (kind == PyUnicode_2BYTE_KIND) {
2107 const Py_UCS2 *u = PyUnicode_2BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002108 max_char = ucs2lib_find_max_char(u, u + len);
2109 if (max_char >= 256)
2110 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002111 }
2112 else {
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002113 const Py_UCS4 *u = PyUnicode_4BYTE_DATA(unicode);
Victor Stinner25a4b292011-10-06 12:31:55 +02002114 assert(kind == PyUnicode_4BYTE_KIND);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002115 max_char = ucs4lib_find_max_char(u, u + len);
2116 if (max_char >= 0x10000)
2117 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002118 }
Victor Stinner25a4b292011-10-06 12:31:55 +02002119 copy = PyUnicode_New(len, max_char);
Victor Stinnerca439ee2012-06-16 03:17:34 +02002120 if (copy != NULL)
2121 _PyUnicode_FastCopyCharacters(copy, 0, unicode, 0, len);
Victor Stinner25a4b292011-10-06 12:31:55 +02002122 Py_DECREF(unicode);
2123 *p_unicode = copy;
2124}
2125
Victor Stinner034f6cf2011-09-30 02:26:44 +02002126PyObject*
Victor Stinnerbf6e5602011-12-12 01:53:47 +01002127_PyUnicode_Copy(PyObject *unicode)
Victor Stinner034f6cf2011-09-30 02:26:44 +02002128{
Victor Stinner87af4f22011-11-21 23:03:47 +01002129 Py_ssize_t length;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002130 PyObject *copy;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002131
Victor Stinner034f6cf2011-09-30 02:26:44 +02002132 if (!PyUnicode_Check(unicode)) {
2133 PyErr_BadInternalCall();
2134 return NULL;
2135 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05002136 if (PyUnicode_READY(unicode) == -1)
Victor Stinner034f6cf2011-09-30 02:26:44 +02002137 return NULL;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002138
Victor Stinner87af4f22011-11-21 23:03:47 +01002139 length = PyUnicode_GET_LENGTH(unicode);
2140 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002141 if (!copy)
2142 return NULL;
2143 assert(PyUnicode_KIND(copy) == PyUnicode_KIND(unicode));
2144
Victor Stinner87af4f22011-11-21 23:03:47 +01002145 Py_MEMCPY(PyUnicode_DATA(copy), PyUnicode_DATA(unicode),
2146 length * PyUnicode_KIND(unicode));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002147 assert(_PyUnicode_CheckConsistency(copy, 1));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002148 return copy;
Victor Stinner034f6cf2011-09-30 02:26:44 +02002149}
2150
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002151
Victor Stinnerbc603d12011-10-02 01:00:40 +02002152/* Widen Unicode objects to larger buffers. Don't write terminating null
2153 character. Return NULL on error. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002154
2155void*
2156_PyUnicode_AsKind(PyObject *s, unsigned int kind)
2157{
Victor Stinnerbc603d12011-10-02 01:00:40 +02002158 Py_ssize_t len;
2159 void *result;
2160 unsigned int skind;
2161
Benjamin Petersonbac79492012-01-14 13:34:47 -05002162 if (PyUnicode_READY(s) == -1)
Victor Stinnerbc603d12011-10-02 01:00:40 +02002163 return NULL;
2164
2165 len = PyUnicode_GET_LENGTH(s);
2166 skind = PyUnicode_KIND(s);
2167 if (skind >= kind) {
Victor Stinner01698042011-10-04 00:04:26 +02002168 PyErr_SetString(PyExc_SystemError, "invalid widening attempt");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002169 return NULL;
2170 }
Benjamin Petersonead6b532011-12-20 17:23:42 -06002171 switch (kind) {
Victor Stinnerbc603d12011-10-02 01:00:40 +02002172 case PyUnicode_2BYTE_KIND:
2173 result = PyMem_Malloc(len * sizeof(Py_UCS2));
2174 if (!result)
2175 return PyErr_NoMemory();
2176 assert(skind == PyUnicode_1BYTE_KIND);
2177 _PyUnicode_CONVERT_BYTES(
2178 Py_UCS1, Py_UCS2,
2179 PyUnicode_1BYTE_DATA(s),
2180 PyUnicode_1BYTE_DATA(s) + len,
2181 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002182 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002183 case PyUnicode_4BYTE_KIND:
2184 result = PyMem_Malloc(len * sizeof(Py_UCS4));
2185 if (!result)
2186 return PyErr_NoMemory();
2187 if (skind == PyUnicode_2BYTE_KIND) {
2188 _PyUnicode_CONVERT_BYTES(
2189 Py_UCS2, Py_UCS4,
2190 PyUnicode_2BYTE_DATA(s),
2191 PyUnicode_2BYTE_DATA(s) + len,
2192 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002193 }
Victor Stinnerbc603d12011-10-02 01:00:40 +02002194 else {
2195 assert(skind == PyUnicode_1BYTE_KIND);
2196 _PyUnicode_CONVERT_BYTES(
2197 Py_UCS1, Py_UCS4,
2198 PyUnicode_1BYTE_DATA(s),
2199 PyUnicode_1BYTE_DATA(s) + len,
2200 result);
2201 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002202 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002203 default:
2204 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002205 }
Victor Stinner01698042011-10-04 00:04:26 +02002206 PyErr_SetString(PyExc_SystemError, "invalid kind");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002207 return NULL;
2208}
2209
2210static Py_UCS4*
2211as_ucs4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2212 int copy_null)
2213{
2214 int kind;
2215 void *data;
2216 Py_ssize_t len, targetlen;
2217 if (PyUnicode_READY(string) == -1)
2218 return NULL;
2219 kind = PyUnicode_KIND(string);
2220 data = PyUnicode_DATA(string);
2221 len = PyUnicode_GET_LENGTH(string);
2222 targetlen = len;
2223 if (copy_null)
2224 targetlen++;
2225 if (!target) {
2226 if (PY_SSIZE_T_MAX / sizeof(Py_UCS4) < targetlen) {
2227 PyErr_NoMemory();
2228 return NULL;
2229 }
2230 target = PyMem_Malloc(targetlen * sizeof(Py_UCS4));
2231 if (!target) {
2232 PyErr_NoMemory();
2233 return NULL;
2234 }
2235 }
2236 else {
2237 if (targetsize < targetlen) {
2238 PyErr_Format(PyExc_SystemError,
2239 "string is longer than the buffer");
2240 if (copy_null && 0 < targetsize)
2241 target[0] = 0;
2242 return NULL;
2243 }
2244 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002245 if (kind == PyUnicode_1BYTE_KIND) {
2246 Py_UCS1 *start = (Py_UCS1 *) data;
2247 _PyUnicode_CONVERT_BYTES(Py_UCS1, Py_UCS4, start, start + len, target);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002248 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002249 else if (kind == PyUnicode_2BYTE_KIND) {
2250 Py_UCS2 *start = (Py_UCS2 *) data;
2251 _PyUnicode_CONVERT_BYTES(Py_UCS2, Py_UCS4, start, start + len, target);
2252 }
2253 else {
2254 assert(kind == PyUnicode_4BYTE_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002255 Py_MEMCPY(target, data, len * sizeof(Py_UCS4));
Antoine Pitrou950468e2011-10-11 22:45:48 +02002256 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002257 if (copy_null)
2258 target[len] = 0;
2259 return target;
2260}
2261
2262Py_UCS4*
2263PyUnicode_AsUCS4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2264 int copy_null)
2265{
Antoine Pitroude20b0b2011-11-10 21:47:38 +01002266 if (target == NULL || targetsize < 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002267 PyErr_BadInternalCall();
2268 return NULL;
2269 }
2270 return as_ucs4(string, target, targetsize, copy_null);
2271}
2272
2273Py_UCS4*
2274PyUnicode_AsUCS4Copy(PyObject *string)
2275{
2276 return as_ucs4(string, NULL, 0, 1);
2277}
2278
2279#ifdef HAVE_WCHAR_H
Mark Dickinson081dfee2009-03-18 14:47:41 +00002280
Alexander Belopolsky40018472011-02-26 01:02:56 +00002281PyObject *
2282PyUnicode_FromWideChar(register const wchar_t *w, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002283{
Guido van Rossumd57fd912000-03-10 22:53:23 +00002284 if (w == NULL) {
Victor Stinner382955f2011-12-11 21:44:00 +01002285 if (size == 0) {
2286 Py_INCREF(unicode_empty);
2287 return unicode_empty;
2288 }
Benjamin Peterson29060642009-01-31 22:14:21 +00002289 PyErr_BadInternalCall();
2290 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002291 }
2292
Martin v. Löwis790465f2008-04-05 20:41:37 +00002293 if (size == -1) {
2294 size = wcslen(w);
2295 }
2296
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002297 return PyUnicode_FromUnicode(w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002298}
2299
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002300#endif /* HAVE_WCHAR_H */
Mark Dickinson081dfee2009-03-18 14:47:41 +00002301
Walter Dörwald346737f2007-05-31 10:44:43 +00002302static void
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002303makefmt(char *fmt, int longflag, int longlongflag, int size_tflag,
Victor Stinnere215d962012-10-06 23:03:36 +02002304 char c)
Walter Dörwald346737f2007-05-31 10:44:43 +00002305{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002306 *fmt++ = '%';
Benjamin Peterson14339b62009-01-31 16:36:08 +00002307 if (longflag)
2308 *fmt++ = 'l';
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002309 else if (longlongflag) {
2310 /* longlongflag should only ever be nonzero on machines with
2311 HAVE_LONG_LONG defined */
2312#ifdef HAVE_LONG_LONG
2313 char *f = PY_FORMAT_LONG_LONG;
2314 while (*f)
2315 *fmt++ = *f++;
2316#else
2317 /* we shouldn't ever get here */
2318 assert(0);
2319 *fmt++ = 'l';
2320#endif
2321 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002322 else if (size_tflag) {
2323 char *f = PY_FORMAT_SIZE_T;
2324 while (*f)
2325 *fmt++ = *f++;
2326 }
2327 *fmt++ = c;
2328 *fmt = '\0';
Walter Dörwald346737f2007-05-31 10:44:43 +00002329}
2330
Victor Stinnere215d962012-10-06 23:03:36 +02002331/* maximum number of characters required for output of %ld. 21 characters
2332 allows for 64-bit integers (in decimal) and an optional sign. */
2333#define MAX_LONG_CHARS 21
2334/* maximum number of characters required for output of %lld.
2335 We need at most ceil(log10(256)*SIZEOF_LONG_LONG) digits,
2336 plus 1 for the sign. 53/22 is an upper bound for log10(256). */
2337#define MAX_LONG_LONG_CHARS (2 + (SIZEOF_LONG_LONG*53-1) / 22)
Victor Stinner96865452011-03-01 23:44:09 +00002338
2339static const char*
Victor Stinnere215d962012-10-06 23:03:36 +02002340unicode_fromformat_arg(_PyUnicodeWriter *writer,
2341 const char *f, va_list *vargs)
Victor Stinner96865452011-03-01 23:44:09 +00002342{
Victor Stinnere215d962012-10-06 23:03:36 +02002343 const char *p;
2344 Py_ssize_t len;
2345 int zeropad;
2346 int width;
2347 int precision;
2348 int longflag;
2349 int longlongflag;
2350 int size_tflag;
2351 int fill;
2352
2353 p = f;
2354 f++;
2355 zeropad = (*f == '0');
Victor Stinner96865452011-03-01 23:44:09 +00002356
2357 /* parse the width.precision part, e.g. "%2.5s" => width=2, precision=5 */
Victor Stinner96865452011-03-01 23:44:09 +00002358 width = 0;
Victor Stinnere215d962012-10-06 23:03:36 +02002359 while (Py_ISDIGIT((unsigned)*f)) {
Victor Stinner3921e902012-10-06 23:05:00 +02002360 if (width > (INT_MAX - ((int)*f - '0')) / 10) {
2361 PyErr_SetString(PyExc_ValueError,
2362 "width too big");
2363 return NULL;
2364 }
Victor Stinnere215d962012-10-06 23:03:36 +02002365 width = (width*10) + (*f - '0');
2366 f++;
2367 }
Victor Stinner96865452011-03-01 23:44:09 +00002368 precision = 0;
2369 if (*f == '.') {
2370 f++;
Victor Stinnere215d962012-10-06 23:03:36 +02002371 while (Py_ISDIGIT((unsigned)*f)) {
Victor Stinner3921e902012-10-06 23:05:00 +02002372 if (precision > (INT_MAX - ((int)*f - '0')) / 10) {
2373 PyErr_SetString(PyExc_ValueError,
2374 "precision too big");
2375 return NULL;
2376 }
Victor Stinnere215d962012-10-06 23:03:36 +02002377 precision = (precision*10) + (*f - '0');
2378 f++;
2379 }
Victor Stinner96865452011-03-01 23:44:09 +00002380 if (*f == '%') {
2381 /* "%.3%s" => f points to "3" */
2382 f--;
2383 }
2384 }
2385 if (*f == '\0') {
Victor Stinnere215d962012-10-06 23:03:36 +02002386 /* bogus format "%.123" => go backward, f points to "3" */
Victor Stinner96865452011-03-01 23:44:09 +00002387 f--;
2388 }
Victor Stinner96865452011-03-01 23:44:09 +00002389
2390 /* Handle %ld, %lu, %lld and %llu. */
2391 longflag = 0;
2392 longlongflag = 0;
Victor Stinnere7faec12011-03-02 00:01:53 +00002393 size_tflag = 0;
Victor Stinner96865452011-03-01 23:44:09 +00002394 if (*f == 'l') {
Victor Stinner6d970f42011-03-02 00:04:25 +00002395 if (f[1] == 'd' || f[1] == 'u' || f[1] == 'i') {
Victor Stinner96865452011-03-01 23:44:09 +00002396 longflag = 1;
2397 ++f;
2398 }
2399#ifdef HAVE_LONG_LONG
2400 else if (f[1] == 'l' &&
Victor Stinner6d970f42011-03-02 00:04:25 +00002401 (f[2] == 'd' || f[2] == 'u' || f[2] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002402 longlongflag = 1;
2403 f += 2;
2404 }
2405#endif
2406 }
2407 /* handle the size_t flag. */
Victor Stinner6d970f42011-03-02 00:04:25 +00002408 else if (*f == 'z' && (f[1] == 'd' || f[1] == 'u' || f[1] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002409 size_tflag = 1;
2410 ++f;
2411 }
Victor Stinnere215d962012-10-06 23:03:36 +02002412
2413 if (f[1] == '\0')
2414 writer->overallocate = 0;
2415
2416 switch (*f) {
2417 case 'c':
2418 {
2419 int ordinal = va_arg(*vargs, int);
Victor Stinnerff5a8482012-10-06 23:05:45 +02002420 if (ordinal < 0 || ordinal > MAX_UNICODE) {
2421 PyErr_SetString(PyExc_ValueError,
2422 "character argument not in range(0x110000)");
2423 return NULL;
2424 }
Victor Stinnere215d962012-10-06 23:03:36 +02002425 if (_PyUnicodeWriter_Prepare(writer, 1, ordinal) == -1)
2426 return NULL;
2427 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, ordinal);
2428 writer->pos++;
2429 break;
2430 }
2431
2432 case 'i':
2433 case 'd':
2434 case 'u':
2435 case 'x':
2436 {
2437 /* used by sprintf */
2438 char fmt[10]; /* should be enough for "%0lld\0" */
2439 char small_buffer[MAX_LONG_CHARS];
2440 char *buffer;
2441 int err;
2442
2443 if (sizeof(small_buffer) - 1 < precision) {
2444 buffer = PyMem_Malloc(precision + 1);
2445 if (buffer == NULL) {
2446 PyErr_NoMemory();
2447 return NULL;
2448 }
2449 }
2450 else
2451 buffer = small_buffer;
2452
2453 if (*f == 'u') {
2454 makefmt(fmt, longflag, longlongflag, size_tflag, *f);
2455
2456 if (longflag)
2457 len = sprintf(buffer, fmt,
2458 va_arg(*vargs, unsigned long));
2459#ifdef HAVE_LONG_LONG
2460 else if (longlongflag)
2461 len = sprintf(buffer, fmt,
2462 va_arg(*vargs, unsigned PY_LONG_LONG));
2463#endif
2464 else if (size_tflag)
2465 len = sprintf(buffer, fmt,
2466 va_arg(*vargs, size_t));
2467 else
2468 len = sprintf(buffer, fmt,
2469 va_arg(*vargs, unsigned int));
2470 }
2471 else if (*f == 'x') {
2472 makefmt(fmt, 0, 0, 0, 'x');
2473 len = sprintf(buffer, fmt, va_arg(*vargs, int));
2474 }
2475 else {
2476 makefmt(fmt, longflag, longlongflag, size_tflag, *f);
2477
2478 if (longflag)
2479 len = sprintf(buffer, fmt,
2480 va_arg(*vargs, long));
2481#ifdef HAVE_LONG_LONG
2482 else if (longlongflag)
2483 len = sprintf(buffer, fmt,
2484 va_arg(*vargs, PY_LONG_LONG));
2485#endif
2486 else if (size_tflag)
2487 len = sprintf(buffer, fmt,
2488 va_arg(*vargs, Py_ssize_t));
2489 else
2490 len = sprintf(buffer, fmt,
2491 va_arg(*vargs, int));
2492 }
2493 assert(len >= 0);
2494
2495 err = 0;
2496 if (precision < len)
2497 precision = len;
2498 if (width > precision) {
2499 Py_UCS4 fillchar;
2500 fill = width - precision;
2501 fillchar = zeropad?'0':' ';
2502 if (_PyUnicodeWriter_Prepare(writer, fill, fillchar) != -1) {
2503 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, fillchar) == -1)
2504 err = 1;
2505 }
2506 else
2507 err = 1;
2508 if (!err)
2509 writer->pos += fill;
2510 }
2511 if (!err && precision > len) {
2512 fill = precision - len;
2513 if (_PyUnicodeWriter_Prepare(writer, fill, '0') != -1) {
2514 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, '0') == -1)
2515 err = 1;
2516 }
2517 else
2518 err = 1;
2519 if (!err)
2520 writer->pos += fill;
2521 }
2522 if (!err) {
2523 if (_PyUnicodeWriter_WriteCstr(writer, buffer, len) == -1)
2524 err = 1;
2525 }
2526
2527 if (buffer != small_buffer) {
2528 PyMem_Free(buffer);
2529 buffer = small_buffer;
2530 }
2531 if (err)
2532 return NULL;
2533
2534 break;
2535 }
2536
2537 case 'p':
2538 {
2539 char number[MAX_LONG_LONG_CHARS];
2540
2541 len = sprintf(number, "%p", va_arg(*vargs, void*));
2542 assert(len >= 0);
2543
2544 /* %p is ill-defined: ensure leading 0x. */
2545 if (number[1] == 'X')
2546 number[1] = 'x';
2547 else if (number[1] != 'x') {
2548 memmove(number + 2, number,
2549 strlen(number) + 1);
2550 number[0] = '0';
2551 number[1] = 'x';
2552 len += 2;
2553 }
2554
2555 if (_PyUnicodeWriter_WriteCstr(writer, number, len) == -1)
2556 return NULL;
2557 break;
2558 }
2559
2560 case 's':
2561 {
2562 /* UTF-8 */
2563 const char *s = va_arg(*vargs, const char*);
2564 PyObject *str = PyUnicode_DecodeUTF8Stateful(s, strlen(s), "replace", NULL);
2565 if (!str)
2566 return NULL;
2567 if (_PyUnicodeWriter_WriteStr(writer, str) == -1) {
2568 Py_DECREF(str);
2569 return NULL;
2570 }
2571 Py_DECREF(str);
2572 break;
2573 }
2574
2575 case 'U':
2576 {
2577 PyObject *obj = va_arg(*vargs, PyObject *);
2578 assert(obj && _PyUnicode_CHECK(obj));
2579
2580 if (_PyUnicodeWriter_WriteStr(writer, obj) == -1)
2581 return NULL;
2582 break;
2583 }
2584
2585 case 'V':
2586 {
2587 PyObject *obj = va_arg(*vargs, PyObject *);
2588 const char *str = va_arg(*vargs, const char *);
2589 PyObject *str_obj;
2590 assert(obj || str);
2591 if (obj) {
2592 assert(_PyUnicode_CHECK(obj));
2593 if (_PyUnicodeWriter_WriteStr(writer, obj) == -1)
2594 return NULL;
2595 }
2596 else {
2597 str_obj = PyUnicode_DecodeUTF8Stateful(str, strlen(str), "replace", NULL);
2598 if (!str_obj)
2599 return NULL;
2600 if (_PyUnicodeWriter_WriteStr(writer, str_obj) == -1) {
2601 Py_DECREF(str_obj);
2602 return NULL;
2603 }
2604 Py_DECREF(str_obj);
2605 }
2606 break;
2607 }
2608
2609 case 'S':
2610 {
2611 PyObject *obj = va_arg(*vargs, PyObject *);
2612 PyObject *str;
2613 assert(obj);
2614 str = PyObject_Str(obj);
2615 if (!str)
2616 return NULL;
2617 if (_PyUnicodeWriter_WriteStr(writer, str) == -1) {
2618 Py_DECREF(str);
2619 return NULL;
2620 }
2621 Py_DECREF(str);
2622 break;
2623 }
2624
2625 case 'R':
2626 {
2627 PyObject *obj = va_arg(*vargs, PyObject *);
2628 PyObject *repr;
2629 assert(obj);
2630 repr = PyObject_Repr(obj);
2631 if (!repr)
2632 return NULL;
2633 if (_PyUnicodeWriter_WriteStr(writer, repr) == -1) {
2634 Py_DECREF(repr);
2635 return NULL;
2636 }
2637 Py_DECREF(repr);
2638 break;
2639 }
2640
2641 case 'A':
2642 {
2643 PyObject *obj = va_arg(*vargs, PyObject *);
2644 PyObject *ascii;
2645 assert(obj);
2646 ascii = PyObject_ASCII(obj);
2647 if (!ascii)
2648 return NULL;
2649 if (_PyUnicodeWriter_WriteStr(writer, ascii) == -1) {
2650 Py_DECREF(ascii);
2651 return NULL;
2652 }
2653 Py_DECREF(ascii);
2654 break;
2655 }
2656
2657 case '%':
2658 if (_PyUnicodeWriter_Prepare(writer, 1, '%') == 1)
2659 return NULL;
2660 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '%');
2661 writer->pos++;
2662 break;
2663
2664 default:
2665 /* if we stumble upon an unknown formatting code, copy the rest
2666 of the format string to the output string. (we cannot just
2667 skip the code, since there's no way to know what's in the
2668 argument list) */
2669 len = strlen(p);
2670 if (_PyUnicodeWriter_WriteCstr(writer, p, len) == -1)
2671 return NULL;
2672 f = p+len;
2673 return f;
2674 }
2675
2676 f++;
Victor Stinner96865452011-03-01 23:44:09 +00002677 return f;
2678}
2679
Walter Dörwaldd2034312007-05-18 16:29:38 +00002680PyObject *
2681PyUnicode_FromFormatV(const char *format, va_list vargs)
2682{
Victor Stinnere215d962012-10-06 23:03:36 +02002683 va_list vargs2;
2684 const char *f;
2685 _PyUnicodeWriter writer;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002686
Victor Stinnere215d962012-10-06 23:03:36 +02002687 _PyUnicodeWriter_Init(&writer, strlen(format) + 100);
2688
2689 /* va_list may be an array (of 1 item) on some platforms (ex: AMD64).
2690 Copy it to be able to pass a reference to a subfunction. */
2691 Py_VA_COPY(vargs2, vargs);
2692
2693 for (f = format; *f; ) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00002694 if (*f == '%') {
Victor Stinnere215d962012-10-06 23:03:36 +02002695 f = unicode_fromformat_arg(&writer, f, &vargs2);
2696 if (f == NULL)
2697 goto fail;
Victor Stinner1205f272010-09-11 00:54:47 +00002698 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002699 else {
Victor Stinnere215d962012-10-06 23:03:36 +02002700 const char *p;
2701 Py_ssize_t len;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002702
Victor Stinnere215d962012-10-06 23:03:36 +02002703 p = f;
2704 do
2705 {
2706 if ((unsigned char)*p > 127) {
2707 PyErr_Format(PyExc_ValueError,
2708 "PyUnicode_FromFormatV() expects an ASCII-encoded format "
2709 "string, got a non-ASCII byte: 0x%02x",
2710 (unsigned char)*p);
2711 return NULL;
2712 }
2713 p++;
2714 }
2715 while (*p != '\0' && *p != '%');
2716 len = p - f;
2717
2718 if (*p == '\0')
2719 writer.overallocate = 0;
2720 if (_PyUnicodeWriter_Prepare(&writer, len, 127) == -1)
2721 goto fail;
2722 unicode_write_cstr(writer.buffer, writer.pos, f, len);
2723 writer.pos += len;
2724
2725 f = p;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002726 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002727 }
Victor Stinnere215d962012-10-06 23:03:36 +02002728 return _PyUnicodeWriter_Finish(&writer);
2729
2730 fail:
2731 _PyUnicodeWriter_Dealloc(&writer);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002732 return NULL;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002733}
2734
Walter Dörwaldd2034312007-05-18 16:29:38 +00002735PyObject *
2736PyUnicode_FromFormat(const char *format, ...)
2737{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002738 PyObject* ret;
2739 va_list vargs;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002740
2741#ifdef HAVE_STDARG_PROTOTYPES
Benjamin Peterson14339b62009-01-31 16:36:08 +00002742 va_start(vargs, format);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002743#else
Benjamin Peterson14339b62009-01-31 16:36:08 +00002744 va_start(vargs);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002745#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00002746 ret = PyUnicode_FromFormatV(format, vargs);
2747 va_end(vargs);
2748 return ret;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002749}
2750
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002751#ifdef HAVE_WCHAR_H
2752
Victor Stinner5593d8a2010-10-02 11:11:27 +00002753/* Helper function for PyUnicode_AsWideChar() and PyUnicode_AsWideCharString():
2754 convert a Unicode object to a wide character string.
2755
Victor Stinnerd88d9832011-09-06 02:00:05 +02002756 - If w is NULL: return the number of wide characters (including the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002757 character) required to convert the unicode object. Ignore size argument.
2758
Victor Stinnerd88d9832011-09-06 02:00:05 +02002759 - Otherwise: return the number of wide characters (excluding the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002760 character) written into w. Write at most size wide characters (including
Victor Stinnerd88d9832011-09-06 02:00:05 +02002761 the null character). */
Victor Stinner5593d8a2010-10-02 11:11:27 +00002762static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002763unicode_aswidechar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002764 wchar_t *w,
2765 Py_ssize_t size)
2766{
Victor Stinner5593d8a2010-10-02 11:11:27 +00002767 Py_ssize_t res;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002768 const wchar_t *wstr;
2769
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002770 wstr = PyUnicode_AsUnicodeAndSize(unicode, &res);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002771 if (wstr == NULL)
2772 return -1;
2773
Victor Stinner5593d8a2010-10-02 11:11:27 +00002774 if (w != NULL) {
Victor Stinner5593d8a2010-10-02 11:11:27 +00002775 if (size > res)
2776 size = res + 1;
2777 else
2778 res = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002779 Py_MEMCPY(w, wstr, size * sizeof(wchar_t));
Victor Stinner5593d8a2010-10-02 11:11:27 +00002780 return res;
2781 }
2782 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002783 return res + 1;
Victor Stinner137c34c2010-09-29 10:25:54 +00002784}
2785
2786Py_ssize_t
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002787PyUnicode_AsWideChar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002788 wchar_t *w,
2789 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002790{
2791 if (unicode == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002792 PyErr_BadInternalCall();
2793 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002794 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002795 return unicode_aswidechar(unicode, w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002796}
2797
Victor Stinner137c34c2010-09-29 10:25:54 +00002798wchar_t*
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00002799PyUnicode_AsWideCharString(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002800 Py_ssize_t *size)
2801{
2802 wchar_t* buffer;
2803 Py_ssize_t buflen;
2804
2805 if (unicode == NULL) {
2806 PyErr_BadInternalCall();
2807 return NULL;
2808 }
2809
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002810 buflen = unicode_aswidechar(unicode, NULL, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002811 if (buflen == -1)
2812 return NULL;
Victor Stinner5593d8a2010-10-02 11:11:27 +00002813 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < buflen) {
Victor Stinner137c34c2010-09-29 10:25:54 +00002814 PyErr_NoMemory();
2815 return NULL;
2816 }
2817
Victor Stinner137c34c2010-09-29 10:25:54 +00002818 buffer = PyMem_MALLOC(buflen * sizeof(wchar_t));
2819 if (buffer == NULL) {
2820 PyErr_NoMemory();
2821 return NULL;
2822 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002823 buflen = unicode_aswidechar(unicode, buffer, buflen);
Stefan Krah8528c312012-08-19 21:52:43 +02002824 if (buflen == -1) {
2825 PyMem_FREE(buffer);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002826 return NULL;
Stefan Krah8528c312012-08-19 21:52:43 +02002827 }
Victor Stinner5593d8a2010-10-02 11:11:27 +00002828 if (size != NULL)
2829 *size = buflen;
Victor Stinner137c34c2010-09-29 10:25:54 +00002830 return buffer;
2831}
2832
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002833#endif /* HAVE_WCHAR_H */
Guido van Rossumd57fd912000-03-10 22:53:23 +00002834
Alexander Belopolsky40018472011-02-26 01:02:56 +00002835PyObject *
2836PyUnicode_FromOrdinal(int ordinal)
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002837{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002838 PyObject *v;
Victor Stinner8faf8212011-12-08 22:14:11 +01002839 if (ordinal < 0 || ordinal > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002840 PyErr_SetString(PyExc_ValueError,
2841 "chr() arg not in range(0x110000)");
2842 return NULL;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002843 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00002844
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002845 if (ordinal < 256)
2846 return get_latin1_char(ordinal);
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002847
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002848 v = PyUnicode_New(1, ordinal);
2849 if (v == NULL)
2850 return NULL;
2851 PyUnicode_WRITE(PyUnicode_KIND(v), PyUnicode_DATA(v), 0, ordinal);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002852 assert(_PyUnicode_CheckConsistency(v, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002853 return v;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002854}
2855
Alexander Belopolsky40018472011-02-26 01:02:56 +00002856PyObject *
2857PyUnicode_FromObject(register PyObject *obj)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002858{
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002859 /* XXX Perhaps we should make this API an alias of
Benjamin Peterson29060642009-01-31 22:14:21 +00002860 PyObject_Str() instead ?! */
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002861 if (PyUnicode_CheckExact(obj)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -05002862 if (PyUnicode_READY(obj) == -1)
Victor Stinnerd3a83d52011-10-01 03:09:33 +02002863 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +00002864 Py_INCREF(obj);
2865 return obj;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002866 }
2867 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002868 /* For a Unicode subtype that's not a Unicode object,
2869 return a true Unicode object with the same data. */
Victor Stinnerbf6e5602011-12-12 01:53:47 +01002870 return _PyUnicode_Copy(obj);
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002871 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00002872 PyErr_Format(PyExc_TypeError,
2873 "Can't convert '%.100s' object to str implicitly",
Christian Heimes90aa7642007-12-19 02:45:37 +00002874 Py_TYPE(obj)->tp_name);
Guido van Rossum98297ee2007-11-06 21:34:58 +00002875 return NULL;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002876}
2877
Alexander Belopolsky40018472011-02-26 01:02:56 +00002878PyObject *
2879PyUnicode_FromEncodedObject(register PyObject *obj,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002880 const char *encoding,
2881 const char *errors)
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002882{
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002883 Py_buffer buffer;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002884 PyObject *v;
Tim Petersced69f82003-09-16 20:30:58 +00002885
Guido van Rossumd57fd912000-03-10 22:53:23 +00002886 if (obj == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002887 PyErr_BadInternalCall();
2888 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002889 }
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002890
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002891 /* Decoding bytes objects is the most common case and should be fast */
2892 if (PyBytes_Check(obj)) {
2893 if (PyBytes_GET_SIZE(obj) == 0) {
2894 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02002895 v = unicode_empty;
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002896 }
2897 else {
2898 v = PyUnicode_Decode(
2899 PyBytes_AS_STRING(obj), PyBytes_GET_SIZE(obj),
2900 encoding, errors);
2901 }
2902 return v;
2903 }
2904
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002905 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002906 PyErr_SetString(PyExc_TypeError,
2907 "decoding str is not supported");
2908 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002909 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002910
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002911 /* Retrieve a bytes buffer view through the PEP 3118 buffer interface */
2912 if (PyObject_GetBuffer(obj, &buffer, PyBUF_SIMPLE) < 0) {
2913 PyErr_Format(PyExc_TypeError,
2914 "coercing to str: need bytes, bytearray "
2915 "or buffer-like object, %.80s found",
2916 Py_TYPE(obj)->tp_name);
2917 return NULL;
Marc-André Lemburg6871f6a2001-09-20 12:53:16 +00002918 }
Tim Petersced69f82003-09-16 20:30:58 +00002919
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002920 if (buffer.len == 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002921 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02002922 v = unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002923 }
Tim Petersced69f82003-09-16 20:30:58 +00002924 else
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002925 v = PyUnicode_Decode((char*) buffer.buf, buffer.len, encoding, errors);
Marc-André Lemburgad7c98e2001-01-17 17:09:53 +00002926
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002927 PyBuffer_Release(&buffer);
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002928 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002929}
2930
Victor Stinner600d3be2010-06-10 12:00:55 +00002931/* Convert encoding to lower case and replace '_' with '-' in order to
Victor Stinner37296e82010-06-10 13:36:23 +00002932 catch e.g. UTF_8. Return 0 on error (encoding is longer than lower_len-1),
2933 1 on success. */
2934static int
2935normalize_encoding(const char *encoding,
2936 char *lower,
2937 size_t lower_len)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002938{
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002939 const char *e;
Victor Stinner600d3be2010-06-10 12:00:55 +00002940 char *l;
2941 char *l_end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002942
Benjamin Peterson7a6debe2011-10-15 09:25:28 -04002943 if (encoding == NULL) {
2944 strcpy(lower, "utf-8");
2945 return 1;
2946 }
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002947 e = encoding;
2948 l = lower;
Victor Stinner600d3be2010-06-10 12:00:55 +00002949 l_end = &lower[lower_len - 1];
Victor Stinner37296e82010-06-10 13:36:23 +00002950 while (*e) {
2951 if (l == l_end)
2952 return 0;
David Malcolm96960882010-11-05 17:23:41 +00002953 if (Py_ISUPPER(*e)) {
2954 *l++ = Py_TOLOWER(*e++);
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002955 }
2956 else if (*e == '_') {
2957 *l++ = '-';
2958 e++;
2959 }
2960 else {
2961 *l++ = *e++;
2962 }
2963 }
2964 *l = '\0';
Victor Stinner37296e82010-06-10 13:36:23 +00002965 return 1;
Victor Stinner600d3be2010-06-10 12:00:55 +00002966}
2967
Alexander Belopolsky40018472011-02-26 01:02:56 +00002968PyObject *
2969PyUnicode_Decode(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002970 Py_ssize_t size,
2971 const char *encoding,
2972 const char *errors)
Victor Stinner600d3be2010-06-10 12:00:55 +00002973{
2974 PyObject *buffer = NULL, *unicode;
2975 Py_buffer info;
2976 char lower[11]; /* Enough for any encoding shortcut */
2977
Fred Drakee4315f52000-05-09 19:53:39 +00002978 /* Shortcuts for common default encodings */
Victor Stinner37296e82010-06-10 13:36:23 +00002979 if (normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00002980 if ((strcmp(lower, "utf-8") == 0) ||
2981 (strcmp(lower, "utf8") == 0))
Victor Stinnera1d12bb2011-12-11 21:53:09 +01002982 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
Victor Stinner37296e82010-06-10 13:36:23 +00002983 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00002984 (strcmp(lower, "latin1") == 0) ||
Victor Stinner37296e82010-06-10 13:36:23 +00002985 (strcmp(lower, "iso-8859-1") == 0))
2986 return PyUnicode_DecodeLatin1(s, size, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02002987#ifdef HAVE_MBCS
Victor Stinner37296e82010-06-10 13:36:23 +00002988 else if (strcmp(lower, "mbcs") == 0)
2989 return PyUnicode_DecodeMBCS(s, size, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00002990#endif
Victor Stinner37296e82010-06-10 13:36:23 +00002991 else if (strcmp(lower, "ascii") == 0)
2992 return PyUnicode_DecodeASCII(s, size, errors);
2993 else if (strcmp(lower, "utf-16") == 0)
2994 return PyUnicode_DecodeUTF16(s, size, errors, 0);
2995 else if (strcmp(lower, "utf-32") == 0)
2996 return PyUnicode_DecodeUTF32(s, size, errors, 0);
2997 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002998
2999 /* Decode via the codec registry */
Guido van Rossumbe801ac2007-10-08 03:32:34 +00003000 buffer = NULL;
Antoine Pitrouc3b39242009-01-03 16:59:18 +00003001 if (PyBuffer_FillInfo(&info, NULL, (void *)s, size, 1, PyBUF_FULL_RO) < 0)
Guido van Rossumbe801ac2007-10-08 03:32:34 +00003002 goto onError;
Antoine Pitrouee58fa42008-08-19 18:22:14 +00003003 buffer = PyMemoryView_FromBuffer(&info);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003004 if (buffer == NULL)
3005 goto onError;
3006 unicode = PyCodec_Decode(buffer, encoding, errors);
3007 if (unicode == NULL)
3008 goto onError;
3009 if (!PyUnicode_Check(unicode)) {
3010 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00003011 "decoder did not return a str object (type=%.400s)",
Christian Heimes90aa7642007-12-19 02:45:37 +00003012 Py_TYPE(unicode)->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003013 Py_DECREF(unicode);
3014 goto onError;
3015 }
3016 Py_DECREF(buffer);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003017 return unicode_result(unicode);
Tim Petersced69f82003-09-16 20:30:58 +00003018
Benjamin Peterson29060642009-01-31 22:14:21 +00003019 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003020 Py_XDECREF(buffer);
3021 return NULL;
3022}
3023
Alexander Belopolsky40018472011-02-26 01:02:56 +00003024PyObject *
3025PyUnicode_AsDecodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003026 const char *encoding,
3027 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003028{
3029 PyObject *v;
3030
3031 if (!PyUnicode_Check(unicode)) {
3032 PyErr_BadArgument();
3033 goto onError;
3034 }
3035
3036 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003037 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003038
3039 /* Decode via the codec registry */
3040 v = PyCodec_Decode(unicode, encoding, errors);
3041 if (v == NULL)
3042 goto onError;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003043 return unicode_result(v);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003044
Benjamin Peterson29060642009-01-31 22:14:21 +00003045 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003046 return NULL;
3047}
3048
Alexander Belopolsky40018472011-02-26 01:02:56 +00003049PyObject *
3050PyUnicode_AsDecodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003051 const char *encoding,
3052 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003053{
3054 PyObject *v;
3055
3056 if (!PyUnicode_Check(unicode)) {
3057 PyErr_BadArgument();
3058 goto onError;
3059 }
3060
3061 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003062 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003063
3064 /* Decode via the codec registry */
3065 v = PyCodec_Decode(unicode, encoding, errors);
3066 if (v == NULL)
3067 goto onError;
3068 if (!PyUnicode_Check(v)) {
3069 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00003070 "decoder did not return a str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003071 Py_TYPE(v)->tp_name);
3072 Py_DECREF(v);
3073 goto onError;
3074 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003075 return unicode_result(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003076
Benjamin Peterson29060642009-01-31 22:14:21 +00003077 onError:
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003078 return NULL;
3079}
3080
Alexander Belopolsky40018472011-02-26 01:02:56 +00003081PyObject *
3082PyUnicode_Encode(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003083 Py_ssize_t size,
3084 const char *encoding,
3085 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003086{
3087 PyObject *v, *unicode;
Tim Petersced69f82003-09-16 20:30:58 +00003088
Guido van Rossumd57fd912000-03-10 22:53:23 +00003089 unicode = PyUnicode_FromUnicode(s, size);
3090 if (unicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003091 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003092 v = PyUnicode_AsEncodedString(unicode, encoding, errors);
3093 Py_DECREF(unicode);
3094 return v;
3095}
3096
Alexander Belopolsky40018472011-02-26 01:02:56 +00003097PyObject *
3098PyUnicode_AsEncodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003099 const char *encoding,
3100 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003101{
3102 PyObject *v;
3103
3104 if (!PyUnicode_Check(unicode)) {
3105 PyErr_BadArgument();
3106 goto onError;
3107 }
3108
3109 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003110 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003111
3112 /* Encode via the codec registry */
3113 v = PyCodec_Encode(unicode, encoding, errors);
3114 if (v == NULL)
3115 goto onError;
3116 return v;
3117
Benjamin Peterson29060642009-01-31 22:14:21 +00003118 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003119 return NULL;
3120}
3121
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003122static size_t
3123wcstombs_errorpos(const wchar_t *wstr)
3124{
3125 size_t len;
3126#if SIZEOF_WCHAR_T == 2
3127 wchar_t buf[3];
3128#else
3129 wchar_t buf[2];
3130#endif
3131 char outbuf[MB_LEN_MAX];
3132 const wchar_t *start, *previous;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003133
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003134#if SIZEOF_WCHAR_T == 2
3135 buf[2] = 0;
3136#else
3137 buf[1] = 0;
3138#endif
3139 start = wstr;
3140 while (*wstr != L'\0')
3141 {
3142 previous = wstr;
3143#if SIZEOF_WCHAR_T == 2
3144 if (Py_UNICODE_IS_HIGH_SURROGATE(wstr[0])
3145 && Py_UNICODE_IS_LOW_SURROGATE(wstr[1]))
3146 {
3147 buf[0] = wstr[0];
3148 buf[1] = wstr[1];
3149 wstr += 2;
3150 }
3151 else {
3152 buf[0] = *wstr;
3153 buf[1] = 0;
3154 wstr++;
3155 }
3156#else
3157 buf[0] = *wstr;
3158 wstr++;
3159#endif
3160 len = wcstombs(outbuf, buf, sizeof(outbuf));
Victor Stinner2f197072011-12-17 07:08:30 +01003161 if (len == (size_t)-1)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003162 return previous - start;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003163 }
3164
3165 /* failed to find the unencodable character */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003166 return 0;
3167}
3168
Victor Stinner1b579672011-12-17 05:47:23 +01003169static int
3170locale_error_handler(const char *errors, int *surrogateescape)
3171{
3172 if (errors == NULL) {
3173 *surrogateescape = 0;
3174 return 0;
3175 }
3176
3177 if (strcmp(errors, "strict") == 0) {
3178 *surrogateescape = 0;
3179 return 0;
3180 }
3181 if (strcmp(errors, "surrogateescape") == 0) {
3182 *surrogateescape = 1;
3183 return 0;
3184 }
3185 PyErr_Format(PyExc_ValueError,
3186 "only 'strict' and 'surrogateescape' error handlers "
3187 "are supported, not '%s'",
3188 errors);
3189 return -1;
3190}
3191
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003192PyObject *
Victor Stinner1b579672011-12-17 05:47:23 +01003193PyUnicode_EncodeLocale(PyObject *unicode, const char *errors)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003194{
3195 Py_ssize_t wlen, wlen2;
3196 wchar_t *wstr;
3197 PyObject *bytes = NULL;
3198 char *errmsg;
Victor Stinner1f33f2b2011-12-17 04:45:09 +01003199 PyObject *reason;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003200 PyObject *exc;
3201 size_t error_pos;
Victor Stinner1b579672011-12-17 05:47:23 +01003202 int surrogateescape;
3203
3204 if (locale_error_handler(errors, &surrogateescape) < 0)
3205 return NULL;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003206
3207 wstr = PyUnicode_AsWideCharString(unicode, &wlen);
3208 if (wstr == NULL)
3209 return NULL;
3210
3211 wlen2 = wcslen(wstr);
3212 if (wlen2 != wlen) {
3213 PyMem_Free(wstr);
3214 PyErr_SetString(PyExc_TypeError, "embedded null character");
3215 return NULL;
3216 }
3217
3218 if (surrogateescape) {
3219 /* locale encoding with surrogateescape */
3220 char *str;
3221
3222 str = _Py_wchar2char(wstr, &error_pos);
3223 if (str == NULL) {
3224 if (error_pos == (size_t)-1) {
3225 PyErr_NoMemory();
3226 PyMem_Free(wstr);
3227 return NULL;
3228 }
3229 else {
3230 goto encode_error;
3231 }
3232 }
3233 PyMem_Free(wstr);
3234
3235 bytes = PyBytes_FromString(str);
3236 PyMem_Free(str);
3237 }
3238 else {
3239 size_t len, len2;
3240
3241 len = wcstombs(NULL, wstr, 0);
3242 if (len == (size_t)-1) {
Victor Stinner2f197072011-12-17 07:08:30 +01003243 error_pos = (size_t)-1;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003244 goto encode_error;
3245 }
3246
3247 bytes = PyBytes_FromStringAndSize(NULL, len);
3248 if (bytes == NULL) {
3249 PyMem_Free(wstr);
3250 return NULL;
3251 }
3252
3253 len2 = wcstombs(PyBytes_AS_STRING(bytes), wstr, len+1);
3254 if (len2 == (size_t)-1 || len2 > len) {
Victor Stinner2f197072011-12-17 07:08:30 +01003255 error_pos = (size_t)-1;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003256 goto encode_error;
3257 }
3258 PyMem_Free(wstr);
3259 }
3260 return bytes;
3261
3262encode_error:
3263 errmsg = strerror(errno);
3264 assert(errmsg != NULL);
Victor Stinner2f197072011-12-17 07:08:30 +01003265
3266 if (error_pos == (size_t)-1)
3267 error_pos = wcstombs_errorpos(wstr);
3268
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003269 PyMem_Free(wstr);
3270 Py_XDECREF(bytes);
3271
Victor Stinner2f197072011-12-17 07:08:30 +01003272 if (errmsg != NULL) {
3273 size_t errlen;
3274 wstr = _Py_char2wchar(errmsg, &errlen);
3275 if (wstr != NULL) {
3276 reason = PyUnicode_FromWideChar(wstr, errlen);
3277 PyMem_Free(wstr);
3278 } else
3279 errmsg = NULL;
3280 }
3281 if (errmsg == NULL)
Victor Stinner1f33f2b2011-12-17 04:45:09 +01003282 reason = PyUnicode_FromString(
3283 "wcstombs() encountered an unencodable "
3284 "wide character");
3285 if (reason == NULL)
3286 return NULL;
3287
3288 exc = PyObject_CallFunction(PyExc_UnicodeEncodeError, "sOnnO",
3289 "locale", unicode,
3290 (Py_ssize_t)error_pos,
3291 (Py_ssize_t)(error_pos+1),
3292 reason);
3293 Py_DECREF(reason);
3294 if (exc != NULL) {
3295 PyCodec_StrictErrors(exc);
3296 Py_XDECREF(exc);
3297 }
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003298 return NULL;
3299}
3300
Victor Stinnerad158722010-10-27 00:25:46 +00003301PyObject *
3302PyUnicode_EncodeFSDefault(PyObject *unicode)
Victor Stinnerae6265f2010-05-15 16:27:27 +00003303{
Victor Stinner99b95382011-07-04 14:23:54 +02003304#ifdef HAVE_MBCS
Victor Stinnerac931b12011-11-20 18:27:03 +01003305 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003306#elif defined(__APPLE__)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003307 return _PyUnicode_AsUTF8String(unicode, "surrogateescape");
Victor Stinnerad158722010-10-27 00:25:46 +00003308#else
Victor Stinner793b5312011-04-27 00:24:21 +02003309 PyInterpreterState *interp = PyThreadState_GET()->interp;
3310 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3311 cannot use it to encode and decode filenames before it is loaded. Load
3312 the Python codec requires to encode at least its own filename. Use the C
3313 version of the locale codec until the codec registry is initialized and
3314 the Python codec is loaded.
3315
3316 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3317 cannot only rely on it: check also interp->fscodec_initialized for
3318 subinterpreters. */
3319 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Victor Stinnerae6265f2010-05-15 16:27:27 +00003320 return PyUnicode_AsEncodedString(unicode,
3321 Py_FileSystemDefaultEncoding,
3322 "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00003323 }
3324 else {
Victor Stinner1b579672011-12-17 05:47:23 +01003325 return PyUnicode_EncodeLocale(unicode, "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00003326 }
Victor Stinnerad158722010-10-27 00:25:46 +00003327#endif
Victor Stinnerae6265f2010-05-15 16:27:27 +00003328}
3329
Alexander Belopolsky40018472011-02-26 01:02:56 +00003330PyObject *
3331PyUnicode_AsEncodedString(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003332 const char *encoding,
3333 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003334{
3335 PyObject *v;
Victor Stinner600d3be2010-06-10 12:00:55 +00003336 char lower[11]; /* Enough for any encoding shortcut */
Tim Petersced69f82003-09-16 20:30:58 +00003337
Guido van Rossumd57fd912000-03-10 22:53:23 +00003338 if (!PyUnicode_Check(unicode)) {
3339 PyErr_BadArgument();
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003340 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003341 }
Fred Drakee4315f52000-05-09 19:53:39 +00003342
Fred Drakee4315f52000-05-09 19:53:39 +00003343 /* Shortcuts for common default encodings */
Victor Stinner37296e82010-06-10 13:36:23 +00003344 if (normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003345 if ((strcmp(lower, "utf-8") == 0) ||
3346 (strcmp(lower, "utf8") == 0))
Victor Stinnera5c68c32011-03-02 01:03:14 +00003347 {
Victor Stinner2f283c22011-03-02 01:21:46 +00003348 if (errors == NULL || strcmp(errors, "strict") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003349 return _PyUnicode_AsUTF8String(unicode, NULL);
Victor Stinner2f283c22011-03-02 01:21:46 +00003350 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003351 return _PyUnicode_AsUTF8String(unicode, errors);
Victor Stinnera5c68c32011-03-02 01:03:14 +00003352 }
Victor Stinner37296e82010-06-10 13:36:23 +00003353 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003354 (strcmp(lower, "latin1") == 0) ||
Victor Stinner37296e82010-06-10 13:36:23 +00003355 (strcmp(lower, "iso-8859-1") == 0))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003356 return _PyUnicode_AsLatin1String(unicode, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02003357#ifdef HAVE_MBCS
Victor Stinnerac931b12011-11-20 18:27:03 +01003358 else if (strcmp(lower, "mbcs") == 0)
3359 return PyUnicode_EncodeCodePage(CP_ACP, unicode, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003360#endif
Victor Stinner37296e82010-06-10 13:36:23 +00003361 else if (strcmp(lower, "ascii") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003362 return _PyUnicode_AsASCIIString(unicode, errors);
Victor Stinner37296e82010-06-10 13:36:23 +00003363 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003364
3365 /* Encode via the codec registry */
3366 v = PyCodec_Encode(unicode, encoding, errors);
3367 if (v == NULL)
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003368 return NULL;
3369
3370 /* The normal path */
3371 if (PyBytes_Check(v))
3372 return v;
3373
3374 /* If the codec returns a buffer, raise a warning and convert to bytes */
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003375 if (PyByteArray_Check(v)) {
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003376 int error;
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003377 PyObject *b;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003378
3379 error = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
3380 "encoder %s returned bytearray instead of bytes",
3381 encoding);
3382 if (error) {
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003383 Py_DECREF(v);
3384 return NULL;
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003385 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003386
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003387 b = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(v), Py_SIZE(v));
3388 Py_DECREF(v);
3389 return b;
3390 }
3391
3392 PyErr_Format(PyExc_TypeError,
3393 "encoder did not return a bytes object (type=%.400s)",
3394 Py_TYPE(v)->tp_name);
3395 Py_DECREF(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003396 return NULL;
3397}
3398
Alexander Belopolsky40018472011-02-26 01:02:56 +00003399PyObject *
3400PyUnicode_AsEncodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003401 const char *encoding,
3402 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003403{
3404 PyObject *v;
3405
3406 if (!PyUnicode_Check(unicode)) {
3407 PyErr_BadArgument();
3408 goto onError;
3409 }
3410
3411 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003412 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003413
3414 /* Encode via the codec registry */
3415 v = PyCodec_Encode(unicode, encoding, errors);
3416 if (v == NULL)
3417 goto onError;
3418 if (!PyUnicode_Check(v)) {
3419 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00003420 "encoder did not return an str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003421 Py_TYPE(v)->tp_name);
3422 Py_DECREF(v);
3423 goto onError;
3424 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003425 return v;
Tim Petersced69f82003-09-16 20:30:58 +00003426
Benjamin Peterson29060642009-01-31 22:14:21 +00003427 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003428 return NULL;
3429}
3430
Victor Stinner2f197072011-12-17 07:08:30 +01003431static size_t
3432mbstowcs_errorpos(const char *str, size_t len)
3433{
3434#ifdef HAVE_MBRTOWC
3435 const char *start = str;
3436 mbstate_t mbs;
3437 size_t converted;
3438 wchar_t ch;
3439
3440 memset(&mbs, 0, sizeof mbs);
3441 while (len)
3442 {
3443 converted = mbrtowc(&ch, (char*)str, len, &mbs);
3444 if (converted == 0)
3445 /* Reached end of string */
3446 break;
3447 if (converted == (size_t)-1 || converted == (size_t)-2) {
3448 /* Conversion error or incomplete character */
3449 return str - start;
3450 }
3451 else {
3452 str += converted;
3453 len -= converted;
3454 }
3455 }
3456 /* failed to find the undecodable byte sequence */
3457 return 0;
3458#endif
3459 return 0;
3460}
3461
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003462PyObject*
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003463PyUnicode_DecodeLocaleAndSize(const char *str, Py_ssize_t len,
Victor Stinner1b579672011-12-17 05:47:23 +01003464 const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003465{
3466 wchar_t smallbuf[256];
3467 size_t smallbuf_len = Py_ARRAY_LENGTH(smallbuf);
3468 wchar_t *wstr;
3469 size_t wlen, wlen2;
3470 PyObject *unicode;
Victor Stinner1b579672011-12-17 05:47:23 +01003471 int surrogateescape;
Victor Stinner2f197072011-12-17 07:08:30 +01003472 size_t error_pos;
3473 char *errmsg;
3474 PyObject *reason, *exc;
Victor Stinner1b579672011-12-17 05:47:23 +01003475
3476 if (locale_error_handler(errors, &surrogateescape) < 0)
3477 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003478
3479 if (str[len] != '\0' || len != strlen(str)) {
3480 PyErr_SetString(PyExc_TypeError, "embedded null character");
3481 return NULL;
3482 }
3483
3484 if (surrogateescape)
3485 {
3486 wstr = _Py_char2wchar(str, &wlen);
3487 if (wstr == NULL) {
3488 if (wlen == (size_t)-1)
3489 PyErr_NoMemory();
3490 else
3491 PyErr_SetFromErrno(PyExc_OSError);
3492 return NULL;
3493 }
3494
3495 unicode = PyUnicode_FromWideChar(wstr, wlen);
3496 PyMem_Free(wstr);
3497 }
3498 else {
3499#ifndef HAVE_BROKEN_MBSTOWCS
3500 wlen = mbstowcs(NULL, str, 0);
3501#else
3502 wlen = len;
3503#endif
Victor Stinner2f197072011-12-17 07:08:30 +01003504 if (wlen == (size_t)-1)
3505 goto decode_error;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003506 if (wlen+1 <= smallbuf_len) {
3507 wstr = smallbuf;
3508 }
3509 else {
3510 if (wlen > PY_SSIZE_T_MAX / sizeof(wchar_t) - 1)
3511 return PyErr_NoMemory();
3512
3513 wstr = PyMem_Malloc((wlen+1) * sizeof(wchar_t));
3514 if (!wstr)
3515 return PyErr_NoMemory();
3516 }
3517
3518 /* This shouldn't fail now */
3519 wlen2 = mbstowcs(wstr, str, wlen+1);
3520 if (wlen2 == (size_t)-1) {
3521 if (wstr != smallbuf)
3522 PyMem_Free(wstr);
Victor Stinner2f197072011-12-17 07:08:30 +01003523 goto decode_error;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003524 }
3525#ifdef HAVE_BROKEN_MBSTOWCS
3526 assert(wlen2 == wlen);
3527#endif
3528 unicode = PyUnicode_FromWideChar(wstr, wlen2);
3529 if (wstr != smallbuf)
3530 PyMem_Free(wstr);
3531 }
3532 return unicode;
Victor Stinner2f197072011-12-17 07:08:30 +01003533
3534decode_error:
3535 errmsg = strerror(errno);
3536 assert(errmsg != NULL);
3537
3538 error_pos = mbstowcs_errorpos(str, len);
3539 if (errmsg != NULL) {
3540 size_t errlen;
3541 wstr = _Py_char2wchar(errmsg, &errlen);
3542 if (wstr != NULL) {
3543 reason = PyUnicode_FromWideChar(wstr, errlen);
3544 PyMem_Free(wstr);
3545 } else
3546 errmsg = NULL;
3547 }
3548 if (errmsg == NULL)
3549 reason = PyUnicode_FromString(
3550 "mbstowcs() encountered an invalid multibyte sequence");
3551 if (reason == NULL)
3552 return NULL;
3553
3554 exc = PyObject_CallFunction(PyExc_UnicodeDecodeError, "sy#nnO",
3555 "locale", str, len,
3556 (Py_ssize_t)error_pos,
3557 (Py_ssize_t)(error_pos+1),
3558 reason);
3559 Py_DECREF(reason);
3560 if (exc != NULL) {
3561 PyCodec_StrictErrors(exc);
3562 Py_XDECREF(exc);
3563 }
3564 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003565}
3566
3567PyObject*
Victor Stinner1b579672011-12-17 05:47:23 +01003568PyUnicode_DecodeLocale(const char *str, const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003569{
3570 Py_ssize_t size = (Py_ssize_t)strlen(str);
Victor Stinner1b579672011-12-17 05:47:23 +01003571 return PyUnicode_DecodeLocaleAndSize(str, size, errors);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003572}
3573
3574
3575PyObject*
Christian Heimes5894ba72007-11-04 11:43:14 +00003576PyUnicode_DecodeFSDefault(const char *s) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003577 Py_ssize_t size = (Py_ssize_t)strlen(s);
Christian Heimes5894ba72007-11-04 11:43:14 +00003578 return PyUnicode_DecodeFSDefaultAndSize(s, size);
3579}
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003580
Christian Heimes5894ba72007-11-04 11:43:14 +00003581PyObject*
3582PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
3583{
Victor Stinner99b95382011-07-04 14:23:54 +02003584#ifdef HAVE_MBCS
Victor Stinnerad158722010-10-27 00:25:46 +00003585 return PyUnicode_DecodeMBCS(s, size, NULL);
3586#elif defined(__APPLE__)
Victor Stinnera1d12bb2011-12-11 21:53:09 +01003587 return PyUnicode_DecodeUTF8Stateful(s, size, "surrogateescape", NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003588#else
Victor Stinner793b5312011-04-27 00:24:21 +02003589 PyInterpreterState *interp = PyThreadState_GET()->interp;
3590 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3591 cannot use it to encode and decode filenames before it is loaded. Load
3592 the Python codec requires to encode at least its own filename. Use the C
3593 version of the locale codec until the codec registry is initialized and
3594 the Python codec is loaded.
3595
3596 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3597 cannot only rely on it: check also interp->fscodec_initialized for
3598 subinterpreters. */
3599 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003600 return PyUnicode_Decode(s, size,
3601 Py_FileSystemDefaultEncoding,
Victor Stinnerb9a20ad2010-04-30 16:37:52 +00003602 "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003603 }
3604 else {
Victor Stinner1b579672011-12-17 05:47:23 +01003605 return PyUnicode_DecodeLocaleAndSize(s, size, "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003606 }
Victor Stinnerad158722010-10-27 00:25:46 +00003607#endif
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003608}
3609
Martin v. Löwis011e8422009-05-05 04:43:17 +00003610
3611int
Antoine Pitrou13348842012-01-29 18:36:34 +01003612_PyUnicode_HasNULChars(PyObject* s)
3613{
3614 static PyObject *nul = NULL;
3615
3616 if (nul == NULL)
3617 nul = PyUnicode_FromStringAndSize("\0", 1);
3618 if (nul == NULL)
3619 return -1;
3620 return PyUnicode_Contains(s, nul);
3621}
3622
3623
3624int
Martin v. Löwis011e8422009-05-05 04:43:17 +00003625PyUnicode_FSConverter(PyObject* arg, void* addr)
3626{
3627 PyObject *output = NULL;
3628 Py_ssize_t size;
3629 void *data;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003630 if (arg == NULL) {
3631 Py_DECREF(*(PyObject**)addr);
3632 return 1;
3633 }
Victor Stinnerdcb24032010-04-22 12:08:36 +00003634 if (PyBytes_Check(arg)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00003635 output = arg;
3636 Py_INCREF(output);
3637 }
3638 else {
3639 arg = PyUnicode_FromObject(arg);
3640 if (!arg)
3641 return 0;
Victor Stinnerae6265f2010-05-15 16:27:27 +00003642 output = PyUnicode_EncodeFSDefault(arg);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003643 Py_DECREF(arg);
3644 if (!output)
3645 return 0;
3646 if (!PyBytes_Check(output)) {
3647 Py_DECREF(output);
3648 PyErr_SetString(PyExc_TypeError, "encoder failed to return bytes");
3649 return 0;
3650 }
3651 }
Victor Stinner0ea2a462010-04-30 00:22:08 +00003652 size = PyBytes_GET_SIZE(output);
3653 data = PyBytes_AS_STRING(output);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003654 if (size != strlen(data)) {
Benjamin Peterson7a6b44a2011-08-18 13:51:47 -05003655 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
Martin v. Löwis011e8422009-05-05 04:43:17 +00003656 Py_DECREF(output);
3657 return 0;
3658 }
3659 *(PyObject**)addr = output;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003660 return Py_CLEANUP_SUPPORTED;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003661}
3662
3663
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003664int
3665PyUnicode_FSDecoder(PyObject* arg, void* addr)
3666{
3667 PyObject *output = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003668 if (arg == NULL) {
3669 Py_DECREF(*(PyObject**)addr);
3670 return 1;
3671 }
3672 if (PyUnicode_Check(arg)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -05003673 if (PyUnicode_READY(arg) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003674 return 0;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003675 output = arg;
3676 Py_INCREF(output);
3677 }
3678 else {
3679 arg = PyBytes_FromObject(arg);
3680 if (!arg)
3681 return 0;
3682 output = PyUnicode_DecodeFSDefaultAndSize(PyBytes_AS_STRING(arg),
3683 PyBytes_GET_SIZE(arg));
3684 Py_DECREF(arg);
3685 if (!output)
3686 return 0;
3687 if (!PyUnicode_Check(output)) {
3688 Py_DECREF(output);
3689 PyErr_SetString(PyExc_TypeError, "decoder failed to return unicode");
3690 return 0;
3691 }
3692 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05003693 if (PyUnicode_READY(output) == -1) {
Victor Stinner065836e2011-10-27 01:56:33 +02003694 Py_DECREF(output);
3695 return 0;
3696 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003697 if (findchar(PyUnicode_DATA(output), PyUnicode_KIND(output),
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02003698 PyUnicode_GET_LENGTH(output), 0, 1) >= 0) {
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003699 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
3700 Py_DECREF(output);
3701 return 0;
3702 }
3703 *(PyObject**)addr = output;
3704 return Py_CLEANUP_SUPPORTED;
3705}
3706
3707
Martin v. Löwis5b222132007-06-10 09:51:05 +00003708char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003709PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *psize)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003710{
Christian Heimesf3863112007-11-22 07:46:41 +00003711 PyObject *bytes;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003712
Neal Norwitze0a0a6e2007-08-25 01:04:21 +00003713 if (!PyUnicode_Check(unicode)) {
3714 PyErr_BadArgument();
3715 return NULL;
3716 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003717 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003718 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003719
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003720 if (PyUnicode_UTF8(unicode) == NULL) {
3721 assert(!PyUnicode_IS_COMPACT_ASCII(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003722 bytes = _PyUnicode_AsUTF8String(unicode, "strict");
3723 if (bytes == NULL)
3724 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003725 _PyUnicode_UTF8(unicode) = PyObject_MALLOC(PyBytes_GET_SIZE(bytes) + 1);
3726 if (_PyUnicode_UTF8(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003727 Py_DECREF(bytes);
3728 return NULL;
3729 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003730 _PyUnicode_UTF8_LENGTH(unicode) = PyBytes_GET_SIZE(bytes);
3731 Py_MEMCPY(_PyUnicode_UTF8(unicode),
3732 PyBytes_AS_STRING(bytes),
3733 _PyUnicode_UTF8_LENGTH(unicode) + 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003734 Py_DECREF(bytes);
3735 }
3736
3737 if (psize)
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003738 *psize = PyUnicode_UTF8_LENGTH(unicode);
3739 return PyUnicode_UTF8(unicode);
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003740}
3741
3742char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003743PyUnicode_AsUTF8(PyObject *unicode)
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003744{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003745 return PyUnicode_AsUTF8AndSize(unicode, NULL);
3746}
3747
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003748Py_UNICODE *
3749PyUnicode_AsUnicodeAndSize(PyObject *unicode, Py_ssize_t *size)
3750{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003751 const unsigned char *one_byte;
3752#if SIZEOF_WCHAR_T == 4
3753 const Py_UCS2 *two_bytes;
3754#else
3755 const Py_UCS4 *four_bytes;
3756 const Py_UCS4 *ucs4_end;
3757 Py_ssize_t num_surrogates;
3758#endif
3759 wchar_t *w;
3760 wchar_t *wchar_end;
3761
3762 if (!PyUnicode_Check(unicode)) {
3763 PyErr_BadArgument();
3764 return NULL;
3765 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003766 if (_PyUnicode_WSTR(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003767 /* Non-ASCII compact unicode object */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003768 assert(_PyUnicode_KIND(unicode) != 0);
3769 assert(PyUnicode_IS_READY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003770
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003771 if (PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003772#if SIZEOF_WCHAR_T == 2
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003773 four_bytes = PyUnicode_4BYTE_DATA(unicode);
3774 ucs4_end = four_bytes + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003775 num_surrogates = 0;
3776
3777 for (; four_bytes < ucs4_end; ++four_bytes) {
3778 if (*four_bytes > 0xFFFF)
3779 ++num_surrogates;
3780 }
3781
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003782 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(
3783 sizeof(wchar_t) * (_PyUnicode_LENGTH(unicode) + 1 + num_surrogates));
3784 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003785 PyErr_NoMemory();
3786 return NULL;
3787 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003788 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode) + num_surrogates;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003789
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003790 w = _PyUnicode_WSTR(unicode);
3791 wchar_end = w + _PyUnicode_WSTR_LENGTH(unicode);
3792 four_bytes = PyUnicode_4BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003793 for (; four_bytes < ucs4_end; ++four_bytes, ++w) {
3794 if (*four_bytes > 0xFFFF) {
Victor Stinner8faf8212011-12-08 22:14:11 +01003795 assert(*four_bytes <= MAX_UNICODE);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003796 /* encode surrogate pair in this case */
Victor Stinner551ac952011-11-29 22:58:13 +01003797 *w++ = Py_UNICODE_HIGH_SURROGATE(*four_bytes);
3798 *w = Py_UNICODE_LOW_SURROGATE(*four_bytes);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003799 }
3800 else
3801 *w = *four_bytes;
3802
3803 if (w > wchar_end) {
3804 assert(0 && "Miscalculated string end");
3805 }
3806 }
3807 *w = 0;
3808#else
3809 /* sizeof(wchar_t) == 4 */
3810 Py_FatalError("Impossible unicode object state, wstr and str "
3811 "should share memory already.");
3812 return NULL;
3813#endif
3814 }
3815 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003816 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(sizeof(wchar_t) *
3817 (_PyUnicode_LENGTH(unicode) + 1));
3818 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003819 PyErr_NoMemory();
3820 return NULL;
3821 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003822 if (!PyUnicode_IS_COMPACT_ASCII(unicode))
3823 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode);
3824 w = _PyUnicode_WSTR(unicode);
3825 wchar_end = w + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003826
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003827 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND) {
3828 one_byte = PyUnicode_1BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003829 for (; w < wchar_end; ++one_byte, ++w)
3830 *w = *one_byte;
3831 /* null-terminate the wstr */
3832 *w = 0;
3833 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003834 else if (PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003835#if SIZEOF_WCHAR_T == 4
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003836 two_bytes = PyUnicode_2BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003837 for (; w < wchar_end; ++two_bytes, ++w)
3838 *w = *two_bytes;
3839 /* null-terminate the wstr */
3840 *w = 0;
3841#else
3842 /* sizeof(wchar_t) == 2 */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003843 PyObject_FREE(_PyUnicode_WSTR(unicode));
3844 _PyUnicode_WSTR(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003845 Py_FatalError("Impossible unicode object state, wstr "
3846 "and str should share memory already.");
3847 return NULL;
3848#endif
3849 }
3850 else {
3851 assert(0 && "This should never happen.");
3852 }
3853 }
3854 }
3855 if (size != NULL)
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003856 *size = PyUnicode_WSTR_LENGTH(unicode);
3857 return _PyUnicode_WSTR(unicode);
Martin v. Löwis5b222132007-06-10 09:51:05 +00003858}
3859
Alexander Belopolsky40018472011-02-26 01:02:56 +00003860Py_UNICODE *
3861PyUnicode_AsUnicode(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003862{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003863 return PyUnicode_AsUnicodeAndSize(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003864}
3865
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003866
Alexander Belopolsky40018472011-02-26 01:02:56 +00003867Py_ssize_t
3868PyUnicode_GetSize(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003869{
3870 if (!PyUnicode_Check(unicode)) {
3871 PyErr_BadArgument();
3872 goto onError;
3873 }
3874 return PyUnicode_GET_SIZE(unicode);
3875
Benjamin Peterson29060642009-01-31 22:14:21 +00003876 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003877 return -1;
3878}
3879
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003880Py_ssize_t
3881PyUnicode_GetLength(PyObject *unicode)
3882{
Victor Stinner07621332012-06-16 04:53:46 +02003883 if (!PyUnicode_Check(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003884 PyErr_BadArgument();
3885 return -1;
3886 }
Victor Stinner07621332012-06-16 04:53:46 +02003887 if (PyUnicode_READY(unicode) == -1)
3888 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003889 return PyUnicode_GET_LENGTH(unicode);
3890}
3891
3892Py_UCS4
3893PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
3894{
Victor Stinner2fe5ced2011-10-02 00:25:40 +02003895 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
3896 PyErr_BadArgument();
3897 return (Py_UCS4)-1;
3898 }
Victor Stinnerc4b49542011-12-11 22:44:26 +01003899 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinner2fe5ced2011-10-02 00:25:40 +02003900 PyErr_SetString(PyExc_IndexError, "string index out of range");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003901 return (Py_UCS4)-1;
3902 }
3903 return PyUnicode_READ_CHAR(unicode, index);
3904}
3905
3906int
3907PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 ch)
3908{
3909 if (!PyUnicode_Check(unicode) || !PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02003910 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003911 return -1;
3912 }
Victor Stinner488fa492011-12-12 00:01:39 +01003913 assert(PyUnicode_IS_READY(unicode));
Victor Stinnerc4b49542011-12-11 22:44:26 +01003914 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02003915 PyErr_SetString(PyExc_IndexError, "string index out of range");
3916 return -1;
3917 }
Victor Stinner488fa492011-12-12 00:01:39 +01003918 if (unicode_check_modifiable(unicode))
Victor Stinnercd9950f2011-10-02 00:34:53 +02003919 return -1;
Victor Stinnerc9590ad2012-03-04 01:34:37 +01003920 if (ch > PyUnicode_MAX_CHAR_VALUE(unicode)) {
3921 PyErr_SetString(PyExc_ValueError, "character out of range");
3922 return -1;
3923 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003924 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
3925 index, ch);
3926 return 0;
3927}
3928
Alexander Belopolsky40018472011-02-26 01:02:56 +00003929const char *
3930PyUnicode_GetDefaultEncoding(void)
Fred Drakee4315f52000-05-09 19:53:39 +00003931{
Victor Stinner42cb4622010-09-01 19:39:01 +00003932 return "utf-8";
Fred Drakee4315f52000-05-09 19:53:39 +00003933}
3934
Victor Stinner554f3f02010-06-16 23:33:54 +00003935/* create or adjust a UnicodeDecodeError */
3936static void
3937make_decode_exception(PyObject **exceptionObject,
3938 const char *encoding,
3939 const char *input, Py_ssize_t length,
3940 Py_ssize_t startpos, Py_ssize_t endpos,
3941 const char *reason)
3942{
3943 if (*exceptionObject == NULL) {
3944 *exceptionObject = PyUnicodeDecodeError_Create(
3945 encoding, input, length, startpos, endpos, reason);
3946 }
3947 else {
3948 if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
3949 goto onError;
3950 if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
3951 goto onError;
3952 if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
3953 goto onError;
3954 }
3955 return;
3956
3957onError:
3958 Py_DECREF(*exceptionObject);
3959 *exceptionObject = NULL;
3960}
3961
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003962/* error handling callback helper:
3963 build arguments, call the callback and check the arguments,
Fred Drakedb390c12005-10-28 14:39:47 +00003964 if no exception occurred, copy the replacement to the output
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003965 and adjust various state variables.
3966 return 0 on success, -1 on error
3967*/
3968
Alexander Belopolsky40018472011-02-26 01:02:56 +00003969static int
3970unicode_decode_call_errorhandler(const char *errors, PyObject **errorHandler,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003971 const char *encoding, const char *reason,
3972 const char **input, const char **inend, Py_ssize_t *startinpos,
3973 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003974 PyObject **output, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003975{
Benjamin Peterson142957c2008-07-04 19:55:29 +00003976 static char *argparse = "O!n;decoding error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003977
3978 PyObject *restuple = NULL;
3979 PyObject *repunicode = NULL;
Victor Stinner596a6c42011-11-09 00:02:18 +01003980 Py_ssize_t outsize;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003981 Py_ssize_t insize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003982 Py_ssize_t requiredsize;
3983 Py_ssize_t newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003984 PyObject *inputobj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003985 int res = -1;
3986
Victor Stinner596a6c42011-11-09 00:02:18 +01003987 if (_PyUnicode_KIND(*output) != PyUnicode_WCHAR_KIND)
3988 outsize = PyUnicode_GET_LENGTH(*output);
3989 else
3990 outsize = _PyUnicode_WSTR_LENGTH(*output);
3991
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003992 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003993 *errorHandler = PyCodec_LookupError(errors);
3994 if (*errorHandler == NULL)
3995 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003996 }
3997
Victor Stinner554f3f02010-06-16 23:33:54 +00003998 make_decode_exception(exceptionObject,
3999 encoding,
4000 *input, *inend - *input,
4001 *startinpos, *endinpos,
4002 reason);
4003 if (*exceptionObject == NULL)
4004 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004005
4006 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
4007 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004008 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004009 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00004010 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00004011 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004012 }
4013 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00004014 goto onError;
Benjamin Petersonbac79492012-01-14 13:34:47 -05004015 if (PyUnicode_READY(repunicode) == -1)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004016 goto onError;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004017
4018 /* Copy back the bytes variables, which might have been modified by the
4019 callback */
4020 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4021 if (!inputobj)
4022 goto onError;
Christian Heimes72b710a2008-05-26 13:28:38 +00004023 if (!PyBytes_Check(inputobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004024 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
Walter Dörwalde78178e2007-07-30 13:31:40 +00004025 }
Christian Heimes72b710a2008-05-26 13:28:38 +00004026 *input = PyBytes_AS_STRING(inputobj);
4027 insize = PyBytes_GET_SIZE(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004028 *inend = *input + insize;
Walter Dörwald36f938f2007-08-10 10:11:43 +00004029 /* we can DECREF safely, as the exception has another reference,
4030 so the object won't go away. */
4031 Py_DECREF(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004032
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004033 if (newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004034 newpos = insize+newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004035 if (newpos<0 || newpos>insize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004036 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
4037 goto onError;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004038 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004039
Victor Stinner596a6c42011-11-09 00:02:18 +01004040 if (_PyUnicode_KIND(*output) != PyUnicode_WCHAR_KIND) {
4041 /* need more space? (at least enough for what we
4042 have+the replacement+the rest of the string (starting
4043 at the new input position), so we won't have to check space
4044 when there are no errors in the rest of the string) */
4045 Py_ssize_t replen = PyUnicode_GET_LENGTH(repunicode);
4046 requiredsize = *outpos + replen + insize-newpos;
4047 if (requiredsize > outsize) {
4048 if (requiredsize<2*outsize)
4049 requiredsize = 2*outsize;
4050 if (unicode_resize(output, requiredsize) < 0)
4051 goto onError;
4052 }
Victor Stinner1b487b42012-05-03 12:29:04 +02004053 if (unicode_widen(output, *outpos,
4054 PyUnicode_MAX_CHAR_VALUE(repunicode)) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004055 goto onError;
Victor Stinnerd3f08822012-05-29 12:57:52 +02004056 _PyUnicode_FastCopyCharacters(*output, *outpos, repunicode, 0, replen);
Victor Stinner596a6c42011-11-09 00:02:18 +01004057 *outpos += replen;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004058 }
Victor Stinner596a6c42011-11-09 00:02:18 +01004059 else {
4060 wchar_t *repwstr;
4061 Py_ssize_t repwlen;
4062 repwstr = PyUnicode_AsUnicodeAndSize(repunicode, &repwlen);
4063 if (repwstr == NULL)
4064 goto onError;
4065 /* need more space? (at least enough for what we
4066 have+the replacement+the rest of the string (starting
4067 at the new input position), so we won't have to check space
4068 when there are no errors in the rest of the string) */
4069 requiredsize = *outpos + repwlen + insize-newpos;
4070 if (requiredsize > outsize) {
4071 if (requiredsize < 2*outsize)
4072 requiredsize = 2*outsize;
4073 if (unicode_resize(output, requiredsize) < 0)
4074 goto onError;
4075 }
4076 wcsncpy(_PyUnicode_WSTR(*output) + *outpos, repwstr, repwlen);
4077 *outpos += repwlen;
4078 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004079 *endinpos = newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004080 *inptr = *input + newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004081
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004082 /* we made it! */
4083 res = 0;
4084
Benjamin Peterson29060642009-01-31 22:14:21 +00004085 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004086 Py_XDECREF(restuple);
4087 return res;
4088}
4089
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004090/* --- UTF-7 Codec -------------------------------------------------------- */
4091
Antoine Pitrou244651a2009-05-04 18:56:13 +00004092/* See RFC2152 for details. We encode conservatively and decode liberally. */
4093
4094/* Three simple macros defining base-64. */
4095
4096/* Is c a base-64 character? */
4097
4098#define IS_BASE64(c) \
4099 (((c) >= 'A' && (c) <= 'Z') || \
4100 ((c) >= 'a' && (c) <= 'z') || \
4101 ((c) >= '0' && (c) <= '9') || \
4102 (c) == '+' || (c) == '/')
4103
4104/* given that c is a base-64 character, what is its base-64 value? */
4105
4106#define FROM_BASE64(c) \
4107 (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' : \
4108 ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 : \
4109 ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 : \
4110 (c) == '+' ? 62 : 63)
4111
4112/* What is the base-64 character of the bottom 6 bits of n? */
4113
4114#define TO_BASE64(n) \
4115 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
4116
4117/* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
4118 * decoded as itself. We are permissive on decoding; the only ASCII
4119 * byte not decoding to itself is the + which begins a base64
4120 * string. */
4121
4122#define DECODE_DIRECT(c) \
4123 ((c) <= 127 && (c) != '+')
4124
4125/* The UTF-7 encoder treats ASCII characters differently according to
4126 * whether they are Set D, Set O, Whitespace, or special (i.e. none of
4127 * the above). See RFC2152. This array identifies these different
4128 * sets:
4129 * 0 : "Set D"
4130 * alphanumeric and '(),-./:?
4131 * 1 : "Set O"
4132 * !"#$%&*;<=>@[]^_`{|}
4133 * 2 : "whitespace"
4134 * ht nl cr sp
4135 * 3 : special (must be base64 encoded)
4136 * everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
4137 */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004138
Tim Petersced69f82003-09-16 20:30:58 +00004139static
Antoine Pitrou244651a2009-05-04 18:56:13 +00004140char utf7_category[128] = {
4141/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
4142 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
4143/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
4144 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
4145/* sp ! " # $ % & ' ( ) * + , - . / */
4146 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
4147/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
4148 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
4149/* @ A B C D E F G H I J K L M N O */
4150 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4151/* P Q R S T U V W X Y Z [ \ ] ^ _ */
4152 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
4153/* ` a b c d e f g h i j k l m n o */
4154 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4155/* p q r s t u v w x y z { | } ~ del */
4156 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004157};
4158
Antoine Pitrou244651a2009-05-04 18:56:13 +00004159/* ENCODE_DIRECT: this character should be encoded as itself. The
4160 * answer depends on whether we are encoding set O as itself, and also
4161 * on whether we are encoding whitespace as itself. RFC2152 makes it
4162 * clear that the answers to these questions vary between
4163 * applications, so this code needs to be flexible. */
Marc-André Lemburge115ec82005-10-19 22:33:31 +00004164
Antoine Pitrou244651a2009-05-04 18:56:13 +00004165#define ENCODE_DIRECT(c, directO, directWS) \
4166 ((c) < 128 && (c) > 0 && \
4167 ((utf7_category[(c)] == 0) || \
4168 (directWS && (utf7_category[(c)] == 2)) || \
4169 (directO && (utf7_category[(c)] == 1))))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004170
Alexander Belopolsky40018472011-02-26 01:02:56 +00004171PyObject *
4172PyUnicode_DecodeUTF7(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004173 Py_ssize_t size,
4174 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004175{
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004176 return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
4177}
4178
Antoine Pitrou244651a2009-05-04 18:56:13 +00004179/* The decoder. The only state we preserve is our read position,
4180 * i.e. how many characters we have consumed. So if we end in the
4181 * middle of a shift sequence we have to back off the read position
4182 * and the output to the beginning of the sequence, otherwise we lose
4183 * all the shift state (seen bits, number of bits seen, high
4184 * surrogate). */
4185
Alexander Belopolsky40018472011-02-26 01:02:56 +00004186PyObject *
4187PyUnicode_DecodeUTF7Stateful(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004188 Py_ssize_t size,
4189 const char *errors,
4190 Py_ssize_t *consumed)
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004191{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004192 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004193 Py_ssize_t startinpos;
4194 Py_ssize_t endinpos;
4195 Py_ssize_t outpos;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004196 const char *e;
Victor Stinner7931d9a2011-11-04 00:22:48 +01004197 PyObject *unicode;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004198 const char *errmsg = "";
4199 int inShift = 0;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004200 Py_ssize_t shiftOutStart;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004201 unsigned int base64bits = 0;
4202 unsigned long base64buffer = 0;
Victor Stinner24729f32011-11-10 20:31:37 +01004203 Py_UCS4 surrogate = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004204 PyObject *errorHandler = NULL;
4205 PyObject *exc = NULL;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004206
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004207 /* Start off assuming it's all ASCII. Widen later as necessary. */
4208 unicode = PyUnicode_New(size, 127);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004209 if (!unicode)
4210 return NULL;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004211 if (size == 0) {
4212 if (consumed)
4213 *consumed = 0;
Victor Stinner7931d9a2011-11-04 00:22:48 +01004214 return unicode;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004215 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004216
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004217 shiftOutStart = outpos = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004218 e = s + size;
4219
4220 while (s < e) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004221 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00004222 restart:
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00004223 ch = (unsigned char) *s;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004224
Antoine Pitrou244651a2009-05-04 18:56:13 +00004225 if (inShift) { /* in a base-64 section */
4226 if (IS_BASE64(ch)) { /* consume a base-64 character */
4227 base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
4228 base64bits += 6;
4229 s++;
4230 if (base64bits >= 16) {
4231 /* we have enough bits for a UTF-16 value */
Victor Stinner24729f32011-11-10 20:31:37 +01004232 Py_UCS4 outCh = (Py_UCS4)(base64buffer >> (base64bits-16));
Antoine Pitrou244651a2009-05-04 18:56:13 +00004233 base64bits -= 16;
4234 base64buffer &= (1 << base64bits) - 1; /* clear high bits */
4235 if (surrogate) {
4236 /* expecting a second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004237 if (Py_UNICODE_IS_LOW_SURROGATE(outCh)) {
4238 Py_UCS4 ch2 = Py_UNICODE_JOIN_SURROGATES(surrogate, outCh);
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004239 if (unicode_putchar(&unicode, &outpos, ch2) < 0)
4240 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004241 surrogate = 0;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01004242 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004243 }
4244 else {
Antoine Pitrou78edf752011-11-15 01:44:16 +01004245 if (unicode_putchar(&unicode, &outpos, surrogate) < 0)
4246 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004247 surrogate = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004248 }
4249 }
Victor Stinner551ac952011-11-29 22:58:13 +01004250 if (Py_UNICODE_IS_HIGH_SURROGATE(outCh)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004251 /* first surrogate */
4252 surrogate = outCh;
4253 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004254 else {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004255 if (unicode_putchar(&unicode, &outpos, outCh) < 0)
4256 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004257 }
4258 }
4259 }
4260 else { /* now leaving a base-64 section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004261 inShift = 0;
4262 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004263 if (surrogate) {
Antoine Pitrou78edf752011-11-15 01:44:16 +01004264 if (unicode_putchar(&unicode, &outpos, surrogate) < 0)
4265 goto onError;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01004266 surrogate = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004267 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004268 if (base64bits > 0) { /* left-over bits */
4269 if (base64bits >= 6) {
4270 /* We've seen at least one base-64 character */
4271 errmsg = "partial character in shift sequence";
4272 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004273 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004274 else {
4275 /* Some bits remain; they should be zero */
4276 if (base64buffer != 0) {
4277 errmsg = "non-zero padding bits in shift sequence";
4278 goto utf7Error;
4279 }
4280 }
4281 }
4282 if (ch != '-') {
4283 /* '-' is absorbed; other terminating
4284 characters are preserved */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004285 if (unicode_putchar(&unicode, &outpos, ch) < 0)
4286 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004287 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004288 }
4289 }
4290 else if ( ch == '+' ) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004291 startinpos = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004292 s++; /* consume '+' */
4293 if (s < e && *s == '-') { /* '+-' encodes '+' */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004294 s++;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004295 if (unicode_putchar(&unicode, &outpos, '+') < 0)
4296 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004297 }
4298 else { /* begin base64-encoded section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004299 inShift = 1;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004300 shiftOutStart = outpos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004301 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004302 }
4303 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004304 else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004305 if (unicode_putchar(&unicode, &outpos, ch) < 0)
4306 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004307 s++;
4308 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004309 else {
4310 startinpos = s-starts;
4311 s++;
4312 errmsg = "unexpected special character";
4313 goto utf7Error;
4314 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004315 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004316utf7Error:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004317 endinpos = s-starts;
4318 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00004319 errors, &errorHandler,
4320 "utf7", errmsg,
4321 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004322 &unicode, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00004323 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004324 }
4325
Antoine Pitrou244651a2009-05-04 18:56:13 +00004326 /* end of string */
4327
4328 if (inShift && !consumed) { /* in shift sequence, no more to follow */
4329 /* if we're in an inconsistent state, that's an error */
4330 if (surrogate ||
4331 (base64bits >= 6) ||
4332 (base64bits > 0 && base64buffer != 0)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004333 endinpos = size;
4334 if (unicode_decode_call_errorhandler(
4335 errors, &errorHandler,
4336 "utf7", "unterminated shift sequence",
4337 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004338 &unicode, &outpos))
Antoine Pitrou244651a2009-05-04 18:56:13 +00004339 goto onError;
4340 if (s < e)
4341 goto restart;
4342 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004343 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004344
4345 /* return state */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004346 if (consumed) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004347 if (inShift) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004348 outpos = shiftOutStart; /* back off output */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004349 *consumed = startinpos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004350 }
4351 else {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004352 *consumed = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004353 }
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004354 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004355
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004356 if (unicode_resize(&unicode, outpos) < 0)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004357 goto onError;
4358
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004359 Py_XDECREF(errorHandler);
4360 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01004361 return unicode_result(unicode);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004362
Benjamin Peterson29060642009-01-31 22:14:21 +00004363 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004364 Py_XDECREF(errorHandler);
4365 Py_XDECREF(exc);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004366 Py_DECREF(unicode);
4367 return NULL;
4368}
4369
4370
Alexander Belopolsky40018472011-02-26 01:02:56 +00004371PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004372_PyUnicode_EncodeUTF7(PyObject *str,
4373 int base64SetO,
4374 int base64WhiteSpace,
4375 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004376{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004377 int kind;
4378 void *data;
4379 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004380 PyObject *v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004381 int inShift = 0;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004382 Py_ssize_t i;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004383 unsigned int base64bits = 0;
4384 unsigned long base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004385 char * out;
4386 char * start;
4387
Benjamin Petersonbac79492012-01-14 13:34:47 -05004388 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004389 return NULL;
4390 kind = PyUnicode_KIND(str);
4391 data = PyUnicode_DATA(str);
4392 len = PyUnicode_GET_LENGTH(str);
4393
4394 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004395 return PyBytes_FromStringAndSize(NULL, 0);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004396
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004397 /* It might be possible to tighten this worst case */
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004398 if (len > PY_SSIZE_T_MAX / 8)
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004399 return PyErr_NoMemory();
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004400 v = PyBytes_FromStringAndSize(NULL, len * 8);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004401 if (v == NULL)
4402 return NULL;
4403
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004404 start = out = PyBytes_AS_STRING(v);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004405 for (i = 0; i < len; ++i) {
Victor Stinner0e368262011-11-10 20:12:49 +01004406 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004407
Antoine Pitrou244651a2009-05-04 18:56:13 +00004408 if (inShift) {
4409 if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4410 /* shifting out */
4411 if (base64bits) { /* output remaining bits */
4412 *out++ = TO_BASE64(base64buffer << (6-base64bits));
4413 base64buffer = 0;
4414 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004415 }
4416 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004417 /* Characters not in the BASE64 set implicitly unshift the sequence
4418 so no '-' is required, except if the character is itself a '-' */
4419 if (IS_BASE64(ch) || ch == '-') {
4420 *out++ = '-';
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004421 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004422 *out++ = (char) ch;
4423 }
4424 else {
4425 goto encode_char;
Tim Petersced69f82003-09-16 20:30:58 +00004426 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004427 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004428 else { /* not in a shift sequence */
4429 if (ch == '+') {
4430 *out++ = '+';
4431 *out++ = '-';
4432 }
4433 else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4434 *out++ = (char) ch;
4435 }
4436 else {
4437 *out++ = '+';
4438 inShift = 1;
4439 goto encode_char;
4440 }
4441 }
4442 continue;
4443encode_char:
Antoine Pitrou244651a2009-05-04 18:56:13 +00004444 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01004445 assert(ch <= MAX_UNICODE);
Victor Stinner0d3721d2011-11-22 03:27:53 +01004446
Antoine Pitrou244651a2009-05-04 18:56:13 +00004447 /* code first surrogate */
4448 base64bits += 16;
4449 base64buffer = (base64buffer << 16) | 0xd800 | ((ch-0x10000) >> 10);
4450 while (base64bits >= 6) {
4451 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4452 base64bits -= 6;
4453 }
4454 /* prepare second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004455 ch = Py_UNICODE_LOW_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004456 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004457 base64bits += 16;
4458 base64buffer = (base64buffer << 16) | ch;
4459 while (base64bits >= 6) {
4460 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4461 base64bits -= 6;
4462 }
Hye-Shik Chang1bc09b72004-01-03 19:35:43 +00004463 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004464 if (base64bits)
4465 *out++= TO_BASE64(base64buffer << (6-base64bits) );
4466 if (inShift)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004467 *out++ = '-';
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004468 if (_PyBytes_Resize(&v, out - start) < 0)
4469 return NULL;
4470 return v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004471}
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004472PyObject *
4473PyUnicode_EncodeUTF7(const Py_UNICODE *s,
4474 Py_ssize_t size,
4475 int base64SetO,
4476 int base64WhiteSpace,
4477 const char *errors)
4478{
4479 PyObject *result;
4480 PyObject *tmp = PyUnicode_FromUnicode(s, size);
4481 if (tmp == NULL)
4482 return NULL;
Victor Stinner0e368262011-11-10 20:12:49 +01004483 result = _PyUnicode_EncodeUTF7(tmp, base64SetO,
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004484 base64WhiteSpace, errors);
4485 Py_DECREF(tmp);
4486 return result;
4487}
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004488
Antoine Pitrou244651a2009-05-04 18:56:13 +00004489#undef IS_BASE64
4490#undef FROM_BASE64
4491#undef TO_BASE64
4492#undef DECODE_DIRECT
4493#undef ENCODE_DIRECT
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004494
Guido van Rossumd57fd912000-03-10 22:53:23 +00004495/* --- UTF-8 Codec -------------------------------------------------------- */
4496
Alexander Belopolsky40018472011-02-26 01:02:56 +00004497PyObject *
4498PyUnicode_DecodeUTF8(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004499 Py_ssize_t size,
4500 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004501{
Walter Dörwald69652032004-09-07 20:24:22 +00004502 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
4503}
4504
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004505#include "stringlib/asciilib.h"
4506#include "stringlib/codecs.h"
4507#include "stringlib/undef.h"
4508
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004509#include "stringlib/ucs1lib.h"
4510#include "stringlib/codecs.h"
4511#include "stringlib/undef.h"
4512
4513#include "stringlib/ucs2lib.h"
4514#include "stringlib/codecs.h"
4515#include "stringlib/undef.h"
4516
4517#include "stringlib/ucs4lib.h"
4518#include "stringlib/codecs.h"
4519#include "stringlib/undef.h"
4520
Antoine Pitrouab868312009-01-10 15:40:25 +00004521/* Mask to quickly check whether a C 'long' contains a
4522 non-ASCII, UTF8-encoded char. */
4523#if (SIZEOF_LONG == 8)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004524# define ASCII_CHAR_MASK 0x8080808080808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004525#elif (SIZEOF_LONG == 4)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004526# define ASCII_CHAR_MASK 0x80808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004527#else
4528# error C 'long' size should be either 4 or 8!
4529#endif
4530
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004531static Py_ssize_t
4532ascii_decode(const char *start, const char *end, Py_UCS1 *dest)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004533{
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004534 const char *p = start;
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004535 const char *aligned_end = (const char *) _Py_ALIGN_DOWN(end, SIZEOF_LONG);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004536
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004537#if SIZEOF_LONG <= SIZEOF_VOID_P
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004538 assert(_Py_IS_ALIGNED(dest, SIZEOF_LONG));
4539 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004540 /* Fast path, see in STRINGLIB(utf8_decode) for
4541 an explanation. */
4542 /* Help register allocation */
4543 register const char *_p = p;
4544 register Py_UCS1 * q = dest;
4545 while (_p < aligned_end) {
4546 unsigned long value = *(const unsigned long *) _p;
4547 if (value & ASCII_CHAR_MASK)
Benjamin Peterson29060642009-01-31 22:14:21 +00004548 break;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004549 *((unsigned long *)q) = value;
4550 _p += SIZEOF_LONG;
4551 q += SIZEOF_LONG;
Benjamin Peterson14339b62009-01-31 16:36:08 +00004552 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004553 p = _p;
4554 while (p < end) {
4555 if ((unsigned char)*p & 0x80)
4556 break;
4557 *q++ = *p++;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004558 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004559 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004560 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004561#endif
4562 while (p < end) {
4563 /* Fast path, see in STRINGLIB(utf8_decode) in stringlib/codecs.h
4564 for an explanation. */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004565 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004566 /* Help register allocation */
4567 register const char *_p = p;
4568 while (_p < aligned_end) {
4569 unsigned long value = *(unsigned long *) _p;
4570 if (value & ASCII_CHAR_MASK)
4571 break;
4572 _p += SIZEOF_LONG;
4573 }
4574 p = _p;
4575 if (_p == end)
4576 break;
4577 }
4578 if ((unsigned char)*p & 0x80)
4579 break;
4580 ++p;
4581 }
4582 memcpy(dest, start, p - start);
4583 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004584}
Antoine Pitrouab868312009-01-10 15:40:25 +00004585
Victor Stinner785938e2011-12-11 20:09:03 +01004586PyObject *
4587PyUnicode_DecodeUTF8Stateful(const char *s,
4588 Py_ssize_t size,
4589 const char *errors,
4590 Py_ssize_t *consumed)
4591{
Victor Stinner785938e2011-12-11 20:09:03 +01004592 PyObject *unicode;
Victor Stinner785938e2011-12-11 20:09:03 +01004593 const char *starts = s;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004594 const char *end = s + size;
4595 Py_ssize_t outpos;
4596
4597 Py_ssize_t startinpos;
4598 Py_ssize_t endinpos;
4599 const char *errmsg = "";
4600 PyObject *errorHandler = NULL;
4601 PyObject *exc = NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01004602
4603 if (size == 0) {
4604 if (consumed)
4605 *consumed = 0;
Victor Stinner382955f2011-12-11 21:44:00 +01004606 Py_INCREF(unicode_empty);
4607 return unicode_empty;
Victor Stinner785938e2011-12-11 20:09:03 +01004608 }
4609
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004610 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
4611 if (size == 1 && (unsigned char)s[0] < 128) {
Victor Stinner785938e2011-12-11 20:09:03 +01004612 if (consumed)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004613 *consumed = 1;
4614 return get_latin1_char((unsigned char)s[0]);
Victor Stinner785938e2011-12-11 20:09:03 +01004615 }
4616
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004617 unicode = PyUnicode_New(size, 127);
Victor Stinner785938e2011-12-11 20:09:03 +01004618 if (!unicode)
4619 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01004620
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004621 outpos = ascii_decode(s, end, PyUnicode_1BYTE_DATA(unicode));
4622 s += outpos;
4623 while (s < end) {
4624 Py_UCS4 ch;
4625 int kind = PyUnicode_KIND(unicode);
4626 if (kind == PyUnicode_1BYTE_KIND) {
4627 if (PyUnicode_IS_ASCII(unicode))
4628 ch = asciilib_utf8_decode(&s, end,
4629 PyUnicode_1BYTE_DATA(unicode), &outpos);
4630 else
4631 ch = ucs1lib_utf8_decode(&s, end,
4632 PyUnicode_1BYTE_DATA(unicode), &outpos);
4633 } else if (kind == PyUnicode_2BYTE_KIND) {
4634 ch = ucs2lib_utf8_decode(&s, end,
4635 PyUnicode_2BYTE_DATA(unicode), &outpos);
4636 } else {
4637 assert(kind == PyUnicode_4BYTE_KIND);
4638 ch = ucs4lib_utf8_decode(&s, end,
4639 PyUnicode_4BYTE_DATA(unicode), &outpos);
4640 }
4641
4642 switch (ch) {
4643 case 0:
4644 if (s == end || consumed)
4645 goto End;
4646 errmsg = "unexpected end of data";
4647 startinpos = s - starts;
4648 endinpos = startinpos + 1;
4649 while (endinpos < size && (starts[endinpos] & 0xC0) == 0x80)
4650 endinpos++;
4651 break;
4652 case 1:
4653 errmsg = "invalid start byte";
4654 startinpos = s - starts;
4655 endinpos = startinpos + 1;
4656 break;
4657 case 2:
4658 errmsg = "invalid continuation byte";
4659 startinpos = s - starts;
4660 endinpos = startinpos + 1;
4661 while (endinpos < size && (starts[endinpos] & 0xC0) == 0x80)
4662 endinpos++;
4663 break;
4664 default:
4665 if (unicode_putchar(&unicode, &outpos, ch) < 0)
4666 goto onError;
4667 continue;
4668 }
4669
4670 if (unicode_decode_call_errorhandler(
4671 errors, &errorHandler,
4672 "utf-8", errmsg,
4673 &starts, &end, &startinpos, &endinpos, &exc, &s,
4674 &unicode, &outpos))
4675 goto onError;
Victor Stinner785938e2011-12-11 20:09:03 +01004676 }
4677
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004678End:
4679 if (unicode_resize(&unicode, outpos) < 0)
4680 goto onError;
4681
4682 if (consumed)
4683 *consumed = s - starts;
4684
4685 Py_XDECREF(errorHandler);
4686 Py_XDECREF(exc);
4687 assert(_PyUnicode_CheckConsistency(unicode, 1));
4688 return unicode;
4689
4690onError:
4691 Py_XDECREF(errorHandler);
4692 Py_XDECREF(exc);
4693 Py_XDECREF(unicode);
4694 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01004695}
4696
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004697#ifdef __APPLE__
4698
4699/* Simplified UTF-8 decoder using surrogateescape error handler,
4700 used to decode the command line arguments on Mac OS X. */
4701
4702wchar_t*
4703_Py_DecodeUTF8_surrogateescape(const char *s, Py_ssize_t size)
4704{
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004705 const char *e;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004706 wchar_t *unicode;
4707 Py_ssize_t outpos;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004708
4709 /* Note: size will always be longer than the resulting Unicode
4710 character count */
4711 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < (size + 1)) {
4712 PyErr_NoMemory();
4713 return NULL;
4714 }
4715 unicode = PyMem_Malloc((size + 1) * sizeof(wchar_t));
4716 if (!unicode)
4717 return NULL;
4718
4719 /* Unpack UTF-8 encoded data */
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004720 e = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004721 outpos = 0;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004722 while (s < e) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004723 Py_UCS4 ch;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004724#if SIZEOF_WCHAR_T == 4
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004725 ch = ucs4lib_utf8_decode(&s, e, (Py_UCS4 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004726#else
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004727 ch = ucs2lib_utf8_decode(&s, e, (Py_UCS2 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004728#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004729 if (ch > 0xFF) {
4730#if SIZEOF_WCHAR_T == 4
4731 assert(0);
4732#else
4733 assert(Py_UNICODE_IS_SURROGATE(ch));
4734 /* compute and append the two surrogates: */
4735 unicode[outpos++] = (wchar_t)Py_UNICODE_HIGH_SURROGATE(ch);
4736 unicode[outpos++] = (wchar_t)Py_UNICODE_LOW_SURROGATE(ch);
4737#endif
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004738 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004739 else {
4740 if (!ch && s == e)
4741 break;
4742 /* surrogateescape */
4743 unicode[outpos++] = 0xDC00 + (unsigned char)*s++;
4744 }
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004745 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004746 unicode[outpos] = L'\0';
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004747 return unicode;
4748}
4749
4750#endif /* __APPLE__ */
Antoine Pitrouab868312009-01-10 15:40:25 +00004751
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004752/* Primary internal function which creates utf8 encoded bytes objects.
4753
4754 Allocation strategy: if the string is short, convert into a stack buffer
Tim Peters602f7402002-04-27 18:03:26 +00004755 and allocate exactly as much space needed at the end. Else allocate the
4756 maximum possible needed (4 result bytes per Unicode character), and return
4757 the excess memory at the end.
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004758*/
Tim Peters7e3d9612002-04-21 03:26:37 +00004759PyObject *
Victor Stinner7931d9a2011-11-04 00:22:48 +01004760_PyUnicode_AsUTF8String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004761{
Victor Stinner6099a032011-12-18 14:22:26 +01004762 enum PyUnicode_Kind kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004763 void *data;
4764 Py_ssize_t size;
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00004765
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004766 if (!PyUnicode_Check(unicode)) {
4767 PyErr_BadArgument();
4768 return NULL;
4769 }
4770
4771 if (PyUnicode_READY(unicode) == -1)
4772 return NULL;
4773
Victor Stinnere90fe6a2011-10-01 16:48:13 +02004774 if (PyUnicode_UTF8(unicode))
4775 return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode),
4776 PyUnicode_UTF8_LENGTH(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004777
4778 kind = PyUnicode_KIND(unicode);
4779 data = PyUnicode_DATA(unicode);
4780 size = PyUnicode_GET_LENGTH(unicode);
4781
Benjamin Petersonead6b532011-12-20 17:23:42 -06004782 switch (kind) {
Victor Stinner6099a032011-12-18 14:22:26 +01004783 default:
4784 assert(0);
4785 case PyUnicode_1BYTE_KIND:
4786 /* the string cannot be ASCII, or PyUnicode_UTF8() would be set */
4787 assert(!PyUnicode_IS_ASCII(unicode));
4788 return ucs1lib_utf8_encoder(unicode, data, size, errors);
4789 case PyUnicode_2BYTE_KIND:
4790 return ucs2lib_utf8_encoder(unicode, data, size, errors);
4791 case PyUnicode_4BYTE_KIND:
4792 return ucs4lib_utf8_encoder(unicode, data, size, errors);
Tim Peters602f7402002-04-27 18:03:26 +00004793 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004794}
4795
Alexander Belopolsky40018472011-02-26 01:02:56 +00004796PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004797PyUnicode_EncodeUTF8(const Py_UNICODE *s,
4798 Py_ssize_t size,
4799 const char *errors)
4800{
4801 PyObject *v, *unicode;
4802
4803 unicode = PyUnicode_FromUnicode(s, size);
4804 if (unicode == NULL)
4805 return NULL;
4806 v = _PyUnicode_AsUTF8String(unicode, errors);
4807 Py_DECREF(unicode);
4808 return v;
4809}
4810
4811PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00004812PyUnicode_AsUTF8String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004813{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004814 return _PyUnicode_AsUTF8String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004815}
4816
Walter Dörwald41980ca2007-08-16 21:55:45 +00004817/* --- UTF-32 Codec ------------------------------------------------------- */
4818
4819PyObject *
4820PyUnicode_DecodeUTF32(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004821 Py_ssize_t size,
4822 const char *errors,
4823 int *byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004824{
4825 return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
4826}
4827
4828PyObject *
4829PyUnicode_DecodeUTF32Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004830 Py_ssize_t size,
4831 const char *errors,
4832 int *byteorder,
4833 Py_ssize_t *consumed)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004834{
4835 const char *starts = s;
4836 Py_ssize_t startinpos;
4837 Py_ssize_t endinpos;
4838 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01004839 PyObject *unicode;
Mark Dickinson7db923c2010-06-12 09:10:14 +00004840 const unsigned char *q, *e;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004841 int bo = 0; /* assume native ordering by default */
4842 const char *errmsg = "";
Walter Dörwald41980ca2007-08-16 21:55:45 +00004843 /* Offsets from q for retrieving bytes in the right order. */
4844#ifdef BYTEORDER_IS_LITTLE_ENDIAN
4845 int iorder[] = {0, 1, 2, 3};
4846#else
4847 int iorder[] = {3, 2, 1, 0};
4848#endif
4849 PyObject *errorHandler = NULL;
4850 PyObject *exc = NULL;
Victor Stinner313a1202010-06-11 23:56:51 +00004851
Walter Dörwald41980ca2007-08-16 21:55:45 +00004852 q = (unsigned char *)s;
4853 e = q + size;
4854
4855 if (byteorder)
4856 bo = *byteorder;
4857
4858 /* Check for BOM marks (U+FEFF) in the input and adjust current
4859 byte order setting accordingly. In native mode, the leading BOM
4860 mark is skipped, in all other modes, it is copied to the output
4861 stream as-is (giving a ZWNBSP character). */
4862 if (bo == 0) {
4863 if (size >= 4) {
4864 const Py_UCS4 bom = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
Benjamin Peterson29060642009-01-31 22:14:21 +00004865 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00004866#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Benjamin Peterson29060642009-01-31 22:14:21 +00004867 if (bom == 0x0000FEFF) {
4868 q += 4;
4869 bo = -1;
4870 }
4871 else if (bom == 0xFFFE0000) {
4872 q += 4;
4873 bo = 1;
4874 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004875#else
Benjamin Peterson29060642009-01-31 22:14:21 +00004876 if (bom == 0x0000FEFF) {
4877 q += 4;
4878 bo = 1;
4879 }
4880 else if (bom == 0xFFFE0000) {
4881 q += 4;
4882 bo = -1;
4883 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004884#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00004885 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004886 }
4887
4888 if (bo == -1) {
4889 /* force LE */
4890 iorder[0] = 0;
4891 iorder[1] = 1;
4892 iorder[2] = 2;
4893 iorder[3] = 3;
4894 }
4895 else if (bo == 1) {
4896 /* force BE */
4897 iorder[0] = 3;
4898 iorder[1] = 2;
4899 iorder[2] = 1;
4900 iorder[3] = 0;
4901 }
4902
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00004903 /* This might be one to much, because of a BOM */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004904 unicode = PyUnicode_New((size+3)/4, 127);
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00004905 if (!unicode)
4906 return NULL;
4907 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01004908 return unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004909 outpos = 0;
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00004910
Walter Dörwald41980ca2007-08-16 21:55:45 +00004911 while (q < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004912 Py_UCS4 ch;
4913 /* remaining bytes at the end? (size should be divisible by 4) */
4914 if (e-q<4) {
4915 if (consumed)
4916 break;
4917 errmsg = "truncated data";
4918 startinpos = ((const char *)q)-starts;
4919 endinpos = ((const char *)e)-starts;
4920 goto utf32Error;
4921 /* The remaining input chars are ignored if the callback
4922 chooses to skip the input */
4923 }
4924 ch = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
4925 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00004926
Benjamin Peterson29060642009-01-31 22:14:21 +00004927 if (ch >= 0x110000)
4928 {
4929 errmsg = "codepoint not in range(0x110000)";
4930 startinpos = ((const char *)q)-starts;
4931 endinpos = startinpos+4;
4932 goto utf32Error;
4933 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004934 if (unicode_putchar(&unicode, &outpos, ch) < 0)
4935 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00004936 q += 4;
4937 continue;
4938 utf32Error:
Benjamin Peterson29060642009-01-31 22:14:21 +00004939 if (unicode_decode_call_errorhandler(
4940 errors, &errorHandler,
4941 "utf32", errmsg,
4942 &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004943 &unicode, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00004944 goto onError;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004945 }
4946
4947 if (byteorder)
4948 *byteorder = bo;
4949
4950 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00004951 *consumed = (const char *)q-starts;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004952
4953 /* Adjust length */
Victor Stinner16e6a802011-12-12 13:24:15 +01004954 if (unicode_resize(&unicode, outpos) < 0)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004955 goto onError;
4956
4957 Py_XDECREF(errorHandler);
4958 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01004959 return unicode_result(unicode);
Walter Dörwald41980ca2007-08-16 21:55:45 +00004960
Benjamin Peterson29060642009-01-31 22:14:21 +00004961 onError:
Walter Dörwald41980ca2007-08-16 21:55:45 +00004962 Py_DECREF(unicode);
4963 Py_XDECREF(errorHandler);
4964 Py_XDECREF(exc);
4965 return NULL;
4966}
4967
4968PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004969_PyUnicode_EncodeUTF32(PyObject *str,
4970 const char *errors,
4971 int byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004972{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004973 int kind;
4974 void *data;
4975 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004976 PyObject *v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004977 unsigned char *p;
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004978 Py_ssize_t nsize, i;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004979 /* Offsets from p for storing byte pairs in the right order. */
4980#ifdef BYTEORDER_IS_LITTLE_ENDIAN
4981 int iorder[] = {0, 1, 2, 3};
4982#else
4983 int iorder[] = {3, 2, 1, 0};
4984#endif
4985
Benjamin Peterson29060642009-01-31 22:14:21 +00004986#define STORECHAR(CH) \
4987 do { \
4988 p[iorder[3]] = ((CH) >> 24) & 0xff; \
4989 p[iorder[2]] = ((CH) >> 16) & 0xff; \
4990 p[iorder[1]] = ((CH) >> 8) & 0xff; \
4991 p[iorder[0]] = (CH) & 0xff; \
4992 p += 4; \
Walter Dörwald41980ca2007-08-16 21:55:45 +00004993 } while(0)
4994
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004995 if (!PyUnicode_Check(str)) {
4996 PyErr_BadArgument();
4997 return NULL;
4998 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05004999 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005000 return NULL;
5001 kind = PyUnicode_KIND(str);
5002 data = PyUnicode_DATA(str);
5003 len = PyUnicode_GET_LENGTH(str);
5004
5005 nsize = len + (byteorder == 0);
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01005006 if (nsize > PY_SSIZE_T_MAX / 4)
Benjamin Peterson29060642009-01-31 22:14:21 +00005007 return PyErr_NoMemory();
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01005008 v = PyBytes_FromStringAndSize(NULL, nsize * 4);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005009 if (v == NULL)
5010 return NULL;
5011
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005012 p = (unsigned char *)PyBytes_AS_STRING(v);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005013 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005014 STORECHAR(0xFEFF);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005015 if (len == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005016 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005017
5018 if (byteorder == -1) {
5019 /* force LE */
5020 iorder[0] = 0;
5021 iorder[1] = 1;
5022 iorder[2] = 2;
5023 iorder[3] = 3;
5024 }
5025 else if (byteorder == 1) {
5026 /* force BE */
5027 iorder[0] = 3;
5028 iorder[1] = 2;
5029 iorder[2] = 1;
5030 iorder[3] = 0;
5031 }
5032
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005033 for (i = 0; i < len; i++)
5034 STORECHAR(PyUnicode_READ(kind, data, i));
Guido van Rossum98297ee2007-11-06 21:34:58 +00005035
5036 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005037 return v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005038#undef STORECHAR
5039}
5040
Alexander Belopolsky40018472011-02-26 01:02:56 +00005041PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005042PyUnicode_EncodeUTF32(const Py_UNICODE *s,
5043 Py_ssize_t size,
5044 const char *errors,
5045 int byteorder)
5046{
5047 PyObject *result;
5048 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5049 if (tmp == NULL)
5050 return NULL;
5051 result = _PyUnicode_EncodeUTF32(tmp, errors, byteorder);
5052 Py_DECREF(tmp);
5053 return result;
5054}
5055
5056PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005057PyUnicode_AsUTF32String(PyObject *unicode)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005058{
Victor Stinnerb960b342011-11-20 19:12:52 +01005059 return _PyUnicode_EncodeUTF32(unicode, NULL, 0);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005060}
5061
Guido van Rossumd57fd912000-03-10 22:53:23 +00005062/* --- UTF-16 Codec ------------------------------------------------------- */
5063
Tim Peters772747b2001-08-09 22:21:55 +00005064PyObject *
5065PyUnicode_DecodeUTF16(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005066 Py_ssize_t size,
5067 const char *errors,
5068 int *byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005069{
Walter Dörwald69652032004-09-07 20:24:22 +00005070 return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
5071}
5072
5073PyObject *
5074PyUnicode_DecodeUTF16Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005075 Py_ssize_t size,
5076 const char *errors,
5077 int *byteorder,
5078 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00005079{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005080 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005081 Py_ssize_t startinpos;
5082 Py_ssize_t endinpos;
5083 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01005084 PyObject *unicode;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005085 const unsigned char *q, *e;
Tim Peters772747b2001-08-09 22:21:55 +00005086 int bo = 0; /* assume native ordering by default */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005087 int native_ordering;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00005088 const char *errmsg = "";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005089 PyObject *errorHandler = NULL;
5090 PyObject *exc = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005091
Tim Peters772747b2001-08-09 22:21:55 +00005092 q = (unsigned char *)s;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005093 e = q + size;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005094
5095 if (byteorder)
Tim Peters772747b2001-08-09 22:21:55 +00005096 bo = *byteorder;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005097
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005098 /* Check for BOM marks (U+FEFF) in the input and adjust current
5099 byte order setting accordingly. In native mode, the leading BOM
5100 mark is skipped, in all other modes, it is copied to the output
5101 stream as-is (giving a ZWNBSP character). */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005102 if (bo == 0 && size >= 2) {
5103 const Py_UCS4 bom = (q[1] << 8) | q[0];
5104 if (bom == 0xFEFF) {
5105 q += 2;
5106 bo = -1;
Benjamin Peterson29060642009-01-31 22:14:21 +00005107 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005108 else if (bom == 0xFFFE) {
5109 q += 2;
5110 bo = 1;
5111 }
5112 if (byteorder)
5113 *byteorder = bo;
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005114 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005115
Antoine Pitrou63065d72012-05-15 23:48:04 +02005116 if (q == e) {
5117 if (consumed)
5118 *consumed = size;
5119 Py_INCREF(unicode_empty);
5120 return unicode_empty;
Tim Peters772747b2001-08-09 22:21:55 +00005121 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005122
Antoine Pitrouab868312009-01-10 15:40:25 +00005123#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Antoine Pitrou63065d72012-05-15 23:48:04 +02005124 native_ordering = bo <= 0;
Antoine Pitrouab868312009-01-10 15:40:25 +00005125#else
Antoine Pitrou63065d72012-05-15 23:48:04 +02005126 native_ordering = bo >= 0;
Antoine Pitrouab868312009-01-10 15:40:25 +00005127#endif
Tim Peters772747b2001-08-09 22:21:55 +00005128
Antoine Pitrou63065d72012-05-15 23:48:04 +02005129 /* Note: size will always be longer than the resulting Unicode
5130 character count */
5131 unicode = PyUnicode_New((e - q + 1) / 2, 127);
5132 if (!unicode)
5133 return NULL;
5134
5135 outpos = 0;
5136 while (1) {
5137 Py_UCS4 ch = 0;
5138 if (e - q >= 2) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005139 int kind = PyUnicode_KIND(unicode);
Antoine Pitrou63065d72012-05-15 23:48:04 +02005140 if (kind == PyUnicode_1BYTE_KIND) {
5141 if (PyUnicode_IS_ASCII(unicode))
5142 ch = asciilib_utf16_decode(&q, e,
5143 PyUnicode_1BYTE_DATA(unicode), &outpos,
5144 native_ordering);
5145 else
5146 ch = ucs1lib_utf16_decode(&q, e,
5147 PyUnicode_1BYTE_DATA(unicode), &outpos,
5148 native_ordering);
5149 } else if (kind == PyUnicode_2BYTE_KIND) {
5150 ch = ucs2lib_utf16_decode(&q, e,
5151 PyUnicode_2BYTE_DATA(unicode), &outpos,
5152 native_ordering);
5153 } else {
5154 assert(kind == PyUnicode_4BYTE_KIND);
5155 ch = ucs4lib_utf16_decode(&q, e,
5156 PyUnicode_4BYTE_DATA(unicode), &outpos,
5157 native_ordering);
Antoine Pitrouab868312009-01-10 15:40:25 +00005158 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005159 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005160
Antoine Pitrou63065d72012-05-15 23:48:04 +02005161 switch (ch)
5162 {
5163 case 0:
5164 /* remaining byte at the end? (size should be even) */
5165 if (q == e || consumed)
5166 goto End;
5167 errmsg = "truncated data";
5168 startinpos = ((const char *)q) - starts;
5169 endinpos = ((const char *)e) - starts;
5170 break;
5171 /* The remaining input chars are ignored if the callback
5172 chooses to skip the input */
5173 case 1:
5174 errmsg = "unexpected end of data";
5175 startinpos = ((const char *)q) - 2 - starts;
5176 endinpos = ((const char *)e) - starts;
5177 break;
5178 case 2:
5179 errmsg = "illegal encoding";
5180 startinpos = ((const char *)q) - 2 - starts;
5181 endinpos = startinpos + 2;
5182 break;
5183 case 3:
5184 errmsg = "illegal UTF-16 surrogate";
5185 startinpos = ((const char *)q) - 4 - starts;
5186 endinpos = startinpos + 2;
5187 break;
5188 default:
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005189 if (unicode_putchar(&unicode, &outpos, ch) < 0)
5190 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005191 continue;
5192 }
5193
Benjamin Peterson29060642009-01-31 22:14:21 +00005194 if (unicode_decode_call_errorhandler(
Antoine Pitrouab868312009-01-10 15:40:25 +00005195 errors,
5196 &errorHandler,
5197 "utf16", errmsg,
5198 &starts,
5199 (const char **)&e,
5200 &startinpos,
5201 &endinpos,
5202 &exc,
5203 (const char **)&q,
5204 &unicode,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005205 &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00005206 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005207 }
5208
Antoine Pitrou63065d72012-05-15 23:48:04 +02005209End:
Walter Dörwald69652032004-09-07 20:24:22 +00005210 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005211 *consumed = (const char *)q-starts;
Walter Dörwald69652032004-09-07 20:24:22 +00005212
Guido van Rossumd57fd912000-03-10 22:53:23 +00005213 /* Adjust length */
Victor Stinner16e6a802011-12-12 13:24:15 +01005214 if (unicode_resize(&unicode, outpos) < 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005215 goto onError;
5216
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005217 Py_XDECREF(errorHandler);
5218 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01005219 return unicode_result(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005220
Benjamin Peterson29060642009-01-31 22:14:21 +00005221 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00005222 Py_DECREF(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005223 Py_XDECREF(errorHandler);
5224 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005225 return NULL;
5226}
5227
Tim Peters772747b2001-08-09 22:21:55 +00005228PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005229_PyUnicode_EncodeUTF16(PyObject *str,
5230 const char *errors,
5231 int byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005232{
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005233 enum PyUnicode_Kind kind;
5234 const void *data;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005235 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005236 PyObject *v;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005237 unsigned short *out;
5238 Py_ssize_t bytesize;
5239 Py_ssize_t pairs;
5240#ifdef WORDS_BIGENDIAN
5241 int native_ordering = byteorder >= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005242#else
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005243 int native_ordering = byteorder <= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005244#endif
5245
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005246 if (!PyUnicode_Check(str)) {
5247 PyErr_BadArgument();
5248 return NULL;
5249 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005250 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005251 return NULL;
5252 kind = PyUnicode_KIND(str);
5253 data = PyUnicode_DATA(str);
5254 len = PyUnicode_GET_LENGTH(str);
Victor Stinner0e368262011-11-10 20:12:49 +01005255
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005256 pairs = 0;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005257 if (kind == PyUnicode_4BYTE_KIND) {
5258 const Py_UCS4 *in = (const Py_UCS4 *)data;
5259 const Py_UCS4 *end = in + len;
5260 while (in < end)
5261 if (*in++ >= 0x10000)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005262 pairs++;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005263 }
5264 if (len > PY_SSIZE_T_MAX / 2 - pairs - (byteorder == 0))
Benjamin Peterson29060642009-01-31 22:14:21 +00005265 return PyErr_NoMemory();
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005266 bytesize = (len + pairs + (byteorder == 0)) * 2;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005267 v = PyBytes_FromStringAndSize(NULL, bytesize);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005268 if (v == NULL)
5269 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005270
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005271 /* output buffer is 2-bytes aligned */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02005272 assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 2));
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005273 out = (unsigned short *)PyBytes_AS_STRING(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005274 if (byteorder == 0)
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005275 *out++ = 0xFEFF;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005276 if (len == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005277 goto done;
Tim Peters772747b2001-08-09 22:21:55 +00005278
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005279 switch (kind) {
5280 case PyUnicode_1BYTE_KIND: {
5281 ucs1lib_utf16_encode(out, (const Py_UCS1 *)data, len, native_ordering);
5282 break;
Tim Peters772747b2001-08-09 22:21:55 +00005283 }
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005284 case PyUnicode_2BYTE_KIND: {
5285 ucs2lib_utf16_encode(out, (const Py_UCS2 *)data, len, native_ordering);
5286 break;
Tim Peters772747b2001-08-09 22:21:55 +00005287 }
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005288 case PyUnicode_4BYTE_KIND: {
5289 ucs4lib_utf16_encode(out, (const Py_UCS4 *)data, len, native_ordering);
5290 break;
5291 }
5292 default:
5293 assert(0);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005294 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005295
5296 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005297 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005298}
5299
Alexander Belopolsky40018472011-02-26 01:02:56 +00005300PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005301PyUnicode_EncodeUTF16(const Py_UNICODE *s,
5302 Py_ssize_t size,
5303 const char *errors,
5304 int byteorder)
5305{
5306 PyObject *result;
5307 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5308 if (tmp == NULL)
5309 return NULL;
5310 result = _PyUnicode_EncodeUTF16(tmp, errors, byteorder);
5311 Py_DECREF(tmp);
5312 return result;
5313}
5314
5315PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005316PyUnicode_AsUTF16String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005317{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005318 return _PyUnicode_EncodeUTF16(unicode, NULL, 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005319}
5320
5321/* --- Unicode Escape Codec ----------------------------------------------- */
5322
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005323/* Helper function for PyUnicode_DecodeUnicodeEscape, determines
5324 if all the escapes in the string make it still a valid ASCII string.
5325 Returns -1 if any escapes were found which cause the string to
5326 pop out of ASCII range. Otherwise returns the length of the
5327 required buffer to hold the string.
5328 */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02005329static Py_ssize_t
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005330length_of_escaped_ascii_string(const char *s, Py_ssize_t size)
5331{
5332 const unsigned char *p = (const unsigned char *)s;
5333 const unsigned char *end = p + size;
5334 Py_ssize_t length = 0;
5335
5336 if (size < 0)
5337 return -1;
5338
5339 for (; p < end; ++p) {
5340 if (*p > 127) {
5341 /* Non-ASCII */
5342 return -1;
5343 }
5344 else if (*p != '\\') {
5345 /* Normal character */
5346 ++length;
5347 }
5348 else {
5349 /* Backslash-escape, check next char */
5350 ++p;
5351 /* Escape sequence reaches till end of string or
5352 non-ASCII follow-up. */
5353 if (p >= end || *p > 127)
5354 return -1;
5355 switch (*p) {
5356 case '\n':
5357 /* backslash + \n result in zero characters */
5358 break;
5359 case '\\': case '\'': case '\"':
5360 case 'b': case 'f': case 't':
5361 case 'n': case 'r': case 'v': case 'a':
5362 ++length;
5363 break;
5364 case '0': case '1': case '2': case '3':
5365 case '4': case '5': case '6': case '7':
5366 case 'x': case 'u': case 'U': case 'N':
5367 /* these do not guarantee ASCII characters */
5368 return -1;
5369 default:
5370 /* count the backslash + the other character */
5371 length += 2;
5372 }
5373 }
5374 }
5375 return length;
5376}
5377
Fredrik Lundh06d12682001-01-24 07:59:11 +00005378static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
Marc-André Lemburg0f774e32000-06-28 16:43:35 +00005379
Alexander Belopolsky40018472011-02-26 01:02:56 +00005380PyObject *
5381PyUnicode_DecodeUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005382 Py_ssize_t size,
Victor Stinnerc17f5402011-09-29 00:16:58 +02005383 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005384{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005385 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005386 Py_ssize_t startinpos;
5387 Py_ssize_t endinpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005388 int j;
Victor Stinner7931d9a2011-11-04 00:22:48 +01005389 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005390 const char *end;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005391 char* message;
5392 Py_UCS4 chr = 0xffffffff; /* in case 'getcode' messes up */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005393 PyObject *errorHandler = NULL;
5394 PyObject *exc = NULL;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005395 Py_ssize_t len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005396 Py_ssize_t i;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005397
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005398 len = length_of_escaped_ascii_string(s, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005399
5400 /* After length_of_escaped_ascii_string() there are two alternatives,
5401 either the string is pure ASCII with named escapes like \n, etc.
5402 and we determined it's exact size (common case)
5403 or it contains \x, \u, ... escape sequences. then we create a
5404 legacy wchar string and resize it at the end of this function. */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005405 if (len >= 0) {
5406 v = PyUnicode_New(len, 127);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005407 if (!v)
5408 goto onError;
5409 assert(PyUnicode_KIND(v) == PyUnicode_1BYTE_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005410 }
5411 else {
5412 /* Escaped strings will always be longer than the resulting
5413 Unicode string, so we start with size here and then reduce the
5414 length after conversion to the true value.
5415 (but if the error callback returns a long replacement string
5416 we'll have to allocate more space) */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005417 v = PyUnicode_New(size, 127);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005418 if (!v)
5419 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005420 len = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005421 }
5422
Guido van Rossumd57fd912000-03-10 22:53:23 +00005423 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01005424 return v;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005425 i = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005426 end = s + size;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005427
Guido van Rossumd57fd912000-03-10 22:53:23 +00005428 while (s < end) {
5429 unsigned char c;
Victor Stinner24729f32011-11-10 20:31:37 +01005430 Py_UCS4 x;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005431 int digits;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005432
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005433 /* The only case in which i == ascii_length is a backslash
5434 followed by a newline. */
5435 assert(i <= len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005436
Guido van Rossumd57fd912000-03-10 22:53:23 +00005437 /* Non-escape characters are interpreted as Unicode ordinals */
5438 if (*s != '\\') {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005439 if (unicode_putchar(&v, &i, (unsigned char) *s++) < 0)
5440 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005441 continue;
5442 }
5443
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005444 startinpos = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005445 /* \ - Escapes */
5446 s++;
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005447 c = *s++;
5448 if (s > end)
5449 c = '\0'; /* Invalid after \ */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005450
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005451 /* The only case in which i == ascii_length is a backslash
5452 followed by a newline. */
5453 assert(i < len || (i == len && c == '\n'));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005454
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005455 switch (c) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005456
Benjamin Peterson29060642009-01-31 22:14:21 +00005457 /* \x escapes */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005458#define WRITECHAR(ch) \
5459 do { \
5460 if (unicode_putchar(&v, &i, ch) < 0) \
5461 goto onError; \
5462 }while(0)
5463
Guido van Rossumd57fd912000-03-10 22:53:23 +00005464 case '\n': break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005465 case '\\': WRITECHAR('\\'); break;
5466 case '\'': WRITECHAR('\''); break;
5467 case '\"': WRITECHAR('\"'); break;
5468 case 'b': WRITECHAR('\b'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005469 /* FF */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005470 case 'f': WRITECHAR('\014'); break;
5471 case 't': WRITECHAR('\t'); break;
5472 case 'n': WRITECHAR('\n'); break;
5473 case 'r': WRITECHAR('\r'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005474 /* VT */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005475 case 'v': WRITECHAR('\013'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005476 /* BEL, not classic C */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005477 case 'a': WRITECHAR('\007'); break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005478
Benjamin Peterson29060642009-01-31 22:14:21 +00005479 /* \OOO (octal) escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005480 case '0': case '1': case '2': case '3':
5481 case '4': case '5': case '6': case '7':
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005482 x = s[-1] - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005483 if (s < end && '0' <= *s && *s <= '7') {
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005484 x = (x<<3) + *s++ - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005485 if (s < end && '0' <= *s && *s <= '7')
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005486 x = (x<<3) + *s++ - '0';
Guido van Rossumd57fd912000-03-10 22:53:23 +00005487 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005488 WRITECHAR(x);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005489 break;
5490
Benjamin Peterson29060642009-01-31 22:14:21 +00005491 /* hex escapes */
5492 /* \xXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005493 case 'x':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005494 digits = 2;
5495 message = "truncated \\xXX escape";
5496 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005497
Benjamin Peterson29060642009-01-31 22:14:21 +00005498 /* \uXXXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005499 case 'u':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005500 digits = 4;
5501 message = "truncated \\uXXXX escape";
5502 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005503
Benjamin Peterson29060642009-01-31 22:14:21 +00005504 /* \UXXXXXXXX */
Fredrik Lundhdf846752000-09-03 11:29:49 +00005505 case 'U':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005506 digits = 8;
5507 message = "truncated \\UXXXXXXXX escape";
5508 hexescape:
5509 chr = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005510 if (s+digits>end) {
5511 endinpos = size;
5512 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005513 errors, &errorHandler,
5514 "unicodeescape", "end of string in escape sequence",
5515 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005516 &v, &i))
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005517 goto onError;
5518 goto nextByte;
5519 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005520 for (j = 0; j < digits; ++j) {
5521 c = (unsigned char) s[j];
David Malcolm96960882010-11-05 17:23:41 +00005522 if (!Py_ISXDIGIT(c)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005523 endinpos = (s+j+1)-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005524 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005525 errors, &errorHandler,
5526 "unicodeescape", message,
5527 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005528 &v, &i))
Fredrik Lundhdf846752000-09-03 11:29:49 +00005529 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005530 len = PyUnicode_GET_LENGTH(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005531 goto nextByte;
Fredrik Lundhdf846752000-09-03 11:29:49 +00005532 }
5533 chr = (chr<<4) & ~0xF;
5534 if (c >= '0' && c <= '9')
5535 chr += c - '0';
5536 else if (c >= 'a' && c <= 'f')
5537 chr += 10 + c - 'a';
5538 else
5539 chr += 10 + c - 'A';
5540 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005541 s += j;
Jeremy Hylton504de6b2003-10-06 05:08:26 +00005542 if (chr == 0xffffffff && PyErr_Occurred())
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005543 /* _decoding_error will have already written into the
5544 target buffer. */
5545 break;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005546 store:
Fredrik Lundhdf846752000-09-03 11:29:49 +00005547 /* when we get here, chr is a 32-bit unicode character */
Victor Stinner8faf8212011-12-08 22:14:11 +01005548 if (chr <= MAX_UNICODE) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005549 WRITECHAR(chr);
Fredrik Lundhdf846752000-09-03 11:29:49 +00005550 } else {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005551 endinpos = s-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005552 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005553 errors, &errorHandler,
5554 "unicodeescape", "illegal Unicode character",
5555 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005556 &v, &i))
Fredrik Lundhdf846752000-09-03 11:29:49 +00005557 goto onError;
5558 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00005559 break;
5560
Benjamin Peterson29060642009-01-31 22:14:21 +00005561 /* \N{name} */
Fredrik Lundhccc74732001-02-18 22:13:49 +00005562 case 'N':
5563 message = "malformed \\N character escape";
5564 if (ucnhash_CAPI == NULL) {
5565 /* load the unicode data module */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005566 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
5567 PyUnicodeData_CAPSULE_NAME, 1);
Fredrik Lundhccc74732001-02-18 22:13:49 +00005568 if (ucnhash_CAPI == NULL)
5569 goto ucnhashError;
5570 }
5571 if (*s == '{') {
5572 const char *start = s+1;
5573 /* look for the closing brace */
5574 while (*s != '}' && s < end)
5575 s++;
5576 if (s > start && s < end && *s == '}') {
5577 /* found a name. look it up in the unicode database */
5578 message = "unknown Unicode character name";
5579 s++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005580 if (ucnhash_CAPI->getcode(NULL, start, (int)(s-start-1),
Ezio Melotti931b8aa2011-10-21 21:57:36 +03005581 &chr, 0))
Fredrik Lundhccc74732001-02-18 22:13:49 +00005582 goto store;
5583 }
5584 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005585 endinpos = s-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005586 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005587 errors, &errorHandler,
5588 "unicodeescape", message,
5589 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005590 &v, &i))
Fredrik Lundhccc74732001-02-18 22:13:49 +00005591 goto onError;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005592 break;
5593
5594 default:
Walter Dörwald8c077222002-03-25 11:16:18 +00005595 if (s > end) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005596 message = "\\ at end of string";
5597 s--;
5598 endinpos = s-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005599 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005600 errors, &errorHandler,
5601 "unicodeescape", message,
5602 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005603 &v, &i))
Walter Dörwald8c077222002-03-25 11:16:18 +00005604 goto onError;
5605 }
5606 else {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005607 WRITECHAR('\\');
5608 WRITECHAR(s[-1]);
Walter Dörwald8c077222002-03-25 11:16:18 +00005609 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00005610 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005611 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005612 nextByte:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005613 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005614 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005615#undef WRITECHAR
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005616
Victor Stinner16e6a802011-12-12 13:24:15 +01005617 if (unicode_resize(&v, i) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005618 goto onError;
Walter Dörwaldd4ade082003-08-15 15:00:26 +00005619 Py_XDECREF(errorHandler);
5620 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01005621 return unicode_result(v);
Walter Dörwald8c077222002-03-25 11:16:18 +00005622
Benjamin Peterson29060642009-01-31 22:14:21 +00005623 ucnhashError:
Fredrik Lundh06d12682001-01-24 07:59:11 +00005624 PyErr_SetString(
5625 PyExc_UnicodeError,
5626 "\\N escapes not supported (can't load unicodedata module)"
5627 );
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00005628 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005629 Py_XDECREF(errorHandler);
5630 Py_XDECREF(exc);
Fredrik Lundhf6056062001-01-20 11:15:25 +00005631 return NULL;
5632
Benjamin Peterson29060642009-01-31 22:14:21 +00005633 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00005634 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005635 Py_XDECREF(errorHandler);
5636 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005637 return NULL;
5638}
5639
5640/* Return a Unicode-Escape string version of the Unicode object.
5641
5642 If quotes is true, the string is enclosed in u"" or u'' quotes as
5643 appropriate.
5644
5645*/
5646
Alexander Belopolsky40018472011-02-26 01:02:56 +00005647PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005648PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005649{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005650 Py_ssize_t i, len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005651 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005652 char *p;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005653 int kind;
5654 void *data;
5655 Py_ssize_t expandsize = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005656
Ezio Melottie7f90372012-10-05 03:33:31 +03005657 /* Initial allocation is based on the longest-possible character
Thomas Wouters89f507f2006-12-13 04:49:30 +00005658 escape.
5659
Ezio Melottie7f90372012-10-05 03:33:31 +03005660 For UCS1 strings it's '\xxx', 4 bytes per source character.
5661 For UCS2 strings it's '\uxxxx', 6 bytes per source character.
5662 For UCS4 strings it's '\U00xxxxxx', 10 bytes per source character.
Thomas Wouters89f507f2006-12-13 04:49:30 +00005663 */
5664
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005665 if (!PyUnicode_Check(unicode)) {
5666 PyErr_BadArgument();
5667 return NULL;
5668 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005669 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005670 return NULL;
5671 len = PyUnicode_GET_LENGTH(unicode);
5672 kind = PyUnicode_KIND(unicode);
5673 data = PyUnicode_DATA(unicode);
Benjamin Petersonead6b532011-12-20 17:23:42 -06005674 switch (kind) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005675 case PyUnicode_1BYTE_KIND: expandsize = 4; break;
5676 case PyUnicode_2BYTE_KIND: expandsize = 6; break;
5677 case PyUnicode_4BYTE_KIND: expandsize = 10; break;
5678 }
5679
5680 if (len == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005681 return PyBytes_FromStringAndSize(NULL, 0);
5682
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005683 if (len > (PY_SSIZE_T_MAX - 2 - 1) / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005684 return PyErr_NoMemory();
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005685
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005686 repr = PyBytes_FromStringAndSize(NULL,
Benjamin Peterson29060642009-01-31 22:14:21 +00005687 2
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005688 + expandsize*len
Benjamin Peterson29060642009-01-31 22:14:21 +00005689 + 1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005690 if (repr == NULL)
5691 return NULL;
5692
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005693 p = PyBytes_AS_STRING(repr);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005694
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005695 for (i = 0; i < len; i++) {
Victor Stinner3326cb62011-11-10 20:15:25 +01005696 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005697
Walter Dörwald79e913e2007-05-12 11:08:06 +00005698 /* Escape backslashes */
5699 if (ch == '\\') {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005700 *p++ = '\\';
5701 *p++ = (char) ch;
Walter Dörwald79e913e2007-05-12 11:08:06 +00005702 continue;
Tim Petersced69f82003-09-16 20:30:58 +00005703 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005704
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005705 /* Map 21-bit characters to '\U00xxxxxx' */
5706 else if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01005707 assert(ch <= MAX_UNICODE);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005708 *p++ = '\\';
5709 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005710 *p++ = Py_hexdigits[(ch >> 28) & 0x0000000F];
5711 *p++ = Py_hexdigits[(ch >> 24) & 0x0000000F];
5712 *p++ = Py_hexdigits[(ch >> 20) & 0x0000000F];
5713 *p++ = Py_hexdigits[(ch >> 16) & 0x0000000F];
5714 *p++ = Py_hexdigits[(ch >> 12) & 0x0000000F];
5715 *p++ = Py_hexdigits[(ch >> 8) & 0x0000000F];
5716 *p++ = Py_hexdigits[(ch >> 4) & 0x0000000F];
5717 *p++ = Py_hexdigits[ch & 0x0000000F];
Benjamin Peterson29060642009-01-31 22:14:21 +00005718 continue;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005719 }
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005720
Guido van Rossumd57fd912000-03-10 22:53:23 +00005721 /* Map 16-bit characters to '\uxxxx' */
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005722 if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005723 *p++ = '\\';
5724 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005725 *p++ = Py_hexdigits[(ch >> 12) & 0x000F];
5726 *p++ = Py_hexdigits[(ch >> 8) & 0x000F];
5727 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
5728 *p++ = Py_hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00005729 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005730
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005731 /* Map special whitespace to '\t', \n', '\r' */
5732 else if (ch == '\t') {
5733 *p++ = '\\';
5734 *p++ = 't';
5735 }
5736 else if (ch == '\n') {
5737 *p++ = '\\';
5738 *p++ = 'n';
5739 }
5740 else if (ch == '\r') {
5741 *p++ = '\\';
5742 *p++ = 'r';
5743 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005744
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005745 /* Map non-printable US ASCII to '\xhh' */
Marc-André Lemburg11326de2001-11-28 12:56:20 +00005746 else if (ch < ' ' || ch >= 0x7F) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005747 *p++ = '\\';
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005748 *p++ = 'x';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005749 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
5750 *p++ = Py_hexdigits[ch & 0x000F];
Tim Petersced69f82003-09-16 20:30:58 +00005751 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005752
Guido van Rossumd57fd912000-03-10 22:53:23 +00005753 /* Copy everything else as-is */
5754 else
5755 *p++ = (char) ch;
5756 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005757
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005758 assert(p - PyBytes_AS_STRING(repr) > 0);
5759 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0)
5760 return NULL;
5761 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005762}
5763
Alexander Belopolsky40018472011-02-26 01:02:56 +00005764PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005765PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
5766 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005767{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005768 PyObject *result;
5769 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5770 if (tmp == NULL)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005771 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005772 result = PyUnicode_AsUnicodeEscapeString(tmp);
5773 Py_DECREF(tmp);
5774 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005775}
5776
5777/* --- Raw Unicode Escape Codec ------------------------------------------- */
5778
Alexander Belopolsky40018472011-02-26 01:02:56 +00005779PyObject *
5780PyUnicode_DecodeRawUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005781 Py_ssize_t size,
5782 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005783{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005784 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005785 Py_ssize_t startinpos;
5786 Py_ssize_t endinpos;
5787 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01005788 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005789 const char *end;
5790 const char *bs;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005791 PyObject *errorHandler = NULL;
5792 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00005793
Guido van Rossumd57fd912000-03-10 22:53:23 +00005794 /* Escaped strings will always be longer than the resulting
5795 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005796 length after conversion to the true value. (But decoding error
5797 handler might have to resize the string) */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005798 v = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005799 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005800 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005801 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01005802 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005803 outpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005804 end = s + size;
5805 while (s < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005806 unsigned char c;
5807 Py_UCS4 x;
5808 int i;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00005809 int count;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005810
Benjamin Peterson29060642009-01-31 22:14:21 +00005811 /* Non-escape characters are interpreted as Unicode ordinals */
5812 if (*s != '\\') {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005813 if (unicode_putchar(&v, &outpos, (unsigned char)*s++) < 0)
5814 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005815 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00005816 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005817 startinpos = s-starts;
5818
5819 /* \u-escapes are only interpreted iff the number of leading
5820 backslashes if odd */
5821 bs = s;
5822 for (;s < end;) {
5823 if (*s != '\\')
5824 break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005825 if (unicode_putchar(&v, &outpos, (unsigned char)*s++) < 0)
5826 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005827 }
5828 if (((s - bs) & 1) == 0 ||
5829 s >= end ||
5830 (*s != 'u' && *s != 'U')) {
5831 continue;
5832 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005833 outpos--;
Benjamin Peterson29060642009-01-31 22:14:21 +00005834 count = *s=='u' ? 4 : 8;
5835 s++;
5836
5837 /* \uXXXX with 4 hex digits, \Uxxxxxxxx with 8 */
Benjamin Peterson29060642009-01-31 22:14:21 +00005838 for (x = 0, i = 0; i < count; ++i, ++s) {
5839 c = (unsigned char)*s;
David Malcolm96960882010-11-05 17:23:41 +00005840 if (!Py_ISXDIGIT(c)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005841 endinpos = s-starts;
5842 if (unicode_decode_call_errorhandler(
5843 errors, &errorHandler,
5844 "rawunicodeescape", "truncated \\uXXXX",
5845 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005846 &v, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00005847 goto onError;
5848 goto nextByte;
5849 }
5850 x = (x<<4) & ~0xF;
5851 if (c >= '0' && c <= '9')
5852 x += c - '0';
5853 else if (c >= 'a' && c <= 'f')
5854 x += 10 + c - 'a';
5855 else
5856 x += 10 + c - 'A';
5857 }
Victor Stinner8faf8212011-12-08 22:14:11 +01005858 if (x <= MAX_UNICODE) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005859 if (unicode_putchar(&v, &outpos, x) < 0)
5860 goto onError;
Christian Heimesfe337bf2008-03-23 21:54:12 +00005861 } else {
5862 endinpos = s-starts;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00005863 if (unicode_decode_call_errorhandler(
5864 errors, &errorHandler,
5865 "rawunicodeescape", "\\Uxxxxxxxx out of range",
Benjamin Peterson29060642009-01-31 22:14:21 +00005866 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005867 &v, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00005868 goto onError;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00005869 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005870 nextByte:
5871 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005872 }
Victor Stinner16e6a802011-12-12 13:24:15 +01005873 if (unicode_resize(&v, outpos) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005874 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005875 Py_XDECREF(errorHandler);
5876 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01005877 return unicode_result(v);
Tim Petersced69f82003-09-16 20:30:58 +00005878
Benjamin Peterson29060642009-01-31 22:14:21 +00005879 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00005880 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005881 Py_XDECREF(errorHandler);
5882 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005883 return NULL;
5884}
5885
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005886
Alexander Belopolsky40018472011-02-26 01:02:56 +00005887PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005888PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005889{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005890 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005891 char *p;
5892 char *q;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005893 Py_ssize_t expandsize, pos;
5894 int kind;
5895 void *data;
5896 Py_ssize_t len;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005897
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005898 if (!PyUnicode_Check(unicode)) {
5899 PyErr_BadArgument();
5900 return NULL;
5901 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005902 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005903 return NULL;
5904 kind = PyUnicode_KIND(unicode);
5905 data = PyUnicode_DATA(unicode);
5906 len = PyUnicode_GET_LENGTH(unicode);
Benjamin Peterson1518e872011-11-23 10:44:52 -06005907 /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6
5908 bytes, and 1 byte characters 4. */
5909 expandsize = kind * 2 + 2;
Victor Stinner0e368262011-11-10 20:12:49 +01005910
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005911 if (len > PY_SSIZE_T_MAX / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005912 return PyErr_NoMemory();
Benjamin Peterson14339b62009-01-31 16:36:08 +00005913
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005914 repr = PyBytes_FromStringAndSize(NULL, expandsize * len);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005915 if (repr == NULL)
5916 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005917 if (len == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005918 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005919
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005920 p = q = PyBytes_AS_STRING(repr);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005921 for (pos = 0; pos < len; pos++) {
5922 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Benjamin Peterson29060642009-01-31 22:14:21 +00005923 /* Map 32-bit characters to '\Uxxxxxxxx' */
5924 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01005925 assert(ch <= MAX_UNICODE);
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00005926 *p++ = '\\';
5927 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005928 *p++ = Py_hexdigits[(ch >> 28) & 0xf];
5929 *p++ = Py_hexdigits[(ch >> 24) & 0xf];
5930 *p++ = Py_hexdigits[(ch >> 20) & 0xf];
5931 *p++ = Py_hexdigits[(ch >> 16) & 0xf];
5932 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
5933 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
5934 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
5935 *p++ = Py_hexdigits[ch & 15];
Tim Petersced69f82003-09-16 20:30:58 +00005936 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005937 /* Map 16-bit characters to '\uxxxx' */
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005938 else if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005939 *p++ = '\\';
5940 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005941 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
5942 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
5943 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
5944 *p++ = Py_hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00005945 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005946 /* Copy everything else as-is */
5947 else
Guido van Rossumd57fd912000-03-10 22:53:23 +00005948 *p++ = (char) ch;
5949 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005950
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005951 assert(p > q);
5952 if (_PyBytes_Resize(&repr, p - q) < 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005953 return NULL;
5954 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005955}
5956
Alexander Belopolsky40018472011-02-26 01:02:56 +00005957PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005958PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
5959 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005960{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005961 PyObject *result;
5962 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5963 if (tmp == NULL)
Walter Dörwald711005d2007-05-12 12:03:26 +00005964 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005965 result = PyUnicode_AsRawUnicodeEscapeString(tmp);
5966 Py_DECREF(tmp);
5967 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005968}
5969
Walter Dörwalda47d1c02005-08-30 10:23:14 +00005970/* --- Unicode Internal Codec ------------------------------------------- */
5971
Alexander Belopolsky40018472011-02-26 01:02:56 +00005972PyObject *
5973_PyUnicode_DecodeUnicodeInternal(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005974 Py_ssize_t size,
5975 const char *errors)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00005976{
5977 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005978 Py_ssize_t startinpos;
5979 Py_ssize_t endinpos;
5980 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01005981 PyObject *v;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00005982 const char *end;
5983 const char *reason;
5984 PyObject *errorHandler = NULL;
5985 PyObject *exc = NULL;
5986
Victor Stinner9f4b1e92011-11-10 20:56:30 +01005987 if (PyErr_WarnEx(PyExc_DeprecationWarning,
Ezio Melotti11060a42011-11-16 09:39:10 +02005988 "unicode_internal codec has been deprecated",
Victor Stinner9f4b1e92011-11-10 20:56:30 +01005989 1))
5990 return NULL;
5991
Thomas Wouters89f507f2006-12-13 04:49:30 +00005992 /* XXX overflow detection missing */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005993 v = PyUnicode_New((size+Py_UNICODE_SIZE-1)/ Py_UNICODE_SIZE, 127);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00005994 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005995 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005996 if (PyUnicode_GET_LENGTH(v) == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01005997 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005998 outpos = 0;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00005999 end = s + size;
6000
6001 while (s < end) {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006002 Py_UNICODE uch;
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006003 Py_UCS4 ch;
6004 /* We copy the raw representation one byte at a time because the
6005 pointer may be unaligned (see test_codeccallbacks). */
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006006 ((char *) &uch)[0] = s[0];
6007 ((char *) &uch)[1] = s[1];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006008#ifdef Py_UNICODE_WIDE
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006009 ((char *) &uch)[2] = s[2];
6010 ((char *) &uch)[3] = s[3];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006011#endif
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006012 ch = uch;
6013
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006014 /* We have to sanity check the raw data, otherwise doom looms for
6015 some malformed UCS-4 data. */
6016 if (
Benjamin Peterson29060642009-01-31 22:14:21 +00006017#ifdef Py_UNICODE_WIDE
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006018 ch > 0x10ffff ||
Benjamin Peterson29060642009-01-31 22:14:21 +00006019#endif
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006020 end-s < Py_UNICODE_SIZE
6021 )
Benjamin Peterson29060642009-01-31 22:14:21 +00006022 {
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006023 startinpos = s - starts;
6024 if (end-s < Py_UNICODE_SIZE) {
6025 endinpos = end-starts;
6026 reason = "truncated input";
6027 }
6028 else {
6029 endinpos = s - starts + Py_UNICODE_SIZE;
6030 reason = "illegal code point (> 0x10FFFF)";
6031 }
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006032 if (unicode_decode_call_errorhandler(
6033 errors, &errorHandler,
6034 "unicode_internal", reason,
Walter Dörwalde78178e2007-07-30 13:31:40 +00006035 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006036 &v, &outpos))
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006037 goto onError;
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006038 continue;
6039 }
6040
6041 s += Py_UNICODE_SIZE;
6042#ifndef Py_UNICODE_WIDE
Victor Stinner551ac952011-11-29 22:58:13 +01006043 if (Py_UNICODE_IS_HIGH_SURROGATE(ch) && s < end)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006044 {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006045 Py_UNICODE uch2;
6046 ((char *) &uch2)[0] = s[0];
6047 ((char *) &uch2)[1] = s[1];
Victor Stinner551ac952011-11-29 22:58:13 +01006048 if (Py_UNICODE_IS_LOW_SURROGATE(uch2))
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006049 {
Victor Stinner551ac952011-11-29 22:58:13 +01006050 ch = Py_UNICODE_JOIN_SURROGATES(uch, uch2);
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006051 s += Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006052 }
6053 }
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006054#endif
6055
6056 if (unicode_putchar(&v, &outpos, ch) < 0)
6057 goto onError;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006058 }
6059
Victor Stinner16e6a802011-12-12 13:24:15 +01006060 if (unicode_resize(&v, outpos) < 0)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006061 goto onError;
6062 Py_XDECREF(errorHandler);
6063 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006064 return unicode_result(v);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006065
Benjamin Peterson29060642009-01-31 22:14:21 +00006066 onError:
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006067 Py_XDECREF(v);
6068 Py_XDECREF(errorHandler);
6069 Py_XDECREF(exc);
6070 return NULL;
6071}
6072
Guido van Rossumd57fd912000-03-10 22:53:23 +00006073/* --- Latin-1 Codec ------------------------------------------------------ */
6074
Alexander Belopolsky40018472011-02-26 01:02:56 +00006075PyObject *
6076PyUnicode_DecodeLatin1(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006077 Py_ssize_t size,
6078 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006079{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006080 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Victor Stinnere57b1c02011-09-28 22:20:48 +02006081 return _PyUnicode_FromUCS1((unsigned char*)s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006082}
6083
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006084/* create or adjust a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006085static void
6086make_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006087 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006088 PyObject *unicode,
6089 Py_ssize_t startpos, Py_ssize_t endpos,
6090 const char *reason)
6091{
6092 if (*exceptionObject == NULL) {
6093 *exceptionObject = PyObject_CallFunction(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006094 PyExc_UnicodeEncodeError, "sOnns",
Martin v. Löwis9e816682011-11-02 12:45:42 +01006095 encoding, unicode, startpos, endpos, reason);
6096 }
6097 else {
6098 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
6099 goto onError;
6100 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
6101 goto onError;
6102 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
6103 goto onError;
6104 return;
6105 onError:
6106 Py_DECREF(*exceptionObject);
6107 *exceptionObject = NULL;
6108 }
6109}
6110
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006111/* raises a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006112static void
6113raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006114 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006115 PyObject *unicode,
6116 Py_ssize_t startpos, Py_ssize_t endpos,
6117 const char *reason)
6118{
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006119 make_encode_exception(exceptionObject,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006120 encoding, unicode, startpos, endpos, reason);
6121 if (*exceptionObject != NULL)
6122 PyCodec_StrictErrors(*exceptionObject);
6123}
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006124
6125/* error handling callback helper:
6126 build arguments, call the callback and check the arguments,
6127 put the result into newpos and return the replacement string, which
6128 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006129static PyObject *
6130unicode_encode_call_errorhandler(const char *errors,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006131 PyObject **errorHandler,
6132 const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006133 PyObject *unicode, PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006134 Py_ssize_t startpos, Py_ssize_t endpos,
6135 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006136{
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006137 static char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006138 Py_ssize_t len;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006139 PyObject *restuple;
6140 PyObject *resunicode;
6141
6142 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006143 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006144 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006145 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006146 }
6147
Benjamin Petersonbac79492012-01-14 13:34:47 -05006148 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006149 return NULL;
6150 len = PyUnicode_GET_LENGTH(unicode);
6151
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006152 make_encode_exception(exceptionObject,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006153 encoding, unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006154 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006155 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006156
6157 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00006158 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006159 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006160 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006161 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006162 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00006163 Py_DECREF(restuple);
6164 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006165 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006166 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00006167 &resunicode, newpos)) {
6168 Py_DECREF(restuple);
6169 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006170 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006171 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
6172 PyErr_SetString(PyExc_TypeError, &argparse[3]);
6173 Py_DECREF(restuple);
6174 return NULL;
6175 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006176 if (*newpos<0)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006177 *newpos = len + *newpos;
6178 if (*newpos<0 || *newpos>len) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006179 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
6180 Py_DECREF(restuple);
6181 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00006182 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006183 Py_INCREF(resunicode);
6184 Py_DECREF(restuple);
6185 return resunicode;
6186}
6187
Alexander Belopolsky40018472011-02-26 01:02:56 +00006188static PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006189unicode_encode_ucs1(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006190 const char *errors,
Victor Stinnerfcd96532011-11-04 00:28:50 +01006191 unsigned int limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006192{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006193 /* input state */
6194 Py_ssize_t pos=0, size;
6195 int kind;
6196 void *data;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006197 /* output object */
6198 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006199 /* pointer into the output */
6200 char *str;
6201 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00006202 Py_ssize_t ressize;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006203 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
6204 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006205 PyObject *errorHandler = NULL;
6206 PyObject *exc = NULL;
6207 /* the following variable is used for caching string comparisons
6208 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
6209 int known_errorHandler = -1;
6210
Benjamin Petersonbac79492012-01-14 13:34:47 -05006211 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006212 return NULL;
6213 size = PyUnicode_GET_LENGTH(unicode);
6214 kind = PyUnicode_KIND(unicode);
6215 data = PyUnicode_DATA(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006216 /* allocate enough for a simple encoding without
6217 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00006218 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00006219 return PyBytes_FromStringAndSize(NULL, 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006220 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006221 if (res == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00006222 return NULL;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006223 str = PyBytes_AS_STRING(res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006224 ressize = size;
6225
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006226 while (pos < size) {
6227 Py_UCS4 c = PyUnicode_READ(kind, data, pos);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006228
Benjamin Peterson29060642009-01-31 22:14:21 +00006229 /* can we encode this? */
6230 if (c<limit) {
6231 /* no overflow check, because we know that the space is enough */
6232 *str++ = (char)c;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006233 ++pos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006234 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006235 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006236 Py_ssize_t requiredsize;
6237 PyObject *repunicode;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006238 Py_ssize_t repsize, newpos, respos, i;
Benjamin Peterson29060642009-01-31 22:14:21 +00006239 /* startpos for collecting unencodable chars */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006240 Py_ssize_t collstart = pos;
6241 Py_ssize_t collend = pos;
Benjamin Peterson29060642009-01-31 22:14:21 +00006242 /* find all unecodable characters */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006243 while ((collend < size) && (PyUnicode_READ(kind, data, collend)>=limit))
Benjamin Peterson29060642009-01-31 22:14:21 +00006244 ++collend;
6245 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
6246 if (known_errorHandler==-1) {
6247 if ((errors==NULL) || (!strcmp(errors, "strict")))
6248 known_errorHandler = 1;
6249 else if (!strcmp(errors, "replace"))
6250 known_errorHandler = 2;
6251 else if (!strcmp(errors, "ignore"))
6252 known_errorHandler = 3;
6253 else if (!strcmp(errors, "xmlcharrefreplace"))
6254 known_errorHandler = 4;
6255 else
6256 known_errorHandler = 0;
6257 }
6258 switch (known_errorHandler) {
6259 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006260 raise_encode_exception(&exc, encoding, unicode, collstart, collend, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006261 goto onError;
6262 case 2: /* replace */
6263 while (collstart++<collend)
6264 *str++ = '?'; /* fall through */
6265 case 3: /* ignore */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006266 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006267 break;
6268 case 4: /* xmlcharrefreplace */
6269 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006270 /* determine replacement size */
6271 for (i = collstart, repsize = 0; i < collend; ++i) {
6272 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
6273 if (ch < 10)
Benjamin Peterson29060642009-01-31 22:14:21 +00006274 repsize += 2+1+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006275 else if (ch < 100)
Benjamin Peterson29060642009-01-31 22:14:21 +00006276 repsize += 2+2+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006277 else if (ch < 1000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006278 repsize += 2+3+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006279 else if (ch < 10000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006280 repsize += 2+4+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006281 else if (ch < 100000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006282 repsize += 2+5+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006283 else if (ch < 1000000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006284 repsize += 2+6+1;
Victor Stinner0d3721d2011-11-22 03:27:53 +01006285 else {
Victor Stinner8faf8212011-12-08 22:14:11 +01006286 assert(ch <= MAX_UNICODE);
Benjamin Peterson29060642009-01-31 22:14:21 +00006287 repsize += 2+7+1;
Victor Stinner0d3721d2011-11-22 03:27:53 +01006288 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006289 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006290 requiredsize = respos+repsize+(size-collend);
Benjamin Peterson29060642009-01-31 22:14:21 +00006291 if (requiredsize > ressize) {
6292 if (requiredsize<2*ressize)
6293 requiredsize = 2*ressize;
6294 if (_PyBytes_Resize(&res, requiredsize))
6295 goto onError;
6296 str = PyBytes_AS_STRING(res) + respos;
6297 ressize = requiredsize;
6298 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006299 /* generate replacement */
6300 for (i = collstart; i < collend; ++i) {
6301 str += sprintf(str, "&#%d;", PyUnicode_READ(kind, data, i));
Benjamin Peterson29060642009-01-31 22:14:21 +00006302 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006303 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006304 break;
6305 default:
6306 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006307 encoding, reason, unicode, &exc,
6308 collstart, collend, &newpos);
6309 if (repunicode == NULL || (PyUnicode_Check(repunicode) &&
Benjamin Petersonbac79492012-01-14 13:34:47 -05006310 PyUnicode_READY(repunicode) == -1))
Benjamin Peterson29060642009-01-31 22:14:21 +00006311 goto onError;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006312 if (PyBytes_Check(repunicode)) {
6313 /* Directly copy bytes result to output. */
6314 repsize = PyBytes_Size(repunicode);
6315 if (repsize > 1) {
6316 /* Make room for all additional bytes. */
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006317 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006318 if (_PyBytes_Resize(&res, ressize+repsize-1)) {
6319 Py_DECREF(repunicode);
6320 goto onError;
6321 }
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006322 str = PyBytes_AS_STRING(res) + respos;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006323 ressize += repsize-1;
6324 }
6325 memcpy(str, PyBytes_AsString(repunicode), repsize);
6326 str += repsize;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006327 pos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006328 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006329 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006330 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006331 /* need more space? (at least enough for what we
6332 have+the replacement+the rest of the string, so
6333 we won't have to check space for encodable characters) */
6334 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006335 repsize = PyUnicode_GET_LENGTH(repunicode);
6336 requiredsize = respos+repsize+(size-collend);
Benjamin Peterson29060642009-01-31 22:14:21 +00006337 if (requiredsize > ressize) {
6338 if (requiredsize<2*ressize)
6339 requiredsize = 2*ressize;
6340 if (_PyBytes_Resize(&res, requiredsize)) {
6341 Py_DECREF(repunicode);
6342 goto onError;
6343 }
6344 str = PyBytes_AS_STRING(res) + respos;
6345 ressize = requiredsize;
6346 }
6347 /* check if there is anything unencodable in the replacement
6348 and copy it to the output */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006349 for (i = 0; repsize-->0; ++i, ++str) {
6350 c = PyUnicode_READ_CHAR(repunicode, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00006351 if (c >= limit) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006352 raise_encode_exception(&exc, encoding, unicode,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006353 pos, pos+1, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006354 Py_DECREF(repunicode);
6355 goto onError;
6356 }
6357 *str = (char)c;
6358 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006359 pos = newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006360 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006361 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00006362 }
6363 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006364 /* Resize if we allocated to much */
6365 size = str - PyBytes_AS_STRING(res);
6366 if (size < ressize) { /* If this falls res will be NULL */
Alexandre Vassalottibad1b922008-12-27 09:49:09 +00006367 assert(size >= 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006368 if (_PyBytes_Resize(&res, size) < 0)
6369 goto onError;
6370 }
6371
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006372 Py_XDECREF(errorHandler);
6373 Py_XDECREF(exc);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006374 return res;
6375
6376 onError:
6377 Py_XDECREF(res);
6378 Py_XDECREF(errorHandler);
6379 Py_XDECREF(exc);
6380 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006381}
6382
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006383/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006384PyObject *
6385PyUnicode_EncodeLatin1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006386 Py_ssize_t size,
6387 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006388{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006389 PyObject *result;
6390 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6391 if (unicode == NULL)
6392 return NULL;
6393 result = unicode_encode_ucs1(unicode, errors, 256);
6394 Py_DECREF(unicode);
6395 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006396}
6397
Alexander Belopolsky40018472011-02-26 01:02:56 +00006398PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006399_PyUnicode_AsLatin1String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006400{
6401 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006402 PyErr_BadArgument();
6403 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006404 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006405 if (PyUnicode_READY(unicode) == -1)
6406 return NULL;
6407 /* Fast path: if it is a one-byte string, construct
6408 bytes object directly. */
6409 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND)
6410 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6411 PyUnicode_GET_LENGTH(unicode));
6412 /* Non-Latin-1 characters present. Defer to above function to
6413 raise the exception. */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006414 return unicode_encode_ucs1(unicode, errors, 256);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006415}
6416
6417PyObject*
6418PyUnicode_AsLatin1String(PyObject *unicode)
6419{
6420 return _PyUnicode_AsLatin1String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006421}
6422
6423/* --- 7-bit ASCII Codec -------------------------------------------------- */
6424
Alexander Belopolsky40018472011-02-26 01:02:56 +00006425PyObject *
6426PyUnicode_DecodeASCII(const char *s,
6427 Py_ssize_t size,
6428 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006429{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006430 const char *starts = s;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006431 PyObject *unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006432 int kind;
6433 void *data;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006434 Py_ssize_t startinpos;
6435 Py_ssize_t endinpos;
6436 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006437 const char *e;
6438 PyObject *errorHandler = NULL;
6439 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006440
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006441 if (size == 0) {
6442 Py_INCREF(unicode_empty);
6443 return unicode_empty;
6444 }
6445
Guido van Rossumd57fd912000-03-10 22:53:23 +00006446 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Victor Stinner702c7342011-10-05 13:50:52 +02006447 if (size == 1 && (unsigned char)s[0] < 128)
6448 return get_latin1_char((unsigned char)s[0]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006449
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006450 unicode = PyUnicode_New(size, 127);
6451 if (unicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006452 goto onError;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006453
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006454 e = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006455 data = PyUnicode_1BYTE_DATA(unicode);
6456 outpos = ascii_decode(s, e, (Py_UCS1 *)data);
6457 if (outpos == size)
6458 return unicode;
6459
6460 s += outpos;
6461 kind = PyUnicode_1BYTE_KIND;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006462 while (s < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006463 register unsigned char c = (unsigned char)*s;
6464 if (c < 128) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006465 PyUnicode_WRITE(kind, data, outpos++, c);
Benjamin Peterson29060642009-01-31 22:14:21 +00006466 ++s;
6467 }
6468 else {
6469 startinpos = s-starts;
6470 endinpos = startinpos + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00006471 if (unicode_decode_call_errorhandler(
6472 errors, &errorHandler,
6473 "ascii", "ordinal not in range(128)",
6474 &starts, &e, &startinpos, &endinpos, &exc, &s,
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006475 &unicode, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00006476 goto onError;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006477 kind = PyUnicode_KIND(unicode);
6478 data = PyUnicode_DATA(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00006479 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006480 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006481 if (unicode_resize(&unicode, outpos) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006482 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006483 Py_XDECREF(errorHandler);
6484 Py_XDECREF(exc);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006485 assert(_PyUnicode_CheckConsistency(unicode, 1));
6486 return unicode;
Tim Petersced69f82003-09-16 20:30:58 +00006487
Benjamin Peterson29060642009-01-31 22:14:21 +00006488 onError:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006489 Py_XDECREF(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006490 Py_XDECREF(errorHandler);
6491 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006492 return NULL;
6493}
6494
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006495/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006496PyObject *
6497PyUnicode_EncodeASCII(const Py_UNICODE *p,
6498 Py_ssize_t size,
6499 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006500{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006501 PyObject *result;
6502 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6503 if (unicode == NULL)
6504 return NULL;
6505 result = unicode_encode_ucs1(unicode, errors, 128);
6506 Py_DECREF(unicode);
6507 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006508}
6509
Alexander Belopolsky40018472011-02-26 01:02:56 +00006510PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006511_PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006512{
6513 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006514 PyErr_BadArgument();
6515 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006516 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006517 if (PyUnicode_READY(unicode) == -1)
6518 return NULL;
6519 /* Fast path: if it is an ASCII-only string, construct bytes object
6520 directly. Else defer to above function to raise the exception. */
6521 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
6522 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6523 PyUnicode_GET_LENGTH(unicode));
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006524 return unicode_encode_ucs1(unicode, errors, 128);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006525}
6526
6527PyObject *
6528PyUnicode_AsASCIIString(PyObject *unicode)
6529{
6530 return _PyUnicode_AsASCIIString(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006531}
6532
Victor Stinner99b95382011-07-04 14:23:54 +02006533#ifdef HAVE_MBCS
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006534
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006535/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006536
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00006537#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006538#define NEED_RETRY
6539#endif
6540
Victor Stinner3a50e702011-10-18 21:21:00 +02006541#ifndef WC_ERR_INVALID_CHARS
6542# define WC_ERR_INVALID_CHARS 0x0080
6543#endif
6544
6545static char*
6546code_page_name(UINT code_page, PyObject **obj)
6547{
6548 *obj = NULL;
6549 if (code_page == CP_ACP)
6550 return "mbcs";
6551 if (code_page == CP_UTF7)
6552 return "CP_UTF7";
6553 if (code_page == CP_UTF8)
6554 return "CP_UTF8";
6555
6556 *obj = PyBytes_FromFormat("cp%u", code_page);
6557 if (*obj == NULL)
6558 return NULL;
6559 return PyBytes_AS_STRING(*obj);
6560}
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006561
Alexander Belopolsky40018472011-02-26 01:02:56 +00006562static int
Victor Stinner3a50e702011-10-18 21:21:00 +02006563is_dbcs_lead_byte(UINT code_page, const char *s, int offset)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006564{
6565 const char *curr = s + offset;
Victor Stinner3a50e702011-10-18 21:21:00 +02006566 const char *prev;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006567
Victor Stinner3a50e702011-10-18 21:21:00 +02006568 if (!IsDBCSLeadByteEx(code_page, *curr))
6569 return 0;
6570
6571 prev = CharPrevExA(code_page, s, curr, 0);
6572 if (prev == curr)
6573 return 1;
6574 /* FIXME: This code is limited to "true" double-byte encodings,
6575 as it assumes an incomplete character consists of a single
6576 byte. */
6577 if (curr - prev == 2)
6578 return 1;
6579 if (!IsDBCSLeadByteEx(code_page, *prev))
6580 return 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006581 return 0;
6582}
6583
Victor Stinner3a50e702011-10-18 21:21:00 +02006584static DWORD
6585decode_code_page_flags(UINT code_page)
6586{
6587 if (code_page == CP_UTF7) {
6588 /* The CP_UTF7 decoder only supports flags=0 */
6589 return 0;
6590 }
6591 else
6592 return MB_ERR_INVALID_CHARS;
6593}
6594
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006595/*
Victor Stinner3a50e702011-10-18 21:21:00 +02006596 * Decode a byte string from a Windows code page into unicode object in strict
6597 * mode.
6598 *
6599 * Returns consumed size if succeed, returns -2 on decode error, or raise a
6600 * WindowsError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006601 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006602static int
Victor Stinner3a50e702011-10-18 21:21:00 +02006603decode_code_page_strict(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01006604 PyObject **v,
Victor Stinner3a50e702011-10-18 21:21:00 +02006605 const char *in,
6606 int insize)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006607{
Victor Stinner3a50e702011-10-18 21:21:00 +02006608 const DWORD flags = decode_code_page_flags(code_page);
Victor Stinner24729f32011-11-10 20:31:37 +01006609 wchar_t *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02006610 DWORD outsize;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006611
6612 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02006613 assert(insize > 0);
6614 outsize = MultiByteToWideChar(code_page, flags, in, insize, NULL, 0);
6615 if (outsize <= 0)
6616 goto error;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006617
6618 if (*v == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006619 /* Create unicode object */
Victor Stinnerab595942011-12-17 04:59:06 +01006620 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01006621 *v = (PyObject*)_PyUnicode_New(outsize);
Benjamin Peterson29060642009-01-31 22:14:21 +00006622 if (*v == NULL)
6623 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02006624 out = PyUnicode_AS_UNICODE(*v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006625 }
6626 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006627 /* Extend unicode object */
Victor Stinner3a50e702011-10-18 21:21:00 +02006628 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
Victor Stinner16e6a802011-12-12 13:24:15 +01006629 if (unicode_resize(v, n + outsize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006630 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02006631 out = PyUnicode_AS_UNICODE(*v) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006632 }
6633
6634 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02006635 outsize = MultiByteToWideChar(code_page, flags, in, insize, out, outsize);
6636 if (outsize <= 0)
6637 goto error;
6638 return insize;
Victor Stinner554f3f02010-06-16 23:33:54 +00006639
Victor Stinner3a50e702011-10-18 21:21:00 +02006640error:
6641 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
6642 return -2;
6643 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00006644 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006645}
6646
Victor Stinner3a50e702011-10-18 21:21:00 +02006647/*
6648 * Decode a byte string from a code page into unicode object with an error
6649 * handler.
6650 *
6651 * Returns consumed size if succeed, or raise a WindowsError or
6652 * UnicodeDecodeError exception and returns -1 on error.
6653 */
6654static int
6655decode_code_page_errors(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01006656 PyObject **v,
6657 const char *in, const int size,
Victor Stinner3a50e702011-10-18 21:21:00 +02006658 const char *errors)
6659{
6660 const char *startin = in;
6661 const char *endin = in + size;
6662 const DWORD flags = decode_code_page_flags(code_page);
6663 /* Ideally, we should get reason from FormatMessage. This is the Windows
6664 2000 English version of the message. */
6665 const char *reason = "No mapping for the Unicode character exists "
6666 "in the target code page.";
6667 /* each step cannot decode more than 1 character, but a character can be
6668 represented as a surrogate pair */
6669 wchar_t buffer[2], *startout, *out;
6670 int insize, outsize;
6671 PyObject *errorHandler = NULL;
6672 PyObject *exc = NULL;
6673 PyObject *encoding_obj = NULL;
6674 char *encoding;
6675 DWORD err;
6676 int ret = -1;
6677
6678 assert(size > 0);
6679
6680 encoding = code_page_name(code_page, &encoding_obj);
6681 if (encoding == NULL)
6682 return -1;
6683
6684 if (errors == NULL || strcmp(errors, "strict") == 0) {
6685 /* The last error was ERROR_NO_UNICODE_TRANSLATION, then we raise a
6686 UnicodeDecodeError. */
6687 make_decode_exception(&exc, encoding, in, size, 0, 0, reason);
6688 if (exc != NULL) {
6689 PyCodec_StrictErrors(exc);
6690 Py_CLEAR(exc);
6691 }
6692 goto error;
6693 }
6694
6695 if (*v == NULL) {
6696 /* Create unicode object */
6697 if (size > PY_SSIZE_T_MAX / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
6698 PyErr_NoMemory();
6699 goto error;
6700 }
Victor Stinnerab595942011-12-17 04:59:06 +01006701 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01006702 *v = (PyObject*)_PyUnicode_New(size * Py_ARRAY_LENGTH(buffer));
Victor Stinner3a50e702011-10-18 21:21:00 +02006703 if (*v == NULL)
6704 goto error;
6705 startout = PyUnicode_AS_UNICODE(*v);
6706 }
6707 else {
6708 /* Extend unicode object */
6709 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
6710 if (size > (PY_SSIZE_T_MAX - n) / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
6711 PyErr_NoMemory();
6712 goto error;
6713 }
Victor Stinner16e6a802011-12-12 13:24:15 +01006714 if (unicode_resize(v, n + size * Py_ARRAY_LENGTH(buffer)) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02006715 goto error;
6716 startout = PyUnicode_AS_UNICODE(*v) + n;
6717 }
6718
6719 /* Decode the byte string character per character */
6720 out = startout;
6721 while (in < endin)
6722 {
6723 /* Decode a character */
6724 insize = 1;
6725 do
6726 {
6727 outsize = MultiByteToWideChar(code_page, flags,
6728 in, insize,
6729 buffer, Py_ARRAY_LENGTH(buffer));
6730 if (outsize > 0)
6731 break;
6732 err = GetLastError();
6733 if (err != ERROR_NO_UNICODE_TRANSLATION
6734 && err != ERROR_INSUFFICIENT_BUFFER)
6735 {
6736 PyErr_SetFromWindowsErr(0);
6737 goto error;
6738 }
6739 insize++;
6740 }
6741 /* 4=maximum length of a UTF-8 sequence */
6742 while (insize <= 4 && (in + insize) <= endin);
6743
6744 if (outsize <= 0) {
6745 Py_ssize_t startinpos, endinpos, outpos;
6746
6747 startinpos = in - startin;
6748 endinpos = startinpos + 1;
6749 outpos = out - PyUnicode_AS_UNICODE(*v);
6750 if (unicode_decode_call_errorhandler(
6751 errors, &errorHandler,
6752 encoding, reason,
6753 &startin, &endin, &startinpos, &endinpos, &exc, &in,
Victor Stinner596a6c42011-11-09 00:02:18 +01006754 v, &outpos))
Victor Stinner3a50e702011-10-18 21:21:00 +02006755 {
6756 goto error;
6757 }
Victor Stinner596a6c42011-11-09 00:02:18 +01006758 out = PyUnicode_AS_UNICODE(*v) + outpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02006759 }
6760 else {
6761 in += insize;
6762 memcpy(out, buffer, outsize * sizeof(wchar_t));
6763 out += outsize;
6764 }
6765 }
6766
6767 /* write a NUL character at the end */
6768 *out = 0;
6769
6770 /* Extend unicode object */
6771 outsize = out - startout;
6772 assert(outsize <= PyUnicode_WSTR_LENGTH(*v));
Victor Stinner16e6a802011-12-12 13:24:15 +01006773 if (unicode_resize(v, outsize) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02006774 goto error;
Victor Stinner76a31a62011-11-04 00:05:13 +01006775 ret = size;
Victor Stinner3a50e702011-10-18 21:21:00 +02006776
6777error:
6778 Py_XDECREF(encoding_obj);
6779 Py_XDECREF(errorHandler);
6780 Py_XDECREF(exc);
6781 return ret;
6782}
6783
Victor Stinner3a50e702011-10-18 21:21:00 +02006784static PyObject *
6785decode_code_page_stateful(int code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01006786 const char *s, Py_ssize_t size,
6787 const char *errors, Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006788{
Victor Stinner76a31a62011-11-04 00:05:13 +01006789 PyObject *v = NULL;
6790 int chunk_size, final, converted, done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006791
Victor Stinner3a50e702011-10-18 21:21:00 +02006792 if (code_page < 0) {
6793 PyErr_SetString(PyExc_ValueError, "invalid code page number");
6794 return NULL;
6795 }
6796
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006797 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00006798 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006799
Victor Stinner76a31a62011-11-04 00:05:13 +01006800 do
6801 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006802#ifdef NEED_RETRY
Victor Stinner76a31a62011-11-04 00:05:13 +01006803 if (size > INT_MAX) {
6804 chunk_size = INT_MAX;
6805 final = 0;
6806 done = 0;
6807 }
6808 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006809#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01006810 {
6811 chunk_size = (int)size;
6812 final = (consumed == NULL);
6813 done = 1;
6814 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006815
Victor Stinner76a31a62011-11-04 00:05:13 +01006816 /* Skip trailing lead-byte unless 'final' is set */
6817 if (!final && is_dbcs_lead_byte(code_page, s, chunk_size - 1))
6818 --chunk_size;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006819
Victor Stinner76a31a62011-11-04 00:05:13 +01006820 if (chunk_size == 0 && done) {
6821 if (v != NULL)
6822 break;
6823 Py_INCREF(unicode_empty);
6824 return unicode_empty;
6825 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006826
Victor Stinner76a31a62011-11-04 00:05:13 +01006827
6828 converted = decode_code_page_strict(code_page, &v,
6829 s, chunk_size);
6830 if (converted == -2)
6831 converted = decode_code_page_errors(code_page, &v,
6832 s, chunk_size,
6833 errors);
6834 assert(converted != 0);
6835
6836 if (converted < 0) {
6837 Py_XDECREF(v);
6838 return NULL;
6839 }
6840
6841 if (consumed)
6842 *consumed += converted;
6843
6844 s += converted;
6845 size -= converted;
6846 } while (!done);
Victor Stinner3a50e702011-10-18 21:21:00 +02006847
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006848 return unicode_result(v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006849}
6850
Alexander Belopolsky40018472011-02-26 01:02:56 +00006851PyObject *
Victor Stinner3a50e702011-10-18 21:21:00 +02006852PyUnicode_DecodeCodePageStateful(int code_page,
6853 const char *s,
6854 Py_ssize_t size,
6855 const char *errors,
6856 Py_ssize_t *consumed)
6857{
6858 return decode_code_page_stateful(code_page, s, size, errors, consumed);
6859}
6860
6861PyObject *
6862PyUnicode_DecodeMBCSStateful(const char *s,
6863 Py_ssize_t size,
6864 const char *errors,
6865 Py_ssize_t *consumed)
6866{
6867 return decode_code_page_stateful(CP_ACP, s, size, errors, consumed);
6868}
6869
6870PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00006871PyUnicode_DecodeMBCS(const char *s,
6872 Py_ssize_t size,
6873 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006874{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006875 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
6876}
6877
Victor Stinner3a50e702011-10-18 21:21:00 +02006878static DWORD
6879encode_code_page_flags(UINT code_page, const char *errors)
6880{
6881 if (code_page == CP_UTF8) {
6882 if (winver.dwMajorVersion >= 6)
6883 /* CP_UTF8 supports WC_ERR_INVALID_CHARS on Windows Vista
6884 and later */
6885 return WC_ERR_INVALID_CHARS;
6886 else
6887 /* CP_UTF8 only supports flags=0 on Windows older than Vista */
6888 return 0;
6889 }
6890 else if (code_page == CP_UTF7) {
6891 /* CP_UTF7 only supports flags=0 */
6892 return 0;
6893 }
6894 else {
6895 if (errors != NULL && strcmp(errors, "replace") == 0)
6896 return 0;
6897 else
6898 return WC_NO_BEST_FIT_CHARS;
6899 }
6900}
6901
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006902/*
Victor Stinner3a50e702011-10-18 21:21:00 +02006903 * Encode a Unicode string to a Windows code page into a byte string in strict
6904 * mode.
6905 *
6906 * Returns consumed characters if succeed, returns -2 on encode error, or raise
6907 * a WindowsError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006908 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006909static int
Victor Stinner3a50e702011-10-18 21:21:00 +02006910encode_code_page_strict(UINT code_page, PyObject **outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01006911 PyObject *unicode, Py_ssize_t offset, int len,
Victor Stinner3a50e702011-10-18 21:21:00 +02006912 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006913{
Victor Stinner554f3f02010-06-16 23:33:54 +00006914 BOOL usedDefaultChar = FALSE;
Victor Stinner3a50e702011-10-18 21:21:00 +02006915 BOOL *pusedDefaultChar = &usedDefaultChar;
6916 int outsize;
Victor Stinner554f3f02010-06-16 23:33:54 +00006917 PyObject *exc = NULL;
Victor Stinner24729f32011-11-10 20:31:37 +01006918 wchar_t *p;
Victor Stinner2fc507f2011-11-04 20:06:39 +01006919 Py_ssize_t size;
Victor Stinner3a50e702011-10-18 21:21:00 +02006920 const DWORD flags = encode_code_page_flags(code_page, NULL);
6921 char *out;
Victor Stinner2fc507f2011-11-04 20:06:39 +01006922 /* Create a substring so that we can get the UTF-16 representation
6923 of just the slice under consideration. */
6924 PyObject *substring;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006925
Martin v. Löwis3d325192011-11-04 18:23:06 +01006926 assert(len > 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006927
Victor Stinner3a50e702011-10-18 21:21:00 +02006928 if (code_page != CP_UTF8 && code_page != CP_UTF7)
Victor Stinner554f3f02010-06-16 23:33:54 +00006929 pusedDefaultChar = &usedDefaultChar;
Victor Stinner3a50e702011-10-18 21:21:00 +02006930 else
Victor Stinner554f3f02010-06-16 23:33:54 +00006931 pusedDefaultChar = NULL;
Victor Stinner554f3f02010-06-16 23:33:54 +00006932
Victor Stinner2fc507f2011-11-04 20:06:39 +01006933 substring = PyUnicode_Substring(unicode, offset, offset+len);
6934 if (substring == NULL)
6935 return -1;
6936 p = PyUnicode_AsUnicodeAndSize(substring, &size);
6937 if (p == NULL) {
6938 Py_DECREF(substring);
6939 return -1;
6940 }
Martin v. Löwis3d325192011-11-04 18:23:06 +01006941
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006942 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02006943 outsize = WideCharToMultiByte(code_page, flags,
6944 p, size,
6945 NULL, 0,
6946 NULL, pusedDefaultChar);
6947 if (outsize <= 0)
6948 goto error;
6949 /* If we used a default char, then we failed! */
Victor Stinner2fc507f2011-11-04 20:06:39 +01006950 if (pusedDefaultChar && *pusedDefaultChar) {
6951 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02006952 return -2;
Victor Stinner2fc507f2011-11-04 20:06:39 +01006953 }
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006954
Victor Stinner3a50e702011-10-18 21:21:00 +02006955 if (*outbytes == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006956 /* Create string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02006957 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
Victor Stinner2fc507f2011-11-04 20:06:39 +01006958 if (*outbytes == NULL) {
6959 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00006960 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01006961 }
Victor Stinner3a50e702011-10-18 21:21:00 +02006962 out = PyBytes_AS_STRING(*outbytes);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006963 }
6964 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006965 /* Extend string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02006966 const Py_ssize_t n = PyBytes_Size(*outbytes);
6967 if (outsize > PY_SSIZE_T_MAX - n) {
6968 PyErr_NoMemory();
Victor Stinner2fc507f2011-11-04 20:06:39 +01006969 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00006970 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02006971 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01006972 if (_PyBytes_Resize(outbytes, n + outsize) < 0) {
6973 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02006974 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01006975 }
Victor Stinner3a50e702011-10-18 21:21:00 +02006976 out = PyBytes_AS_STRING(*outbytes) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006977 }
6978
6979 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02006980 outsize = WideCharToMultiByte(code_page, flags,
6981 p, size,
6982 out, outsize,
6983 NULL, pusedDefaultChar);
Victor Stinner2fc507f2011-11-04 20:06:39 +01006984 Py_CLEAR(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02006985 if (outsize <= 0)
6986 goto error;
6987 if (pusedDefaultChar && *pusedDefaultChar)
6988 return -2;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006989 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00006990
Victor Stinner3a50e702011-10-18 21:21:00 +02006991error:
Victor Stinner2fc507f2011-11-04 20:06:39 +01006992 Py_XDECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02006993 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
6994 return -2;
6995 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00006996 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006997}
6998
Victor Stinner3a50e702011-10-18 21:21:00 +02006999/*
7000 * Encode a Unicode string to a Windows code page into a byte string using a
7001 * error handler.
7002 *
7003 * Returns consumed characters if succeed, or raise a WindowsError and returns
7004 * -1 on other error.
7005 */
7006static int
7007encode_code_page_errors(UINT code_page, PyObject **outbytes,
Victor Stinner7581cef2011-11-03 22:32:33 +01007008 PyObject *unicode, Py_ssize_t unicode_offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007009 Py_ssize_t insize, const char* errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007010{
Victor Stinner3a50e702011-10-18 21:21:00 +02007011 const DWORD flags = encode_code_page_flags(code_page, errors);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007012 Py_ssize_t pos = unicode_offset;
7013 Py_ssize_t endin = unicode_offset + insize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007014 /* Ideally, we should get reason from FormatMessage. This is the Windows
7015 2000 English version of the message. */
7016 const char *reason = "invalid character";
7017 /* 4=maximum length of a UTF-8 sequence */
7018 char buffer[4];
7019 BOOL usedDefaultChar = FALSE, *pusedDefaultChar;
7020 Py_ssize_t outsize;
7021 char *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007022 PyObject *errorHandler = NULL;
7023 PyObject *exc = NULL;
7024 PyObject *encoding_obj = NULL;
7025 char *encoding;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007026 Py_ssize_t newpos, newoutsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007027 PyObject *rep;
7028 int ret = -1;
7029
7030 assert(insize > 0);
7031
7032 encoding = code_page_name(code_page, &encoding_obj);
7033 if (encoding == NULL)
7034 return -1;
7035
7036 if (errors == NULL || strcmp(errors, "strict") == 0) {
7037 /* The last error was ERROR_NO_UNICODE_TRANSLATION,
7038 then we raise a UnicodeEncodeError. */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007039 make_encode_exception(&exc, encoding, unicode, 0, 0, reason);
Victor Stinner3a50e702011-10-18 21:21:00 +02007040 if (exc != NULL) {
7041 PyCodec_StrictErrors(exc);
7042 Py_DECREF(exc);
7043 }
7044 Py_XDECREF(encoding_obj);
7045 return -1;
7046 }
7047
7048 if (code_page != CP_UTF8 && code_page != CP_UTF7)
7049 pusedDefaultChar = &usedDefaultChar;
7050 else
7051 pusedDefaultChar = NULL;
7052
7053 if (Py_ARRAY_LENGTH(buffer) > PY_SSIZE_T_MAX / insize) {
7054 PyErr_NoMemory();
7055 goto error;
7056 }
7057 outsize = insize * Py_ARRAY_LENGTH(buffer);
7058
7059 if (*outbytes == NULL) {
7060 /* Create string object */
7061 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
7062 if (*outbytes == NULL)
7063 goto error;
7064 out = PyBytes_AS_STRING(*outbytes);
7065 }
7066 else {
7067 /* Extend string object */
7068 Py_ssize_t n = PyBytes_Size(*outbytes);
7069 if (n > PY_SSIZE_T_MAX - outsize) {
7070 PyErr_NoMemory();
7071 goto error;
7072 }
7073 if (_PyBytes_Resize(outbytes, n + outsize) < 0)
7074 goto error;
7075 out = PyBytes_AS_STRING(*outbytes) + n;
7076 }
7077
7078 /* Encode the string character per character */
Martin v. Löwis3d325192011-11-04 18:23:06 +01007079 while (pos < endin)
Victor Stinner3a50e702011-10-18 21:21:00 +02007080 {
Victor Stinner2fc507f2011-11-04 20:06:39 +01007081 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, pos);
7082 wchar_t chars[2];
7083 int charsize;
7084 if (ch < 0x10000) {
7085 chars[0] = (wchar_t)ch;
7086 charsize = 1;
7087 }
7088 else {
7089 ch -= 0x10000;
7090 chars[0] = 0xd800 + (ch >> 10);
7091 chars[1] = 0xdc00 + (ch & 0x3ff);
7092 charsize = 2;
7093 }
7094
Victor Stinner3a50e702011-10-18 21:21:00 +02007095 outsize = WideCharToMultiByte(code_page, flags,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007096 chars, charsize,
Victor Stinner3a50e702011-10-18 21:21:00 +02007097 buffer, Py_ARRAY_LENGTH(buffer),
7098 NULL, pusedDefaultChar);
7099 if (outsize > 0) {
7100 if (pusedDefaultChar == NULL || !(*pusedDefaultChar))
7101 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007102 pos++;
Victor Stinner3a50e702011-10-18 21:21:00 +02007103 memcpy(out, buffer, outsize);
7104 out += outsize;
7105 continue;
7106 }
7107 }
7108 else if (GetLastError() != ERROR_NO_UNICODE_TRANSLATION) {
7109 PyErr_SetFromWindowsErr(0);
7110 goto error;
7111 }
7112
Victor Stinner3a50e702011-10-18 21:21:00 +02007113 rep = unicode_encode_call_errorhandler(
7114 errors, &errorHandler, encoding, reason,
Victor Stinner7581cef2011-11-03 22:32:33 +01007115 unicode, &exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007116 pos, pos + 1, &newpos);
Victor Stinner3a50e702011-10-18 21:21:00 +02007117 if (rep == NULL)
7118 goto error;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007119 pos = newpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007120
7121 if (PyBytes_Check(rep)) {
7122 outsize = PyBytes_GET_SIZE(rep);
7123 if (outsize != 1) {
7124 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7125 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7126 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7127 Py_DECREF(rep);
7128 goto error;
7129 }
7130 out = PyBytes_AS_STRING(*outbytes) + offset;
7131 }
7132 memcpy(out, PyBytes_AS_STRING(rep), outsize);
7133 out += outsize;
7134 }
7135 else {
7136 Py_ssize_t i;
7137 enum PyUnicode_Kind kind;
7138 void *data;
7139
Benjamin Petersonbac79492012-01-14 13:34:47 -05007140 if (PyUnicode_READY(rep) == -1) {
Victor Stinner3a50e702011-10-18 21:21:00 +02007141 Py_DECREF(rep);
7142 goto error;
7143 }
7144
7145 outsize = PyUnicode_GET_LENGTH(rep);
7146 if (outsize != 1) {
7147 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7148 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7149 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7150 Py_DECREF(rep);
7151 goto error;
7152 }
7153 out = PyBytes_AS_STRING(*outbytes) + offset;
7154 }
7155 kind = PyUnicode_KIND(rep);
7156 data = PyUnicode_DATA(rep);
7157 for (i=0; i < outsize; i++) {
7158 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7159 if (ch > 127) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007160 raise_encode_exception(&exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007161 encoding, unicode,
7162 pos, pos + 1,
Victor Stinner3a50e702011-10-18 21:21:00 +02007163 "unable to encode error handler result to ASCII");
7164 Py_DECREF(rep);
7165 goto error;
7166 }
7167 *out = (unsigned char)ch;
7168 out++;
7169 }
7170 }
7171 Py_DECREF(rep);
7172 }
7173 /* write a NUL byte */
7174 *out = 0;
7175 outsize = out - PyBytes_AS_STRING(*outbytes);
7176 assert(outsize <= PyBytes_GET_SIZE(*outbytes));
7177 if (_PyBytes_Resize(outbytes, outsize) < 0)
7178 goto error;
7179 ret = 0;
7180
7181error:
7182 Py_XDECREF(encoding_obj);
7183 Py_XDECREF(errorHandler);
7184 Py_XDECREF(exc);
7185 return ret;
7186}
7187
Victor Stinner3a50e702011-10-18 21:21:00 +02007188static PyObject *
7189encode_code_page(int code_page,
Victor Stinner7581cef2011-11-03 22:32:33 +01007190 PyObject *unicode,
Victor Stinner3a50e702011-10-18 21:21:00 +02007191 const char *errors)
7192{
Martin v. Löwis3d325192011-11-04 18:23:06 +01007193 Py_ssize_t len;
Victor Stinner3a50e702011-10-18 21:21:00 +02007194 PyObject *outbytes = NULL;
Victor Stinner7581cef2011-11-03 22:32:33 +01007195 Py_ssize_t offset;
Victor Stinner76a31a62011-11-04 00:05:13 +01007196 int chunk_len, ret, done;
Victor Stinner7581cef2011-11-03 22:32:33 +01007197
Benjamin Petersonbac79492012-01-14 13:34:47 -05007198 if (PyUnicode_READY(unicode) == -1)
Victor Stinner2fc507f2011-11-04 20:06:39 +01007199 return NULL;
7200 len = PyUnicode_GET_LENGTH(unicode);
Guido van Rossum03e29f12000-05-04 15:52:20 +00007201
Victor Stinner3a50e702011-10-18 21:21:00 +02007202 if (code_page < 0) {
7203 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7204 return NULL;
7205 }
7206
Martin v. Löwis3d325192011-11-04 18:23:06 +01007207 if (len == 0)
Victor Stinner76a31a62011-11-04 00:05:13 +01007208 return PyBytes_FromStringAndSize(NULL, 0);
7209
Victor Stinner7581cef2011-11-03 22:32:33 +01007210 offset = 0;
7211 do
7212 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007213#ifdef NEED_RETRY
Victor Stinner2fc507f2011-11-04 20:06:39 +01007214 /* UTF-16 encoding may double the size, so use only INT_MAX/2
Martin v. Löwis3d325192011-11-04 18:23:06 +01007215 chunks. */
7216 if (len > INT_MAX/2) {
7217 chunk_len = INT_MAX/2;
Victor Stinner76a31a62011-11-04 00:05:13 +01007218 done = 0;
7219 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007220 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007221#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007222 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007223 chunk_len = (int)len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007224 done = 1;
7225 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007226
Victor Stinner76a31a62011-11-04 00:05:13 +01007227 ret = encode_code_page_strict(code_page, &outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007228 unicode, offset, chunk_len,
Victor Stinner76a31a62011-11-04 00:05:13 +01007229 errors);
7230 if (ret == -2)
7231 ret = encode_code_page_errors(code_page, &outbytes,
7232 unicode, offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007233 chunk_len, errors);
Victor Stinner7581cef2011-11-03 22:32:33 +01007234 if (ret < 0) {
7235 Py_XDECREF(outbytes);
7236 return NULL;
7237 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007238
Victor Stinner7581cef2011-11-03 22:32:33 +01007239 offset += chunk_len;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007240 len -= chunk_len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007241 } while (!done);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007242
Victor Stinner3a50e702011-10-18 21:21:00 +02007243 return outbytes;
7244}
7245
7246PyObject *
7247PyUnicode_EncodeMBCS(const Py_UNICODE *p,
7248 Py_ssize_t size,
7249 const char *errors)
7250{
Victor Stinner7581cef2011-11-03 22:32:33 +01007251 PyObject *unicode, *res;
7252 unicode = PyUnicode_FromUnicode(p, size);
7253 if (unicode == NULL)
7254 return NULL;
7255 res = encode_code_page(CP_ACP, unicode, errors);
7256 Py_DECREF(unicode);
7257 return res;
Victor Stinner3a50e702011-10-18 21:21:00 +02007258}
7259
7260PyObject *
7261PyUnicode_EncodeCodePage(int code_page,
7262 PyObject *unicode,
7263 const char *errors)
7264{
Victor Stinner7581cef2011-11-03 22:32:33 +01007265 return encode_code_page(code_page, unicode, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007266}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007267
Alexander Belopolsky40018472011-02-26 01:02:56 +00007268PyObject *
7269PyUnicode_AsMBCSString(PyObject *unicode)
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007270{
7271 if (!PyUnicode_Check(unicode)) {
7272 PyErr_BadArgument();
7273 return NULL;
7274 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007275 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007276}
7277
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007278#undef NEED_RETRY
7279
Victor Stinner99b95382011-07-04 14:23:54 +02007280#endif /* HAVE_MBCS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007281
Guido van Rossumd57fd912000-03-10 22:53:23 +00007282/* --- Character Mapping Codec -------------------------------------------- */
7283
Alexander Belopolsky40018472011-02-26 01:02:56 +00007284PyObject *
7285PyUnicode_DecodeCharmap(const char *s,
7286 Py_ssize_t size,
7287 PyObject *mapping,
7288 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007289{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007290 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007291 Py_ssize_t startinpos;
7292 Py_ssize_t endinpos;
7293 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007294 const char *e;
Victor Stinner7931d9a2011-11-04 00:22:48 +01007295 PyObject *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007296 Py_ssize_t extrachars = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007297 PyObject *errorHandler = NULL;
7298 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00007299
Guido van Rossumd57fd912000-03-10 22:53:23 +00007300 /* Default to Latin-1 */
7301 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007302 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007303
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007304 v = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007305 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007306 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007307 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01007308 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007309 outpos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007310 e = s + size;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007311 if (PyUnicode_CheckExact(mapping)) {
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007312 Py_ssize_t maplen;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007313 enum PyUnicode_Kind mapkind;
7314 void *mapdata;
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007315 Py_UCS4 x;
7316
Benjamin Petersonbac79492012-01-14 13:34:47 -05007317 if (PyUnicode_READY(mapping) == -1)
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007318 return NULL;
7319
7320 maplen = PyUnicode_GET_LENGTH(mapping);
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007321 mapdata = PyUnicode_DATA(mapping);
7322 mapkind = PyUnicode_KIND(mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00007323 while (s < e) {
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007324 unsigned char ch;
7325 if (mapkind == PyUnicode_2BYTE_KIND && maplen >= 256) {
7326 enum PyUnicode_Kind outkind = PyUnicode_KIND(v);
7327 if (outkind == PyUnicode_1BYTE_KIND) {
7328 void *outdata = PyUnicode_DATA(v);
7329 Py_UCS4 maxchar = PyUnicode_MAX_CHAR_VALUE(v);
7330 while (s < e) {
7331 unsigned char ch = *s;
7332 x = PyUnicode_READ(PyUnicode_2BYTE_KIND, mapdata, ch);
7333 if (x > maxchar)
7334 goto Error;
7335 PyUnicode_WRITE(PyUnicode_1BYTE_KIND, outdata, outpos++, x);
7336 ++s;
7337 }
7338 break;
7339 }
7340 else if (outkind == PyUnicode_2BYTE_KIND) {
7341 void *outdata = PyUnicode_DATA(v);
7342 while (s < e) {
7343 unsigned char ch = *s;
7344 x = PyUnicode_READ(PyUnicode_2BYTE_KIND, mapdata, ch);
7345 if (x == 0xFFFE)
7346 goto Error;
7347 PyUnicode_WRITE(PyUnicode_2BYTE_KIND, outdata, outpos++, x);
7348 ++s;
7349 }
7350 break;
7351 }
7352 }
7353 ch = *s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007354
Benjamin Peterson29060642009-01-31 22:14:21 +00007355 if (ch < maplen)
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007356 x = PyUnicode_READ(mapkind, mapdata, ch);
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007357 else
7358 x = 0xfffe; /* invalid value */
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007359Error:
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007360 if (x == 0xfffe)
7361 {
Benjamin Peterson29060642009-01-31 22:14:21 +00007362 /* undefined mapping */
Benjamin Peterson29060642009-01-31 22:14:21 +00007363 startinpos = s-starts;
7364 endinpos = startinpos+1;
7365 if (unicode_decode_call_errorhandler(
7366 errors, &errorHandler,
7367 "charmap", "character maps to <undefined>",
7368 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007369 &v, &outpos)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007370 goto onError;
7371 }
7372 continue;
7373 }
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007374
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007375 if (unicode_putchar(&v, &outpos, x) < 0)
7376 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00007377 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007378 }
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007379 }
7380 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007381 while (s < e) {
7382 unsigned char ch = *s;
7383 PyObject *w, *x;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007384
Benjamin Peterson29060642009-01-31 22:14:21 +00007385 /* Get mapping (char ordinal -> integer, Unicode char or None) */
7386 w = PyLong_FromLong((long)ch);
7387 if (w == NULL)
7388 goto onError;
7389 x = PyObject_GetItem(mapping, w);
7390 Py_DECREF(w);
7391 if (x == NULL) {
7392 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7393 /* No mapping found means: mapping is undefined. */
7394 PyErr_Clear();
7395 x = Py_None;
7396 Py_INCREF(x);
7397 } else
7398 goto onError;
7399 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007400
Benjamin Peterson29060642009-01-31 22:14:21 +00007401 /* Apply mapping */
7402 if (PyLong_Check(x)) {
7403 long value = PyLong_AS_LONG(x);
Antoine Pitroua1f76552012-09-23 20:00:04 +02007404 if (value < 0 || value > MAX_UNICODE) {
7405 PyErr_Format(PyExc_TypeError,
7406 "character mapping must be in range(0x%lx)",
7407 (unsigned long)MAX_UNICODE + 1);
Benjamin Peterson29060642009-01-31 22:14:21 +00007408 Py_DECREF(x);
7409 goto onError;
7410 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007411 if (unicode_putchar(&v, &outpos, value) < 0)
7412 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00007413 }
7414 else if (x == Py_None) {
7415 /* undefined mapping */
Benjamin Peterson29060642009-01-31 22:14:21 +00007416 startinpos = s-starts;
7417 endinpos = startinpos+1;
7418 if (unicode_decode_call_errorhandler(
7419 errors, &errorHandler,
7420 "charmap", "character maps to <undefined>",
7421 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007422 &v, &outpos)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007423 Py_DECREF(x);
7424 goto onError;
7425 }
7426 Py_DECREF(x);
7427 continue;
7428 }
7429 else if (PyUnicode_Check(x)) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007430 Py_ssize_t targetsize;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007431
Benjamin Petersonbac79492012-01-14 13:34:47 -05007432 if (PyUnicode_READY(x) == -1)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007433 goto onError;
7434 targetsize = PyUnicode_GET_LENGTH(x);
7435
7436 if (targetsize == 1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007437 /* 1-1 mapping */
Victor Stinner62aa4d02011-11-09 00:03:45 +01007438 if (unicode_putchar(&v, &outpos,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007439 PyUnicode_READ_CHAR(x, 0)) < 0)
7440 goto onError;
7441 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007442 else if (targetsize > 1) {
7443 /* 1-n mapping */
7444 if (targetsize > extrachars) {
7445 /* resize first */
Benjamin Peterson29060642009-01-31 22:14:21 +00007446 Py_ssize_t needed = (targetsize - extrachars) + \
7447 (targetsize << 2);
7448 extrachars += needed;
7449 /* XXX overflow detection missing */
Victor Stinner16e6a802011-12-12 13:24:15 +01007450 if (unicode_resize(&v,
7451 PyUnicode_GET_LENGTH(v) + needed) < 0)
7452 {
Benjamin Peterson29060642009-01-31 22:14:21 +00007453 Py_DECREF(x);
7454 goto onError;
7455 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007456 }
Victor Stinner1b487b42012-05-03 12:29:04 +02007457 if (unicode_widen(&v, outpos, PyUnicode_MAX_CHAR_VALUE(x)) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007458 goto onError;
7459 PyUnicode_CopyCharacters(v, outpos, x, 0, targetsize);
7460 outpos += targetsize;
Benjamin Peterson29060642009-01-31 22:14:21 +00007461 extrachars -= targetsize;
7462 }
7463 /* 1-0 mapping: skip the character */
7464 }
7465 else {
7466 /* wrong return value */
7467 PyErr_SetString(PyExc_TypeError,
7468 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00007469 Py_DECREF(x);
7470 goto onError;
7471 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007472 Py_DECREF(x);
7473 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007474 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00007475 }
Victor Stinner16e6a802011-12-12 13:24:15 +01007476 if (unicode_resize(&v, outpos) < 0)
Antoine Pitroua8f63c02011-11-08 18:37:16 +01007477 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007478 Py_XDECREF(errorHandler);
7479 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01007480 return unicode_result(v);
Tim Petersced69f82003-09-16 20:30:58 +00007481
Benjamin Peterson29060642009-01-31 22:14:21 +00007482 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007483 Py_XDECREF(errorHandler);
7484 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007485 Py_XDECREF(v);
7486 return NULL;
7487}
7488
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007489/* Charmap encoding: the lookup table */
7490
Alexander Belopolsky40018472011-02-26 01:02:56 +00007491struct encoding_map {
Benjamin Peterson29060642009-01-31 22:14:21 +00007492 PyObject_HEAD
7493 unsigned char level1[32];
7494 int count2, count3;
7495 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007496};
7497
7498static PyObject*
7499encoding_map_size(PyObject *obj, PyObject* args)
7500{
7501 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007502 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00007503 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007504}
7505
7506static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007507 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00007508 PyDoc_STR("Return the size (in bytes) of this object") },
7509 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007510};
7511
7512static void
7513encoding_map_dealloc(PyObject* o)
7514{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007515 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007516}
7517
7518static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007519 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007520 "EncodingMap", /*tp_name*/
7521 sizeof(struct encoding_map), /*tp_basicsize*/
7522 0, /*tp_itemsize*/
7523 /* methods */
7524 encoding_map_dealloc, /*tp_dealloc*/
7525 0, /*tp_print*/
7526 0, /*tp_getattr*/
7527 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00007528 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00007529 0, /*tp_repr*/
7530 0, /*tp_as_number*/
7531 0, /*tp_as_sequence*/
7532 0, /*tp_as_mapping*/
7533 0, /*tp_hash*/
7534 0, /*tp_call*/
7535 0, /*tp_str*/
7536 0, /*tp_getattro*/
7537 0, /*tp_setattro*/
7538 0, /*tp_as_buffer*/
7539 Py_TPFLAGS_DEFAULT, /*tp_flags*/
7540 0, /*tp_doc*/
7541 0, /*tp_traverse*/
7542 0, /*tp_clear*/
7543 0, /*tp_richcompare*/
7544 0, /*tp_weaklistoffset*/
7545 0, /*tp_iter*/
7546 0, /*tp_iternext*/
7547 encoding_map_methods, /*tp_methods*/
7548 0, /*tp_members*/
7549 0, /*tp_getset*/
7550 0, /*tp_base*/
7551 0, /*tp_dict*/
7552 0, /*tp_descr_get*/
7553 0, /*tp_descr_set*/
7554 0, /*tp_dictoffset*/
7555 0, /*tp_init*/
7556 0, /*tp_alloc*/
7557 0, /*tp_new*/
7558 0, /*tp_free*/
7559 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007560};
7561
7562PyObject*
7563PyUnicode_BuildEncodingMap(PyObject* string)
7564{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007565 PyObject *result;
7566 struct encoding_map *mresult;
7567 int i;
7568 int need_dict = 0;
7569 unsigned char level1[32];
7570 unsigned char level2[512];
7571 unsigned char *mlevel1, *mlevel2, *mlevel3;
7572 int count2 = 0, count3 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007573 int kind;
7574 void *data;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007575 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007576 Py_UCS4 ch;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007577
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007578 if (!PyUnicode_Check(string) || !PyUnicode_GET_LENGTH(string)) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007579 PyErr_BadArgument();
7580 return NULL;
7581 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007582 kind = PyUnicode_KIND(string);
7583 data = PyUnicode_DATA(string);
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007584 length = PyUnicode_GET_LENGTH(string);
7585 length = Py_MIN(length, 256);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007586 memset(level1, 0xFF, sizeof level1);
7587 memset(level2, 0xFF, sizeof level2);
7588
7589 /* If there isn't a one-to-one mapping of NULL to \0,
7590 or if there are non-BMP characters, we need to use
7591 a mapping dictionary. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007592 if (PyUnicode_READ(kind, data, 0) != 0)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007593 need_dict = 1;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007594 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007595 int l1, l2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007596 ch = PyUnicode_READ(kind, data, i);
7597 if (ch == 0 || ch > 0xFFFF) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007598 need_dict = 1;
7599 break;
7600 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007601 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007602 /* unmapped character */
7603 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007604 l1 = ch >> 11;
7605 l2 = ch >> 7;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007606 if (level1[l1] == 0xFF)
7607 level1[l1] = count2++;
7608 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00007609 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007610 }
7611
7612 if (count2 >= 0xFF || count3 >= 0xFF)
7613 need_dict = 1;
7614
7615 if (need_dict) {
7616 PyObject *result = PyDict_New();
7617 PyObject *key, *value;
7618 if (!result)
7619 return NULL;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007620 for (i = 0; i < length; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007621 key = PyLong_FromLong(PyUnicode_READ(kind, data, i));
Christian Heimes217cfd12007-12-02 14:31:20 +00007622 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007623 if (!key || !value)
7624 goto failed1;
7625 if (PyDict_SetItem(result, key, value) == -1)
7626 goto failed1;
7627 Py_DECREF(key);
7628 Py_DECREF(value);
7629 }
7630 return result;
7631 failed1:
7632 Py_XDECREF(key);
7633 Py_XDECREF(value);
7634 Py_DECREF(result);
7635 return NULL;
7636 }
7637
7638 /* Create a three-level trie */
7639 result = PyObject_MALLOC(sizeof(struct encoding_map) +
7640 16*count2 + 128*count3 - 1);
7641 if (!result)
7642 return PyErr_NoMemory();
7643 PyObject_Init(result, &EncodingMapType);
7644 mresult = (struct encoding_map*)result;
7645 mresult->count2 = count2;
7646 mresult->count3 = count3;
7647 mlevel1 = mresult->level1;
7648 mlevel2 = mresult->level23;
7649 mlevel3 = mresult->level23 + 16*count2;
7650 memcpy(mlevel1, level1, 32);
7651 memset(mlevel2, 0xFF, 16*count2);
7652 memset(mlevel3, 0, 128*count3);
7653 count3 = 0;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007654 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007655 int o1, o2, o3, i2, i3;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007656 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7657 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007658 /* unmapped character */
7659 continue;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007660 o1 = ch>>11;
7661 o2 = (ch>>7) & 0xF;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007662 i2 = 16*mlevel1[o1] + o2;
7663 if (mlevel2[i2] == 0xFF)
7664 mlevel2[i2] = count3++;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007665 o3 = ch & 0x7F;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007666 i3 = 128*mlevel2[i2] + o3;
7667 mlevel3[i3] = i;
7668 }
7669 return result;
7670}
7671
7672static int
Victor Stinner22168992011-11-20 17:09:18 +01007673encoding_map_lookup(Py_UCS4 c, PyObject *mapping)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007674{
7675 struct encoding_map *map = (struct encoding_map*)mapping;
7676 int l1 = c>>11;
7677 int l2 = (c>>7) & 0xF;
7678 int l3 = c & 0x7F;
7679 int i;
7680
Victor Stinner22168992011-11-20 17:09:18 +01007681 if (c > 0xFFFF)
Benjamin Peterson29060642009-01-31 22:14:21 +00007682 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007683 if (c == 0)
7684 return 0;
7685 /* level 1*/
7686 i = map->level1[l1];
7687 if (i == 0xFF) {
7688 return -1;
7689 }
7690 /* level 2*/
7691 i = map->level23[16*i+l2];
7692 if (i == 0xFF) {
7693 return -1;
7694 }
7695 /* level 3 */
7696 i = map->level23[16*map->count2 + 128*i + l3];
7697 if (i == 0) {
7698 return -1;
7699 }
7700 return i;
7701}
7702
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007703/* Lookup the character ch in the mapping. If the character
7704 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00007705 error occurred). */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007706static PyObject *
Victor Stinner22168992011-11-20 17:09:18 +01007707charmapencode_lookup(Py_UCS4 c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007708{
Christian Heimes217cfd12007-12-02 14:31:20 +00007709 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007710 PyObject *x;
7711
7712 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007713 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007714 x = PyObject_GetItem(mapping, w);
7715 Py_DECREF(w);
7716 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007717 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7718 /* No mapping found means: mapping is undefined. */
7719 PyErr_Clear();
7720 x = Py_None;
7721 Py_INCREF(x);
7722 return x;
7723 } else
7724 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007725 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00007726 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00007727 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00007728 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007729 long value = PyLong_AS_LONG(x);
7730 if (value < 0 || value > 255) {
7731 PyErr_SetString(PyExc_TypeError,
7732 "character mapping must be in range(256)");
7733 Py_DECREF(x);
7734 return NULL;
7735 }
7736 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007737 }
Christian Heimes72b710a2008-05-26 13:28:38 +00007738 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00007739 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007740 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007741 /* wrong return value */
7742 PyErr_Format(PyExc_TypeError,
7743 "character mapping must return integer, bytes or None, not %.400s",
7744 x->ob_type->tp_name);
7745 Py_DECREF(x);
7746 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007747 }
7748}
7749
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007750static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00007751charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007752{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007753 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
7754 /* exponentially overallocate to minimize reallocations */
7755 if (requiredsize < 2*outsize)
7756 requiredsize = 2*outsize;
7757 if (_PyBytes_Resize(outobj, requiredsize))
7758 return -1;
7759 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007760}
7761
Benjamin Peterson14339b62009-01-31 16:36:08 +00007762typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00007763 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Alexander Belopolsky40018472011-02-26 01:02:56 +00007764} charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007765/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00007766 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007767 space is available. Return a new reference to the object that
7768 was put in the output buffer, or Py_None, if the mapping was undefined
7769 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00007770 reallocation error occurred. The caller must decref the result */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007771static charmapencode_result
Victor Stinner22168992011-11-20 17:09:18 +01007772charmapencode_output(Py_UCS4 c, PyObject *mapping,
Alexander Belopolsky40018472011-02-26 01:02:56 +00007773 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007774{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007775 PyObject *rep;
7776 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00007777 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007778
Christian Heimes90aa7642007-12-19 02:45:37 +00007779 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007780 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00007781 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007782 if (res == -1)
7783 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00007784 if (outsize<requiredsize)
7785 if (charmapencode_resize(outobj, outpos, requiredsize))
7786 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00007787 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00007788 outstart[(*outpos)++] = (char)res;
7789 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007790 }
7791
7792 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007793 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007794 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007795 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007796 Py_DECREF(rep);
7797 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007798 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007799 if (PyLong_Check(rep)) {
7800 Py_ssize_t requiredsize = *outpos+1;
7801 if (outsize<requiredsize)
7802 if (charmapencode_resize(outobj, outpos, requiredsize)) {
7803 Py_DECREF(rep);
7804 return enc_EXCEPTION;
7805 }
Christian Heimes72b710a2008-05-26 13:28:38 +00007806 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00007807 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00007808 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007809 else {
7810 const char *repchars = PyBytes_AS_STRING(rep);
7811 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
7812 Py_ssize_t requiredsize = *outpos+repsize;
7813 if (outsize<requiredsize)
7814 if (charmapencode_resize(outobj, outpos, requiredsize)) {
7815 Py_DECREF(rep);
7816 return enc_EXCEPTION;
7817 }
Christian Heimes72b710a2008-05-26 13:28:38 +00007818 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00007819 memcpy(outstart + *outpos, repchars, repsize);
7820 *outpos += repsize;
7821 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007822 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007823 Py_DECREF(rep);
7824 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007825}
7826
7827/* handle an error in PyUnicode_EncodeCharmap
7828 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007829static int
7830charmap_encoding_error(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007831 PyObject *unicode, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007832 PyObject **exceptionObject,
Walter Dörwalde5402fb2003-08-14 20:25:29 +00007833 int *known_errorHandler, PyObject **errorHandler, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00007834 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007835{
7836 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007837 Py_ssize_t size, repsize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007838 Py_ssize_t newpos;
Victor Stinnerae4f7c82011-11-20 18:28:55 +01007839 enum PyUnicode_Kind kind;
7840 void *data;
7841 Py_ssize_t index;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007842 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00007843 Py_ssize_t collstartpos = *inpos;
7844 Py_ssize_t collendpos = *inpos+1;
7845 Py_ssize_t collpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007846 char *encoding = "charmap";
7847 char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007848 charmapencode_result x;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007849 Py_UCS4 ch;
Brian Curtin2787ea42011-11-02 15:09:37 -05007850 int val;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007851
Benjamin Petersonbac79492012-01-14 13:34:47 -05007852 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007853 return -1;
7854 size = PyUnicode_GET_LENGTH(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007855 /* find all unencodable characters */
7856 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007857 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00007858 if (Py_TYPE(mapping) == &EncodingMapType) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007859 ch = PyUnicode_READ_CHAR(unicode, collendpos);
Brian Curtin2787ea42011-11-02 15:09:37 -05007860 val = encoding_map_lookup(ch, mapping);
7861 if (val != -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00007862 break;
7863 ++collendpos;
7864 continue;
7865 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007866
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007867 ch = PyUnicode_READ_CHAR(unicode, collendpos);
7868 rep = charmapencode_lookup(ch, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00007869 if (rep==NULL)
7870 return -1;
7871 else if (rep!=Py_None) {
7872 Py_DECREF(rep);
7873 break;
7874 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007875 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00007876 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007877 }
7878 /* cache callback name lookup
7879 * (if not done yet, i.e. it's the first error) */
7880 if (*known_errorHandler==-1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007881 if ((errors==NULL) || (!strcmp(errors, "strict")))
7882 *known_errorHandler = 1;
7883 else if (!strcmp(errors, "replace"))
7884 *known_errorHandler = 2;
7885 else if (!strcmp(errors, "ignore"))
7886 *known_errorHandler = 3;
7887 else if (!strcmp(errors, "xmlcharrefreplace"))
7888 *known_errorHandler = 4;
7889 else
7890 *known_errorHandler = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007891 }
7892 switch (*known_errorHandler) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007893 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007894 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00007895 return -1;
7896 case 2: /* replace */
7897 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007898 x = charmapencode_output('?', mapping, res, respos);
7899 if (x==enc_EXCEPTION) {
7900 return -1;
7901 }
7902 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007903 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00007904 return -1;
7905 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007906 }
7907 /* fall through */
7908 case 3: /* ignore */
7909 *inpos = collendpos;
7910 break;
7911 case 4: /* xmlcharrefreplace */
7912 /* generate replacement (temporarily (mis)uses p) */
7913 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007914 char buffer[2+29+1+1];
7915 char *cp;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007916 sprintf(buffer, "&#%d;", (int)PyUnicode_READ_CHAR(unicode, collpos));
Benjamin Peterson29060642009-01-31 22:14:21 +00007917 for (cp = buffer; *cp; ++cp) {
7918 x = charmapencode_output(*cp, mapping, res, respos);
7919 if (x==enc_EXCEPTION)
7920 return -1;
7921 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007922 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00007923 return -1;
7924 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007925 }
7926 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007927 *inpos = collendpos;
7928 break;
7929 default:
7930 repunicode = unicode_encode_call_errorhandler(errors, errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007931 encoding, reason, unicode, exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00007932 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00007933 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007934 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00007935 if (PyBytes_Check(repunicode)) {
7936 /* Directly copy bytes result to output. */
7937 Py_ssize_t outsize = PyBytes_Size(*res);
7938 Py_ssize_t requiredsize;
7939 repsize = PyBytes_Size(repunicode);
7940 requiredsize = *respos + repsize;
7941 if (requiredsize > outsize)
7942 /* Make room for all additional bytes. */
7943 if (charmapencode_resize(res, respos, requiredsize)) {
7944 Py_DECREF(repunicode);
7945 return -1;
7946 }
7947 memcpy(PyBytes_AsString(*res) + *respos,
7948 PyBytes_AsString(repunicode), repsize);
7949 *respos += repsize;
7950 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00007951 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00007952 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00007953 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007954 /* generate replacement */
Benjamin Petersonbac79492012-01-14 13:34:47 -05007955 if (PyUnicode_READY(repunicode) == -1) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01007956 Py_DECREF(repunicode);
7957 return -1;
7958 }
Victor Stinner9e30aa52011-11-21 02:49:52 +01007959 repsize = PyUnicode_GET_LENGTH(repunicode);
Victor Stinnerae4f7c82011-11-20 18:28:55 +01007960 data = PyUnicode_DATA(repunicode);
7961 kind = PyUnicode_KIND(repunicode);
7962 for (index = 0; index < repsize; index++) {
7963 Py_UCS4 repch = PyUnicode_READ(kind, data, index);
7964 x = charmapencode_output(repch, mapping, res, respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00007965 if (x==enc_EXCEPTION) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01007966 Py_DECREF(repunicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00007967 return -1;
7968 }
7969 else if (x==enc_FAILED) {
7970 Py_DECREF(repunicode);
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007971 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00007972 return -1;
7973 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007974 }
7975 *inpos = newpos;
7976 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007977 }
7978 return 0;
7979}
7980
Alexander Belopolsky40018472011-02-26 01:02:56 +00007981PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007982_PyUnicode_EncodeCharmap(PyObject *unicode,
7983 PyObject *mapping,
7984 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007985{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007986 /* output object */
7987 PyObject *res = NULL;
7988 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00007989 Py_ssize_t inpos = 0;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007990 Py_ssize_t size;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007991 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00007992 Py_ssize_t respos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007993 PyObject *errorHandler = NULL;
7994 PyObject *exc = NULL;
7995 /* the following variable is used for caching string comparisons
7996 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
7997 * 3=ignore, 4=xmlcharrefreplace */
7998 int known_errorHandler = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007999
Benjamin Petersonbac79492012-01-14 13:34:47 -05008000 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008001 return NULL;
8002 size = PyUnicode_GET_LENGTH(unicode);
8003
Guido van Rossumd57fd912000-03-10 22:53:23 +00008004 /* Default to Latin-1 */
8005 if (mapping == NULL)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008006 return unicode_encode_ucs1(unicode, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008007
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008008 /* allocate enough for a simple encoding without
8009 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00008010 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008011 if (res == NULL)
8012 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00008013 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008014 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008015
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008016 while (inpos<size) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008017 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, inpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008018 /* try to encode it */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008019 charmapencode_result x = charmapencode_output(ch, mapping, &res, &respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008020 if (x==enc_EXCEPTION) /* error */
8021 goto onError;
8022 if (x==enc_FAILED) { /* unencodable character */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008023 if (charmap_encoding_error(unicode, &inpos, mapping,
Benjamin Peterson29060642009-01-31 22:14:21 +00008024 &exc,
8025 &known_errorHandler, &errorHandler, errors,
8026 &res, &respos)) {
8027 goto onError;
8028 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008029 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008030 else
8031 /* done with this character => adjust input position */
8032 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008033 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008034
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008035 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00008036 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00008037 if (_PyBytes_Resize(&res, respos) < 0)
8038 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00008039
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008040 Py_XDECREF(exc);
8041 Py_XDECREF(errorHandler);
8042 return res;
8043
Benjamin Peterson29060642009-01-31 22:14:21 +00008044 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008045 Py_XDECREF(res);
8046 Py_XDECREF(exc);
8047 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008048 return NULL;
8049}
8050
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008051/* Deprecated */
8052PyObject *
8053PyUnicode_EncodeCharmap(const Py_UNICODE *p,
8054 Py_ssize_t size,
8055 PyObject *mapping,
8056 const char *errors)
8057{
8058 PyObject *result;
8059 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8060 if (unicode == NULL)
8061 return NULL;
8062 result = _PyUnicode_EncodeCharmap(unicode, mapping, errors);
8063 Py_DECREF(unicode);
Victor Stinnerfc026c92011-11-04 00:24:51 +01008064 return result;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008065}
8066
Alexander Belopolsky40018472011-02-26 01:02:56 +00008067PyObject *
8068PyUnicode_AsCharmapString(PyObject *unicode,
8069 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008070{
8071 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008072 PyErr_BadArgument();
8073 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008074 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008075 return _PyUnicode_EncodeCharmap(unicode, mapping, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008076}
8077
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008078/* create or adjust a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008079static void
8080make_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008081 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008082 Py_ssize_t startpos, Py_ssize_t endpos,
8083 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008084{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008085 if (*exceptionObject == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008086 *exceptionObject = _PyUnicodeTranslateError_Create(
8087 unicode, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008088 }
8089 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008090 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
8091 goto onError;
8092 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
8093 goto onError;
8094 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
8095 goto onError;
8096 return;
8097 onError:
8098 Py_DECREF(*exceptionObject);
8099 *exceptionObject = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008100 }
8101}
8102
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008103/* raises a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008104static void
8105raise_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008106 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008107 Py_ssize_t startpos, Py_ssize_t endpos,
8108 const char *reason)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008109{
8110 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008111 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008112 if (*exceptionObject != NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008113 PyCodec_StrictErrors(*exceptionObject);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008114}
8115
8116/* error handling callback helper:
8117 build arguments, call the callback and check the arguments,
8118 put the result into newpos and return the replacement string, which
8119 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008120static PyObject *
8121unicode_translate_call_errorhandler(const char *errors,
8122 PyObject **errorHandler,
8123 const char *reason,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008124 PyObject *unicode, PyObject **exceptionObject,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008125 Py_ssize_t startpos, Py_ssize_t endpos,
8126 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008127{
Benjamin Peterson142957c2008-07-04 19:55:29 +00008128 static char *argparse = "O!n;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008129
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008130 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008131 PyObject *restuple;
8132 PyObject *resunicode;
8133
8134 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008135 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008136 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008137 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008138 }
8139
8140 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008141 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008142 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008143 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008144
8145 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00008146 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008147 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008148 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008149 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00008150 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00008151 Py_DECREF(restuple);
8152 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008153 }
8154 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type,
Benjamin Peterson29060642009-01-31 22:14:21 +00008155 &resunicode, &i_newpos)) {
8156 Py_DECREF(restuple);
8157 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008158 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00008159 if (i_newpos<0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008160 *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008161 else
8162 *newpos = i_newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008163 if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008164 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
8165 Py_DECREF(restuple);
8166 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00008167 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008168 Py_INCREF(resunicode);
8169 Py_DECREF(restuple);
8170 return resunicode;
8171}
8172
8173/* Lookup the character ch in the mapping and put the result in result,
8174 which must be decrefed by the caller.
8175 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008176static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008177charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008178{
Christian Heimes217cfd12007-12-02 14:31:20 +00008179 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008180 PyObject *x;
8181
8182 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008183 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008184 x = PyObject_GetItem(mapping, w);
8185 Py_DECREF(w);
8186 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008187 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8188 /* No mapping found means: use 1:1 mapping. */
8189 PyErr_Clear();
8190 *result = NULL;
8191 return 0;
8192 } else
8193 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008194 }
8195 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008196 *result = x;
8197 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008198 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008199 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008200 long value = PyLong_AS_LONG(x);
8201 long max = PyUnicode_GetMax();
8202 if (value < 0 || value > max) {
8203 PyErr_Format(PyExc_TypeError,
Guido van Rossum5a2f7e602007-10-24 21:13:09 +00008204 "character mapping must be in range(0x%x)", max+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00008205 Py_DECREF(x);
8206 return -1;
8207 }
8208 *result = x;
8209 return 0;
8210 }
8211 else if (PyUnicode_Check(x)) {
8212 *result = x;
8213 return 0;
8214 }
8215 else {
8216 /* wrong return value */
8217 PyErr_SetString(PyExc_TypeError,
8218 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00008219 Py_DECREF(x);
8220 return -1;
8221 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008222}
8223/* ensure that *outobj is at least requiredsize characters long,
Benjamin Peterson29060642009-01-31 22:14:21 +00008224 if not reallocate and adjust various state variables.
8225 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008226static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008227charmaptranslate_makespace(Py_UCS4 **outobj, Py_ssize_t *psize,
Benjamin Peterson29060642009-01-31 22:14:21 +00008228 Py_ssize_t requiredsize)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008229{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008230 Py_ssize_t oldsize = *psize;
Kristjan Valur Jonsson85634d72012-05-31 09:37:31 +00008231 Py_UCS4 *new_outobj;
Walter Dörwald4894c302003-10-24 14:25:28 +00008232 if (requiredsize > oldsize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008233 /* exponentially overallocate to minimize reallocations */
8234 if (requiredsize < 2 * oldsize)
8235 requiredsize = 2 * oldsize;
Kristjan Valur Jonsson85634d72012-05-31 09:37:31 +00008236 new_outobj = PyMem_Realloc(*outobj, requiredsize * sizeof(Py_UCS4));
8237 if (new_outobj == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008238 return -1;
Kristjan Valur Jonsson85634d72012-05-31 09:37:31 +00008239 *outobj = new_outobj;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008240 *psize = requiredsize;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008241 }
8242 return 0;
8243}
8244/* lookup the character, put the result in the output string and adjust
8245 various state variables. Return a new reference to the object that
8246 was put in the output buffer in *result, or Py_None, if the mapping was
8247 undefined (in which case no character was written).
8248 The called must decref result.
8249 Return 0 on success, -1 on error. */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008250static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008251charmaptranslate_output(PyObject *input, Py_ssize_t ipos,
8252 PyObject *mapping, Py_UCS4 **output,
8253 Py_ssize_t *osize, Py_ssize_t *opos,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008254 PyObject **res)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008255{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008256 Py_UCS4 curinp = PyUnicode_READ_CHAR(input, ipos);
8257 if (charmaptranslate_lookup(curinp, mapping, res))
Benjamin Peterson29060642009-01-31 22:14:21 +00008258 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008259 if (*res==NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008260 /* not found => default to 1:1 mapping */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008261 (*output)[(*opos)++] = curinp;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008262 }
8263 else if (*res==Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008264 ;
Christian Heimes217cfd12007-12-02 14:31:20 +00008265 else if (PyLong_Check(*res)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008266 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008267 (*output)[(*opos)++] = (Py_UCS4)PyLong_AS_LONG(*res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008268 }
8269 else if (PyUnicode_Check(*res)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008270 Py_ssize_t repsize;
8271 if (PyUnicode_READY(*res) == -1)
8272 return -1;
8273 repsize = PyUnicode_GET_LENGTH(*res);
Benjamin Peterson29060642009-01-31 22:14:21 +00008274 if (repsize==1) {
8275 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008276 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +00008277 }
8278 else if (repsize!=0) {
8279 /* more than one character */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008280 Py_ssize_t requiredsize = *opos +
8281 (PyUnicode_GET_LENGTH(input) - ipos) +
Benjamin Peterson29060642009-01-31 22:14:21 +00008282 repsize - 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008283 Py_ssize_t i;
8284 if (charmaptranslate_makespace(output, osize, requiredsize))
Benjamin Peterson29060642009-01-31 22:14:21 +00008285 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008286 for(i = 0; i < repsize; i++)
8287 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00008288 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008289 }
8290 else
Benjamin Peterson29060642009-01-31 22:14:21 +00008291 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008292 return 0;
8293}
8294
Alexander Belopolsky40018472011-02-26 01:02:56 +00008295PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008296_PyUnicode_TranslateCharmap(PyObject *input,
8297 PyObject *mapping,
8298 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008299{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008300 /* input object */
8301 char *idata;
8302 Py_ssize_t size, i;
8303 int kind;
8304 /* output buffer */
8305 Py_UCS4 *output = NULL;
8306 Py_ssize_t osize;
8307 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008308 /* current output position */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008309 Py_ssize_t opos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008310 char *reason = "character maps to <undefined>";
8311 PyObject *errorHandler = NULL;
8312 PyObject *exc = NULL;
8313 /* the following variable is used for caching string comparisons
8314 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8315 * 3=ignore, 4=xmlcharrefreplace */
8316 int known_errorHandler = -1;
8317
Guido van Rossumd57fd912000-03-10 22:53:23 +00008318 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008319 PyErr_BadArgument();
8320 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008321 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008322
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008323 if (PyUnicode_READY(input) == -1)
8324 return NULL;
8325 idata = (char*)PyUnicode_DATA(input);
8326 kind = PyUnicode_KIND(input);
8327 size = PyUnicode_GET_LENGTH(input);
8328 i = 0;
8329
8330 if (size == 0) {
8331 Py_INCREF(input);
8332 return input;
8333 }
8334
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008335 /* allocate enough for a simple 1:1 translation without
8336 replacements, if we need more, we'll resize */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008337 osize = size;
8338 output = PyMem_Malloc(osize * sizeof(Py_UCS4));
8339 opos = 0;
8340 if (output == NULL) {
8341 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00008342 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008343 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008344
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008345 while (i<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008346 /* try to encode it */
8347 PyObject *x = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008348 if (charmaptranslate_output(input, i, mapping,
8349 &output, &osize, &opos, &x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008350 Py_XDECREF(x);
8351 goto onError;
8352 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008353 Py_XDECREF(x);
Benjamin Peterson29060642009-01-31 22:14:21 +00008354 if (x!=Py_None) /* it worked => adjust input pointer */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008355 ++i;
Benjamin Peterson29060642009-01-31 22:14:21 +00008356 else { /* untranslatable character */
8357 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
8358 Py_ssize_t repsize;
8359 Py_ssize_t newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008360 Py_ssize_t uni2;
Benjamin Peterson29060642009-01-31 22:14:21 +00008361 /* startpos for collecting untranslatable chars */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008362 Py_ssize_t collstart = i;
8363 Py_ssize_t collend = i+1;
8364 Py_ssize_t coll;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008365
Benjamin Peterson29060642009-01-31 22:14:21 +00008366 /* find all untranslatable characters */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008367 while (collend < size) {
8368 if (charmaptranslate_lookup(PyUnicode_READ(kind,idata, collend), mapping, &x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008369 goto onError;
8370 Py_XDECREF(x);
8371 if (x!=Py_None)
8372 break;
8373 ++collend;
8374 }
8375 /* cache callback name lookup
8376 * (if not done yet, i.e. it's the first error) */
8377 if (known_errorHandler==-1) {
8378 if ((errors==NULL) || (!strcmp(errors, "strict")))
8379 known_errorHandler = 1;
8380 else if (!strcmp(errors, "replace"))
8381 known_errorHandler = 2;
8382 else if (!strcmp(errors, "ignore"))
8383 known_errorHandler = 3;
8384 else if (!strcmp(errors, "xmlcharrefreplace"))
8385 known_errorHandler = 4;
8386 else
8387 known_errorHandler = 0;
8388 }
8389 switch (known_errorHandler) {
8390 case 1: /* strict */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008391 raise_translate_exception(&exc, input, collstart,
8392 collend, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008393 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00008394 case 2: /* replace */
8395 /* No need to check for space, this is a 1:1 replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008396 for (coll = collstart; coll<collend; coll++)
8397 output[opos++] = '?';
Benjamin Peterson29060642009-01-31 22:14:21 +00008398 /* fall through */
8399 case 3: /* ignore */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008400 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008401 break;
8402 case 4: /* xmlcharrefreplace */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008403 /* generate replacement (temporarily (mis)uses i) */
8404 for (i = collstart; i < collend; ++i) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008405 char buffer[2+29+1+1];
8406 char *cp;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008407 sprintf(buffer, "&#%d;", PyUnicode_READ(kind, idata, i));
8408 if (charmaptranslate_makespace(&output, &osize,
8409 opos+strlen(buffer)+(size-collend)))
Benjamin Peterson29060642009-01-31 22:14:21 +00008410 goto onError;
8411 for (cp = buffer; *cp; ++cp)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008412 output[opos++] = *cp;
Benjamin Peterson29060642009-01-31 22:14:21 +00008413 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008414 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008415 break;
8416 default:
8417 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008418 reason, input, &exc,
8419 collstart, collend, &newpos);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008420 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008421 goto onError;
Benjamin Peterson9ca3ffa2012-01-01 16:04:29 -06008422 if (PyUnicode_READY(repunicode) == -1) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008423 Py_DECREF(repunicode);
8424 goto onError;
8425 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008426 /* generate replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008427 repsize = PyUnicode_GET_LENGTH(repunicode);
8428 if (charmaptranslate_makespace(&output, &osize,
8429 opos+repsize+(size-collend))) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008430 Py_DECREF(repunicode);
8431 goto onError;
8432 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008433 for (uni2 = 0; repsize-->0; ++uni2)
8434 output[opos++] = PyUnicode_READ_CHAR(repunicode, uni2);
8435 i = newpos;
Benjamin Peterson29060642009-01-31 22:14:21 +00008436 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008437 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008438 }
8439 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008440 res = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND, output, opos);
8441 if (!res)
8442 goto onError;
8443 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008444 Py_XDECREF(exc);
8445 Py_XDECREF(errorHandler);
8446 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008447
Benjamin Peterson29060642009-01-31 22:14:21 +00008448 onError:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008449 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008450 Py_XDECREF(exc);
8451 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008452 return NULL;
8453}
8454
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008455/* Deprecated. Use PyUnicode_Translate instead. */
8456PyObject *
8457PyUnicode_TranslateCharmap(const Py_UNICODE *p,
8458 Py_ssize_t size,
8459 PyObject *mapping,
8460 const char *errors)
8461{
Christian Heimes5f520f42012-09-11 14:03:25 +02008462 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008463 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8464 if (!unicode)
8465 return NULL;
Christian Heimes5f520f42012-09-11 14:03:25 +02008466 result = _PyUnicode_TranslateCharmap(unicode, mapping, errors);
8467 Py_DECREF(unicode);
8468 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008469}
8470
Alexander Belopolsky40018472011-02-26 01:02:56 +00008471PyObject *
8472PyUnicode_Translate(PyObject *str,
8473 PyObject *mapping,
8474 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008475{
8476 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +00008477
Guido van Rossumd57fd912000-03-10 22:53:23 +00008478 str = PyUnicode_FromObject(str);
8479 if (str == NULL)
Christian Heimes5f520f42012-09-11 14:03:25 +02008480 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008481 result = _PyUnicode_TranslateCharmap(str, mapping, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008482 Py_DECREF(str);
8483 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008484}
Tim Petersced69f82003-09-16 20:30:58 +00008485
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008486static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02008487fix_decimal_and_space_to_ascii(PyObject *self)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008488{
8489 /* No need to call PyUnicode_READY(self) because this function is only
8490 called as a callback from fixup() which does it already. */
8491 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
8492 const int kind = PyUnicode_KIND(self);
8493 void *data = PyUnicode_DATA(self);
Victor Stinnere6abb482012-05-02 01:15:40 +02008494 Py_UCS4 maxchar = 127, ch, fixed;
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008495 int modified = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008496 Py_ssize_t i;
8497
8498 for (i = 0; i < len; ++i) {
8499 ch = PyUnicode_READ(kind, data, i);
8500 fixed = 0;
8501 if (ch > 127) {
8502 if (Py_UNICODE_ISSPACE(ch))
8503 fixed = ' ';
8504 else {
8505 const int decimal = Py_UNICODE_TODECIMAL(ch);
8506 if (decimal >= 0)
8507 fixed = '0' + decimal;
8508 }
8509 if (fixed != 0) {
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008510 modified = 1;
Victor Stinnere6abb482012-05-02 01:15:40 +02008511 maxchar = MAX_MAXCHAR(maxchar, fixed);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008512 PyUnicode_WRITE(kind, data, i, fixed);
8513 }
Victor Stinnere6abb482012-05-02 01:15:40 +02008514 else
8515 maxchar = MAX_MAXCHAR(maxchar, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008516 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008517 }
8518
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008519 return (modified) ? maxchar : 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008520}
8521
8522PyObject *
8523_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
8524{
8525 if (!PyUnicode_Check(unicode)) {
8526 PyErr_BadInternalCall();
8527 return NULL;
8528 }
8529 if (PyUnicode_READY(unicode) == -1)
8530 return NULL;
8531 if (PyUnicode_MAX_CHAR_VALUE(unicode) <= 127) {
8532 /* If the string is already ASCII, just return the same string */
8533 Py_INCREF(unicode);
8534 return unicode;
8535 }
Victor Stinner9310abb2011-10-05 00:59:23 +02008536 return fixup(unicode, fix_decimal_and_space_to_ascii);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008537}
8538
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008539PyObject *
8540PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
8541 Py_ssize_t length)
8542{
Victor Stinnerf0124502011-11-21 23:12:56 +01008543 PyObject *decimal;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008544 Py_ssize_t i;
Victor Stinnerf0124502011-11-21 23:12:56 +01008545 Py_UCS4 maxchar;
8546 enum PyUnicode_Kind kind;
8547 void *data;
8548
Victor Stinner99d7ad02012-02-22 13:37:39 +01008549 maxchar = 127;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008550 for (i = 0; i < length; i++) {
Victor Stinnerf0124502011-11-21 23:12:56 +01008551 Py_UNICODE ch = s[i];
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008552 if (ch > 127) {
8553 int decimal = Py_UNICODE_TODECIMAL(ch);
8554 if (decimal >= 0)
Victor Stinnerf0124502011-11-21 23:12:56 +01008555 ch = '0' + decimal;
Victor Stinnere6abb482012-05-02 01:15:40 +02008556 maxchar = MAX_MAXCHAR(maxchar, ch);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008557 }
8558 }
Victor Stinnerf0124502011-11-21 23:12:56 +01008559
8560 /* Copy to a new string */
8561 decimal = PyUnicode_New(length, maxchar);
8562 if (decimal == NULL)
8563 return decimal;
8564 kind = PyUnicode_KIND(decimal);
8565 data = PyUnicode_DATA(decimal);
8566 /* Iterate over code points */
8567 for (i = 0; i < length; i++) {
8568 Py_UNICODE ch = s[i];
8569 if (ch > 127) {
8570 int decimal = Py_UNICODE_TODECIMAL(ch);
8571 if (decimal >= 0)
8572 ch = '0' + decimal;
8573 }
8574 PyUnicode_WRITE(kind, data, i, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008575 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008576 return unicode_result(decimal);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008577}
Guido van Rossum9e896b32000-04-05 20:11:21 +00008578/* --- Decimal Encoder ---------------------------------------------------- */
8579
Alexander Belopolsky40018472011-02-26 01:02:56 +00008580int
8581PyUnicode_EncodeDecimal(Py_UNICODE *s,
8582 Py_ssize_t length,
8583 char *output,
8584 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00008585{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008586 PyObject *unicode;
Victor Stinner6345be92011-11-25 20:09:01 +01008587 Py_ssize_t i;
Victor Stinner42bf7752011-11-21 22:52:58 +01008588 enum PyUnicode_Kind kind;
8589 void *data;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008590
8591 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008592 PyErr_BadArgument();
8593 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008594 }
8595
Victor Stinner42bf7752011-11-21 22:52:58 +01008596 unicode = PyUnicode_FromUnicode(s, length);
8597 if (unicode == NULL)
8598 return -1;
8599
Benjamin Petersonbac79492012-01-14 13:34:47 -05008600 if (PyUnicode_READY(unicode) == -1) {
Victor Stinner6345be92011-11-25 20:09:01 +01008601 Py_DECREF(unicode);
8602 return -1;
8603 }
Victor Stinner42bf7752011-11-21 22:52:58 +01008604 kind = PyUnicode_KIND(unicode);
8605 data = PyUnicode_DATA(unicode);
8606
Victor Stinnerb84d7232011-11-22 01:50:07 +01008607 for (i=0; i < length; ) {
Victor Stinner6345be92011-11-25 20:09:01 +01008608 PyObject *exc;
8609 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00008610 int decimal;
Victor Stinner6345be92011-11-25 20:09:01 +01008611 Py_ssize_t startpos;
8612
8613 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +00008614
Benjamin Peterson29060642009-01-31 22:14:21 +00008615 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008616 *output++ = ' ';
Victor Stinnerb84d7232011-11-22 01:50:07 +01008617 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00008618 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008619 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008620 decimal = Py_UNICODE_TODECIMAL(ch);
8621 if (decimal >= 0) {
8622 *output++ = '0' + decimal;
Victor Stinnerb84d7232011-11-22 01:50:07 +01008623 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00008624 continue;
8625 }
8626 if (0 < ch && ch < 256) {
8627 *output++ = (char)ch;
Victor Stinnerb84d7232011-11-22 01:50:07 +01008628 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00008629 continue;
8630 }
Victor Stinner6345be92011-11-25 20:09:01 +01008631
Victor Stinner42bf7752011-11-21 22:52:58 +01008632 startpos = i;
Victor Stinner6345be92011-11-25 20:09:01 +01008633 exc = NULL;
8634 raise_encode_exception(&exc, "decimal", unicode,
8635 startpos, startpos+1,
8636 "invalid decimal Unicode string");
8637 Py_XDECREF(exc);
8638 Py_DECREF(unicode);
8639 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008640 }
8641 /* 0-terminate the output string */
8642 *output++ = '\0';
Victor Stinner42bf7752011-11-21 22:52:58 +01008643 Py_DECREF(unicode);
Guido van Rossum9e896b32000-04-05 20:11:21 +00008644 return 0;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008645}
8646
Guido van Rossumd57fd912000-03-10 22:53:23 +00008647/* --- Helpers ------------------------------------------------------------ */
8648
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008649static Py_ssize_t
Victor Stinner794d5672011-10-10 03:21:36 +02008650any_find_slice(int direction, PyObject* s1, PyObject* s2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008651 Py_ssize_t start,
8652 Py_ssize_t end)
8653{
8654 int kind1, kind2, kind;
8655 void *buf1, *buf2;
8656 Py_ssize_t len1, len2, result;
8657
8658 kind1 = PyUnicode_KIND(s1);
8659 kind2 = PyUnicode_KIND(s2);
8660 kind = kind1 > kind2 ? kind1 : kind2;
8661 buf1 = PyUnicode_DATA(s1);
8662 buf2 = PyUnicode_DATA(s2);
8663 if (kind1 != kind)
8664 buf1 = _PyUnicode_AsKind(s1, kind);
8665 if (!buf1)
8666 return -2;
8667 if (kind2 != kind)
8668 buf2 = _PyUnicode_AsKind(s2, kind);
8669 if (!buf2) {
8670 if (kind1 != kind) PyMem_Free(buf1);
8671 return -2;
8672 }
8673 len1 = PyUnicode_GET_LENGTH(s1);
8674 len2 = PyUnicode_GET_LENGTH(s2);
8675
Victor Stinner794d5672011-10-10 03:21:36 +02008676 if (direction > 0) {
Benjamin Petersonead6b532011-12-20 17:23:42 -06008677 switch (kind) {
Victor Stinner794d5672011-10-10 03:21:36 +02008678 case PyUnicode_1BYTE_KIND:
8679 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
8680 result = asciilib_find_slice(buf1, len1, buf2, len2, start, end);
8681 else
8682 result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end);
8683 break;
8684 case PyUnicode_2BYTE_KIND:
8685 result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end);
8686 break;
8687 case PyUnicode_4BYTE_KIND:
8688 result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end);
8689 break;
8690 default:
8691 assert(0); result = -2;
8692 }
8693 }
8694 else {
Benjamin Petersonead6b532011-12-20 17:23:42 -06008695 switch (kind) {
Victor Stinner794d5672011-10-10 03:21:36 +02008696 case PyUnicode_1BYTE_KIND:
8697 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
8698 result = asciilib_rfind_slice(buf1, len1, buf2, len2, start, end);
8699 else
8700 result = ucs1lib_rfind_slice(buf1, len1, buf2, len2, start, end);
8701 break;
8702 case PyUnicode_2BYTE_KIND:
8703 result = ucs2lib_rfind_slice(buf1, len1, buf2, len2, start, end);
8704 break;
8705 case PyUnicode_4BYTE_KIND:
8706 result = ucs4lib_rfind_slice(buf1, len1, buf2, len2, start, end);
8707 break;
8708 default:
8709 assert(0); result = -2;
8710 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008711 }
8712
8713 if (kind1 != kind)
8714 PyMem_Free(buf1);
8715 if (kind2 != kind)
8716 PyMem_Free(buf2);
8717
8718 return result;
8719}
8720
8721Py_ssize_t
Victor Stinner41a863c2012-02-24 00:37:51 +01008722_PyUnicode_InsertThousandsGrouping(
8723 PyObject *unicode, Py_ssize_t index,
8724 Py_ssize_t n_buffer,
8725 void *digits, Py_ssize_t n_digits,
8726 Py_ssize_t min_width,
8727 const char *grouping, PyObject *thousands_sep,
8728 Py_UCS4 *maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008729{
Victor Stinner41a863c2012-02-24 00:37:51 +01008730 unsigned int kind, thousands_sep_kind;
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008731 char *data, *thousands_sep_data;
Victor Stinner41a863c2012-02-24 00:37:51 +01008732 Py_ssize_t thousands_sep_len;
8733 Py_ssize_t len;
8734
8735 if (unicode != NULL) {
8736 kind = PyUnicode_KIND(unicode);
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008737 data = (char *) PyUnicode_DATA(unicode) + index * kind;
Victor Stinner41a863c2012-02-24 00:37:51 +01008738 }
8739 else {
8740 kind = PyUnicode_1BYTE_KIND;
8741 data = NULL;
8742 }
8743 thousands_sep_kind = PyUnicode_KIND(thousands_sep);
8744 thousands_sep_data = PyUnicode_DATA(thousands_sep);
8745 thousands_sep_len = PyUnicode_GET_LENGTH(thousands_sep);
8746 if (unicode != NULL && thousands_sep_kind != kind) {
Victor Stinner90f50d42012-02-24 01:44:47 +01008747 if (thousands_sep_kind < kind) {
8748 thousands_sep_data = _PyUnicode_AsKind(thousands_sep, kind);
8749 if (!thousands_sep_data)
8750 return -1;
8751 }
8752 else {
8753 data = _PyUnicode_AsKind(unicode, thousands_sep_kind);
8754 if (!data)
8755 return -1;
8756 }
Victor Stinner41a863c2012-02-24 00:37:51 +01008757 }
8758
Benjamin Petersonead6b532011-12-20 17:23:42 -06008759 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008760 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02008761 if (unicode != NULL && PyUnicode_IS_ASCII(unicode))
Victor Stinner41a863c2012-02-24 00:37:51 +01008762 len = asciilib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008763 (Py_UCS1 *) data, n_buffer, (Py_UCS1 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01008764 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008765 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinnerc3cec782011-10-05 21:24:08 +02008766 else
Victor Stinner41a863c2012-02-24 00:37:51 +01008767 len = ucs1lib_InsertThousandsGrouping(
Victor Stinnerc3cec782011-10-05 21:24:08 +02008768 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01008769 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008770 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01008771 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008772 case PyUnicode_2BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01008773 len = ucs2lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008774 (Py_UCS2 *) data, n_buffer, (Py_UCS2 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01008775 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008776 (Py_UCS2 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01008777 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008778 case PyUnicode_4BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01008779 len = ucs4lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008780 (Py_UCS4 *) data, n_buffer, (Py_UCS4 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01008781 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008782 (Py_UCS4 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01008783 break;
8784 default:
8785 assert(0);
8786 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008787 }
Victor Stinner90f50d42012-02-24 01:44:47 +01008788 if (unicode != NULL && thousands_sep_kind != kind) {
8789 if (thousands_sep_kind < kind)
8790 PyMem_Free(thousands_sep_data);
8791 else
8792 PyMem_Free(data);
8793 }
Victor Stinner41a863c2012-02-24 00:37:51 +01008794 if (unicode == NULL) {
8795 *maxchar = 127;
8796 if (len != n_digits) {
Victor Stinnere6abb482012-05-02 01:15:40 +02008797 *maxchar = MAX_MAXCHAR(*maxchar,
8798 PyUnicode_MAX_CHAR_VALUE(thousands_sep));
Victor Stinner41a863c2012-02-24 00:37:51 +01008799 }
8800 }
8801 return len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008802}
8803
8804
Thomas Wouters477c8d52006-05-27 19:21:47 +00008805/* helper macro to fixup start/end slice values */
Antoine Pitrouf2c54842010-01-13 08:07:53 +00008806#define ADJUST_INDICES(start, end, len) \
8807 if (end > len) \
8808 end = len; \
8809 else if (end < 0) { \
8810 end += len; \
8811 if (end < 0) \
8812 end = 0; \
8813 } \
8814 if (start < 0) { \
8815 start += len; \
8816 if (start < 0) \
8817 start = 0; \
8818 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00008819
Alexander Belopolsky40018472011-02-26 01:02:56 +00008820Py_ssize_t
8821PyUnicode_Count(PyObject *str,
8822 PyObject *substr,
8823 Py_ssize_t start,
8824 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008825{
Martin v. Löwis18e16552006-02-15 17:27:45 +00008826 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02008827 PyObject* str_obj;
8828 PyObject* sub_obj;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008829 int kind1, kind2, kind;
8830 void *buf1 = NULL, *buf2 = NULL;
8831 Py_ssize_t len1, len2;
Tim Petersced69f82003-09-16 20:30:58 +00008832
Victor Stinner9db1a8b2011-10-23 20:04:37 +02008833 str_obj = PyUnicode_FromObject(str);
Benjamin Peterson22a29702012-01-02 09:00:30 -06008834 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +00008835 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02008836 sub_obj = PyUnicode_FromObject(substr);
Benjamin Peterson22a29702012-01-02 09:00:30 -06008837 if (!sub_obj) {
8838 Py_DECREF(str_obj);
8839 return -1;
8840 }
Benjamin Peterson4c13a4a2012-01-02 09:07:38 -06008841 if (PyUnicode_READY(sub_obj) == -1 || PyUnicode_READY(str_obj) == -1) {
Benjamin Peterson5e458f52012-01-02 10:12:13 -06008842 Py_DECREF(sub_obj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008843 Py_DECREF(str_obj);
8844 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008845 }
Tim Petersced69f82003-09-16 20:30:58 +00008846
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008847 kind1 = PyUnicode_KIND(str_obj);
8848 kind2 = PyUnicode_KIND(sub_obj);
Antoine Pitroue45c0c52012-05-12 15:49:07 +02008849 kind = kind1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008850 buf1 = PyUnicode_DATA(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008851 buf2 = PyUnicode_DATA(sub_obj);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -05008852 if (kind2 != kind) {
Antoine Pitrou758153b2012-05-12 15:51:51 +02008853 if (kind2 > kind) {
8854 Py_DECREF(sub_obj);
8855 Py_DECREF(str_obj);
Antoine Pitroue45c0c52012-05-12 15:49:07 +02008856 return 0;
Antoine Pitrou758153b2012-05-12 15:51:51 +02008857 }
Victor Stinner7931d9a2011-11-04 00:22:48 +01008858 buf2 = _PyUnicode_AsKind(sub_obj, kind);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -05008859 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008860 if (!buf2)
8861 goto onError;
8862 len1 = PyUnicode_GET_LENGTH(str_obj);
8863 len2 = PyUnicode_GET_LENGTH(sub_obj);
8864
8865 ADJUST_INDICES(start, end, len1);
Benjamin Petersonead6b532011-12-20 17:23:42 -06008866 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008867 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02008868 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sub_obj))
8869 result = asciilib_count(
8870 ((Py_UCS1*)buf1) + start, end - start,
8871 buf2, len2, PY_SSIZE_T_MAX
8872 );
8873 else
8874 result = ucs1lib_count(
8875 ((Py_UCS1*)buf1) + start, end - start,
8876 buf2, len2, PY_SSIZE_T_MAX
8877 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008878 break;
8879 case PyUnicode_2BYTE_KIND:
8880 result = ucs2lib_count(
8881 ((Py_UCS2*)buf1) + start, end - start,
8882 buf2, len2, PY_SSIZE_T_MAX
8883 );
8884 break;
8885 case PyUnicode_4BYTE_KIND:
8886 result = ucs4lib_count(
8887 ((Py_UCS4*)buf1) + start, end - start,
8888 buf2, len2, PY_SSIZE_T_MAX
8889 );
8890 break;
8891 default:
8892 assert(0); result = 0;
8893 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00008894
8895 Py_DECREF(sub_obj);
8896 Py_DECREF(str_obj);
8897
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008898 if (kind2 != kind)
8899 PyMem_Free(buf2);
8900
Guido van Rossumd57fd912000-03-10 22:53:23 +00008901 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008902 onError:
8903 Py_DECREF(sub_obj);
8904 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008905 if (kind2 != kind && buf2)
8906 PyMem_Free(buf2);
8907 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008908}
8909
Alexander Belopolsky40018472011-02-26 01:02:56 +00008910Py_ssize_t
8911PyUnicode_Find(PyObject *str,
8912 PyObject *sub,
8913 Py_ssize_t start,
8914 Py_ssize_t end,
8915 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008916{
Martin v. Löwis18e16552006-02-15 17:27:45 +00008917 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00008918
Guido van Rossumd57fd912000-03-10 22:53:23 +00008919 str = PyUnicode_FromObject(str);
Benjamin Peterson22a29702012-01-02 09:00:30 -06008920 if (!str)
Benjamin Peterson29060642009-01-31 22:14:21 +00008921 return -2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00008922 sub = PyUnicode_FromObject(sub);
Benjamin Peterson22a29702012-01-02 09:00:30 -06008923 if (!sub) {
8924 Py_DECREF(str);
8925 return -2;
8926 }
8927 if (PyUnicode_READY(sub) == -1 || PyUnicode_READY(str) == -1) {
8928 Py_DECREF(sub);
Benjamin Peterson29060642009-01-31 22:14:21 +00008929 Py_DECREF(str);
8930 return -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008931 }
Tim Petersced69f82003-09-16 20:30:58 +00008932
Victor Stinner794d5672011-10-10 03:21:36 +02008933 result = any_find_slice(direction,
8934 str, sub, start, end
8935 );
Thomas Wouters477c8d52006-05-27 19:21:47 +00008936
Guido van Rossumd57fd912000-03-10 22:53:23 +00008937 Py_DECREF(str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00008938 Py_DECREF(sub);
8939
Guido van Rossumd57fd912000-03-10 22:53:23 +00008940 return result;
8941}
8942
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008943Py_ssize_t
8944PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
8945 Py_ssize_t start, Py_ssize_t end,
8946 int direction)
8947{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008948 int kind;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02008949 Py_ssize_t result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008950 if (PyUnicode_READY(str) == -1)
8951 return -2;
Victor Stinner267aa242011-10-02 01:08:37 +02008952 if (start < 0 || end < 0) {
8953 PyErr_SetString(PyExc_IndexError, "string index out of range");
8954 return -2;
8955 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008956 if (end > PyUnicode_GET_LENGTH(str))
8957 end = PyUnicode_GET_LENGTH(str);
8958 kind = PyUnicode_KIND(str);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02008959 result = findchar(PyUnicode_1BYTE_DATA(str) + kind*start,
8960 kind, end-start, ch, direction);
8961 if (result == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008962 return -1;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02008963 else
8964 return start + result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008965}
8966
Alexander Belopolsky40018472011-02-26 01:02:56 +00008967static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +02008968tailmatch(PyObject *self,
8969 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008970 Py_ssize_t start,
8971 Py_ssize_t end,
8972 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008973{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008974 int kind_self;
8975 int kind_sub;
8976 void *data_self;
8977 void *data_sub;
8978 Py_ssize_t offset;
8979 Py_ssize_t i;
8980 Py_ssize_t end_sub;
8981
8982 if (PyUnicode_READY(self) == -1 ||
8983 PyUnicode_READY(substring) == -1)
8984 return 0;
8985
8986 if (PyUnicode_GET_LENGTH(substring) == 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008987 return 1;
8988
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008989 ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
8990 end -= PyUnicode_GET_LENGTH(substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008991 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00008992 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008993
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008994 kind_self = PyUnicode_KIND(self);
8995 data_self = PyUnicode_DATA(self);
8996 kind_sub = PyUnicode_KIND(substring);
8997 data_sub = PyUnicode_DATA(substring);
8998 end_sub = PyUnicode_GET_LENGTH(substring) - 1;
8999
9000 if (direction > 0)
9001 offset = end;
9002 else
9003 offset = start;
9004
9005 if (PyUnicode_READ(kind_self, data_self, offset) ==
9006 PyUnicode_READ(kind_sub, data_sub, 0) &&
9007 PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
9008 PyUnicode_READ(kind_sub, data_sub, end_sub)) {
9009 /* If both are of the same kind, memcmp is sufficient */
9010 if (kind_self == kind_sub) {
9011 return ! memcmp((char *)data_self +
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009012 (offset * PyUnicode_KIND(substring)),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009013 data_sub,
9014 PyUnicode_GET_LENGTH(substring) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009015 PyUnicode_KIND(substring));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009016 }
9017 /* otherwise we have to compare each character by first accesing it */
9018 else {
9019 /* We do not need to compare 0 and len(substring)-1 because
9020 the if statement above ensured already that they are equal
9021 when we end up here. */
Antoine Pitrou057119b2012-09-02 17:56:33 +02009022 /* TODO: honor direction and do a forward or backwards search */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009023 for (i = 1; i < end_sub; ++i) {
9024 if (PyUnicode_READ(kind_self, data_self, offset + i) !=
9025 PyUnicode_READ(kind_sub, data_sub, i))
9026 return 0;
9027 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009028 return 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009029 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009030 }
9031
9032 return 0;
9033}
9034
Alexander Belopolsky40018472011-02-26 01:02:56 +00009035Py_ssize_t
9036PyUnicode_Tailmatch(PyObject *str,
9037 PyObject *substr,
9038 Py_ssize_t start,
9039 Py_ssize_t end,
9040 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009041{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009042 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009043
Guido van Rossumd57fd912000-03-10 22:53:23 +00009044 str = PyUnicode_FromObject(str);
9045 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009046 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009047 substr = PyUnicode_FromObject(substr);
9048 if (substr == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009049 Py_DECREF(str);
9050 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009051 }
Tim Petersced69f82003-09-16 20:30:58 +00009052
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009053 result = tailmatch(str, substr,
Benjamin Peterson29060642009-01-31 22:14:21 +00009054 start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009055 Py_DECREF(str);
9056 Py_DECREF(substr);
9057 return result;
9058}
9059
Guido van Rossumd57fd912000-03-10 22:53:23 +00009060/* Apply fixfct filter to the Unicode object self and return a
9061 reference to the modified object */
9062
Alexander Belopolsky40018472011-02-26 01:02:56 +00009063static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009064fixup(PyObject *self,
9065 Py_UCS4 (*fixfct)(PyObject *s))
Guido van Rossumd57fd912000-03-10 22:53:23 +00009066{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009067 PyObject *u;
9068 Py_UCS4 maxchar_old, maxchar_new = 0;
Victor Stinnereaab6042011-12-11 22:22:39 +01009069 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009070
Victor Stinnerbf6e5602011-12-12 01:53:47 +01009071 u = _PyUnicode_Copy(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009072 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009073 return NULL;
Victor Stinner87af4f22011-11-21 23:03:47 +01009074 maxchar_old = PyUnicode_MAX_CHAR_VALUE(u);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009075
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009076 /* fix functions return the new maximum character in a string,
9077 if the kind of the resulting unicode object does not change,
9078 everything is fine. Otherwise we need to change the string kind
9079 and re-run the fix function. */
Victor Stinner9310abb2011-10-05 00:59:23 +02009080 maxchar_new = fixfct(u);
Victor Stinnereaab6042011-12-11 22:22:39 +01009081
9082 if (maxchar_new == 0) {
9083 /* no changes */;
9084 if (PyUnicode_CheckExact(self)) {
9085 Py_DECREF(u);
9086 Py_INCREF(self);
9087 return self;
9088 }
9089 else
9090 return u;
9091 }
9092
Victor Stinnere6abb482012-05-02 01:15:40 +02009093 maxchar_new = align_maxchar(maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009094
Victor Stinnereaab6042011-12-11 22:22:39 +01009095 if (maxchar_new == maxchar_old)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009096 return u;
Victor Stinnereaab6042011-12-11 22:22:39 +01009097
9098 /* In case the maximum character changed, we need to
9099 convert the string to the new category. */
9100 v = PyUnicode_New(PyUnicode_GET_LENGTH(self), maxchar_new);
9101 if (v == NULL) {
9102 Py_DECREF(u);
9103 return NULL;
9104 }
9105 if (maxchar_new > maxchar_old) {
9106 /* If the maxchar increased so that the kind changed, not all
9107 characters are representable anymore and we need to fix the
9108 string again. This only happens in very few cases. */
Victor Stinnerd3f08822012-05-29 12:57:52 +02009109 _PyUnicode_FastCopyCharacters(v, 0,
9110 self, 0, PyUnicode_GET_LENGTH(self));
Victor Stinnereaab6042011-12-11 22:22:39 +01009111 maxchar_old = fixfct(v);
9112 assert(maxchar_old > 0 && maxchar_old <= maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009113 }
9114 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02009115 _PyUnicode_FastCopyCharacters(v, 0,
9116 u, 0, PyUnicode_GET_LENGTH(self));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009117 }
Victor Stinnereaab6042011-12-11 22:22:39 +01009118 Py_DECREF(u);
9119 assert(_PyUnicode_CheckConsistency(v, 1));
9120 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009121}
9122
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009123static PyObject *
9124ascii_upper_or_lower(PyObject *self, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009125{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009126 Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9127 char *resdata, *data = PyUnicode_DATA(self);
9128 PyObject *res;
Tim Petersced69f82003-09-16 20:30:58 +00009129
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009130 res = PyUnicode_New(len, 127);
9131 if (res == NULL)
9132 return NULL;
9133 resdata = PyUnicode_DATA(res);
9134 if (lower)
9135 _Py_bytes_lower(resdata, data, len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009136 else
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009137 _Py_bytes_upper(resdata, data, len);
9138 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009139}
9140
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009141static Py_UCS4
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009142handle_capital_sigma(int kind, void *data, Py_ssize_t length, Py_ssize_t i)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009143{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009144 Py_ssize_t j;
9145 int final_sigma;
9146 Py_UCS4 c;
9147 /* U+03A3 is in the Final_Sigma context when, it is found like this:
Tim Petersced69f82003-09-16 20:30:58 +00009148
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009149 \p{cased}\p{case-ignorable}*U+03A3!(\p{case-ignorable}*\p{cased})
9150
9151 where ! is a negation and \p{xxx} is a character with property xxx.
9152 */
9153 for (j = i - 1; j >= 0; j--) {
9154 c = PyUnicode_READ(kind, data, j);
9155 if (!_PyUnicode_IsCaseIgnorable(c))
9156 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009157 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009158 final_sigma = j >= 0 && _PyUnicode_IsCased(c);
9159 if (final_sigma) {
9160 for (j = i + 1; j < length; j++) {
9161 c = PyUnicode_READ(kind, data, j);
9162 if (!_PyUnicode_IsCaseIgnorable(c))
9163 break;
9164 }
9165 final_sigma = j == length || !_PyUnicode_IsCased(c);
9166 }
9167 return (final_sigma) ? 0x3C2 : 0x3C3;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009168}
9169
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009170static int
9171lower_ucs4(int kind, void *data, Py_ssize_t length, Py_ssize_t i,
9172 Py_UCS4 c, Py_UCS4 *mapped)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009173{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009174 /* Obscure special case. */
9175 if (c == 0x3A3) {
9176 mapped[0] = handle_capital_sigma(kind, data, length, i);
9177 return 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009178 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009179 return _PyUnicode_ToLowerFull(c, mapped);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009180}
9181
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009182static Py_ssize_t
9183do_capitalize(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009184{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009185 Py_ssize_t i, k = 0;
9186 int n_res, j;
9187 Py_UCS4 c, mapped[3];
Tim Petersced69f82003-09-16 20:30:58 +00009188
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009189 c = PyUnicode_READ(kind, data, 0);
9190 n_res = _PyUnicode_ToUpperFull(c, mapped);
9191 for (j = 0; j < n_res; j++) {
Victor Stinnere6abb482012-05-02 01:15:40 +02009192 *maxchar = MAX_MAXCHAR(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009193 res[k++] = mapped[j];
Guido van Rossumd57fd912000-03-10 22:53:23 +00009194 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009195 for (i = 1; i < length; i++) {
9196 c = PyUnicode_READ(kind, data, i);
9197 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9198 for (j = 0; j < n_res; j++) {
Victor Stinnere6abb482012-05-02 01:15:40 +02009199 *maxchar = MAX_MAXCHAR(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009200 res[k++] = mapped[j];
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009201 }
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009202 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009203 return k;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009204}
9205
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009206static Py_ssize_t
9207do_swapcase(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar) {
9208 Py_ssize_t i, k = 0;
9209
9210 for (i = 0; i < length; i++) {
9211 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9212 int n_res, j;
9213 if (Py_UNICODE_ISUPPER(c)) {
9214 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9215 }
9216 else if (Py_UNICODE_ISLOWER(c)) {
9217 n_res = _PyUnicode_ToUpperFull(c, mapped);
9218 }
9219 else {
9220 n_res = 1;
9221 mapped[0] = c;
9222 }
9223 for (j = 0; j < n_res; j++) {
Victor Stinnere6abb482012-05-02 01:15:40 +02009224 *maxchar = MAX_MAXCHAR(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009225 res[k++] = mapped[j];
9226 }
9227 }
9228 return k;
9229}
9230
9231static Py_ssize_t
9232do_upper_or_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res,
9233 Py_UCS4 *maxchar, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009234{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009235 Py_ssize_t i, k = 0;
9236
9237 for (i = 0; i < length; i++) {
9238 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9239 int n_res, j;
9240 if (lower)
9241 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9242 else
9243 n_res = _PyUnicode_ToUpperFull(c, mapped);
9244 for (j = 0; j < n_res; j++) {
Victor Stinnere6abb482012-05-02 01:15:40 +02009245 *maxchar = MAX_MAXCHAR(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009246 res[k++] = mapped[j];
9247 }
9248 }
9249 return k;
9250}
9251
9252static Py_ssize_t
9253do_upper(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9254{
9255 return do_upper_or_lower(kind, data, length, res, maxchar, 0);
9256}
9257
9258static Py_ssize_t
9259do_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9260{
9261 return do_upper_or_lower(kind, data, length, res, maxchar, 1);
9262}
9263
Benjamin Petersone51757f2012-01-12 21:10:29 -05009264static Py_ssize_t
Benjamin Petersond5890c82012-01-14 13:23:30 -05009265do_casefold(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9266{
9267 Py_ssize_t i, k = 0;
9268
9269 for (i = 0; i < length; i++) {
9270 Py_UCS4 c = PyUnicode_READ(kind, data, i);
9271 Py_UCS4 mapped[3];
9272 int j, n_res = _PyUnicode_ToFoldedFull(c, mapped);
9273 for (j = 0; j < n_res; j++) {
Victor Stinnere6abb482012-05-02 01:15:40 +02009274 *maxchar = MAX_MAXCHAR(*maxchar, mapped[j]);
Benjamin Petersond5890c82012-01-14 13:23:30 -05009275 res[k++] = mapped[j];
9276 }
9277 }
9278 return k;
9279}
9280
9281static Py_ssize_t
Benjamin Petersone51757f2012-01-12 21:10:29 -05009282do_title(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9283{
9284 Py_ssize_t i, k = 0;
9285 int previous_is_cased;
9286
9287 previous_is_cased = 0;
9288 for (i = 0; i < length; i++) {
9289 const Py_UCS4 c = PyUnicode_READ(kind, data, i);
9290 Py_UCS4 mapped[3];
9291 int n_res, j;
9292
9293 if (previous_is_cased)
9294 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9295 else
9296 n_res = _PyUnicode_ToTitleFull(c, mapped);
9297
9298 for (j = 0; j < n_res; j++) {
Victor Stinnere6abb482012-05-02 01:15:40 +02009299 *maxchar = MAX_MAXCHAR(*maxchar, mapped[j]);
Benjamin Petersone51757f2012-01-12 21:10:29 -05009300 res[k++] = mapped[j];
9301 }
9302
9303 previous_is_cased = _PyUnicode_IsCased(c);
9304 }
9305 return k;
9306}
9307
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009308static PyObject *
9309case_operation(PyObject *self,
9310 Py_ssize_t (*perform)(int, void *, Py_ssize_t, Py_UCS4 *, Py_UCS4 *))
9311{
9312 PyObject *res = NULL;
9313 Py_ssize_t length, newlength = 0;
9314 int kind, outkind;
9315 void *data, *outdata;
9316 Py_UCS4 maxchar = 0, *tmp, *tmpend;
9317
Benjamin Petersoneea48462012-01-16 14:28:50 -05009318 assert(PyUnicode_IS_READY(self));
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009319
9320 kind = PyUnicode_KIND(self);
9321 data = PyUnicode_DATA(self);
9322 length = PyUnicode_GET_LENGTH(self);
9323 tmp = PyMem_MALLOC(sizeof(Py_UCS4) * 3 * length);
9324 if (tmp == NULL)
9325 return PyErr_NoMemory();
9326 newlength = perform(kind, data, length, tmp, &maxchar);
9327 res = PyUnicode_New(newlength, maxchar);
9328 if (res == NULL)
9329 goto leave;
9330 tmpend = tmp + newlength;
9331 outdata = PyUnicode_DATA(res);
9332 outkind = PyUnicode_KIND(res);
9333 switch (outkind) {
9334 case PyUnicode_1BYTE_KIND:
9335 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, tmp, tmpend, outdata);
9336 break;
9337 case PyUnicode_2BYTE_KIND:
9338 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, tmp, tmpend, outdata);
9339 break;
9340 case PyUnicode_4BYTE_KIND:
9341 memcpy(outdata, tmp, sizeof(Py_UCS4) * newlength);
9342 break;
9343 default:
9344 assert(0);
9345 break;
9346 }
9347 leave:
9348 PyMem_FREE(tmp);
9349 return res;
9350}
9351
Tim Peters8ce9f162004-08-27 01:49:32 +00009352PyObject *
9353PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009354{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009355 PyObject *sep = NULL;
Victor Stinnerdd077322011-10-07 17:02:31 +02009356 Py_ssize_t seplen;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009357 PyObject *res = NULL; /* the result */
Tim Peters05eba1f2004-08-27 21:32:02 +00009358 PyObject *fseq; /* PySequence_Fast(seq) */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009359 Py_ssize_t seqlen; /* len(fseq) -- number of items in sequence */
9360 PyObject **items;
Tim Peters8ce9f162004-08-27 01:49:32 +00009361 PyObject *item;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009362 Py_ssize_t sz, i, res_offset;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009363 Py_UCS4 maxchar;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009364 Py_UCS4 item_maxchar;
Victor Stinnerdd077322011-10-07 17:02:31 +02009365 int use_memcpy;
9366 unsigned char *res_data = NULL, *sep_data = NULL;
9367 PyObject *last_obj;
9368 unsigned int kind = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009369
Tim Peters05eba1f2004-08-27 21:32:02 +00009370 fseq = PySequence_Fast(seq, "");
9371 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009372 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00009373 }
9374
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009375 /* NOTE: the following code can't call back into Python code,
9376 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00009377 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009378
Tim Peters05eba1f2004-08-27 21:32:02 +00009379 seqlen = PySequence_Fast_GET_SIZE(fseq);
9380 /* If empty sequence, return u"". */
9381 if (seqlen == 0) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009382 Py_DECREF(fseq);
9383 Py_INCREF(unicode_empty);
9384 res = unicode_empty;
9385 return res;
Tim Peters05eba1f2004-08-27 21:32:02 +00009386 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009387
Tim Peters05eba1f2004-08-27 21:32:02 +00009388 /* If singleton sequence with an exact Unicode, return that. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009389 last_obj = NULL;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009390 items = PySequence_Fast_ITEMS(fseq);
Victor Stinneracf47b82011-10-06 12:32:37 +02009391 if (seqlen == 1) {
9392 if (PyUnicode_CheckExact(items[0])) {
9393 res = items[0];
9394 Py_INCREF(res);
9395 Py_DECREF(fseq);
9396 return res;
9397 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009398 seplen = 0;
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009399 maxchar = 0;
Tim Peters8ce9f162004-08-27 01:49:32 +00009400 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009401 else {
Victor Stinneracf47b82011-10-06 12:32:37 +02009402 /* Set up sep and seplen */
9403 if (separator == NULL) {
9404 /* fall back to a blank space separator */
9405 sep = PyUnicode_FromOrdinal(' ');
9406 if (!sep)
9407 goto onError;
Victor Stinnerdd077322011-10-07 17:02:31 +02009408 seplen = 1;
Victor Stinneracf47b82011-10-06 12:32:37 +02009409 maxchar = 32;
Tim Peters05eba1f2004-08-27 21:32:02 +00009410 }
Victor Stinneracf47b82011-10-06 12:32:37 +02009411 else {
9412 if (!PyUnicode_Check(separator)) {
9413 PyErr_Format(PyExc_TypeError,
9414 "separator: expected str instance,"
9415 " %.80s found",
9416 Py_TYPE(separator)->tp_name);
9417 goto onError;
9418 }
9419 if (PyUnicode_READY(separator))
9420 goto onError;
9421 sep = separator;
9422 seplen = PyUnicode_GET_LENGTH(separator);
9423 maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
9424 /* inc refcount to keep this code path symmetric with the
9425 above case of a blank separator */
9426 Py_INCREF(sep);
9427 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009428 last_obj = sep;
Tim Peters05eba1f2004-08-27 21:32:02 +00009429 }
9430
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009431 /* There are at least two things to join, or else we have a subclass
9432 * of str in the sequence.
9433 * Do a pre-pass to figure out the total amount of space we'll
9434 * need (sz), and see whether all argument are strings.
9435 */
9436 sz = 0;
Victor Stinnerdd077322011-10-07 17:02:31 +02009437#ifdef Py_DEBUG
9438 use_memcpy = 0;
9439#else
9440 use_memcpy = 1;
9441#endif
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009442 for (i = 0; i < seqlen; i++) {
9443 const Py_ssize_t old_sz = sz;
9444 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009445 if (!PyUnicode_Check(item)) {
9446 PyErr_Format(PyExc_TypeError,
9447 "sequence item %zd: expected str instance,"
9448 " %.80s found",
9449 i, Py_TYPE(item)->tp_name);
9450 goto onError;
9451 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009452 if (PyUnicode_READY(item) == -1)
9453 goto onError;
9454 sz += PyUnicode_GET_LENGTH(item);
9455 item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
Victor Stinnere6abb482012-05-02 01:15:40 +02009456 maxchar = MAX_MAXCHAR(maxchar, item_maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009457 if (i != 0)
9458 sz += seplen;
9459 if (sz < old_sz || sz > PY_SSIZE_T_MAX) {
9460 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009461 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009462 goto onError;
9463 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009464 if (use_memcpy && last_obj != NULL) {
9465 if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
9466 use_memcpy = 0;
9467 }
9468 last_obj = item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009469 }
Tim Petersced69f82003-09-16 20:30:58 +00009470
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009471 res = PyUnicode_New(sz, maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009472 if (res == NULL)
9473 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +00009474
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009475 /* Catenate everything. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009476#ifdef Py_DEBUG
9477 use_memcpy = 0;
9478#else
9479 if (use_memcpy) {
9480 res_data = PyUnicode_1BYTE_DATA(res);
9481 kind = PyUnicode_KIND(res);
9482 if (seplen != 0)
9483 sep_data = PyUnicode_1BYTE_DATA(sep);
9484 }
9485#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009486 for (i = 0, res_offset = 0; i < seqlen; ++i) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009487 Py_ssize_t itemlen;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009488 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009489 /* Copy item, and maybe the separator. */
Victor Stinner9ce5a832011-10-03 23:36:02 +02009490 if (i && seplen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009491 if (use_memcpy) {
9492 Py_MEMCPY(res_data,
9493 sep_data,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009494 kind * seplen);
9495 res_data += kind * seplen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009496 }
9497 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02009498 _PyUnicode_FastCopyCharacters(res, res_offset, sep, 0, seplen);
Victor Stinnerdd077322011-10-07 17:02:31 +02009499 res_offset += seplen;
9500 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009501 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009502 itemlen = PyUnicode_GET_LENGTH(item);
9503 if (itemlen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009504 if (use_memcpy) {
9505 Py_MEMCPY(res_data,
9506 PyUnicode_DATA(item),
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009507 kind * itemlen);
9508 res_data += kind * itemlen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009509 }
9510 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02009511 _PyUnicode_FastCopyCharacters(res, res_offset, item, 0, itemlen);
Victor Stinnerdd077322011-10-07 17:02:31 +02009512 res_offset += itemlen;
9513 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009514 }
Tim Peters05eba1f2004-08-27 21:32:02 +00009515 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009516 if (use_memcpy)
9517 assert(res_data == PyUnicode_1BYTE_DATA(res)
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009518 + kind * PyUnicode_GET_LENGTH(res));
Victor Stinnerdd077322011-10-07 17:02:31 +02009519 else
9520 assert(res_offset == PyUnicode_GET_LENGTH(res));
Tim Peters8ce9f162004-08-27 01:49:32 +00009521
Tim Peters05eba1f2004-08-27 21:32:02 +00009522 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009523 Py_XDECREF(sep);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009524 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009525 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009526
Benjamin Peterson29060642009-01-31 22:14:21 +00009527 onError:
Tim Peters05eba1f2004-08-27 21:32:02 +00009528 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009529 Py_XDECREF(sep);
Tim Peters8ce9f162004-08-27 01:49:32 +00009530 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009531 return NULL;
9532}
9533
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009534#define FILL(kind, data, value, start, length) \
9535 do { \
9536 Py_ssize_t i_ = 0; \
9537 assert(kind != PyUnicode_WCHAR_KIND); \
9538 switch ((kind)) { \
9539 case PyUnicode_1BYTE_KIND: { \
9540 unsigned char * to_ = (unsigned char *)((data)) + (start); \
Victor Stinnerf2c76aa2012-05-03 13:10:40 +02009541 memset(to_, (unsigned char)value, (length)); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009542 break; \
9543 } \
9544 case PyUnicode_2BYTE_KIND: { \
9545 Py_UCS2 * to_ = (Py_UCS2 *)((data)) + (start); \
9546 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9547 break; \
9548 } \
Benjamin Petersone157cf12012-01-01 15:56:20 -06009549 case PyUnicode_4BYTE_KIND: { \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009550 Py_UCS4 * to_ = (Py_UCS4 *)((data)) + (start); \
9551 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9552 break; \
Benjamin Petersone157cf12012-01-01 15:56:20 -06009553 default: assert(0); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009554 } \
9555 } \
9556 } while (0)
9557
Victor Stinnerd3f08822012-05-29 12:57:52 +02009558void
9559_PyUnicode_FastFill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
9560 Py_UCS4 fill_char)
9561{
9562 const enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
9563 const void *data = PyUnicode_DATA(unicode);
9564 assert(PyUnicode_IS_READY(unicode));
9565 assert(unicode_modifiable(unicode));
9566 assert(fill_char <= PyUnicode_MAX_CHAR_VALUE(unicode));
9567 assert(start >= 0);
9568 assert(start + length <= PyUnicode_GET_LENGTH(unicode));
9569 FILL(kind, data, fill_char, start, length);
9570}
9571
Victor Stinner3fe55312012-01-04 00:33:50 +01009572Py_ssize_t
9573PyUnicode_Fill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
9574 Py_UCS4 fill_char)
9575{
9576 Py_ssize_t maxlen;
Victor Stinner3fe55312012-01-04 00:33:50 +01009577
9578 if (!PyUnicode_Check(unicode)) {
9579 PyErr_BadInternalCall();
9580 return -1;
9581 }
9582 if (PyUnicode_READY(unicode) == -1)
9583 return -1;
9584 if (unicode_check_modifiable(unicode))
9585 return -1;
9586
Victor Stinnerd3f08822012-05-29 12:57:52 +02009587 if (start < 0) {
9588 PyErr_SetString(PyExc_IndexError, "string index out of range");
9589 return -1;
9590 }
Victor Stinner3fe55312012-01-04 00:33:50 +01009591 if (fill_char > PyUnicode_MAX_CHAR_VALUE(unicode)) {
9592 PyErr_SetString(PyExc_ValueError,
9593 "fill character is bigger than "
9594 "the string maximum character");
9595 return -1;
9596 }
9597
9598 maxlen = PyUnicode_GET_LENGTH(unicode) - start;
9599 length = Py_MIN(maxlen, length);
9600 if (length <= 0)
9601 return 0;
9602
Victor Stinnerd3f08822012-05-29 12:57:52 +02009603 _PyUnicode_FastFill(unicode, start, length, fill_char);
Victor Stinner3fe55312012-01-04 00:33:50 +01009604 return length;
9605}
9606
Victor Stinner9310abb2011-10-05 00:59:23 +02009607static PyObject *
9608pad(PyObject *self,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009609 Py_ssize_t left,
9610 Py_ssize_t right,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009611 Py_UCS4 fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009612{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009613 PyObject *u;
9614 Py_UCS4 maxchar;
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009615 int kind;
9616 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009617
9618 if (left < 0)
9619 left = 0;
9620 if (right < 0)
9621 right = 0;
9622
Victor Stinnerc4b49542011-12-11 22:44:26 +01009623 if (left == 0 && right == 0)
9624 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009625
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009626 if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
9627 right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +00009628 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
9629 return NULL;
9630 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009631 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Victor Stinnere6abb482012-05-02 01:15:40 +02009632 maxchar = MAX_MAXCHAR(maxchar, fill);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009633 u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009634 if (!u)
9635 return NULL;
9636
9637 kind = PyUnicode_KIND(u);
9638 data = PyUnicode_DATA(u);
9639 if (left)
9640 FILL(kind, data, fill, 0, left);
9641 if (right)
9642 FILL(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
Victor Stinnerd3f08822012-05-29 12:57:52 +02009643 _PyUnicode_FastCopyCharacters(u, left, self, 0, _PyUnicode_LENGTH(self));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009644 assert(_PyUnicode_CheckConsistency(u, 1));
9645 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009646}
9647
Alexander Belopolsky40018472011-02-26 01:02:56 +00009648PyObject *
9649PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009650{
Guido van Rossumd57fd912000-03-10 22:53:23 +00009651 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009652
9653 string = PyUnicode_FromObject(string);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009654 if (string == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009655 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -06009656 if (PyUnicode_READY(string) == -1) {
9657 Py_DECREF(string);
9658 return NULL;
9659 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009660
Benjamin Petersonead6b532011-12-20 17:23:42 -06009661 switch (PyUnicode_KIND(string)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009662 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009663 if (PyUnicode_IS_ASCII(string))
9664 list = asciilib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009665 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009666 PyUnicode_GET_LENGTH(string), keepends);
9667 else
9668 list = ucs1lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009669 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009670 PyUnicode_GET_LENGTH(string), keepends);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009671 break;
9672 case PyUnicode_2BYTE_KIND:
9673 list = ucs2lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009674 string, PyUnicode_2BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009675 PyUnicode_GET_LENGTH(string), keepends);
9676 break;
9677 case PyUnicode_4BYTE_KIND:
9678 list = ucs4lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009679 string, PyUnicode_4BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009680 PyUnicode_GET_LENGTH(string), keepends);
9681 break;
9682 default:
9683 assert(0);
9684 list = 0;
9685 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009686 Py_DECREF(string);
9687 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009688}
9689
Alexander Belopolsky40018472011-02-26 01:02:56 +00009690static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009691split(PyObject *self,
9692 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009693 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009694{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009695 int kind1, kind2, kind;
9696 void *buf1, *buf2;
9697 Py_ssize_t len1, len2;
9698 PyObject* out;
9699
Guido van Rossumd57fd912000-03-10 22:53:23 +00009700 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00009701 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009702
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009703 if (PyUnicode_READY(self) == -1)
9704 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009705
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009706 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -06009707 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009708 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009709 if (PyUnicode_IS_ASCII(self))
9710 return asciilib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009711 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009712 PyUnicode_GET_LENGTH(self), maxcount
9713 );
9714 else
9715 return ucs1lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009716 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009717 PyUnicode_GET_LENGTH(self), maxcount
9718 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009719 case PyUnicode_2BYTE_KIND:
9720 return ucs2lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009721 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009722 PyUnicode_GET_LENGTH(self), maxcount
9723 );
9724 case PyUnicode_4BYTE_KIND:
9725 return ucs4lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009726 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009727 PyUnicode_GET_LENGTH(self), maxcount
9728 );
9729 default:
9730 assert(0);
9731 return NULL;
9732 }
9733
9734 if (PyUnicode_READY(substring) == -1)
9735 return NULL;
9736
9737 kind1 = PyUnicode_KIND(self);
9738 kind2 = PyUnicode_KIND(substring);
9739 kind = kind1 > kind2 ? kind1 : kind2;
9740 buf1 = PyUnicode_DATA(self);
9741 buf2 = PyUnicode_DATA(substring);
9742 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009743 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009744 if (!buf1)
9745 return NULL;
9746 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009747 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009748 if (!buf2) {
9749 if (kind1 != kind) PyMem_Free(buf1);
9750 return NULL;
9751 }
9752 len1 = PyUnicode_GET_LENGTH(self);
9753 len2 = PyUnicode_GET_LENGTH(substring);
9754
Benjamin Petersonead6b532011-12-20 17:23:42 -06009755 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009756 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009757 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
9758 out = asciilib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009759 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +02009760 else
9761 out = ucs1lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009762 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009763 break;
9764 case PyUnicode_2BYTE_KIND:
9765 out = ucs2lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009766 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009767 break;
9768 case PyUnicode_4BYTE_KIND:
9769 out = ucs4lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009770 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009771 break;
9772 default:
9773 out = NULL;
9774 }
9775 if (kind1 != kind)
9776 PyMem_Free(buf1);
9777 if (kind2 != kind)
9778 PyMem_Free(buf2);
9779 return out;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009780}
9781
Alexander Belopolsky40018472011-02-26 01:02:56 +00009782static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009783rsplit(PyObject *self,
9784 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009785 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009786{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009787 int kind1, kind2, kind;
9788 void *buf1, *buf2;
9789 Py_ssize_t len1, len2;
9790 PyObject* out;
9791
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009792 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00009793 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009794
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009795 if (PyUnicode_READY(self) == -1)
9796 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009797
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009798 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -06009799 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009800 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009801 if (PyUnicode_IS_ASCII(self))
9802 return asciilib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009803 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009804 PyUnicode_GET_LENGTH(self), maxcount
9805 );
9806 else
9807 return ucs1lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009808 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009809 PyUnicode_GET_LENGTH(self), maxcount
9810 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009811 case PyUnicode_2BYTE_KIND:
9812 return ucs2lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009813 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009814 PyUnicode_GET_LENGTH(self), maxcount
9815 );
9816 case PyUnicode_4BYTE_KIND:
9817 return ucs4lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009818 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009819 PyUnicode_GET_LENGTH(self), maxcount
9820 );
9821 default:
9822 assert(0);
9823 return NULL;
9824 }
9825
9826 if (PyUnicode_READY(substring) == -1)
9827 return NULL;
9828
9829 kind1 = PyUnicode_KIND(self);
9830 kind2 = PyUnicode_KIND(substring);
9831 kind = kind1 > kind2 ? kind1 : kind2;
9832 buf1 = PyUnicode_DATA(self);
9833 buf2 = PyUnicode_DATA(substring);
9834 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009835 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009836 if (!buf1)
9837 return NULL;
9838 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009839 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009840 if (!buf2) {
9841 if (kind1 != kind) PyMem_Free(buf1);
9842 return NULL;
9843 }
9844 len1 = PyUnicode_GET_LENGTH(self);
9845 len2 = PyUnicode_GET_LENGTH(substring);
9846
Benjamin Petersonead6b532011-12-20 17:23:42 -06009847 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009848 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009849 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
9850 out = asciilib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009851 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +02009852 else
9853 out = ucs1lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009854 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009855 break;
9856 case PyUnicode_2BYTE_KIND:
9857 out = ucs2lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009858 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009859 break;
9860 case PyUnicode_4BYTE_KIND:
9861 out = ucs4lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009862 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009863 break;
9864 default:
9865 out = NULL;
9866 }
9867 if (kind1 != kind)
9868 PyMem_Free(buf1);
9869 if (kind2 != kind)
9870 PyMem_Free(buf2);
9871 return out;
9872}
9873
9874static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +02009875anylib_find(int kind, PyObject *str1, void *buf1, Py_ssize_t len1,
9876 PyObject *str2, void *buf2, Py_ssize_t len2, Py_ssize_t offset)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009877{
Benjamin Petersonead6b532011-12-20 17:23:42 -06009878 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009879 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009880 if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
9881 return asciilib_find(buf1, len1, buf2, len2, offset);
9882 else
9883 return ucs1lib_find(buf1, len1, buf2, len2, offset);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009884 case PyUnicode_2BYTE_KIND:
9885 return ucs2lib_find(buf1, len1, buf2, len2, offset);
9886 case PyUnicode_4BYTE_KIND:
9887 return ucs4lib_find(buf1, len1, buf2, len2, offset);
9888 }
9889 assert(0);
9890 return -1;
9891}
9892
9893static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +02009894anylib_count(int kind, PyObject *sstr, void* sbuf, Py_ssize_t slen,
9895 PyObject *str1, void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009896{
Benjamin Petersonc0b95d12011-12-20 17:24:05 -06009897 switch (kind) {
9898 case PyUnicode_1BYTE_KIND:
9899 if (PyUnicode_IS_ASCII(sstr) && PyUnicode_IS_ASCII(str1))
9900 return asciilib_count(sbuf, slen, buf1, len1, maxcount);
9901 else
9902 return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
9903 case PyUnicode_2BYTE_KIND:
9904 return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
9905 case PyUnicode_4BYTE_KIND:
9906 return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
9907 }
9908 assert(0);
9909 return 0;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009910}
9911
Alexander Belopolsky40018472011-02-26 01:02:56 +00009912static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009913replace(PyObject *self, PyObject *str1,
9914 PyObject *str2, Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009915{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009916 PyObject *u;
9917 char *sbuf = PyUnicode_DATA(self);
9918 char *buf1 = PyUnicode_DATA(str1);
9919 char *buf2 = PyUnicode_DATA(str2);
9920 int srelease = 0, release1 = 0, release2 = 0;
9921 int skind = PyUnicode_KIND(self);
9922 int kind1 = PyUnicode_KIND(str1);
9923 int kind2 = PyUnicode_KIND(str2);
9924 Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
9925 Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
9926 Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner49a0a212011-10-12 23:46:10 +02009927 int mayshrink;
9928 Py_UCS4 maxchar, maxchar_str2;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009929
9930 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009931 maxcount = PY_SSIZE_T_MAX;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009932 else if (maxcount == 0 || slen == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009933 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009934
Victor Stinner59de0ee2011-10-07 10:01:28 +02009935 if (str1 == str2)
9936 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009937 if (skind < kind1)
9938 /* substring too wide to be present */
9939 goto nothing;
9940
Victor Stinner49a0a212011-10-12 23:46:10 +02009941 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
9942 maxchar_str2 = PyUnicode_MAX_CHAR_VALUE(str2);
9943 /* Replacing str1 with str2 may cause a maxchar reduction in the
9944 result string. */
9945 mayshrink = (maxchar_str2 < maxchar);
Victor Stinnere6abb482012-05-02 01:15:40 +02009946 maxchar = MAX_MAXCHAR(maxchar, maxchar_str2);
Victor Stinner49a0a212011-10-12 23:46:10 +02009947
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009948 if (len1 == len2) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00009949 /* same length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009950 if (len1 == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009951 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009952 if (len1 == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00009953 /* replace characters */
Victor Stinner49a0a212011-10-12 23:46:10 +02009954 Py_UCS4 u1, u2;
9955 int rkind;
Victor Stinnerf6441102011-12-18 02:43:08 +01009956 Py_ssize_t index, pos;
9957 char *src;
9958
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009959 u1 = PyUnicode_READ_CHAR(str1, 0);
Victor Stinnerf6441102011-12-18 02:43:08 +01009960 pos = findchar(sbuf, PyUnicode_KIND(self), slen, u1, 1);
9961 if (pos < 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +00009962 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009963 u2 = PyUnicode_READ_CHAR(str2, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009964 u = PyUnicode_New(slen, maxchar);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009965 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009966 goto error;
Victor Stinnerd3f08822012-05-29 12:57:52 +02009967 _PyUnicode_FastCopyCharacters(u, 0, self, 0, slen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009968 rkind = PyUnicode_KIND(u);
Victor Stinnerf6441102011-12-18 02:43:08 +01009969
9970 PyUnicode_WRITE(rkind, PyUnicode_DATA(u), pos, u2);
9971 index = 0;
9972 src = sbuf;
9973 while (--maxcount)
9974 {
9975 pos++;
9976 src += pos * PyUnicode_KIND(self);
9977 slen -= pos;
9978 index += pos;
9979 pos = findchar(src, PyUnicode_KIND(self), slen, u1, 1);
9980 if (pos < 0)
9981 break;
9982 PyUnicode_WRITE(rkind, PyUnicode_DATA(u), index + pos, u2);
9983 }
Victor Stinner49a0a212011-10-12 23:46:10 +02009984 }
9985 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009986 int rkind = skind;
9987 char *res;
Victor Stinnerf6441102011-12-18 02:43:08 +01009988 Py_ssize_t i;
Victor Stinner25a4b292011-10-06 12:31:55 +02009989
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009990 if (kind1 < rkind) {
9991 /* widen substring */
9992 buf1 = _PyUnicode_AsKind(str1, rkind);
9993 if (!buf1) goto error;
9994 release1 = 1;
9995 }
Victor Stinnerc3cec782011-10-05 21:24:08 +02009996 i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009997 if (i < 0)
9998 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009999 if (rkind > kind2) {
10000 /* widen replacement */
10001 buf2 = _PyUnicode_AsKind(str2, rkind);
10002 if (!buf2) goto error;
10003 release2 = 1;
10004 }
10005 else if (rkind < kind2) {
10006 /* widen self and buf1 */
10007 rkind = kind2;
10008 if (release1) PyMem_Free(buf1);
10009 sbuf = _PyUnicode_AsKind(self, rkind);
10010 if (!sbuf) goto error;
10011 srelease = 1;
10012 buf1 = _PyUnicode_AsKind(str1, rkind);
10013 if (!buf1) goto error;
10014 release1 = 1;
10015 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010016 u = PyUnicode_New(slen, maxchar);
10017 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010018 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010019 assert(PyUnicode_KIND(u) == rkind);
10020 res = PyUnicode_DATA(u);
Victor Stinner25a4b292011-10-06 12:31:55 +020010021
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010022 memcpy(res, sbuf, rkind * slen);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010023 /* change everything in-place, starting with this one */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010024 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010025 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010026 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010027 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010028
10029 while ( --maxcount > 0) {
Victor Stinnerc3cec782011-10-05 21:24:08 +020010030 i = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010031 sbuf+rkind*i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010032 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010033 if (i == -1)
10034 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010035 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010036 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010037 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010038 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010039 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010040 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010041 }
10042 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010043 Py_ssize_t n, i, j, ires;
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010044 Py_ssize_t new_size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010045 int rkind = skind;
10046 char *res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010047
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010048 if (kind1 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010049 /* widen substring */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010050 buf1 = _PyUnicode_AsKind(str1, rkind);
10051 if (!buf1) goto error;
10052 release1 = 1;
10053 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010054 n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010055 if (n == 0)
10056 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010057 if (kind2 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010058 /* widen replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010059 buf2 = _PyUnicode_AsKind(str2, rkind);
10060 if (!buf2) goto error;
10061 release2 = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010062 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010063 else if (kind2 > rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010064 /* widen self and buf1 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010065 rkind = kind2;
10066 sbuf = _PyUnicode_AsKind(self, rkind);
10067 if (!sbuf) goto error;
10068 srelease = 1;
10069 if (release1) PyMem_Free(buf1);
10070 buf1 = _PyUnicode_AsKind(str1, rkind);
10071 if (!buf1) goto error;
10072 release1 = 1;
10073 }
10074 /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
10075 PyUnicode_GET_LENGTH(str1))); */
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010076 if (len2 > len1 && len2 - len1 > (PY_SSIZE_T_MAX - slen) / n) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010077 PyErr_SetString(PyExc_OverflowError,
10078 "replace string is too long");
10079 goto error;
10080 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010081 new_size = slen + n * (len2 - len1);
Victor Stinner49a0a212011-10-12 23:46:10 +020010082 if (new_size == 0) {
10083 Py_INCREF(unicode_empty);
10084 u = unicode_empty;
10085 goto done;
10086 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010087 if (new_size > (PY_SSIZE_T_MAX >> (rkind-1))) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010088 PyErr_SetString(PyExc_OverflowError,
10089 "replace string is too long");
10090 goto error;
10091 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010092 u = PyUnicode_New(new_size, maxchar);
10093 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010094 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010095 assert(PyUnicode_KIND(u) == rkind);
10096 res = PyUnicode_DATA(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010097 ires = i = 0;
10098 if (len1 > 0) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010099 while (n-- > 0) {
10100 /* look for next match */
Victor Stinnerc3cec782011-10-05 21:24:08 +020010101 j = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010102 sbuf + rkind * i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010103 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010104 if (j == -1)
10105 break;
10106 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010107 /* copy unchanged part [i:j] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010108 memcpy(res + rkind * ires,
10109 sbuf + rkind * i,
10110 rkind * (j-i));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010111 ires += j - i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010112 }
10113 /* copy substitution string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010114 if (len2 > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010115 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010116 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010117 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010118 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010119 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010120 i = j + len1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010121 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010122 if (i < slen)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010123 /* copy tail [i:] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010124 memcpy(res + rkind * ires,
10125 sbuf + rkind * i,
10126 rkind * (slen-i));
Victor Stinner49a0a212011-10-12 23:46:10 +020010127 }
10128 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010129 /* interleave */
10130 while (n > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010131 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010132 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010133 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010134 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010135 if (--n <= 0)
10136 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010137 memcpy(res + rkind * ires,
10138 sbuf + rkind * i,
10139 rkind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010140 ires++;
10141 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010142 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010143 memcpy(res + rkind * ires,
10144 sbuf + rkind * i,
10145 rkind * (slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +000010146 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010147 }
10148
10149 if (mayshrink) {
Victor Stinner25a4b292011-10-06 12:31:55 +020010150 unicode_adjust_maxchar(&u);
10151 if (u == NULL)
10152 goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010153 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010154
10155 done:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010156 if (srelease)
10157 PyMem_FREE(sbuf);
10158 if (release1)
10159 PyMem_FREE(buf1);
10160 if (release2)
10161 PyMem_FREE(buf2);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010162 assert(_PyUnicode_CheckConsistency(u, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010163 return u;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010164
Benjamin Peterson29060642009-01-31 22:14:21 +000010165 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +000010166 /* nothing to replace; return original string (when possible) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010167 if (srelease)
10168 PyMem_FREE(sbuf);
10169 if (release1)
10170 PyMem_FREE(buf1);
10171 if (release2)
10172 PyMem_FREE(buf2);
Victor Stinnerc4b49542011-12-11 22:44:26 +010010173 return unicode_result_unchanged(self);
10174
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010175 error:
10176 if (srelease && sbuf)
10177 PyMem_FREE(sbuf);
10178 if (release1 && buf1)
10179 PyMem_FREE(buf1);
10180 if (release2 && buf2)
10181 PyMem_FREE(buf2);
10182 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010183}
10184
10185/* --- Unicode Object Methods --------------------------------------------- */
10186
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010187PyDoc_STRVAR(title__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010188 "S.title() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010189\n\
10190Return a titlecased version of S, i.e. words start with title case\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010191characters, all remaining cased characters have lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010192
10193static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010194unicode_title(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010195{
Benjamin Petersoneea48462012-01-16 14:28:50 -050010196 if (PyUnicode_READY(self) == -1)
10197 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010198 return case_operation(self, do_title);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010199}
10200
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010201PyDoc_STRVAR(capitalize__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010202 "S.capitalize() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010203\n\
10204Return a capitalized version of S, i.e. make the first character\n\
Senthil Kumarane51ee8a2010-07-05 12:00:56 +000010205have upper case and the rest lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010206
10207static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010208unicode_capitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010209{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050010210 if (PyUnicode_READY(self) == -1)
10211 return NULL;
10212 if (PyUnicode_GET_LENGTH(self) == 0)
10213 return unicode_result_unchanged(self);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010214 return case_operation(self, do_capitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010215}
10216
Benjamin Petersond5890c82012-01-14 13:23:30 -050010217PyDoc_STRVAR(casefold__doc__,
10218 "S.casefold() -> str\n\
10219\n\
10220Return a version of S suitable for caseless comparisons.");
10221
10222static PyObject *
10223unicode_casefold(PyObject *self)
10224{
10225 if (PyUnicode_READY(self) == -1)
10226 return NULL;
10227 if (PyUnicode_IS_ASCII(self))
10228 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010229 return case_operation(self, do_casefold);
Benjamin Petersond5890c82012-01-14 13:23:30 -050010230}
10231
10232
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010233/* Argument converter. Coerces to a single unicode character */
10234
10235static int
10236convert_uc(PyObject *obj, void *addr)
10237{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010238 Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010239 PyObject *uniobj;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010240
Benjamin Peterson14339b62009-01-31 16:36:08 +000010241 uniobj = PyUnicode_FromObject(obj);
10242 if (uniobj == NULL) {
10243 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010244 "The fill character cannot be converted to Unicode");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010245 return 0;
10246 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010247 if (PyUnicode_GET_LENGTH(uniobj) != 1) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010248 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010249 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010250 Py_DECREF(uniobj);
10251 return 0;
10252 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010253 *fillcharloc = PyUnicode_READ_CHAR(uniobj, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010254 Py_DECREF(uniobj);
10255 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010256}
10257
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010258PyDoc_STRVAR(center__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010259 "S.center(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010260\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010261Return S centered in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010262done using the specified fill character (default is a space)");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010263
10264static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010265unicode_center(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010266{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010267 Py_ssize_t marg, left;
10268 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010269 Py_UCS4 fillchar = ' ';
10270
Victor Stinnere9a29352011-10-01 02:14:59 +020010271 if (!PyArg_ParseTuple(args, "n|O&:center", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010272 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010273
Benjamin Petersonbac79492012-01-14 13:34:47 -050010274 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010275 return NULL;
10276
Victor Stinnerc4b49542011-12-11 22:44:26 +010010277 if (PyUnicode_GET_LENGTH(self) >= width)
10278 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010279
Victor Stinnerc4b49542011-12-11 22:44:26 +010010280 marg = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010281 left = marg / 2 + (marg & width & 1);
10282
Victor Stinner9310abb2011-10-05 00:59:23 +020010283 return pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010284}
10285
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010286/* This function assumes that str1 and str2 are readied by the caller. */
10287
Marc-André Lemburge5034372000-08-08 08:04:29 +000010288static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010289unicode_compare(PyObject *str1, PyObject *str2)
Marc-André Lemburge5034372000-08-08 08:04:29 +000010290{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010291 int kind1, kind2;
10292 void *data1, *data2;
Victor Stinner770e19e2012-10-04 22:59:45 +020010293 Py_ssize_t len1, len2;
10294 Py_ssize_t i, len;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010295
Victor Stinner90db9c42012-10-04 21:53:50 +020010296 /* a string is equal to itself */
10297 if (str1 == str2)
10298 return 0;
10299
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010300 kind1 = PyUnicode_KIND(str1);
10301 kind2 = PyUnicode_KIND(str2);
10302 data1 = PyUnicode_DATA(str1);
10303 data2 = PyUnicode_DATA(str2);
10304 len1 = PyUnicode_GET_LENGTH(str1);
10305 len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner770e19e2012-10-04 22:59:45 +020010306 len = Py_MIN(len1, len2);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010307
Victor Stinner770e19e2012-10-04 22:59:45 +020010308 if (kind1 == 1 && kind2 == 1) {
10309 int cmp = memcmp(data1, data2, len);
10310 /* normalize result of memcmp() into the range [-1; 1] */
10311 if (cmp < 0)
10312 return -1;
10313 if (cmp > 0)
10314 return 1;
10315 }
10316 else {
10317 for (i = 0; i < len; ++i) {
10318 Py_UCS4 c1, c2;
10319 c1 = PyUnicode_READ(kind1, data1, i);
10320 c2 = PyUnicode_READ(kind2, data2, i);
Fredrik Lundh45714e92001-06-26 16:39:36 +000010321
Victor Stinner770e19e2012-10-04 22:59:45 +020010322 if (c1 != c2)
10323 return (c1 < c2) ? -1 : 1;
10324 }
Marc-André Lemburge5034372000-08-08 08:04:29 +000010325 }
10326
Victor Stinner770e19e2012-10-04 22:59:45 +020010327 if (len1 == len2)
10328 return 0;
10329 if (len1 < len2)
10330 return -1;
10331 else
10332 return 1;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010333}
10334
Alexander Belopolsky40018472011-02-26 01:02:56 +000010335int
10336PyUnicode_Compare(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010337{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010338 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10339 if (PyUnicode_READY(left) == -1 ||
10340 PyUnicode_READY(right) == -1)
10341 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010342 return unicode_compare(left, right);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010343 }
Guido van Rossum09dc34f2007-05-04 04:17:33 +000010344 PyErr_Format(PyExc_TypeError,
10345 "Can't compare %.100s and %.100s",
10346 left->ob_type->tp_name,
10347 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010348 return -1;
10349}
10350
Martin v. Löwis5b222132007-06-10 09:51:05 +000010351int
10352PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
10353{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010354 Py_ssize_t i;
10355 int kind;
10356 void *data;
10357 Py_UCS4 chr;
10358
Victor Stinner910337b2011-10-03 03:20:16 +020010359 assert(_PyUnicode_CHECK(uni));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010360 if (PyUnicode_READY(uni) == -1)
10361 return -1;
10362 kind = PyUnicode_KIND(uni);
10363 data = PyUnicode_DATA(uni);
Martin v. Löwis5b222132007-06-10 09:51:05 +000010364 /* Compare Unicode string and source character set string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010365 for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
10366 if (chr != str[i])
10367 return (chr < (unsigned char)(str[i])) ? -1 : 1;
Benjamin Peterson8667a9b2010-01-09 21:45:28 +000010368 /* This check keeps Python strings that end in '\0' from comparing equal
10369 to C strings identical up to that point. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010370 if (PyUnicode_GET_LENGTH(uni) != i || chr)
Benjamin Peterson29060642009-01-31 22:14:21 +000010371 return 1; /* uni is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010372 if (str[i])
Benjamin Peterson29060642009-01-31 22:14:21 +000010373 return -1; /* str is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010374 return 0;
10375}
10376
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010377
Benjamin Peterson29060642009-01-31 22:14:21 +000010378#define TEST_COND(cond) \
Benjamin Peterson14339b62009-01-31 16:36:08 +000010379 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010380
Alexander Belopolsky40018472011-02-26 01:02:56 +000010381PyObject *
10382PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010383{
10384 int result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010385
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010386 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10387 PyObject *v;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010388 if (PyUnicode_READY(left) == -1 ||
10389 PyUnicode_READY(right) == -1)
10390 return NULL;
10391 if (PyUnicode_GET_LENGTH(left) != PyUnicode_GET_LENGTH(right) ||
10392 PyUnicode_KIND(left) != PyUnicode_KIND(right)) {
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010393 if (op == Py_EQ) {
10394 Py_INCREF(Py_False);
10395 return Py_False;
10396 }
10397 if (op == Py_NE) {
10398 Py_INCREF(Py_True);
10399 return Py_True;
10400 }
10401 }
Victor Stinner90db9c42012-10-04 21:53:50 +020010402 result = unicode_compare(left, right);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010403
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010404 /* Convert the return value to a Boolean */
10405 switch (op) {
10406 case Py_EQ:
10407 v = TEST_COND(result == 0);
10408 break;
10409 case Py_NE:
10410 v = TEST_COND(result != 0);
10411 break;
10412 case Py_LE:
10413 v = TEST_COND(result <= 0);
10414 break;
10415 case Py_GE:
10416 v = TEST_COND(result >= 0);
10417 break;
10418 case Py_LT:
10419 v = TEST_COND(result == -1);
10420 break;
10421 case Py_GT:
10422 v = TEST_COND(result == 1);
10423 break;
10424 default:
10425 PyErr_BadArgument();
10426 return NULL;
10427 }
10428 Py_INCREF(v);
10429 return v;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010430 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000010431
Brian Curtindfc80e32011-08-10 20:28:54 -050010432 Py_RETURN_NOTIMPLEMENTED;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010433}
10434
Alexander Belopolsky40018472011-02-26 01:02:56 +000010435int
10436PyUnicode_Contains(PyObject *container, PyObject *element)
Guido van Rossum403d68b2000-03-13 15:55:09 +000010437{
Thomas Wouters477c8d52006-05-27 19:21:47 +000010438 PyObject *str, *sub;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010439 int kind1, kind2, kind;
10440 void *buf1, *buf2;
10441 Py_ssize_t len1, len2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010442 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010443
10444 /* Coerce the two arguments */
Thomas Wouters477c8d52006-05-27 19:21:47 +000010445 sub = PyUnicode_FromObject(element);
10446 if (!sub) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010447 PyErr_Format(PyExc_TypeError,
10448 "'in <string>' requires string as left operand, not %s",
10449 element->ob_type->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010450 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010451 }
10452
Thomas Wouters477c8d52006-05-27 19:21:47 +000010453 str = PyUnicode_FromObject(container);
Benjamin Peterson22a29702012-01-02 09:00:30 -060010454 if (!str) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010455 Py_DECREF(sub);
10456 return -1;
10457 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060010458 if (PyUnicode_READY(sub) == -1 || PyUnicode_READY(str) == -1) {
10459 Py_DECREF(sub);
10460 Py_DECREF(str);
10461 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000010462
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010463 kind1 = PyUnicode_KIND(str);
10464 kind2 = PyUnicode_KIND(sub);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010465 kind = kind1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010466 buf1 = PyUnicode_DATA(str);
10467 buf2 = PyUnicode_DATA(sub);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010468 if (kind2 != kind) {
Antoine Pitrou758153b2012-05-12 15:51:51 +020010469 if (kind2 > kind) {
10470 Py_DECREF(sub);
10471 Py_DECREF(str);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010472 return 0;
Antoine Pitrou758153b2012-05-12 15:51:51 +020010473 }
Victor Stinner7931d9a2011-11-04 00:22:48 +010010474 buf2 = _PyUnicode_AsKind(sub, kind);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010475 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010476 if (!buf2) {
10477 Py_DECREF(sub);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010478 Py_DECREF(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010479 return -1;
10480 }
10481 len1 = PyUnicode_GET_LENGTH(str);
10482 len2 = PyUnicode_GET_LENGTH(sub);
10483
Benjamin Petersonead6b532011-12-20 17:23:42 -060010484 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010485 case PyUnicode_1BYTE_KIND:
10486 result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
10487 break;
10488 case PyUnicode_2BYTE_KIND:
10489 result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
10490 break;
10491 case PyUnicode_4BYTE_KIND:
10492 result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
10493 break;
10494 default:
10495 result = -1;
10496 assert(0);
10497 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000010498
10499 Py_DECREF(str);
10500 Py_DECREF(sub);
10501
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010502 if (kind2 != kind)
10503 PyMem_Free(buf2);
10504
Guido van Rossum403d68b2000-03-13 15:55:09 +000010505 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010506}
10507
Guido van Rossumd57fd912000-03-10 22:53:23 +000010508/* Concat to string or Unicode object giving a new Unicode object. */
10509
Alexander Belopolsky40018472011-02-26 01:02:56 +000010510PyObject *
10511PyUnicode_Concat(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010512{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010513 PyObject *u = NULL, *v = NULL, *w;
Victor Stinner127226b2011-10-13 01:12:34 +020010514 Py_UCS4 maxchar, maxchar2;
Victor Stinner488fa492011-12-12 00:01:39 +010010515 Py_ssize_t u_len, v_len, new_len;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010516
10517 /* Coerce the two arguments */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010518 u = PyUnicode_FromObject(left);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010519 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010520 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010521 v = PyUnicode_FromObject(right);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010522 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010523 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010524
10525 /* Shortcuts */
Victor Stinnera464fc12011-10-02 20:39:30 +020010526 if (v == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010527 Py_DECREF(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010528 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010529 }
Victor Stinnera464fc12011-10-02 20:39:30 +020010530 if (u == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010531 Py_DECREF(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010532 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010533 }
10534
Victor Stinner488fa492011-12-12 00:01:39 +010010535 u_len = PyUnicode_GET_LENGTH(u);
10536 v_len = PyUnicode_GET_LENGTH(v);
10537 if (u_len > PY_SSIZE_T_MAX - v_len) {
10538 PyErr_SetString(PyExc_OverflowError,
10539 "strings are too large to concat");
10540 goto onError;
10541 }
10542 new_len = u_len + v_len;
10543
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010544 maxchar = PyUnicode_MAX_CHAR_VALUE(u);
Victor Stinner127226b2011-10-13 01:12:34 +020010545 maxchar2 = PyUnicode_MAX_CHAR_VALUE(v);
Victor Stinnere6abb482012-05-02 01:15:40 +020010546 maxchar = MAX_MAXCHAR(maxchar, maxchar2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010547
Guido van Rossumd57fd912000-03-10 22:53:23 +000010548 /* Concat the two Unicode strings */
Victor Stinner488fa492011-12-12 00:01:39 +010010549 w = PyUnicode_New(new_len, maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010550 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010551 goto onError;
Victor Stinnerd3f08822012-05-29 12:57:52 +020010552 _PyUnicode_FastCopyCharacters(w, 0, u, 0, u_len);
10553 _PyUnicode_FastCopyCharacters(w, u_len, v, 0, v_len);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010554 Py_DECREF(u);
10555 Py_DECREF(v);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010556 assert(_PyUnicode_CheckConsistency(w, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010557 return w;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010558
Benjamin Peterson29060642009-01-31 22:14:21 +000010559 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000010560 Py_XDECREF(u);
10561 Py_XDECREF(v);
10562 return NULL;
10563}
10564
Walter Dörwald1ab83302007-05-18 17:15:44 +000010565void
Victor Stinner23e56682011-10-03 03:54:37 +020010566PyUnicode_Append(PyObject **p_left, PyObject *right)
Walter Dörwald1ab83302007-05-18 17:15:44 +000010567{
Victor Stinner23e56682011-10-03 03:54:37 +020010568 PyObject *left, *res;
Victor Stinner488fa492011-12-12 00:01:39 +010010569 Py_UCS4 maxchar, maxchar2;
10570 Py_ssize_t left_len, right_len, new_len;
Victor Stinner23e56682011-10-03 03:54:37 +020010571
10572 if (p_left == NULL) {
10573 if (!PyErr_Occurred())
10574 PyErr_BadInternalCall();
Benjamin Peterson14339b62009-01-31 16:36:08 +000010575 return;
10576 }
Victor Stinner23e56682011-10-03 03:54:37 +020010577 left = *p_left;
10578 if (right == NULL || !PyUnicode_Check(left)) {
10579 if (!PyErr_Occurred())
10580 PyErr_BadInternalCall();
10581 goto error;
10582 }
10583
Benjamin Petersonbac79492012-01-14 13:34:47 -050010584 if (PyUnicode_READY(left) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020010585 goto error;
Benjamin Petersonbac79492012-01-14 13:34:47 -050010586 if (PyUnicode_READY(right) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020010587 goto error;
10588
Victor Stinner488fa492011-12-12 00:01:39 +010010589 /* Shortcuts */
10590 if (left == unicode_empty) {
10591 Py_DECREF(left);
10592 Py_INCREF(right);
10593 *p_left = right;
10594 return;
10595 }
10596 if (right == unicode_empty)
10597 return;
10598
10599 left_len = PyUnicode_GET_LENGTH(left);
10600 right_len = PyUnicode_GET_LENGTH(right);
10601 if (left_len > PY_SSIZE_T_MAX - right_len) {
10602 PyErr_SetString(PyExc_OverflowError,
10603 "strings are too large to concat");
10604 goto error;
10605 }
10606 new_len = left_len + right_len;
10607
10608 if (unicode_modifiable(left)
10609 && PyUnicode_CheckExact(right)
10610 && PyUnicode_KIND(right) <= PyUnicode_KIND(left)
Victor Stinnerb0923652011-10-04 01:17:31 +020010611 /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
10612 to change the structure size, but characters are stored just after
Georg Brandl7597add2011-10-05 16:36:47 +020010613 the structure, and so it requires to move all characters which is
Victor Stinnerb0923652011-10-04 01:17:31 +020010614 not so different than duplicating the string. */
Victor Stinner488fa492011-12-12 00:01:39 +010010615 && !(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
10616 {
10617 /* append inplace */
10618 if (unicode_resize(p_left, new_len) != 0) {
10619 /* XXX if _PyUnicode_Resize() fails, 'left' has been
10620 * deallocated so it cannot be put back into
10621 * 'variable'. The MemoryError is raised when there
10622 * is no value in 'variable', which might (very
10623 * remotely) be a cause of incompatibilities.
10624 */
10625 goto error;
Victor Stinner23e56682011-10-03 03:54:37 +020010626 }
Victor Stinner488fa492011-12-12 00:01:39 +010010627 /* copy 'right' into the newly allocated area of 'left' */
Victor Stinnerd3f08822012-05-29 12:57:52 +020010628 _PyUnicode_FastCopyCharacters(*p_left, left_len, right, 0, right_len);
Victor Stinner23e56682011-10-03 03:54:37 +020010629 }
Victor Stinner488fa492011-12-12 00:01:39 +010010630 else {
10631 maxchar = PyUnicode_MAX_CHAR_VALUE(left);
10632 maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
Victor Stinnere6abb482012-05-02 01:15:40 +020010633 maxchar = MAX_MAXCHAR(maxchar, maxchar2);
Victor Stinner23e56682011-10-03 03:54:37 +020010634
Victor Stinner488fa492011-12-12 00:01:39 +010010635 /* Concat the two Unicode strings */
10636 res = PyUnicode_New(new_len, maxchar);
10637 if (res == NULL)
10638 goto error;
Victor Stinnerd3f08822012-05-29 12:57:52 +020010639 _PyUnicode_FastCopyCharacters(res, 0, left, 0, left_len);
10640 _PyUnicode_FastCopyCharacters(res, left_len, right, 0, right_len);
Victor Stinner488fa492011-12-12 00:01:39 +010010641 Py_DECREF(left);
10642 *p_left = res;
10643 }
10644 assert(_PyUnicode_CheckConsistency(*p_left, 1));
Victor Stinner23e56682011-10-03 03:54:37 +020010645 return;
10646
10647error:
Victor Stinner488fa492011-12-12 00:01:39 +010010648 Py_CLEAR(*p_left);
Walter Dörwald1ab83302007-05-18 17:15:44 +000010649}
10650
10651void
10652PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
10653{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010654 PyUnicode_Append(pleft, right);
10655 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +000010656}
10657
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010658PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010659 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010660\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000010661Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010662string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010663interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010664
10665static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010666unicode_count(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010667{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010668 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010669 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010670 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010671 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010672 int kind1, kind2, kind;
10673 void *buf1, *buf2;
10674 Py_ssize_t len1, len2, iresult;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010675
Jesus Ceaac451502011-04-20 17:09:23 +020010676 if (!stringlib_parse_args_finds_unicode("count", args, &substring,
10677 &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000010678 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000010679
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010680 kind1 = PyUnicode_KIND(self);
10681 kind2 = PyUnicode_KIND(substring);
Benjamin Petersonb63f49f2012-05-03 18:31:07 -040010682 if (kind2 > kind1)
10683 return PyLong_FromLong(0);
10684 kind = kind1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010685 buf1 = PyUnicode_DATA(self);
10686 buf2 = PyUnicode_DATA(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010687 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010688 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010689 if (!buf2) {
10690 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010691 return NULL;
10692 }
10693 len1 = PyUnicode_GET_LENGTH(self);
10694 len2 = PyUnicode_GET_LENGTH(substring);
10695
10696 ADJUST_INDICES(start, end, len1);
Benjamin Petersonead6b532011-12-20 17:23:42 -060010697 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010698 case PyUnicode_1BYTE_KIND:
10699 iresult = ucs1lib_count(
10700 ((Py_UCS1*)buf1) + start, end - start,
10701 buf2, len2, PY_SSIZE_T_MAX
10702 );
10703 break;
10704 case PyUnicode_2BYTE_KIND:
10705 iresult = ucs2lib_count(
10706 ((Py_UCS2*)buf1) + start, end - start,
10707 buf2, len2, PY_SSIZE_T_MAX
10708 );
10709 break;
10710 case PyUnicode_4BYTE_KIND:
10711 iresult = ucs4lib_count(
10712 ((Py_UCS4*)buf1) + start, end - start,
10713 buf2, len2, PY_SSIZE_T_MAX
10714 );
10715 break;
10716 default:
10717 assert(0); iresult = 0;
10718 }
10719
10720 result = PyLong_FromSsize_t(iresult);
10721
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010722 if (kind2 != kind)
10723 PyMem_Free(buf2);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010724
10725 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010726
Guido van Rossumd57fd912000-03-10 22:53:23 +000010727 return result;
10728}
10729
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010730PyDoc_STRVAR(encode__doc__,
Victor Stinnerc911bbf2010-11-07 19:04:46 +000010731 "S.encode(encoding='utf-8', errors='strict') -> bytes\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010732\n\
Victor Stinnere14e2122010-11-07 18:41:46 +000010733Encode S using the codec registered for encoding. Default encoding\n\
10734is 'utf-8'. errors may be given to set a different error\n\
Fred Drakee4315f52000-05-09 19:53:39 +000010735handling scheme. Default is 'strict' meaning that encoding errors raise\n\
Walter Dörwald3aeb6322002-09-02 13:14:32 +000010736a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
10737'xmlcharrefreplace' as well as any other name registered with\n\
10738codecs.register_error that can handle UnicodeEncodeErrors.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010739
10740static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010741unicode_encode(PyObject *self, PyObject *args, PyObject *kwargs)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010742{
Benjamin Peterson308d6372009-09-18 21:42:35 +000010743 static char *kwlist[] = {"encoding", "errors", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000010744 char *encoding = NULL;
10745 char *errors = NULL;
Guido van Rossum35d94282007-08-27 18:20:11 +000010746
Benjamin Peterson308d6372009-09-18 21:42:35 +000010747 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:encode",
10748 kwlist, &encoding, &errors))
Guido van Rossumd57fd912000-03-10 22:53:23 +000010749 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010750 return PyUnicode_AsEncodedString(self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +000010751}
10752
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010753PyDoc_STRVAR(expandtabs__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010754 "S.expandtabs([tabsize]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010755\n\
10756Return a copy of S where all tab characters are expanded using spaces.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010757If tabsize is not given, a tab size of 8 characters is assumed.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010758
10759static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010760unicode_expandtabs(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010761{
Antoine Pitroue71d5742011-10-04 15:55:09 +020010762 Py_ssize_t i, j, line_pos, src_len, incr;
10763 Py_UCS4 ch;
10764 PyObject *u;
10765 void *src_data, *dest_data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010766 int tabsize = 8;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010767 int kind;
Antoine Pitroue19aa382011-10-04 16:04:01 +020010768 int found;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010769
10770 if (!PyArg_ParseTuple(args, "|i:expandtabs", &tabsize))
Benjamin Peterson29060642009-01-31 22:14:21 +000010771 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010772
Antoine Pitrou22425222011-10-04 19:10:51 +020010773 if (PyUnicode_READY(self) == -1)
10774 return NULL;
10775
Thomas Wouters7e474022000-07-16 12:04:32 +000010776 /* First pass: determine size of output string */
Antoine Pitroue71d5742011-10-04 15:55:09 +020010777 src_len = PyUnicode_GET_LENGTH(self);
10778 i = j = line_pos = 0;
10779 kind = PyUnicode_KIND(self);
10780 src_data = PyUnicode_DATA(self);
Antoine Pitroue19aa382011-10-04 16:04:01 +020010781 found = 0;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010782 for (; i < src_len; i++) {
10783 ch = PyUnicode_READ(kind, src_data, i);
10784 if (ch == '\t') {
Antoine Pitroue19aa382011-10-04 16:04:01 +020010785 found = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000010786 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020010787 incr = tabsize - (line_pos % tabsize); /* cannot overflow */
Benjamin Peterson29060642009-01-31 22:14:21 +000010788 if (j > PY_SSIZE_T_MAX - incr)
Antoine Pitroue71d5742011-10-04 15:55:09 +020010789 goto overflow;
10790 line_pos += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000010791 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010792 }
Benjamin Peterson29060642009-01-31 22:14:21 +000010793 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010794 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000010795 if (j > PY_SSIZE_T_MAX - 1)
Antoine Pitroue71d5742011-10-04 15:55:09 +020010796 goto overflow;
10797 line_pos++;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010798 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010799 if (ch == '\n' || ch == '\r')
10800 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010801 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020010802 }
Victor Stinnerc4b49542011-12-11 22:44:26 +010010803 if (!found)
10804 return unicode_result_unchanged(self);
Guido van Rossumcd16bf62007-06-13 18:07:49 +000010805
Guido van Rossumd57fd912000-03-10 22:53:23 +000010806 /* Second pass: create output string and fill it */
Antoine Pitroue71d5742011-10-04 15:55:09 +020010807 u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +000010808 if (!u)
10809 return NULL;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010810 dest_data = PyUnicode_DATA(u);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010811
Antoine Pitroue71d5742011-10-04 15:55:09 +020010812 i = j = line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010813
Antoine Pitroue71d5742011-10-04 15:55:09 +020010814 for (; i < src_len; i++) {
10815 ch = PyUnicode_READ(kind, src_data, i);
10816 if (ch == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +000010817 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020010818 incr = tabsize - (line_pos % tabsize);
10819 line_pos += incr;
Victor Stinnerda79e632012-02-22 13:37:04 +010010820 FILL(kind, dest_data, ' ', j, incr);
10821 j += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000010822 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000010823 }
Benjamin Peterson29060642009-01-31 22:14:21 +000010824 else {
Antoine Pitroue71d5742011-10-04 15:55:09 +020010825 line_pos++;
10826 PyUnicode_WRITE(kind, dest_data, j, ch);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010827 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010828 if (ch == '\n' || ch == '\r')
10829 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010830 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020010831 }
10832 assert (j == PyUnicode_GET_LENGTH(u));
Victor Stinnerd3df8ab2011-11-22 01:22:34 +010010833 return unicode_result(u);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010834
Antoine Pitroue71d5742011-10-04 15:55:09 +020010835 overflow:
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010836 PyErr_SetString(PyExc_OverflowError, "new string is too long");
10837 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010838}
10839
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010840PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010841 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010842\n\
10843Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080010844such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010845arguments start and end are interpreted as in slice notation.\n\
10846\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010847Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010848
10849static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010850unicode_find(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010851{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010852 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000010853 Py_ssize_t start;
10854 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010855 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010856
Jesus Ceaac451502011-04-20 17:09:23 +020010857 if (!stringlib_parse_args_finds_unicode("find", args, &substring,
10858 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000010859 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010860
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010861 if (PyUnicode_READY(self) == -1)
10862 return NULL;
10863 if (PyUnicode_READY(substring) == -1)
10864 return NULL;
10865
Victor Stinner7931d9a2011-11-04 00:22:48 +010010866 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010867
10868 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010869
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010870 if (result == -2)
10871 return NULL;
10872
Christian Heimes217cfd12007-12-02 14:31:20 +000010873 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010874}
10875
10876static PyObject *
Victor Stinner2fe5ced2011-10-02 00:25:40 +020010877unicode_getitem(PyObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010878{
Victor Stinnerb6cd0142012-05-03 02:17:04 +020010879 void *data;
10880 enum PyUnicode_Kind kind;
10881 Py_UCS4 ch;
10882 PyObject *res;
10883
10884 if (!PyUnicode_Check(self) || PyUnicode_READY(self) == -1) {
10885 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010886 return NULL;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020010887 }
10888 if (index < 0 || index >= PyUnicode_GET_LENGTH(self)) {
10889 PyErr_SetString(PyExc_IndexError, "string index out of range");
10890 return NULL;
10891 }
10892 kind = PyUnicode_KIND(self);
10893 data = PyUnicode_DATA(self);
10894 ch = PyUnicode_READ(kind, data, index);
10895 if (ch < 256)
10896 return get_latin1_char(ch);
10897
10898 res = PyUnicode_New(1, ch);
10899 if (res == NULL)
10900 return NULL;
10901 kind = PyUnicode_KIND(res);
10902 data = PyUnicode_DATA(res);
10903 PyUnicode_WRITE(kind, data, 0, ch);
10904 assert(_PyUnicode_CheckConsistency(res, 1));
10905 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010906}
10907
Guido van Rossumc2504932007-09-18 19:42:40 +000010908/* Believe it or not, this produces the same value for ASCII strings
Mark Dickinson57e683e2011-09-24 18:18:40 +010010909 as bytes_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +000010910static Py_hash_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010911unicode_hash(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010912{
Guido van Rossumc2504932007-09-18 19:42:40 +000010913 Py_ssize_t len;
Mark Dickinson57e683e2011-09-24 18:18:40 +010010914 Py_uhash_t x;
Guido van Rossumc2504932007-09-18 19:42:40 +000010915
Benjamin Petersonf6622c82012-04-09 14:53:07 -040010916#ifdef Py_DEBUG
Benjamin Peterson69e97272012-02-21 11:08:50 -050010917 assert(_Py_HashSecret_Initialized);
Benjamin Petersonf6622c82012-04-09 14:53:07 -040010918#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010919 if (_PyUnicode_HASH(self) != -1)
10920 return _PyUnicode_HASH(self);
10921 if (PyUnicode_READY(self) == -1)
10922 return -1;
10923 len = PyUnicode_GET_LENGTH(self);
Georg Brandl16fa2a12012-02-21 00:50:13 +010010924 /*
10925 We make the hash of the empty string be 0, rather than using
10926 (prefix ^ suffix), since this slightly obfuscates the hash secret
10927 */
10928 if (len == 0) {
10929 _PyUnicode_HASH(self) = 0;
10930 return 0;
10931 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010932
10933 /* The hash function as a macro, gets expanded three times below. */
Georg Brandl2fb477c2012-02-21 00:33:36 +010010934#define HASH(P) \
10935 x ^= (Py_uhash_t) *P << 7; \
10936 while (--len >= 0) \
10937 x = (_PyHASH_MULTIPLIER * x) ^ (Py_uhash_t) *P++; \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010938
Georg Brandl2fb477c2012-02-21 00:33:36 +010010939 x = (Py_uhash_t) _Py_HashSecret.prefix;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010940 switch (PyUnicode_KIND(self)) {
10941 case PyUnicode_1BYTE_KIND: {
10942 const unsigned char *c = PyUnicode_1BYTE_DATA(self);
10943 HASH(c);
10944 break;
10945 }
10946 case PyUnicode_2BYTE_KIND: {
10947 const Py_UCS2 *s = PyUnicode_2BYTE_DATA(self);
10948 HASH(s);
10949 break;
10950 }
10951 default: {
10952 Py_UCS4 *l;
10953 assert(PyUnicode_KIND(self) == PyUnicode_4BYTE_KIND &&
10954 "Impossible switch case in unicode_hash");
10955 l = PyUnicode_4BYTE_DATA(self);
10956 HASH(l);
10957 break;
10958 }
10959 }
Georg Brandl2fb477c2012-02-21 00:33:36 +010010960 x ^= (Py_uhash_t) PyUnicode_GET_LENGTH(self);
10961 x ^= (Py_uhash_t) _Py_HashSecret.suffix;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010962
Guido van Rossumc2504932007-09-18 19:42:40 +000010963 if (x == -1)
10964 x = -2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010965 _PyUnicode_HASH(self) = x;
Guido van Rossumc2504932007-09-18 19:42:40 +000010966 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010967}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010968#undef HASH
Guido van Rossumd57fd912000-03-10 22:53:23 +000010969
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010970PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010971 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010972\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010973Like S.find() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010974
10975static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010976unicode_index(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010977{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010978 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010979 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000010980 Py_ssize_t start;
10981 Py_ssize_t end;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010982
Jesus Ceaac451502011-04-20 17:09:23 +020010983 if (!stringlib_parse_args_finds_unicode("index", args, &substring,
10984 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000010985 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010986
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010987 if (PyUnicode_READY(self) == -1)
10988 return NULL;
10989 if (PyUnicode_READY(substring) == -1)
10990 return NULL;
10991
Victor Stinner7931d9a2011-11-04 00:22:48 +010010992 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010993
10994 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010995
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010996 if (result == -2)
10997 return NULL;
10998
Guido van Rossumd57fd912000-03-10 22:53:23 +000010999 if (result < 0) {
11000 PyErr_SetString(PyExc_ValueError, "substring not found");
11001 return NULL;
11002 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011003
Christian Heimes217cfd12007-12-02 14:31:20 +000011004 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011005}
11006
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011007PyDoc_STRVAR(islower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011008 "S.islower() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011009\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011010Return True if all cased characters in S are lowercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011011at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011012
11013static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011014unicode_islower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011015{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011016 Py_ssize_t i, length;
11017 int kind;
11018 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011019 int cased;
11020
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011021 if (PyUnicode_READY(self) == -1)
11022 return NULL;
11023 length = PyUnicode_GET_LENGTH(self);
11024 kind = PyUnicode_KIND(self);
11025 data = PyUnicode_DATA(self);
11026
Guido van Rossumd57fd912000-03-10 22:53:23 +000011027 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011028 if (length == 1)
11029 return PyBool_FromLong(
11030 Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011031
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011032 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011033 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011034 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011035
Guido van Rossumd57fd912000-03-10 22:53:23 +000011036 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011037 for (i = 0; i < length; i++) {
11038 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011039
Benjamin Peterson29060642009-01-31 22:14:21 +000011040 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
11041 return PyBool_FromLong(0);
11042 else if (!cased && Py_UNICODE_ISLOWER(ch))
11043 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011044 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011045 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011046}
11047
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011048PyDoc_STRVAR(isupper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011049 "S.isupper() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011050\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011051Return True if all cased characters in S are uppercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011052at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011053
11054static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011055unicode_isupper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011056{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011057 Py_ssize_t i, length;
11058 int kind;
11059 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011060 int cased;
11061
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011062 if (PyUnicode_READY(self) == -1)
11063 return NULL;
11064 length = PyUnicode_GET_LENGTH(self);
11065 kind = PyUnicode_KIND(self);
11066 data = PyUnicode_DATA(self);
11067
Guido van Rossumd57fd912000-03-10 22:53:23 +000011068 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011069 if (length == 1)
11070 return PyBool_FromLong(
11071 Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011072
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011073 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011074 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011075 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011076
Guido van Rossumd57fd912000-03-10 22:53:23 +000011077 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011078 for (i = 0; i < length; i++) {
11079 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011080
Benjamin Peterson29060642009-01-31 22:14:21 +000011081 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
11082 return PyBool_FromLong(0);
11083 else if (!cased && Py_UNICODE_ISUPPER(ch))
11084 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011085 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011086 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011087}
11088
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011089PyDoc_STRVAR(istitle__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011090 "S.istitle() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011091\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011092Return True if S is a titlecased string and there is at least one\n\
11093character in S, i.e. upper- and titlecase characters may only\n\
11094follow uncased characters and lowercase characters only cased ones.\n\
11095Return False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011096
11097static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011098unicode_istitle(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011099{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011100 Py_ssize_t i, length;
11101 int kind;
11102 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011103 int cased, previous_is_cased;
11104
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011105 if (PyUnicode_READY(self) == -1)
11106 return NULL;
11107 length = PyUnicode_GET_LENGTH(self);
11108 kind = PyUnicode_KIND(self);
11109 data = PyUnicode_DATA(self);
11110
Guido van Rossumd57fd912000-03-10 22:53:23 +000011111 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011112 if (length == 1) {
11113 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11114 return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
11115 (Py_UNICODE_ISUPPER(ch) != 0));
11116 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011117
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011118 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011119 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011120 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011121
Guido van Rossumd57fd912000-03-10 22:53:23 +000011122 cased = 0;
11123 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011124 for (i = 0; i < length; i++) {
11125 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011126
Benjamin Peterson29060642009-01-31 22:14:21 +000011127 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
11128 if (previous_is_cased)
11129 return PyBool_FromLong(0);
11130 previous_is_cased = 1;
11131 cased = 1;
11132 }
11133 else if (Py_UNICODE_ISLOWER(ch)) {
11134 if (!previous_is_cased)
11135 return PyBool_FromLong(0);
11136 previous_is_cased = 1;
11137 cased = 1;
11138 }
11139 else
11140 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011141 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011142 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011143}
11144
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011145PyDoc_STRVAR(isspace__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011146 "S.isspace() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011147\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011148Return True if all characters in S are whitespace\n\
11149and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011150
11151static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011152unicode_isspace(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011153{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011154 Py_ssize_t i, length;
11155 int kind;
11156 void *data;
11157
11158 if (PyUnicode_READY(self) == -1)
11159 return NULL;
11160 length = PyUnicode_GET_LENGTH(self);
11161 kind = PyUnicode_KIND(self);
11162 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011163
Guido van Rossumd57fd912000-03-10 22:53:23 +000011164 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011165 if (length == 1)
11166 return PyBool_FromLong(
11167 Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011168
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011169 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011170 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011171 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011172
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011173 for (i = 0; i < length; i++) {
11174 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011175 if (!Py_UNICODE_ISSPACE(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011176 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011177 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011178 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011179}
11180
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011181PyDoc_STRVAR(isalpha__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011182 "S.isalpha() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011183\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011184Return True if all characters in S are alphabetic\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011185and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011186
11187static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011188unicode_isalpha(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011189{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011190 Py_ssize_t i, length;
11191 int kind;
11192 void *data;
11193
11194 if (PyUnicode_READY(self) == -1)
11195 return NULL;
11196 length = PyUnicode_GET_LENGTH(self);
11197 kind = PyUnicode_KIND(self);
11198 data = PyUnicode_DATA(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011199
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011200 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011201 if (length == 1)
11202 return PyBool_FromLong(
11203 Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011204
11205 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011206 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011207 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011208
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011209 for (i = 0; i < length; i++) {
11210 if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011211 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011212 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011213 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011214}
11215
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011216PyDoc_STRVAR(isalnum__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011217 "S.isalnum() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011218\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011219Return True if all characters in S are alphanumeric\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011220and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011221
11222static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011223unicode_isalnum(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011224{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011225 int kind;
11226 void *data;
11227 Py_ssize_t len, i;
11228
11229 if (PyUnicode_READY(self) == -1)
11230 return NULL;
11231
11232 kind = PyUnicode_KIND(self);
11233 data = PyUnicode_DATA(self);
11234 len = PyUnicode_GET_LENGTH(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011235
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011236 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011237 if (len == 1) {
11238 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11239 return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
11240 }
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011241
11242 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011243 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011244 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011245
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011246 for (i = 0; i < len; i++) {
11247 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011248 if (!Py_UNICODE_ISALNUM(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011249 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011250 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011251 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011252}
11253
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011254PyDoc_STRVAR(isdecimal__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011255 "S.isdecimal() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011256\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011257Return True if there are only decimal characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011258False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011259
11260static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011261unicode_isdecimal(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011262{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011263 Py_ssize_t i, length;
11264 int kind;
11265 void *data;
11266
11267 if (PyUnicode_READY(self) == -1)
11268 return NULL;
11269 length = PyUnicode_GET_LENGTH(self);
11270 kind = PyUnicode_KIND(self);
11271 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011272
Guido van Rossumd57fd912000-03-10 22:53:23 +000011273 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011274 if (length == 1)
11275 return PyBool_FromLong(
11276 Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011277
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011278 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011279 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011280 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011281
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011282 for (i = 0; i < length; i++) {
11283 if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011284 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011285 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011286 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011287}
11288
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011289PyDoc_STRVAR(isdigit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011290 "S.isdigit() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011291\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011292Return True if all characters in S are digits\n\
11293and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011294
11295static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011296unicode_isdigit(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011297{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011298 Py_ssize_t i, length;
11299 int kind;
11300 void *data;
11301
11302 if (PyUnicode_READY(self) == -1)
11303 return NULL;
11304 length = PyUnicode_GET_LENGTH(self);
11305 kind = PyUnicode_KIND(self);
11306 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011307
Guido van Rossumd57fd912000-03-10 22:53:23 +000011308 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011309 if (length == 1) {
11310 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11311 return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
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
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011318 for (i = 0; i < length; i++) {
11319 if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011320 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011321 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011322 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011323}
11324
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011325PyDoc_STRVAR(isnumeric__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011326 "S.isnumeric() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011327\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011328Return True if there are only numeric characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011329False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011330
11331static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011332unicode_isnumeric(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011333{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011334 Py_ssize_t i, length;
11335 int kind;
11336 void *data;
11337
11338 if (PyUnicode_READY(self) == -1)
11339 return NULL;
11340 length = PyUnicode_GET_LENGTH(self);
11341 kind = PyUnicode_KIND(self);
11342 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011343
Guido van Rossumd57fd912000-03-10 22:53:23 +000011344 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011345 if (length == 1)
11346 return PyBool_FromLong(
11347 Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011348
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011349 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011350 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011351 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011352
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011353 for (i = 0; i < length; i++) {
11354 if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011355 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011356 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011357 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011358}
11359
Martin v. Löwis47383402007-08-15 07:32:56 +000011360int
11361PyUnicode_IsIdentifier(PyObject *self)
11362{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011363 int kind;
11364 void *data;
11365 Py_ssize_t i;
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011366 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +000011367
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011368 if (PyUnicode_READY(self) == -1) {
11369 Py_FatalError("identifier not ready");
Benjamin Peterson29060642009-01-31 22:14:21 +000011370 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011371 }
11372
11373 /* Special case for empty strings */
11374 if (PyUnicode_GET_LENGTH(self) == 0)
11375 return 0;
11376 kind = PyUnicode_KIND(self);
11377 data = PyUnicode_DATA(self);
Martin v. Löwis47383402007-08-15 07:32:56 +000011378
11379 /* PEP 3131 says that the first character must be in
11380 XID_Start and subsequent characters in XID_Continue,
11381 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +000011382 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +000011383 letters, digits, underscore). However, given the current
11384 definition of XID_Start and XID_Continue, it is sufficient
11385 to check just for these, except that _ must be allowed
11386 as starting an identifier. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011387 first = PyUnicode_READ(kind, data, 0);
Benjamin Petersonf413b802011-08-12 22:17:18 -050011388 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +000011389 return 0;
11390
Benjamin Peterson9c6e6a02011-09-28 08:09:05 -040011391 for (i = 1; i < PyUnicode_GET_LENGTH(self); i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011392 if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011393 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +000011394 return 1;
11395}
11396
11397PyDoc_STRVAR(isidentifier__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011398 "S.isidentifier() -> bool\n\
Martin v. Löwis47383402007-08-15 07:32:56 +000011399\n\
11400Return True if S is a valid identifier according\n\
11401to the language definition.");
11402
11403static PyObject*
11404unicode_isidentifier(PyObject *self)
11405{
11406 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
11407}
11408
Georg Brandl559e5d72008-06-11 18:37:52 +000011409PyDoc_STRVAR(isprintable__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011410 "S.isprintable() -> bool\n\
Georg Brandl559e5d72008-06-11 18:37:52 +000011411\n\
11412Return True if all characters in S are considered\n\
11413printable in repr() or S is empty, False otherwise.");
11414
11415static PyObject*
11416unicode_isprintable(PyObject *self)
11417{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011418 Py_ssize_t i, length;
11419 int kind;
11420 void *data;
11421
11422 if (PyUnicode_READY(self) == -1)
11423 return NULL;
11424 length = PyUnicode_GET_LENGTH(self);
11425 kind = PyUnicode_KIND(self);
11426 data = PyUnicode_DATA(self);
Georg Brandl559e5d72008-06-11 18:37:52 +000011427
11428 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011429 if (length == 1)
11430 return PyBool_FromLong(
11431 Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
Georg Brandl559e5d72008-06-11 18:37:52 +000011432
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011433 for (i = 0; i < length; i++) {
11434 if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
Georg Brandl559e5d72008-06-11 18:37:52 +000011435 Py_RETURN_FALSE;
11436 }
11437 }
11438 Py_RETURN_TRUE;
11439}
11440
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011441PyDoc_STRVAR(join__doc__,
Georg Brandl495f7b52009-10-27 15:28:25 +000011442 "S.join(iterable) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011443\n\
11444Return a string which is the concatenation of the strings in the\n\
Georg Brandl495f7b52009-10-27 15:28:25 +000011445iterable. The separator between elements is S.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011446
11447static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011448unicode_join(PyObject *self, PyObject *data)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011449{
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011450 return PyUnicode_Join(self, data);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011451}
11452
Martin v. Löwis18e16552006-02-15 17:27:45 +000011453static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011454unicode_length(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011455{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011456 if (PyUnicode_READY(self) == -1)
11457 return -1;
11458 return PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011459}
11460
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011461PyDoc_STRVAR(ljust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011462 "S.ljust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011463\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000011464Return S left-justified in a Unicode string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011465done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011466
11467static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020011468unicode_ljust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011469{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011470 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011471 Py_UCS4 fillchar = ' ';
11472
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011473 if (!PyArg_ParseTuple(args, "n|O&:ljust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011474 return NULL;
11475
Benjamin Petersonbac79492012-01-14 13:34:47 -050011476 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010011477 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011478
Victor Stinnerc4b49542011-12-11 22:44:26 +010011479 if (PyUnicode_GET_LENGTH(self) >= width)
11480 return unicode_result_unchanged(self);
11481
11482 return pad(self, 0, width - PyUnicode_GET_LENGTH(self), fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011483}
11484
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011485PyDoc_STRVAR(lower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011486 "S.lower() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011487\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011488Return a copy of the string S converted to lowercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011489
11490static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020011491unicode_lower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011492{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050011493 if (PyUnicode_READY(self) == -1)
11494 return NULL;
11495 if (PyUnicode_IS_ASCII(self))
11496 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010011497 return case_operation(self, do_lower);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011498}
11499
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011500#define LEFTSTRIP 0
11501#define RIGHTSTRIP 1
11502#define BOTHSTRIP 2
11503
11504/* Arrays indexed by above */
11505static const char *stripformat[] = {"|O:lstrip", "|O:rstrip", "|O:strip"};
11506
11507#define STRIPNAME(i) (stripformat[i]+3)
11508
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011509/* externally visible for str.strip(unicode) */
11510PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011511_PyUnicode_XStrip(PyObject *self, int striptype, PyObject *sepobj)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011512{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011513 void *data;
11514 int kind;
11515 Py_ssize_t i, j, len;
11516 BLOOM_MASK sepmask;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011517
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011518 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
11519 return NULL;
11520
11521 kind = PyUnicode_KIND(self);
11522 data = PyUnicode_DATA(self);
11523 len = PyUnicode_GET_LENGTH(self);
11524 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
11525 PyUnicode_DATA(sepobj),
11526 PyUnicode_GET_LENGTH(sepobj));
Thomas Wouters477c8d52006-05-27 19:21:47 +000011527
Benjamin Peterson14339b62009-01-31 16:36:08 +000011528 i = 0;
11529 if (striptype != RIGHTSTRIP) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011530 while (i < len &&
11531 BLOOM_MEMBER(sepmask, PyUnicode_READ(kind, data, i), sepobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011532 i++;
11533 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011534 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011535
Benjamin Peterson14339b62009-01-31 16:36:08 +000011536 j = len;
11537 if (striptype != LEFTSTRIP) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011538 do {
11539 j--;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011540 } while (j >= i &&
11541 BLOOM_MEMBER(sepmask, PyUnicode_READ(kind, data, j), sepobj));
Benjamin Peterson29060642009-01-31 22:14:21 +000011542 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011543 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011544
Victor Stinner7931d9a2011-11-04 00:22:48 +010011545 return PyUnicode_Substring(self, i, j);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011546}
11547
11548PyObject*
11549PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
11550{
11551 unsigned char *data;
11552 int kind;
Victor Stinner12bab6d2011-10-01 01:53:49 +020011553 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011554
Victor Stinnerde636f32011-10-01 03:55:54 +020011555 if (PyUnicode_READY(self) == -1)
11556 return NULL;
11557
Victor Stinner684d5fd2012-05-03 02:32:34 +020011558 length = PyUnicode_GET_LENGTH(self);
11559 end = Py_MIN(end, length);
Victor Stinnerde636f32011-10-01 03:55:54 +020011560
Victor Stinner684d5fd2012-05-03 02:32:34 +020011561 if (start == 0 && end == length)
Victor Stinnerc4b49542011-12-11 22:44:26 +010011562 return unicode_result_unchanged(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011563
Victor Stinnerde636f32011-10-01 03:55:54 +020011564 if (start < 0 || end < 0) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020011565 PyErr_SetString(PyExc_IndexError, "string index out of range");
11566 return NULL;
11567 }
Victor Stinner684d5fd2012-05-03 02:32:34 +020011568 if (start >= length || end < start) {
Victor Stinner3a7f79772012-05-03 03:36:40 +020011569 Py_INCREF(unicode_empty);
11570 return unicode_empty;
Victor Stinner684d5fd2012-05-03 02:32:34 +020011571 }
Victor Stinner12bab6d2011-10-01 01:53:49 +020011572
Victor Stinner684d5fd2012-05-03 02:32:34 +020011573 length = end - start;
Victor Stinnerb9275c12011-10-05 14:01:42 +020011574 if (PyUnicode_IS_ASCII(self)) {
Victor Stinnerb9275c12011-10-05 14:01:42 +020011575 data = PyUnicode_1BYTE_DATA(self);
Victor Stinnerd3f08822012-05-29 12:57:52 +020011576 return _PyUnicode_FromASCII((char*)(data + start), length);
Victor Stinnerb9275c12011-10-05 14:01:42 +020011577 }
11578 else {
11579 kind = PyUnicode_KIND(self);
11580 data = PyUnicode_1BYTE_DATA(self);
11581 return PyUnicode_FromKindAndData(kind,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020011582 data + kind * start,
Victor Stinnerb9275c12011-10-05 14:01:42 +020011583 length);
11584 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011585}
Guido van Rossumd57fd912000-03-10 22:53:23 +000011586
11587static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011588do_strip(PyObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011589{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011590 int kind;
11591 void *data;
11592 Py_ssize_t len, i, j;
11593
11594 if (PyUnicode_READY(self) == -1)
11595 return NULL;
11596
11597 kind = PyUnicode_KIND(self);
11598 data = PyUnicode_DATA(self);
11599 len = PyUnicode_GET_LENGTH(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011600
Benjamin Peterson14339b62009-01-31 16:36:08 +000011601 i = 0;
11602 if (striptype != RIGHTSTRIP) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011603 while (i < len && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, i))) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000011604 i++;
11605 }
11606 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011607
Benjamin Peterson14339b62009-01-31 16:36:08 +000011608 j = len;
11609 if (striptype != LEFTSTRIP) {
11610 do {
11611 j--;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011612 } while (j >= i && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, j)));
Benjamin Peterson14339b62009-01-31 16:36:08 +000011613 j++;
11614 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011615
Victor Stinner7931d9a2011-11-04 00:22:48 +010011616 return PyUnicode_Substring(self, i, j);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011617}
11618
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011619
11620static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011621do_argstrip(PyObject *self, int striptype, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011622{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011623 PyObject *sep = NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011624
Benjamin Peterson14339b62009-01-31 16:36:08 +000011625 if (!PyArg_ParseTuple(args, (char *)stripformat[striptype], &sep))
11626 return NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011627
Benjamin Peterson14339b62009-01-31 16:36:08 +000011628 if (sep != NULL && sep != Py_None) {
11629 if (PyUnicode_Check(sep))
11630 return _PyUnicode_XStrip(self, striptype, sep);
11631 else {
11632 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000011633 "%s arg must be None or str",
11634 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +000011635 return NULL;
11636 }
11637 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011638
Benjamin Peterson14339b62009-01-31 16:36:08 +000011639 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011640}
11641
11642
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011643PyDoc_STRVAR(strip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011644 "S.strip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011645\n\
11646Return a copy of the string S with leading and trailing\n\
11647whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011648If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011649
11650static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011651unicode_strip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011652{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011653 if (PyTuple_GET_SIZE(args) == 0)
11654 return do_strip(self, BOTHSTRIP); /* Common case */
11655 else
11656 return do_argstrip(self, BOTHSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011657}
11658
11659
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011660PyDoc_STRVAR(lstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011661 "S.lstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011662\n\
11663Return a copy of the string S with leading whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011664If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011665
11666static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011667unicode_lstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011668{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011669 if (PyTuple_GET_SIZE(args) == 0)
11670 return do_strip(self, LEFTSTRIP); /* Common case */
11671 else
11672 return do_argstrip(self, LEFTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011673}
11674
11675
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011676PyDoc_STRVAR(rstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011677 "S.rstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011678\n\
11679Return a copy of the string S with trailing whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011680If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011681
11682static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011683unicode_rstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011684{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011685 if (PyTuple_GET_SIZE(args) == 0)
11686 return do_strip(self, RIGHTSTRIP); /* Common case */
11687 else
11688 return do_argstrip(self, RIGHTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011689}
11690
11691
Guido van Rossumd57fd912000-03-10 22:53:23 +000011692static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011693unicode_repeat(PyObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011694{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011695 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011696 Py_ssize_t nchars, n;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011697
Georg Brandl222de0f2009-04-12 12:01:50 +000011698 if (len < 1) {
11699 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +020011700 return unicode_empty;
Georg Brandl222de0f2009-04-12 12:01:50 +000011701 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011702
Victor Stinnerc4b49542011-12-11 22:44:26 +010011703 /* no repeat, return original string */
11704 if (len == 1)
11705 return unicode_result_unchanged(str);
Tim Peters8f422462000-09-09 06:13:41 +000011706
Benjamin Petersonbac79492012-01-14 13:34:47 -050011707 if (PyUnicode_READY(str) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011708 return NULL;
11709
Victor Stinnerc759f3e2011-10-01 03:09:58 +020011710 if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
Victor Stinner67ca64c2011-10-01 02:47:29 +020011711 PyErr_SetString(PyExc_OverflowError,
11712 "repeated string is too long");
11713 return NULL;
11714 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011715 nchars = len * PyUnicode_GET_LENGTH(str);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011716
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011717 u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011718 if (!u)
11719 return NULL;
Victor Stinner67ca64c2011-10-01 02:47:29 +020011720 assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011721
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011722 if (PyUnicode_GET_LENGTH(str) == 1) {
11723 const int kind = PyUnicode_KIND(str);
11724 const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
Victor Stinner73f53b52011-12-18 03:26:31 +010011725 if (kind == PyUnicode_1BYTE_KIND) {
11726 void *to = PyUnicode_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011727 memset(to, (unsigned char)fill_char, len);
Victor Stinner73f53b52011-12-18 03:26:31 +010011728 }
11729 else if (kind == PyUnicode_2BYTE_KIND) {
11730 Py_UCS2 *ucs2 = PyUnicode_2BYTE_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011731 for (n = 0; n < len; ++n)
Victor Stinner73f53b52011-12-18 03:26:31 +010011732 ucs2[n] = fill_char;
11733 } else {
11734 Py_UCS4 *ucs4 = PyUnicode_4BYTE_DATA(u);
11735 assert(kind == PyUnicode_4BYTE_KIND);
11736 for (n = 0; n < len; ++n)
11737 ucs4[n] = fill_char;
Victor Stinner67ca64c2011-10-01 02:47:29 +020011738 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011739 }
11740 else {
11741 /* number of characters copied this far */
11742 Py_ssize_t done = PyUnicode_GET_LENGTH(str);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020011743 const Py_ssize_t char_size = PyUnicode_KIND(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011744 char *to = (char *) PyUnicode_DATA(u);
11745 Py_MEMCPY(to, PyUnicode_DATA(str),
11746 PyUnicode_GET_LENGTH(str) * char_size);
Benjamin Peterson29060642009-01-31 22:14:21 +000011747 while (done < nchars) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011748 n = (done <= nchars-done) ? done : nchars-done;
11749 Py_MEMCPY(to + (done * char_size), to, n * char_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011750 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +000011751 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011752 }
11753
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020011754 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011755 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011756}
11757
Alexander Belopolsky40018472011-02-26 01:02:56 +000011758PyObject *
11759PyUnicode_Replace(PyObject *obj,
11760 PyObject *subobj,
11761 PyObject *replobj,
11762 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011763{
11764 PyObject *self;
11765 PyObject *str1;
11766 PyObject *str2;
11767 PyObject *result;
11768
11769 self = PyUnicode_FromObject(obj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060011770 if (self == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000011771 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011772 str1 = PyUnicode_FromObject(subobj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060011773 if (str1 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011774 Py_DECREF(self);
11775 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011776 }
11777 str2 = PyUnicode_FromObject(replobj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060011778 if (str2 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011779 Py_DECREF(self);
11780 Py_DECREF(str1);
11781 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011782 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060011783 if (PyUnicode_READY(self) == -1 ||
11784 PyUnicode_READY(str1) == -1 ||
11785 PyUnicode_READY(str2) == -1)
11786 result = NULL;
11787 else
11788 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011789 Py_DECREF(self);
11790 Py_DECREF(str1);
11791 Py_DECREF(str2);
11792 return result;
11793}
11794
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011795PyDoc_STRVAR(replace__doc__,
Ezio Melottic1897e72010-06-26 18:50:39 +000011796 "S.replace(old, new[, count]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011797\n\
11798Return a copy of S with all occurrences of substring\n\
Georg Brandlf08a9dd2008-06-10 16:57:31 +000011799old replaced by new. If the optional argument count is\n\
11800given, only the first count occurrences are replaced.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011801
11802static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011803unicode_replace(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011804{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011805 PyObject *str1;
11806 PyObject *str2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011807 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011808 PyObject *result;
11809
Martin v. Löwis18e16552006-02-15 17:27:45 +000011810 if (!PyArg_ParseTuple(args, "OO|n:replace", &str1, &str2, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011811 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060011812 if (PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000011813 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011814 str1 = PyUnicode_FromObject(str1);
Benjamin Peterson22a29702012-01-02 09:00:30 -060011815 if (str1 == NULL)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011816 return NULL;
11817 str2 = PyUnicode_FromObject(str2);
Benjamin Peterson22a29702012-01-02 09:00:30 -060011818 if (str2 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011819 Py_DECREF(str1);
11820 return NULL;
Walter Dörwaldf6b56ae2003-02-09 23:42:56 +000011821 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060011822 if (PyUnicode_READY(str1) == -1 || PyUnicode_READY(str2) == -1)
11823 result = NULL;
11824 else
11825 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011826
11827 Py_DECREF(str1);
11828 Py_DECREF(str2);
11829 return result;
11830}
11831
Alexander Belopolsky40018472011-02-26 01:02:56 +000011832static PyObject *
11833unicode_repr(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011834{
Walter Dörwald79e913e2007-05-12 11:08:06 +000011835 PyObject *repr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011836 Py_ssize_t isize;
11837 Py_ssize_t osize, squote, dquote, i, o;
11838 Py_UCS4 max, quote;
11839 int ikind, okind;
11840 void *idata, *odata;
Walter Dörwald79e913e2007-05-12 11:08:06 +000011841
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011842 if (PyUnicode_READY(unicode) == -1)
Walter Dörwald79e913e2007-05-12 11:08:06 +000011843 return NULL;
11844
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011845 isize = PyUnicode_GET_LENGTH(unicode);
11846 idata = PyUnicode_DATA(unicode);
Walter Dörwald79e913e2007-05-12 11:08:06 +000011847
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011848 /* Compute length of output, quote characters, and
11849 maximum character */
11850 osize = 2; /* quotes */
11851 max = 127;
11852 squote = dquote = 0;
11853 ikind = PyUnicode_KIND(unicode);
11854 for (i = 0; i < isize; i++) {
11855 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
11856 switch (ch) {
11857 case '\'': squote++; osize++; break;
11858 case '"': dquote++; osize++; break;
11859 case '\\': case '\t': case '\r': case '\n':
11860 osize += 2; break;
11861 default:
11862 /* Fast-path ASCII */
11863 if (ch < ' ' || ch == 0x7f)
11864 osize += 4; /* \xHH */
11865 else if (ch < 0x7f)
11866 osize++;
11867 else if (Py_UNICODE_ISPRINTABLE(ch)) {
11868 osize++;
11869 max = ch > max ? ch : max;
11870 }
11871 else if (ch < 0x100)
11872 osize += 4; /* \xHH */
11873 else if (ch < 0x10000)
11874 osize += 6; /* \uHHHH */
11875 else
11876 osize += 10; /* \uHHHHHHHH */
11877 }
11878 }
11879
11880 quote = '\'';
11881 if (squote) {
11882 if (dquote)
11883 /* Both squote and dquote present. Use squote,
11884 and escape them */
11885 osize += squote;
11886 else
11887 quote = '"';
11888 }
11889
11890 repr = PyUnicode_New(osize, max);
11891 if (repr == NULL)
11892 return NULL;
11893 okind = PyUnicode_KIND(repr);
11894 odata = PyUnicode_DATA(repr);
11895
11896 PyUnicode_WRITE(okind, odata, 0, quote);
11897 PyUnicode_WRITE(okind, odata, osize-1, quote);
11898
11899 for (i = 0, o = 1; i < isize; i++) {
11900 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Walter Dörwald79e913e2007-05-12 11:08:06 +000011901
11902 /* Escape quotes and backslashes */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011903 if ((ch == quote) || (ch == '\\')) {
11904 PyUnicode_WRITE(okind, odata, o++, '\\');
11905 PyUnicode_WRITE(okind, odata, o++, ch);
Walter Dörwald79e913e2007-05-12 11:08:06 +000011906 continue;
11907 }
11908
Benjamin Peterson29060642009-01-31 22:14:21 +000011909 /* Map special whitespace to '\t', \n', '\r' */
Georg Brandl559e5d72008-06-11 18:37:52 +000011910 if (ch == '\t') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011911 PyUnicode_WRITE(okind, odata, o++, '\\');
11912 PyUnicode_WRITE(okind, odata, o++, 't');
Walter Dörwald79e913e2007-05-12 11:08:06 +000011913 }
11914 else if (ch == '\n') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011915 PyUnicode_WRITE(okind, odata, o++, '\\');
11916 PyUnicode_WRITE(okind, odata, o++, 'n');
Walter Dörwald79e913e2007-05-12 11:08:06 +000011917 }
11918 else if (ch == '\r') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011919 PyUnicode_WRITE(okind, odata, o++, '\\');
11920 PyUnicode_WRITE(okind, odata, o++, 'r');
Walter Dörwald79e913e2007-05-12 11:08:06 +000011921 }
11922
11923 /* Map non-printable US ASCII to '\xhh' */
Georg Brandl559e5d72008-06-11 18:37:52 +000011924 else if (ch < ' ' || ch == 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011925 PyUnicode_WRITE(okind, odata, o++, '\\');
11926 PyUnicode_WRITE(okind, odata, o++, 'x');
Victor Stinnerf5cff562011-10-14 02:13:11 +020011927 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
11928 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
Walter Dörwald79e913e2007-05-12 11:08:06 +000011929 }
11930
Georg Brandl559e5d72008-06-11 18:37:52 +000011931 /* Copy ASCII characters as-is */
11932 else if (ch < 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011933 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000011934 }
11935
Benjamin Peterson29060642009-01-31 22:14:21 +000011936 /* Non-ASCII characters */
Georg Brandl559e5d72008-06-11 18:37:52 +000011937 else {
Benjamin Peterson14339b62009-01-31 16:36:08 +000011938 /* Map Unicode whitespace and control characters
Georg Brandl559e5d72008-06-11 18:37:52 +000011939 (categories Z* and C* except ASCII space)
11940 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011941 if (!Py_UNICODE_ISPRINTABLE(ch)) {
Kristján Valur Jónsson55e5dc82012-06-06 21:58:08 +000011942 PyUnicode_WRITE(okind, odata, o++, '\\');
Georg Brandl559e5d72008-06-11 18:37:52 +000011943 /* Map 8-bit characters to '\xhh' */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011944 if (ch <= 0xff) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011945 PyUnicode_WRITE(okind, odata, o++, 'x');
Victor Stinnerf5cff562011-10-14 02:13:11 +020011946 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
11947 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
Georg Brandl559e5d72008-06-11 18:37:52 +000011948 }
Kristján Valur Jónsson55e5dc82012-06-06 21:58:08 +000011949 /* Map 16-bit characters to '\uxxxx' */
11950 else if (ch <= 0xffff) {
11951 PyUnicode_WRITE(okind, odata, o++, 'u');
Victor Stinnerf5cff562011-10-14 02:13:11 +020011952 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
11953 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
11954 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
11955 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000011956 }
Kristján Valur Jónsson55e5dc82012-06-06 21:58:08 +000011957 /* Map 21-bit characters to '\U00xxxxxx' */
Georg Brandl559e5d72008-06-11 18:37:52 +000011958 else {
Kristján Valur Jónsson55e5dc82012-06-06 21:58:08 +000011959 PyUnicode_WRITE(okind, odata, o++, 'U');
11960 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 28) & 0xF]);
11961 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 24) & 0xF]);
11962 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 20) & 0xF]);
11963 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 16) & 0xF]);
Victor Stinnerf5cff562011-10-14 02:13:11 +020011964 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
11965 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
11966 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
11967 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000011968 }
11969 }
11970 /* Copy characters as-is */
11971 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011972 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000011973 }
11974 }
Walter Dörwald79e913e2007-05-12 11:08:06 +000011975 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011976 /* Closing quote already added at the beginning */
Victor Stinner05d11892011-10-06 01:13:58 +020011977 assert(_PyUnicode_CheckConsistency(repr, 1));
Walter Dörwald79e913e2007-05-12 11:08:06 +000011978 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011979}
11980
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011981PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011982 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011983\n\
11984Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080011985such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011986arguments start and end are interpreted as in slice notation.\n\
11987\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011988Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011989
11990static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011991unicode_rfind(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011992{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011993 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011994 Py_ssize_t start;
11995 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011996 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011997
Jesus Ceaac451502011-04-20 17:09:23 +020011998 if (!stringlib_parse_args_finds_unicode("rfind", args, &substring,
11999 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012000 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012001
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012002 if (PyUnicode_READY(self) == -1)
12003 return NULL;
12004 if (PyUnicode_READY(substring) == -1)
12005 return NULL;
12006
Victor Stinner7931d9a2011-11-04 00:22:48 +010012007 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012008
12009 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012010
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012011 if (result == -2)
12012 return NULL;
12013
Christian Heimes217cfd12007-12-02 14:31:20 +000012014 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012015}
12016
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012017PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012018 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012019\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012020Like S.rfind() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012021
12022static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012023unicode_rindex(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012024{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012025 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012026 Py_ssize_t start;
12027 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012028 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012029
Jesus Ceaac451502011-04-20 17:09:23 +020012030 if (!stringlib_parse_args_finds_unicode("rindex", args, &substring,
12031 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012032 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012033
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012034 if (PyUnicode_READY(self) == -1)
12035 return NULL;
12036 if (PyUnicode_READY(substring) == -1)
12037 return NULL;
12038
Victor Stinner7931d9a2011-11-04 00:22:48 +010012039 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012040
12041 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012042
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012043 if (result == -2)
12044 return NULL;
12045
Guido van Rossumd57fd912000-03-10 22:53:23 +000012046 if (result < 0) {
12047 PyErr_SetString(PyExc_ValueError, "substring not found");
12048 return NULL;
12049 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012050
Christian Heimes217cfd12007-12-02 14:31:20 +000012051 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012052}
12053
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012054PyDoc_STRVAR(rjust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012055 "S.rjust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012056\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012057Return S right-justified in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012058done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012059
12060static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012061unicode_rjust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012062{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012063 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012064 Py_UCS4 fillchar = ' ';
12065
Victor Stinnere9a29352011-10-01 02:14:59 +020012066 if (!PyArg_ParseTuple(args, "n|O&:rjust", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012067 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012068
Benjamin Petersonbac79492012-01-14 13:34:47 -050012069 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012070 return NULL;
12071
Victor Stinnerc4b49542011-12-11 22:44:26 +010012072 if (PyUnicode_GET_LENGTH(self) >= width)
12073 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012074
Victor Stinnerc4b49542011-12-11 22:44:26 +010012075 return pad(self, width - PyUnicode_GET_LENGTH(self), 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012076}
12077
Alexander Belopolsky40018472011-02-26 01:02:56 +000012078PyObject *
12079PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012080{
12081 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +000012082
Guido van Rossumd57fd912000-03-10 22:53:23 +000012083 s = PyUnicode_FromObject(s);
12084 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012085 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012086 if (sep != NULL) {
12087 sep = PyUnicode_FromObject(sep);
12088 if (sep == NULL) {
12089 Py_DECREF(s);
12090 return NULL;
12091 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012092 }
12093
Victor Stinner9310abb2011-10-05 00:59:23 +020012094 result = split(s, sep, maxsplit);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012095
12096 Py_DECREF(s);
12097 Py_XDECREF(sep);
12098 return result;
12099}
12100
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012101PyDoc_STRVAR(split__doc__,
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012102 "S.split(sep=None, maxsplit=-1) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012103\n\
12104Return a list of the words in S, using sep as the\n\
12105delimiter string. If maxsplit is given, at most maxsplit\n\
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000012106splits are done. If sep is not specified or is None, any\n\
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +000012107whitespace string is a separator and empty strings are\n\
12108removed from the result.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012109
12110static PyObject*
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012111unicode_split(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012112{
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012113 static char *kwlist[] = {"sep", "maxsplit", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000012114 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012115 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012116
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012117 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:split",
12118 kwlist, &substring, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012119 return NULL;
12120
12121 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012122 return split(self, NULL, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012123 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012124 return split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012125 else
Victor Stinner7931d9a2011-11-04 00:22:48 +010012126 return PyUnicode_Split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012127}
12128
Thomas Wouters477c8d52006-05-27 19:21:47 +000012129PyObject *
12130PyUnicode_Partition(PyObject *str_in, PyObject *sep_in)
12131{
12132 PyObject* str_obj;
12133 PyObject* sep_obj;
12134 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012135 int kind1, kind2, kind;
12136 void *buf1 = NULL, *buf2 = NULL;
12137 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012138
12139 str_obj = PyUnicode_FromObject(str_in);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012140 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012141 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012142 sep_obj = PyUnicode_FromObject(sep_in);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012143 if (!sep_obj) {
12144 Py_DECREF(str_obj);
12145 return NULL;
12146 }
12147 if (PyUnicode_READY(sep_obj) == -1 || PyUnicode_READY(str_obj) == -1) {
12148 Py_DECREF(sep_obj);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012149 Py_DECREF(str_obj);
12150 return NULL;
12151 }
12152
Victor Stinner14f8f022011-10-05 20:58:25 +020012153 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012154 kind2 = PyUnicode_KIND(sep_obj);
Victor Stinner14f8f022011-10-05 20:58:25 +020012155 kind = Py_MAX(kind1, kind2);
12156 buf1 = PyUnicode_DATA(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012157 if (kind1 != kind)
Victor Stinner14f8f022011-10-05 20:58:25 +020012158 buf1 = _PyUnicode_AsKind(str_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012159 if (!buf1)
12160 goto onError;
12161 buf2 = PyUnicode_DATA(sep_obj);
12162 if (kind2 != kind)
12163 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12164 if (!buf2)
12165 goto onError;
12166 len1 = PyUnicode_GET_LENGTH(str_obj);
12167 len2 = PyUnicode_GET_LENGTH(sep_obj);
12168
Benjamin Petersonead6b532011-12-20 17:23:42 -060012169 switch (PyUnicode_KIND(str_obj)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012170 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012171 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12172 out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12173 else
12174 out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012175 break;
12176 case PyUnicode_2BYTE_KIND:
12177 out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12178 break;
12179 case PyUnicode_4BYTE_KIND:
12180 out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12181 break;
12182 default:
12183 assert(0);
12184 out = 0;
12185 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012186
12187 Py_DECREF(sep_obj);
12188 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012189 if (kind1 != kind)
12190 PyMem_Free(buf1);
12191 if (kind2 != kind)
12192 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012193
12194 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012195 onError:
12196 Py_DECREF(sep_obj);
12197 Py_DECREF(str_obj);
12198 if (kind1 != kind && buf1)
12199 PyMem_Free(buf1);
12200 if (kind2 != kind && buf2)
12201 PyMem_Free(buf2);
12202 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012203}
12204
12205
12206PyObject *
12207PyUnicode_RPartition(PyObject *str_in, PyObject *sep_in)
12208{
12209 PyObject* str_obj;
12210 PyObject* sep_obj;
12211 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012212 int kind1, kind2, kind;
12213 void *buf1 = NULL, *buf2 = NULL;
12214 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012215
12216 str_obj = PyUnicode_FromObject(str_in);
12217 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012218 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012219 sep_obj = PyUnicode_FromObject(sep_in);
12220 if (!sep_obj) {
12221 Py_DECREF(str_obj);
12222 return NULL;
12223 }
12224
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012225 kind1 = PyUnicode_KIND(str_in);
12226 kind2 = PyUnicode_KIND(sep_obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +020012227 kind = Py_MAX(kind1, kind2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012228 buf1 = PyUnicode_DATA(str_in);
12229 if (kind1 != kind)
12230 buf1 = _PyUnicode_AsKind(str_in, kind);
12231 if (!buf1)
12232 goto onError;
12233 buf2 = PyUnicode_DATA(sep_obj);
12234 if (kind2 != kind)
12235 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12236 if (!buf2)
12237 goto onError;
12238 len1 = PyUnicode_GET_LENGTH(str_obj);
12239 len2 = PyUnicode_GET_LENGTH(sep_obj);
12240
Benjamin Petersonead6b532011-12-20 17:23:42 -060012241 switch (PyUnicode_KIND(str_in)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012242 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012243 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12244 out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12245 else
12246 out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012247 break;
12248 case PyUnicode_2BYTE_KIND:
12249 out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12250 break;
12251 case PyUnicode_4BYTE_KIND:
12252 out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12253 break;
12254 default:
12255 assert(0);
12256 out = 0;
12257 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012258
12259 Py_DECREF(sep_obj);
12260 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012261 if (kind1 != kind)
12262 PyMem_Free(buf1);
12263 if (kind2 != kind)
12264 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012265
12266 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012267 onError:
12268 Py_DECREF(sep_obj);
12269 Py_DECREF(str_obj);
12270 if (kind1 != kind && buf1)
12271 PyMem_Free(buf1);
12272 if (kind2 != kind && buf2)
12273 PyMem_Free(buf2);
12274 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012275}
12276
12277PyDoc_STRVAR(partition__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012278 "S.partition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012279\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012280Search for the separator sep in S, and return the part before it,\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012281the separator itself, and the part after it. If the separator is not\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012282found, return S and two empty strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012283
12284static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012285unicode_partition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012286{
Victor Stinner9310abb2011-10-05 00:59:23 +020012287 return PyUnicode_Partition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012288}
12289
12290PyDoc_STRVAR(rpartition__doc__,
Ezio Melotti5b2b2422010-01-25 11:58:28 +000012291 "S.rpartition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012292\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012293Search for the separator sep in S, starting at the end of S, and return\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012294the part before it, the separator itself, and the part after it. If the\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012295separator is not found, return two empty strings and S.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012296
12297static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012298unicode_rpartition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012299{
Victor Stinner9310abb2011-10-05 00:59:23 +020012300 return PyUnicode_RPartition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012301}
12302
Alexander Belopolsky40018472011-02-26 01:02:56 +000012303PyObject *
12304PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012305{
12306 PyObject *result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012307
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012308 s = PyUnicode_FromObject(s);
12309 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012310 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012311 if (sep != NULL) {
12312 sep = PyUnicode_FromObject(sep);
12313 if (sep == NULL) {
12314 Py_DECREF(s);
12315 return NULL;
12316 }
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012317 }
12318
Victor Stinner9310abb2011-10-05 00:59:23 +020012319 result = rsplit(s, sep, maxsplit);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012320
12321 Py_DECREF(s);
12322 Py_XDECREF(sep);
12323 return result;
12324}
12325
12326PyDoc_STRVAR(rsplit__doc__,
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012327 "S.rsplit(sep=None, maxsplit=-1) -> list of strings\n\
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012328\n\
12329Return a list of the words in S, using sep as the\n\
12330delimiter string, starting at the end of the string and\n\
12331working to the front. If maxsplit is given, at most maxsplit\n\
12332splits are done. If sep is not specified, any whitespace string\n\
12333is a separator.");
12334
12335static PyObject*
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012336unicode_rsplit(PyObject *self, PyObject *args, PyObject *kwds)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012337{
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012338 static char *kwlist[] = {"sep", "maxsplit", 0};
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012339 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012340 Py_ssize_t maxcount = -1;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012341
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012342 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:rsplit",
12343 kwlist, &substring, &maxcount))
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012344 return NULL;
12345
12346 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012347 return rsplit(self, NULL, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012348 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012349 return rsplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012350 else
Victor Stinner9310abb2011-10-05 00:59:23 +020012351 return PyUnicode_RSplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012352}
12353
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012354PyDoc_STRVAR(splitlines__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012355 "S.splitlines([keepends]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012356\n\
12357Return a list of the lines in S, breaking at line boundaries.\n\
Guido van Rossum86662912000-04-11 15:38:46 +000012358Line breaks are not included in the resulting list unless keepends\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012359is given and true.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012360
12361static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012362unicode_splitlines(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012363{
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012364 static char *kwlist[] = {"keepends", 0};
Guido van Rossum86662912000-04-11 15:38:46 +000012365 int keepends = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012366
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012367 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:splitlines",
12368 kwlist, &keepends))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012369 return NULL;
12370
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012371 return PyUnicode_Splitlines(self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012372}
12373
12374static
Guido van Rossumf15a29f2007-05-04 00:41:39 +000012375PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012376{
Victor Stinnerc4b49542011-12-11 22:44:26 +010012377 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012378}
12379
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012380PyDoc_STRVAR(swapcase__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012381 "S.swapcase() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012382\n\
12383Return a copy of S with uppercase characters converted to lowercase\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012384and vice versa.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012385
12386static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012387unicode_swapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012388{
Benjamin Petersoneea48462012-01-16 14:28:50 -050012389 if (PyUnicode_READY(self) == -1)
12390 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010012391 return case_operation(self, do_swapcase);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012392}
12393
Georg Brandlceee0772007-11-27 23:48:05 +000012394PyDoc_STRVAR(maketrans__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012395 "str.maketrans(x[, y[, z]]) -> dict (static method)\n\
Georg Brandlceee0772007-11-27 23:48:05 +000012396\n\
12397Return a translation table usable for str.translate().\n\
12398If there is only one argument, it must be a dictionary mapping Unicode\n\
12399ordinals (integers) or characters to Unicode ordinals, strings or None.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012400Character keys will be then converted to ordinals.\n\
Georg Brandlceee0772007-11-27 23:48:05 +000012401If there are two arguments, they must be strings of equal length, and\n\
12402in the resulting dictionary, each character in x will be mapped to the\n\
12403character at the same position in y. If there is a third argument, it\n\
12404must be a string, whose characters will be mapped to None in the result.");
12405
12406static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012407unicode_maketrans(PyObject *null, PyObject *args)
Georg Brandlceee0772007-11-27 23:48:05 +000012408{
12409 PyObject *x, *y = NULL, *z = NULL;
12410 PyObject *new = NULL, *key, *value;
12411 Py_ssize_t i = 0;
12412 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012413
Georg Brandlceee0772007-11-27 23:48:05 +000012414 if (!PyArg_ParseTuple(args, "O|UU:maketrans", &x, &y, &z))
12415 return NULL;
12416 new = PyDict_New();
12417 if (!new)
12418 return NULL;
12419 if (y != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012420 int x_kind, y_kind, z_kind;
12421 void *x_data, *y_data, *z_data;
12422
Georg Brandlceee0772007-11-27 23:48:05 +000012423 /* x must be a string too, of equal length */
Georg Brandlceee0772007-11-27 23:48:05 +000012424 if (!PyUnicode_Check(x)) {
12425 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
12426 "be a string if there is a second argument");
12427 goto err;
12428 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012429 if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012430 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
12431 "arguments must have equal length");
12432 goto err;
12433 }
12434 /* create entries for translating chars in x to those in y */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012435 x_kind = PyUnicode_KIND(x);
12436 y_kind = PyUnicode_KIND(y);
12437 x_data = PyUnicode_DATA(x);
12438 y_data = PyUnicode_DATA(y);
12439 for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
12440 key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060012441 if (!key)
Georg Brandlceee0772007-11-27 23:48:05 +000012442 goto err;
Benjamin Peterson822c7902011-12-20 13:32:50 -060012443 value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060012444 if (!value) {
12445 Py_DECREF(key);
12446 goto err;
12447 }
Georg Brandlceee0772007-11-27 23:48:05 +000012448 res = PyDict_SetItem(new, key, value);
12449 Py_DECREF(key);
12450 Py_DECREF(value);
12451 if (res < 0)
12452 goto err;
12453 }
12454 /* create entries for deleting chars in z */
12455 if (z != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012456 z_kind = PyUnicode_KIND(z);
12457 z_data = PyUnicode_DATA(z);
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012458 for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012459 key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000012460 if (!key)
12461 goto err;
12462 res = PyDict_SetItem(new, key, Py_None);
12463 Py_DECREF(key);
12464 if (res < 0)
12465 goto err;
12466 }
12467 }
12468 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012469 int kind;
12470 void *data;
12471
Georg Brandlceee0772007-11-27 23:48:05 +000012472 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +000012473 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012474 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
12475 "to maketrans it must be a dict");
12476 goto err;
12477 }
12478 /* copy entries into the new dict, converting string keys to int keys */
12479 while (PyDict_Next(x, &i, &key, &value)) {
12480 if (PyUnicode_Check(key)) {
12481 /* convert string keys to integer keys */
12482 PyObject *newkey;
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012483 if (PyUnicode_GET_LENGTH(key) != 1) {
Georg Brandlceee0772007-11-27 23:48:05 +000012484 PyErr_SetString(PyExc_ValueError, "string keys in translate "
12485 "table must be of length 1");
12486 goto err;
12487 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012488 kind = PyUnicode_KIND(key);
12489 data = PyUnicode_DATA(key);
12490 newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
Georg Brandlceee0772007-11-27 23:48:05 +000012491 if (!newkey)
12492 goto err;
12493 res = PyDict_SetItem(new, newkey, value);
12494 Py_DECREF(newkey);
12495 if (res < 0)
12496 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +000012497 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012498 /* just keep integer keys */
12499 if (PyDict_SetItem(new, key, value) < 0)
12500 goto err;
12501 } else {
12502 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
12503 "be strings or integers");
12504 goto err;
12505 }
12506 }
12507 }
12508 return new;
12509 err:
12510 Py_DECREF(new);
12511 return NULL;
12512}
12513
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012514PyDoc_STRVAR(translate__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012515 "S.translate(table) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012516\n\
12517Return a copy of the string S, where all characters have been mapped\n\
12518through the given translation table, which must be a mapping of\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012519Unicode ordinals to Unicode ordinals, strings, or None.\n\
Walter Dörwald5c1ee172002-09-04 20:31:32 +000012520Unmapped characters are left untouched. Characters mapped to None\n\
12521are deleted.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012522
12523static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012524unicode_translate(PyObject *self, PyObject *table)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012525{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012526 return _PyUnicode_TranslateCharmap(self, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012527}
12528
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012529PyDoc_STRVAR(upper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012530 "S.upper() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012531\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012532Return a copy of S converted to uppercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012533
12534static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012535unicode_upper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012536{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050012537 if (PyUnicode_READY(self) == -1)
12538 return NULL;
12539 if (PyUnicode_IS_ASCII(self))
12540 return ascii_upper_or_lower(self, 0);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010012541 return case_operation(self, do_upper);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012542}
12543
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012544PyDoc_STRVAR(zfill__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012545 "S.zfill(width) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012546\n\
Benjamin Peterson9aa42992008-09-10 21:57:34 +000012547Pad a numeric string S with zeros on the left, to fill a field\n\
12548of the specified width. The string S is never truncated.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012549
12550static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012551unicode_zfill(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012552{
Martin v. Löwis18e16552006-02-15 17:27:45 +000012553 Py_ssize_t fill;
Victor Stinner9310abb2011-10-05 00:59:23 +020012554 PyObject *u;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012555 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012556 int kind;
12557 void *data;
12558 Py_UCS4 chr;
12559
Martin v. Löwis18e16552006-02-15 17:27:45 +000012560 if (!PyArg_ParseTuple(args, "n:zfill", &width))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012561 return NULL;
12562
Benjamin Petersonbac79492012-01-14 13:34:47 -050012563 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010012564 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012565
Victor Stinnerc4b49542011-12-11 22:44:26 +010012566 if (PyUnicode_GET_LENGTH(self) >= width)
12567 return unicode_result_unchanged(self);
12568
12569 fill = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012570
12571 u = pad(self, fill, 0, '0');
12572
Walter Dörwald068325e2002-04-15 13:36:47 +000012573 if (u == NULL)
12574 return NULL;
12575
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012576 kind = PyUnicode_KIND(u);
12577 data = PyUnicode_DATA(u);
12578 chr = PyUnicode_READ(kind, data, fill);
12579
12580 if (chr == '+' || chr == '-') {
Guido van Rossumd57fd912000-03-10 22:53:23 +000012581 /* move sign to beginning of string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012582 PyUnicode_WRITE(kind, data, 0, chr);
12583 PyUnicode_WRITE(kind, data, fill, '0');
Guido van Rossumd57fd912000-03-10 22:53:23 +000012584 }
12585
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012586 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +010012587 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012588}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012589
12590#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012591static PyObject *
12592unicode__decimal2ascii(PyObject *self)
12593{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012594 return PyUnicode_TransformDecimalAndSpaceToASCII(self);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012595}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012596#endif
12597
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012598PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012599 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012600\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000012601Return True if S starts with the specified prefix, False otherwise.\n\
12602With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012603With optional end, stop comparing S at that position.\n\
12604prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012605
12606static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012607unicode_startswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000012608 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012609{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012610 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012611 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012612 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012613 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012614 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012615
Jesus Ceaac451502011-04-20 17:09:23 +020012616 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000012617 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012618 if (PyTuple_Check(subobj)) {
12619 Py_ssize_t i;
12620 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012621 substring = PyUnicode_FromObject(PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012622 if (substring == NULL)
12623 return NULL;
12624 result = tailmatch(self, substring, start, end, -1);
12625 Py_DECREF(substring);
12626 if (result) {
12627 Py_RETURN_TRUE;
12628 }
12629 }
12630 /* nothing matched */
12631 Py_RETURN_FALSE;
12632 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012633 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030012634 if (substring == NULL) {
12635 if (PyErr_ExceptionMatches(PyExc_TypeError))
12636 PyErr_Format(PyExc_TypeError, "startswith first arg must be str or "
12637 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000012638 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030012639 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012640 result = tailmatch(self, substring, start, end, -1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012641 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012642 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012643}
12644
12645
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012646PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012647 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012648\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000012649Return True if S ends with the specified suffix, False otherwise.\n\
12650With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012651With optional end, stop comparing S at that position.\n\
12652suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012653
12654static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012655unicode_endswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000012656 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012657{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012658 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012659 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012660 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012661 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012662 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012663
Jesus Ceaac451502011-04-20 17:09:23 +020012664 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000012665 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012666 if (PyTuple_Check(subobj)) {
12667 Py_ssize_t i;
12668 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012669 substring = PyUnicode_FromObject(
Benjamin Peterson29060642009-01-31 22:14:21 +000012670 PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012671 if (substring == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000012672 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012673 result = tailmatch(self, substring, start, end, +1);
12674 Py_DECREF(substring);
12675 if (result) {
12676 Py_RETURN_TRUE;
12677 }
12678 }
12679 Py_RETURN_FALSE;
12680 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012681 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030012682 if (substring == NULL) {
12683 if (PyErr_ExceptionMatches(PyExc_TypeError))
12684 PyErr_Format(PyExc_TypeError, "endswith first arg must be str or "
12685 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000012686 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030012687 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012688 result = tailmatch(self, substring, start, end, +1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012689 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012690 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012691}
12692
Victor Stinner202fdca2012-05-07 12:47:02 +020012693Py_LOCAL_INLINE(void)
Victor Stinner3b1a74a2012-05-09 22:25:00 +020012694_PyUnicodeWriter_Update(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020012695{
Victor Stinnerd3f08822012-05-29 12:57:52 +020012696 writer->size = PyUnicode_GET_LENGTH(writer->buffer);
Victor Stinner202fdca2012-05-07 12:47:02 +020012697 writer->maxchar = PyUnicode_MAX_CHAR_VALUE(writer->buffer);
12698 writer->data = PyUnicode_DATA(writer->buffer);
12699 writer->kind = PyUnicode_KIND(writer->buffer);
12700}
12701
Victor Stinnerd3f08822012-05-29 12:57:52 +020012702void
12703_PyUnicodeWriter_Init(_PyUnicodeWriter *writer, Py_ssize_t min_length)
Victor Stinner202fdca2012-05-07 12:47:02 +020012704{
Victor Stinnerd3f08822012-05-29 12:57:52 +020012705 memset(writer, 0, sizeof(*writer));
12706#ifdef Py_DEBUG
12707 writer->kind = 5; /* invalid kind */
12708#endif
12709 writer->min_length = Py_MAX(min_length, 100);
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012710 writer->overallocate = (min_length > 0);
Victor Stinner202fdca2012-05-07 12:47:02 +020012711}
12712
Victor Stinnerd3f08822012-05-29 12:57:52 +020012713int
12714_PyUnicodeWriter_PrepareInternal(_PyUnicodeWriter *writer,
12715 Py_ssize_t length, Py_UCS4 maxchar)
Victor Stinner202fdca2012-05-07 12:47:02 +020012716{
12717 Py_ssize_t newlen;
12718 PyObject *newbuffer;
12719
Victor Stinnerd3f08822012-05-29 12:57:52 +020012720 assert(length > 0);
12721
Victor Stinner202fdca2012-05-07 12:47:02 +020012722 if (length > PY_SSIZE_T_MAX - writer->pos) {
12723 PyErr_NoMemory();
12724 return -1;
12725 }
12726 newlen = writer->pos + length;
12727
Victor Stinnerd3f08822012-05-29 12:57:52 +020012728 if (writer->buffer == NULL) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012729 if (writer->overallocate) {
Victor Stinnerd3f08822012-05-29 12:57:52 +020012730 /* overallocate 25% to limit the number of resize */
12731 if (newlen <= (PY_SSIZE_T_MAX - newlen / 4))
12732 newlen += newlen / 4;
12733 if (newlen < writer->min_length)
12734 newlen = writer->min_length;
12735 }
12736 writer->buffer = PyUnicode_New(newlen, maxchar);
12737 if (writer->buffer == NULL)
12738 return -1;
12739 _PyUnicodeWriter_Update(writer);
12740 return 0;
12741 }
Victor Stinner202fdca2012-05-07 12:47:02 +020012742
Victor Stinnerd3f08822012-05-29 12:57:52 +020012743 if (newlen > writer->size) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012744 if (writer->overallocate) {
Victor Stinnerd3f08822012-05-29 12:57:52 +020012745 /* overallocate 25% to limit the number of resize */
12746 if (newlen <= (PY_SSIZE_T_MAX - newlen / 4))
12747 newlen += newlen / 4;
12748 if (newlen < writer->min_length)
12749 newlen = writer->min_length;
12750 }
12751
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012752 if (maxchar > writer->maxchar || writer->readonly) {
Victor Stinner202fdca2012-05-07 12:47:02 +020012753 /* resize + widen */
12754 newbuffer = PyUnicode_New(newlen, maxchar);
12755 if (newbuffer == NULL)
12756 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020012757 _PyUnicode_FastCopyCharacters(newbuffer, 0,
12758 writer->buffer, 0, writer->pos);
Victor Stinner202fdca2012-05-07 12:47:02 +020012759 Py_DECREF(writer->buffer);
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012760 writer->readonly = 0;
Victor Stinner202fdca2012-05-07 12:47:02 +020012761 }
12762 else {
12763 newbuffer = resize_compact(writer->buffer, newlen);
12764 if (newbuffer == NULL)
12765 return -1;
12766 }
12767 writer->buffer = newbuffer;
Victor Stinner3b1a74a2012-05-09 22:25:00 +020012768 _PyUnicodeWriter_Update(writer);
Victor Stinner202fdca2012-05-07 12:47:02 +020012769 }
12770 else if (maxchar > writer->maxchar) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012771 assert(!writer->readonly);
Victor Stinnerd3f08822012-05-29 12:57:52 +020012772 newbuffer = PyUnicode_New(writer->size, maxchar);
12773 if (newbuffer == NULL)
Victor Stinner202fdca2012-05-07 12:47:02 +020012774 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020012775 _PyUnicode_FastCopyCharacters(newbuffer, 0,
12776 writer->buffer, 0, writer->pos);
12777 Py_DECREF(writer->buffer);
12778 writer->buffer = newbuffer;
Victor Stinner3b1a74a2012-05-09 22:25:00 +020012779 _PyUnicodeWriter_Update(writer);
Victor Stinner202fdca2012-05-07 12:47:02 +020012780 }
12781 return 0;
12782}
12783
Victor Stinnerd3f08822012-05-29 12:57:52 +020012784int
12785_PyUnicodeWriter_WriteStr(_PyUnicodeWriter *writer, PyObject *str)
12786{
12787 Py_UCS4 maxchar;
12788 Py_ssize_t len;
12789
12790 if (PyUnicode_READY(str) == -1)
12791 return -1;
12792 len = PyUnicode_GET_LENGTH(str);
12793 if (len == 0)
12794 return 0;
12795 maxchar = PyUnicode_MAX_CHAR_VALUE(str);
12796 if (maxchar > writer->maxchar || len > writer->size - writer->pos) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012797 if (writer->buffer == NULL && !writer->overallocate) {
Victor Stinnerd3f08822012-05-29 12:57:52 +020012798 Py_INCREF(str);
12799 writer->buffer = str;
12800 _PyUnicodeWriter_Update(writer);
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012801 writer->readonly = 1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020012802 writer->size = 0;
12803 writer->pos += len;
12804 return 0;
12805 }
12806 if (_PyUnicodeWriter_PrepareInternal(writer, len, maxchar) == -1)
12807 return -1;
12808 }
12809 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
12810 str, 0, len);
12811 writer->pos += len;
12812 return 0;
12813}
12814
Victor Stinnere215d962012-10-06 23:03:36 +020012815int
12816_PyUnicodeWriter_WriteCstr(_PyUnicodeWriter *writer, const char *str, Py_ssize_t len)
12817{
12818 Py_UCS4 maxchar;
12819
12820 maxchar = ucs1lib_find_max_char((Py_UCS1*)str, (Py_UCS1*)str + len);
12821 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) == -1)
12822 return -1;
12823 unicode_write_cstr(writer->buffer, writer->pos, str, len);
12824 writer->pos += len;
12825 return 0;
12826}
12827
Victor Stinnerd3f08822012-05-29 12:57:52 +020012828PyObject *
Victor Stinner3b1a74a2012-05-09 22:25:00 +020012829_PyUnicodeWriter_Finish(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020012830{
Victor Stinnerd3f08822012-05-29 12:57:52 +020012831 if (writer->pos == 0) {
12832 Py_XDECREF(writer->buffer);
12833 Py_INCREF(unicode_empty);
12834 return unicode_empty;
12835 }
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012836 if (writer->readonly) {
Victor Stinnerd3f08822012-05-29 12:57:52 +020012837 assert(PyUnicode_GET_LENGTH(writer->buffer) == writer->pos);
12838 return writer->buffer;
12839 }
12840 if (PyUnicode_GET_LENGTH(writer->buffer) != writer->pos) {
12841 PyObject *newbuffer;
12842 newbuffer = resize_compact(writer->buffer, writer->pos);
12843 if (newbuffer == NULL) {
12844 Py_DECREF(writer->buffer);
12845 return NULL;
12846 }
12847 writer->buffer = newbuffer;
Victor Stinner202fdca2012-05-07 12:47:02 +020012848 }
Victor Stinnerf59c28c2012-05-09 03:24:14 +020012849 assert(_PyUnicode_CheckConsistency(writer->buffer, 1));
Victor Stinner202fdca2012-05-07 12:47:02 +020012850 return writer->buffer;
12851}
12852
Victor Stinnerd3f08822012-05-29 12:57:52 +020012853void
Victor Stinner3b1a74a2012-05-09 22:25:00 +020012854_PyUnicodeWriter_Dealloc(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020012855{
12856 Py_CLEAR(writer->buffer);
12857}
12858
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012859#include "stringlib/unicode_format.h"
Eric Smith8c663262007-08-25 02:26:07 +000012860
12861PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012862 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000012863\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012864Return a formatted version of S, using substitutions from args and kwargs.\n\
12865The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +000012866
Eric Smith27bbca62010-11-04 17:06:58 +000012867PyDoc_STRVAR(format_map__doc__,
12868 "S.format_map(mapping) -> str\n\
12869\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012870Return a formatted version of S, using substitutions from mapping.\n\
12871The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +000012872
Eric Smith4a7d76d2008-05-30 18:10:19 +000012873static PyObject *
12874unicode__format__(PyObject* self, PyObject* args)
12875{
Victor Stinnerd3f08822012-05-29 12:57:52 +020012876 PyObject *format_spec;
12877 _PyUnicodeWriter writer;
12878 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +000012879
12880 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
12881 return NULL;
12882
Victor Stinnerd3f08822012-05-29 12:57:52 +020012883 if (PyUnicode_READY(self) == -1)
12884 return NULL;
12885 _PyUnicodeWriter_Init(&writer, 0);
12886 ret = _PyUnicode_FormatAdvancedWriter(&writer,
12887 self, format_spec, 0,
12888 PyUnicode_GET_LENGTH(format_spec));
12889 if (ret == -1) {
12890 _PyUnicodeWriter_Dealloc(&writer);
12891 return NULL;
12892 }
12893 return _PyUnicodeWriter_Finish(&writer);
Eric Smith4a7d76d2008-05-30 18:10:19 +000012894}
12895
Eric Smith8c663262007-08-25 02:26:07 +000012896PyDoc_STRVAR(p_format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012897 "S.__format__(format_spec) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000012898\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012899Return a formatted version of S as described by format_spec.");
Eric Smith8c663262007-08-25 02:26:07 +000012900
12901static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012902unicode__sizeof__(PyObject *v)
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012903{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012904 Py_ssize_t size;
12905
12906 /* If it's a compact object, account for base structure +
12907 character data. */
12908 if (PyUnicode_IS_COMPACT_ASCII(v))
12909 size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(v) + 1;
12910 else if (PyUnicode_IS_COMPACT(v))
12911 size = sizeof(PyCompactUnicodeObject) +
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012912 (PyUnicode_GET_LENGTH(v) + 1) * PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012913 else {
12914 /* If it is a two-block object, account for base object, and
12915 for character block if present. */
12916 size = sizeof(PyUnicodeObject);
Victor Stinnerc3c74152011-10-02 20:39:55 +020012917 if (_PyUnicode_DATA_ANY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012918 size += (PyUnicode_GET_LENGTH(v) + 1) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012919 PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012920 }
12921 /* If the wstr pointer is present, account for it unless it is shared
Victor Stinnera3be6132011-10-03 02:16:37 +020012922 with the data pointer. Check if the data is not shared. */
Victor Stinner03490912011-10-03 23:45:12 +020012923 if (_PyUnicode_HAS_WSTR_MEMORY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012924 size += (PyUnicode_WSTR_LENGTH(v) + 1) * sizeof(wchar_t);
Victor Stinner829c0ad2011-10-03 01:08:02 +020012925 if (_PyUnicode_HAS_UTF8_MEMORY(v))
Victor Stinnere90fe6a2011-10-01 16:48:13 +020012926 size += PyUnicode_UTF8_LENGTH(v) + 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012927
12928 return PyLong_FromSsize_t(size);
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012929}
12930
12931PyDoc_STRVAR(sizeof__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012932 "S.__sizeof__() -> size of S in memory, in bytes");
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012933
12934static PyObject *
Victor Stinner034f6cf2011-09-30 02:26:44 +020012935unicode_getnewargs(PyObject *v)
Guido van Rossum5d9113d2003-01-29 17:58:45 +000012936{
Victor Stinnerbf6e5602011-12-12 01:53:47 +010012937 PyObject *copy = _PyUnicode_Copy(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012938 if (!copy)
12939 return NULL;
12940 return Py_BuildValue("(N)", copy);
Guido van Rossum5d9113d2003-01-29 17:58:45 +000012941}
12942
Guido van Rossumd57fd912000-03-10 22:53:23 +000012943static PyMethodDef unicode_methods[] = {
Benjamin Peterson28a4dce2010-12-12 01:33:04 +000012944 {"encode", (PyCFunction) unicode_encode, METH_VARARGS | METH_KEYWORDS, encode__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012945 {"replace", (PyCFunction) unicode_replace, METH_VARARGS, replace__doc__},
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012946 {"split", (PyCFunction) unicode_split, METH_VARARGS | METH_KEYWORDS, split__doc__},
12947 {"rsplit", (PyCFunction) unicode_rsplit, METH_VARARGS | METH_KEYWORDS, rsplit__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012948 {"join", (PyCFunction) unicode_join, METH_O, join__doc__},
12949 {"capitalize", (PyCFunction) unicode_capitalize, METH_NOARGS, capitalize__doc__},
Benjamin Petersond5890c82012-01-14 13:23:30 -050012950 {"casefold", (PyCFunction) unicode_casefold, METH_NOARGS, casefold__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012951 {"title", (PyCFunction) unicode_title, METH_NOARGS, title__doc__},
12952 {"center", (PyCFunction) unicode_center, METH_VARARGS, center__doc__},
12953 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
12954 {"expandtabs", (PyCFunction) unicode_expandtabs, METH_VARARGS, expandtabs__doc__},
12955 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000012956 {"partition", (PyCFunction) unicode_partition, METH_O, partition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012957 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
12958 {"ljust", (PyCFunction) unicode_ljust, METH_VARARGS, ljust__doc__},
12959 {"lower", (PyCFunction) unicode_lower, METH_NOARGS, lower__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012960 {"lstrip", (PyCFunction) unicode_lstrip, METH_VARARGS, lstrip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012961 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
12962 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
12963 {"rjust", (PyCFunction) unicode_rjust, METH_VARARGS, rjust__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012964 {"rstrip", (PyCFunction) unicode_rstrip, METH_VARARGS, rstrip__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000012965 {"rpartition", (PyCFunction) unicode_rpartition, METH_O, rpartition__doc__},
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012966 {"splitlines", (PyCFunction) unicode_splitlines, METH_VARARGS | METH_KEYWORDS, splitlines__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012967 {"strip", (PyCFunction) unicode_strip, METH_VARARGS, strip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012968 {"swapcase", (PyCFunction) unicode_swapcase, METH_NOARGS, swapcase__doc__},
12969 {"translate", (PyCFunction) unicode_translate, METH_O, translate__doc__},
12970 {"upper", (PyCFunction) unicode_upper, METH_NOARGS, upper__doc__},
12971 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
12972 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
12973 {"islower", (PyCFunction) unicode_islower, METH_NOARGS, islower__doc__},
12974 {"isupper", (PyCFunction) unicode_isupper, METH_NOARGS, isupper__doc__},
12975 {"istitle", (PyCFunction) unicode_istitle, METH_NOARGS, istitle__doc__},
12976 {"isspace", (PyCFunction) unicode_isspace, METH_NOARGS, isspace__doc__},
12977 {"isdecimal", (PyCFunction) unicode_isdecimal, METH_NOARGS, isdecimal__doc__},
12978 {"isdigit", (PyCFunction) unicode_isdigit, METH_NOARGS, isdigit__doc__},
12979 {"isnumeric", (PyCFunction) unicode_isnumeric, METH_NOARGS, isnumeric__doc__},
12980 {"isalpha", (PyCFunction) unicode_isalpha, METH_NOARGS, isalpha__doc__},
12981 {"isalnum", (PyCFunction) unicode_isalnum, METH_NOARGS, isalnum__doc__},
Martin v. Löwis47383402007-08-15 07:32:56 +000012982 {"isidentifier", (PyCFunction) unicode_isidentifier, METH_NOARGS, isidentifier__doc__},
Georg Brandl559e5d72008-06-11 18:37:52 +000012983 {"isprintable", (PyCFunction) unicode_isprintable, METH_NOARGS, isprintable__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012984 {"zfill", (PyCFunction) unicode_zfill, METH_VARARGS, zfill__doc__},
Eric Smith9cd1e092007-08-31 18:39:38 +000012985 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +000012986 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
Eric Smith4a7d76d2008-05-30 18:10:19 +000012987 {"__format__", (PyCFunction) unicode__format__, METH_VARARGS, p_format__doc__},
Georg Brandlceee0772007-11-27 23:48:05 +000012988 {"maketrans", (PyCFunction) unicode_maketrans,
12989 METH_VARARGS | METH_STATIC, maketrans__doc__},
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012990 {"__sizeof__", (PyCFunction) unicode__sizeof__, METH_NOARGS, sizeof__doc__},
Walter Dörwald068325e2002-04-15 13:36:47 +000012991#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012992 /* These methods are just used for debugging the implementation. */
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012993 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000012994#endif
12995
Benjamin Peterson14339b62009-01-31 16:36:08 +000012996 {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000012997 {NULL, NULL}
12998};
12999
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013000static PyObject *
13001unicode_mod(PyObject *v, PyObject *w)
13002{
Brian Curtindfc80e32011-08-10 20:28:54 -050013003 if (!PyUnicode_Check(v))
13004 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson29060642009-01-31 22:14:21 +000013005 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013006}
13007
13008static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013009 0, /*nb_add*/
13010 0, /*nb_subtract*/
13011 0, /*nb_multiply*/
13012 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013013};
13014
Guido van Rossumd57fd912000-03-10 22:53:23 +000013015static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013016 (lenfunc) unicode_length, /* sq_length */
13017 PyUnicode_Concat, /* sq_concat */
13018 (ssizeargfunc) unicode_repeat, /* sq_repeat */
13019 (ssizeargfunc) unicode_getitem, /* sq_item */
13020 0, /* sq_slice */
13021 0, /* sq_ass_item */
13022 0, /* sq_ass_slice */
13023 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013024};
13025
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013026static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013027unicode_subscript(PyObject* self, PyObject* item)
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013028{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013029 if (PyUnicode_READY(self) == -1)
13030 return NULL;
13031
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000013032 if (PyIndex_Check(item)) {
13033 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013034 if (i == -1 && PyErr_Occurred())
13035 return NULL;
13036 if (i < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013037 i += PyUnicode_GET_LENGTH(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013038 return unicode_getitem(self, i);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013039 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000013040 Py_ssize_t start, stop, step, slicelength, cur, i;
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013041 PyObject *result;
13042 void *src_data, *dest_data;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013043 int src_kind, dest_kind;
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013044 Py_UCS4 ch, max_char, kind_limit;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013045
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013046 if (PySlice_GetIndicesEx(item, PyUnicode_GET_LENGTH(self),
Benjamin Peterson29060642009-01-31 22:14:21 +000013047 &start, &stop, &step, &slicelength) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013048 return NULL;
13049 }
13050
13051 if (slicelength <= 0) {
Victor Stinner382955f2011-12-11 21:44:00 +010013052 Py_INCREF(unicode_empty);
13053 return unicode_empty;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013054 } else if (start == 0 && step == 1 &&
Victor Stinnerc4b49542011-12-11 22:44:26 +010013055 slicelength == PyUnicode_GET_LENGTH(self)) {
13056 return unicode_result_unchanged(self);
Thomas Woutersed03b412007-08-28 21:37:11 +000013057 } else if (step == 1) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013058 return PyUnicode_Substring(self,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013059 start, start + slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013060 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013061 /* General case */
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013062 src_kind = PyUnicode_KIND(self);
13063 src_data = PyUnicode_DATA(self);
Victor Stinner55c99112011-10-13 01:17:06 +020013064 if (!PyUnicode_IS_ASCII(self)) {
13065 kind_limit = kind_maxchar_limit(src_kind);
13066 max_char = 0;
13067 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
13068 ch = PyUnicode_READ(src_kind, src_data, cur);
13069 if (ch > max_char) {
13070 max_char = ch;
13071 if (max_char >= kind_limit)
13072 break;
13073 }
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013074 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013075 }
Victor Stinner55c99112011-10-13 01:17:06 +020013076 else
13077 max_char = 127;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013078 result = PyUnicode_New(slicelength, max_char);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013079 if (result == NULL)
13080 return NULL;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013081 dest_kind = PyUnicode_KIND(result);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013082 dest_data = PyUnicode_DATA(result);
13083
13084 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013085 Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
13086 PyUnicode_WRITE(dest_kind, dest_data, i, ch);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013087 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013088 assert(_PyUnicode_CheckConsistency(result, 1));
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013089 return result;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013090 } else {
13091 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
13092 return NULL;
13093 }
13094}
13095
13096static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013097 (lenfunc)unicode_length, /* mp_length */
13098 (binaryfunc)unicode_subscript, /* mp_subscript */
13099 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013100};
13101
Guido van Rossumd57fd912000-03-10 22:53:23 +000013102
Guido van Rossumd57fd912000-03-10 22:53:23 +000013103/* Helpers for PyUnicode_Format() */
13104
Victor Stinnera47082312012-10-04 02:19:54 +020013105struct unicode_formatter_t {
13106 PyObject *args;
13107 int args_owned;
13108 Py_ssize_t arglen, argidx;
13109 PyObject *dict;
13110
13111 enum PyUnicode_Kind fmtkind;
13112 Py_ssize_t fmtcnt, fmtpos;
13113 void *fmtdata;
13114 PyObject *fmtstr;
13115
13116 _PyUnicodeWriter writer;
13117};
13118
13119struct unicode_format_arg_t {
13120 Py_UCS4 ch;
13121 int flags;
13122 Py_ssize_t width;
13123 int prec;
13124 int sign;
13125};
13126
Guido van Rossumd57fd912000-03-10 22:53:23 +000013127static PyObject *
Victor Stinnera47082312012-10-04 02:19:54 +020013128unicode_format_getnextarg(struct unicode_formatter_t *ctx)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013129{
Victor Stinnera47082312012-10-04 02:19:54 +020013130 Py_ssize_t argidx = ctx->argidx;
13131
13132 if (argidx < ctx->arglen) {
13133 ctx->argidx++;
13134 if (ctx->arglen < 0)
13135 return ctx->args;
Benjamin Peterson29060642009-01-31 22:14:21 +000013136 else
Victor Stinnera47082312012-10-04 02:19:54 +020013137 return PyTuple_GetItem(ctx->args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013138 }
13139 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013140 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013141 return NULL;
13142}
13143
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013144/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013145
Victor Stinnera47082312012-10-04 02:19:54 +020013146/* Format a float into the writer if the writer is not NULL, or into *p_output
13147 otherwise.
13148
13149 Return 0 on success, raise an exception and return -1 on error. */
Victor Stinnerd3f08822012-05-29 12:57:52 +020013150static int
Victor Stinnera47082312012-10-04 02:19:54 +020013151formatfloat(PyObject *v, struct unicode_format_arg_t *arg,
13152 PyObject **p_output,
13153 _PyUnicodeWriter *writer)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013154{
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013155 char *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013156 double x;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013157 Py_ssize_t len;
Victor Stinnera47082312012-10-04 02:19:54 +020013158 int prec;
13159 int dtoa_flags;
Tim Petersced69f82003-09-16 20:30:58 +000013160
Guido van Rossumd57fd912000-03-10 22:53:23 +000013161 x = PyFloat_AsDouble(v);
13162 if (x == -1.0 && PyErr_Occurred())
Victor Stinnerd3f08822012-05-29 12:57:52 +020013163 return -1;
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013164
Victor Stinnera47082312012-10-04 02:19:54 +020013165 prec = arg->prec;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013166 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000013167 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +000013168
Victor Stinnera47082312012-10-04 02:19:54 +020013169 if (arg->flags & F_ALT)
13170 dtoa_flags = Py_DTSF_ALT;
13171 else
13172 dtoa_flags = 0;
13173 p = PyOS_double_to_string(x, arg->ch, prec, dtoa_flags, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013174 if (p == NULL)
Victor Stinnerd3f08822012-05-29 12:57:52 +020013175 return -1;
13176 len = strlen(p);
13177 if (writer) {
Christian Heimesf4f99392012-09-10 11:48:41 +020013178 if (_PyUnicodeWriter_Prepare(writer, len, 127) == -1) {
13179 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013180 return -1;
Christian Heimesf4f99392012-09-10 11:48:41 +020013181 }
Victor Stinner184252a2012-06-16 02:57:41 +020013182 unicode_write_cstr(writer->buffer, writer->pos, p, len);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013183 writer->pos += len;
13184 }
13185 else
13186 *p_output = _PyUnicode_FromASCII(p, len);
Eric Smith0923d1d2009-04-16 20:16:10 +000013187 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013188 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013189}
13190
Victor Stinnerd0880d52012-04-27 23:40:13 +020013191/* formatlong() emulates the format codes d, u, o, x and X, and
13192 * the F_ALT flag, for Python's long (unbounded) ints. It's not used for
13193 * Python's regular ints.
13194 * Return value: a new PyUnicodeObject*, or NULL if error.
13195 * The output string is of the form
13196 * "-"? ("0x" | "0X")? digit+
13197 * "0x"/"0X" are present only for x and X conversions, with F_ALT
13198 * set in flags. The case of hex digits will be correct,
13199 * There will be at least prec digits, zero-filled on the left if
13200 * necessary to get that many.
13201 * val object to be converted
13202 * flags bitmask of format flags; only F_ALT is looked at
13203 * prec minimum number of digits; 0-fill on left if needed
13204 * type a character in [duoxX]; u acts the same as d
13205 *
13206 * CAUTION: o, x and X conversions on regular ints can never
13207 * produce a '-' sign, but can for Python's unbounded ints.
13208 */
Tim Peters38fd5b62000-09-21 05:43:11 +000013209static PyObject*
Victor Stinnera47082312012-10-04 02:19:54 +020013210formatlong(PyObject *val, struct unicode_format_arg_t *arg)
Tim Peters38fd5b62000-09-21 05:43:11 +000013211{
Victor Stinnerd0880d52012-04-27 23:40:13 +020013212 PyObject *result = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013213 char *buf;
Victor Stinnerd0880d52012-04-27 23:40:13 +020013214 Py_ssize_t i;
13215 int sign; /* 1 if '-', else 0 */
13216 int len; /* number of characters */
13217 Py_ssize_t llen;
13218 int numdigits; /* len == numnondigits + numdigits */
13219 int numnondigits = 0;
Victor Stinnera47082312012-10-04 02:19:54 +020013220 int prec = arg->prec;
13221 int type = arg->ch;
Tim Peters38fd5b62000-09-21 05:43:11 +000013222
Victor Stinnerd0880d52012-04-27 23:40:13 +020013223 /* Avoid exceeding SSIZE_T_MAX */
13224 if (prec > INT_MAX-3) {
13225 PyErr_SetString(PyExc_OverflowError,
13226 "precision too large");
Benjamin Peterson14339b62009-01-31 16:36:08 +000013227 return NULL;
Victor Stinnerd0880d52012-04-27 23:40:13 +020013228 }
13229
13230 assert(PyLong_Check(val));
13231
13232 switch (type) {
Victor Stinner621ef3d2012-10-02 00:33:47 +020013233 default:
13234 assert(!"'type' not in [diuoxX]");
Victor Stinnerd0880d52012-04-27 23:40:13 +020013235 case 'd':
Victor Stinner621ef3d2012-10-02 00:33:47 +020013236 case 'i':
Victor Stinnerd0880d52012-04-27 23:40:13 +020013237 case 'u':
13238 /* Special-case boolean: we want 0/1 */
Victor Stinnerb11d91d2012-04-28 00:25:34 +020013239 if (PyBool_Check(val))
13240 result = PyNumber_ToBase(val, 10);
13241 else
13242 result = Py_TYPE(val)->tp_str(val);
Victor Stinnerd0880d52012-04-27 23:40:13 +020013243 break;
13244 case 'o':
13245 numnondigits = 2;
13246 result = PyNumber_ToBase(val, 8);
13247 break;
13248 case 'x':
13249 case 'X':
13250 numnondigits = 2;
13251 result = PyNumber_ToBase(val, 16);
13252 break;
Victor Stinnerd0880d52012-04-27 23:40:13 +020013253 }
13254 if (!result)
13255 return NULL;
13256
13257 assert(unicode_modifiable(result));
13258 assert(PyUnicode_IS_READY(result));
13259 assert(PyUnicode_IS_ASCII(result));
13260
13261 /* To modify the string in-place, there can only be one reference. */
13262 if (Py_REFCNT(result) != 1) {
13263 PyErr_BadInternalCall();
13264 return NULL;
13265 }
13266 buf = PyUnicode_DATA(result);
13267 llen = PyUnicode_GET_LENGTH(result);
13268 if (llen > INT_MAX) {
13269 PyErr_SetString(PyExc_ValueError,
13270 "string too large in _PyBytes_FormatLong");
13271 return NULL;
13272 }
13273 len = (int)llen;
13274 sign = buf[0] == '-';
13275 numnondigits += sign;
13276 numdigits = len - numnondigits;
13277 assert(numdigits > 0);
13278
13279 /* Get rid of base marker unless F_ALT */
Victor Stinnera47082312012-10-04 02:19:54 +020013280 if (((arg->flags & F_ALT) == 0 &&
Victor Stinnerd0880d52012-04-27 23:40:13 +020013281 (type == 'o' || type == 'x' || type == 'X'))) {
13282 assert(buf[sign] == '0');
13283 assert(buf[sign+1] == 'x' || buf[sign+1] == 'X' ||
13284 buf[sign+1] == 'o');
13285 numnondigits -= 2;
13286 buf += 2;
13287 len -= 2;
13288 if (sign)
13289 buf[0] = '-';
13290 assert(len == numnondigits + numdigits);
13291 assert(numdigits > 0);
13292 }
13293
13294 /* Fill with leading zeroes to meet minimum width. */
13295 if (prec > numdigits) {
13296 PyObject *r1 = PyBytes_FromStringAndSize(NULL,
13297 numnondigits + prec);
13298 char *b1;
13299 if (!r1) {
13300 Py_DECREF(result);
13301 return NULL;
13302 }
13303 b1 = PyBytes_AS_STRING(r1);
13304 for (i = 0; i < numnondigits; ++i)
13305 *b1++ = *buf++;
13306 for (i = 0; i < prec - numdigits; i++)
13307 *b1++ = '0';
13308 for (i = 0; i < numdigits; i++)
13309 *b1++ = *buf++;
13310 *b1 = '\0';
13311 Py_DECREF(result);
13312 result = r1;
13313 buf = PyBytes_AS_STRING(result);
13314 len = numnondigits + prec;
13315 }
13316
13317 /* Fix up case for hex conversions. */
13318 if (type == 'X') {
13319 /* Need to convert all lower case letters to upper case.
13320 and need to convert 0x to 0X (and -0x to -0X). */
13321 for (i = 0; i < len; i++)
13322 if (buf[i] >= 'a' && buf[i] <= 'x')
13323 buf[i] -= 'a'-'A';
13324 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020013325 if (!PyUnicode_Check(result)
13326 || buf != PyUnicode_DATA(result)) {
Victor Stinnerd0880d52012-04-27 23:40:13 +020013327 PyObject *unicode;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013328 unicode = _PyUnicode_FromASCII(buf, len);
Victor Stinnerd0880d52012-04-27 23:40:13 +020013329 Py_DECREF(result);
13330 result = unicode;
13331 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020013332 else if (len != PyUnicode_GET_LENGTH(result)) {
13333 if (PyUnicode_Resize(&result, len) < 0)
13334 Py_CLEAR(result);
13335 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000013336 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +000013337}
13338
Victor Stinner621ef3d2012-10-02 00:33:47 +020013339/* Format an integer.
13340 * Return 1 if the number has been formatted into the writer,
Victor Stinnera47082312012-10-04 02:19:54 +020013341 * 0 if the number has been formatted into *p_output
Victor Stinner621ef3d2012-10-02 00:33:47 +020013342 * -1 and raise an exception on error */
13343static int
Victor Stinnera47082312012-10-04 02:19:54 +020013344mainformatlong(PyObject *v,
13345 struct unicode_format_arg_t *arg,
13346 PyObject **p_output,
13347 _PyUnicodeWriter *writer)
Victor Stinner621ef3d2012-10-02 00:33:47 +020013348{
13349 PyObject *iobj, *res;
Victor Stinnera47082312012-10-04 02:19:54 +020013350 char type = (char)arg->ch;
Victor Stinner621ef3d2012-10-02 00:33:47 +020013351
13352 if (!PyNumber_Check(v))
13353 goto wrongtype;
13354
13355 if (!PyLong_Check(v)) {
13356 iobj = PyNumber_Long(v);
13357 if (iobj == NULL) {
13358 if (PyErr_ExceptionMatches(PyExc_TypeError))
13359 goto wrongtype;
13360 return -1;
13361 }
13362 assert(PyLong_Check(iobj));
13363 }
13364 else {
13365 iobj = v;
13366 Py_INCREF(iobj);
13367 }
13368
13369 if (PyLong_CheckExact(v)
Victor Stinnera47082312012-10-04 02:19:54 +020013370 && arg->width == -1 && arg->prec == -1
13371 && !(arg->flags & (F_SIGN | F_BLANK))
13372 && type != 'X')
Victor Stinner621ef3d2012-10-02 00:33:47 +020013373 {
13374 /* Fast path */
Victor Stinnera47082312012-10-04 02:19:54 +020013375 int alternate = arg->flags & F_ALT;
Victor Stinner621ef3d2012-10-02 00:33:47 +020013376 int base;
13377
Victor Stinnera47082312012-10-04 02:19:54 +020013378 switch(type)
Victor Stinner621ef3d2012-10-02 00:33:47 +020013379 {
13380 default:
13381 assert(0 && "'type' not in [diuoxX]");
13382 case 'd':
13383 case 'i':
13384 case 'u':
13385 base = 10;
13386 break;
13387 case 'o':
13388 base = 8;
13389 break;
13390 case 'x':
13391 case 'X':
13392 base = 16;
13393 break;
13394 }
13395
Victor Stinnerc89d28f2012-10-02 12:54:07 +020013396 if (_PyLong_FormatWriter(writer, v, base, alternate) == -1) {
13397 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020013398 return -1;
Victor Stinnerc89d28f2012-10-02 12:54:07 +020013399 }
13400 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020013401 return 1;
13402 }
13403
Victor Stinnera47082312012-10-04 02:19:54 +020013404 res = formatlong(iobj, arg);
Victor Stinner621ef3d2012-10-02 00:33:47 +020013405 Py_DECREF(iobj);
13406 if (res == NULL)
13407 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020013408 *p_output = res;
Victor Stinner621ef3d2012-10-02 00:33:47 +020013409 return 0;
13410
13411wrongtype:
13412 PyErr_Format(PyExc_TypeError,
13413 "%%%c format: a number is required, "
Victor Stinnera47082312012-10-04 02:19:54 +020013414 "not %.200s",
13415 type, Py_TYPE(v)->tp_name);
Victor Stinner621ef3d2012-10-02 00:33:47 +020013416 return -1;
13417}
13418
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013419static Py_UCS4
13420formatchar(PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013421{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000013422 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000013423 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013424 if (PyUnicode_GET_LENGTH(v) == 1) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013425 return PyUnicode_READ_CHAR(v, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +000013426 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013427 goto onError;
13428 }
13429 else {
13430 /* Integer input truncated to a character */
13431 long x;
13432 x = PyLong_AsLong(v);
13433 if (x == -1 && PyErr_Occurred())
13434 goto onError;
13435
Victor Stinner8faf8212011-12-08 22:14:11 +010013436 if (x < 0 || x > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013437 PyErr_SetString(PyExc_OverflowError,
13438 "%c arg not in range(0x110000)");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013439 return (Py_UCS4) -1;
Benjamin Peterson29060642009-01-31 22:14:21 +000013440 }
13441
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013442 return (Py_UCS4) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013443 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000013444
Benjamin Peterson29060642009-01-31 22:14:21 +000013445 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000013446 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013447 "%c requires int or char");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013448 return (Py_UCS4) -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013449}
13450
Victor Stinnera47082312012-10-04 02:19:54 +020013451/* Parse options of an argument: flags, width, precision.
13452 Handle also "%(name)" syntax.
13453
13454 Return 0 if the argument has been formatted into arg->str.
13455 Return 1 if the argument has been written into ctx->writer,
13456 Raise an exception and return -1 on error. */
13457static int
13458unicode_format_arg_parse(struct unicode_formatter_t *ctx,
13459 struct unicode_format_arg_t *arg)
13460{
13461#define FORMAT_READ(ctx) \
13462 PyUnicode_READ((ctx)->fmtkind, (ctx)->fmtdata, (ctx)->fmtpos)
13463
13464 PyObject *v;
13465
13466 arg->ch = FORMAT_READ(ctx);
13467 if (arg->ch == '(') {
13468 /* Get argument value from a dictionary. Example: "%(name)s". */
13469 Py_ssize_t keystart;
13470 Py_ssize_t keylen;
13471 PyObject *key;
13472 int pcount = 1;
13473
13474 if (ctx->dict == NULL) {
13475 PyErr_SetString(PyExc_TypeError,
13476 "format requires a mapping");
13477 return -1;
13478 }
13479 ++ctx->fmtpos;
13480 --ctx->fmtcnt;
13481 keystart = ctx->fmtpos;
13482 /* Skip over balanced parentheses */
13483 while (pcount > 0 && --ctx->fmtcnt >= 0) {
13484 arg->ch = FORMAT_READ(ctx);
13485 if (arg->ch == ')')
13486 --pcount;
13487 else if (arg->ch == '(')
13488 ++pcount;
13489 ctx->fmtpos++;
13490 }
13491 keylen = ctx->fmtpos - keystart - 1;
13492 if (ctx->fmtcnt < 0 || pcount > 0) {
13493 PyErr_SetString(PyExc_ValueError,
13494 "incomplete format key");
13495 return -1;
13496 }
13497 key = PyUnicode_Substring(ctx->fmtstr,
13498 keystart, keystart + keylen);
13499 if (key == NULL)
13500 return -1;
13501 if (ctx->args_owned) {
13502 Py_DECREF(ctx->args);
13503 ctx->args_owned = 0;
13504 }
13505 ctx->args = PyObject_GetItem(ctx->dict, key);
13506 Py_DECREF(key);
13507 if (ctx->args == NULL)
13508 return -1;
13509 ctx->args_owned = 1;
13510 ctx->arglen = -1;
13511 ctx->argidx = -2;
13512 }
13513
13514 /* Parse flags. Example: "%+i" => flags=F_SIGN. */
13515 arg->flags = 0;
13516 while (--ctx->fmtcnt >= 0) {
13517 arg->ch = FORMAT_READ(ctx);
13518 ctx->fmtpos++;
13519 switch (arg->ch) {
13520 case '-': arg->flags |= F_LJUST; continue;
13521 case '+': arg->flags |= F_SIGN; continue;
13522 case ' ': arg->flags |= F_BLANK; continue;
13523 case '#': arg->flags |= F_ALT; continue;
13524 case '0': arg->flags |= F_ZERO; continue;
13525 }
13526 break;
13527 }
13528
13529 /* Parse width. Example: "%10s" => width=10 */
13530 arg->width = -1;
13531 if (arg->ch == '*') {
13532 v = unicode_format_getnextarg(ctx);
13533 if (v == NULL)
13534 return -1;
13535 if (!PyLong_Check(v)) {
13536 PyErr_SetString(PyExc_TypeError,
13537 "* wants int");
13538 return -1;
13539 }
13540 arg->width = PyLong_AsLong(v);
13541 if (arg->width == -1 && PyErr_Occurred())
13542 return -1;
13543 if (arg->width < 0) {
13544 arg->flags |= F_LJUST;
13545 arg->width = -arg->width;
13546 }
13547 if (--ctx->fmtcnt >= 0) {
13548 arg->ch = FORMAT_READ(ctx);
13549 ctx->fmtpos++;
13550 }
13551 }
13552 else if (arg->ch >= '0' && arg->ch <= '9') {
13553 arg->width = arg->ch - '0';
13554 while (--ctx->fmtcnt >= 0) {
13555 arg->ch = FORMAT_READ(ctx);
13556 ctx->fmtpos++;
13557 if (arg->ch < '0' || arg->ch > '9')
13558 break;
13559 /* Since arg->ch is unsigned, the RHS would end up as unsigned,
13560 mixing signed and unsigned comparison. Since arg->ch is between
13561 '0' and '9', casting to int is safe. */
13562 if (arg->width > (PY_SSIZE_T_MAX - ((int)arg->ch - '0')) / 10) {
13563 PyErr_SetString(PyExc_ValueError,
13564 "width too big");
13565 return -1;
13566 }
13567 arg->width = arg->width*10 + (arg->ch - '0');
13568 }
13569 }
13570
13571 /* Parse precision. Example: "%.3f" => prec=3 */
13572 arg->prec = -1;
13573 if (arg->ch == '.') {
13574 arg->prec = 0;
13575 if (--ctx->fmtcnt >= 0) {
13576 arg->ch = FORMAT_READ(ctx);
13577 ctx->fmtpos++;
13578 }
13579 if (arg->ch == '*') {
13580 v = unicode_format_getnextarg(ctx);
13581 if (v == NULL)
13582 return -1;
13583 if (!PyLong_Check(v)) {
13584 PyErr_SetString(PyExc_TypeError,
13585 "* wants int");
13586 return -1;
13587 }
13588 arg->prec = PyLong_AsLong(v);
13589 if (arg->prec == -1 && PyErr_Occurred())
13590 return -1;
13591 if (arg->prec < 0)
13592 arg->prec = 0;
13593 if (--ctx->fmtcnt >= 0) {
13594 arg->ch = FORMAT_READ(ctx);
13595 ctx->fmtpos++;
13596 }
13597 }
13598 else if (arg->ch >= '0' && arg->ch <= '9') {
13599 arg->prec = arg->ch - '0';
13600 while (--ctx->fmtcnt >= 0) {
13601 arg->ch = FORMAT_READ(ctx);
13602 ctx->fmtpos++;
13603 if (arg->ch < '0' || arg->ch > '9')
13604 break;
13605 if (arg->prec > (INT_MAX - ((int)arg->ch - '0')) / 10) {
13606 PyErr_SetString(PyExc_ValueError,
Victor Stinner3921e902012-10-06 23:05:00 +020013607 "precision too big");
Victor Stinnera47082312012-10-04 02:19:54 +020013608 return -1;
13609 }
13610 arg->prec = arg->prec*10 + (arg->ch - '0');
13611 }
13612 }
13613 }
13614
13615 /* Ignore "h", "l" and "L" format prefix (ex: "%hi" or "%ls") */
13616 if (ctx->fmtcnt >= 0) {
13617 if (arg->ch == 'h' || arg->ch == 'l' || arg->ch == 'L') {
13618 if (--ctx->fmtcnt >= 0) {
13619 arg->ch = FORMAT_READ(ctx);
13620 ctx->fmtpos++;
13621 }
13622 }
13623 }
13624 if (ctx->fmtcnt < 0) {
13625 PyErr_SetString(PyExc_ValueError,
13626 "incomplete format");
13627 return -1;
13628 }
13629 return 0;
13630
13631#undef FORMAT_READ
13632}
13633
13634/* Format one argument. Supported conversion specifiers:
13635
13636 - "s", "r", "a": any type
13637 - "i", "d", "u", "o", "x", "X": int
13638 - "e", "E", "f", "F", "g", "G": float
13639 - "c": int or str (1 character)
13640
13641 Return 0 if the argument has been formatted into *p_str,
13642 1 if the argument has been written into ctx->writer,
13643 -1 on error. */
13644static int
13645unicode_format_arg_format(struct unicode_formatter_t *ctx,
13646 struct unicode_format_arg_t *arg,
13647 PyObject **p_str)
13648{
13649 PyObject *v;
13650 _PyUnicodeWriter *writer = &ctx->writer;
13651
13652 if (ctx->fmtcnt == 0)
13653 ctx->writer.overallocate = 0;
13654
13655 if (arg->ch == '%') {
13656 if (_PyUnicodeWriter_Prepare(writer, 1, '%') == -1)
13657 return -1;
13658 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '%');
13659 writer->pos += 1;
13660 return 1;
13661 }
13662
13663 v = unicode_format_getnextarg(ctx);
13664 if (v == NULL)
13665 return -1;
13666
13667 arg->sign = 0;
13668
13669 switch (arg->ch) {
13670
13671 case 's':
13672 case 'r':
13673 case 'a':
13674 if (PyLong_CheckExact(v) && arg->width == -1 && arg->prec == -1) {
13675 /* Fast path */
13676 if (_PyLong_FormatWriter(writer, v, 10, arg->flags & F_ALT) == -1)
13677 return -1;
13678 return 1;
13679 }
13680
13681 if (PyUnicode_CheckExact(v) && arg->ch == 's') {
13682 *p_str = v;
13683 Py_INCREF(*p_str);
13684 }
13685 else {
13686 if (arg->ch == 's')
13687 *p_str = PyObject_Str(v);
13688 else if (arg->ch == 'r')
13689 *p_str = PyObject_Repr(v);
13690 else
13691 *p_str = PyObject_ASCII(v);
13692 }
13693 break;
13694
13695 case 'i':
13696 case 'd':
13697 case 'u':
13698 case 'o':
13699 case 'x':
13700 case 'X':
13701 {
13702 int ret = mainformatlong(v, arg, p_str, writer);
13703 if (ret != 0)
13704 return ret;
13705 arg->sign = 1;
13706 break;
13707 }
13708
13709 case 'e':
13710 case 'E':
13711 case 'f':
13712 case 'F':
13713 case 'g':
13714 case 'G':
13715 if (arg->width == -1 && arg->prec == -1
13716 && !(arg->flags & (F_SIGN | F_BLANK)))
13717 {
13718 /* Fast path */
13719 if (formatfloat(v, arg, NULL, writer) == -1)
13720 return -1;
13721 return 1;
13722 }
13723
13724 arg->sign = 1;
13725 if (formatfloat(v, arg, p_str, NULL) == -1)
13726 return -1;
13727 break;
13728
13729 case 'c':
13730 {
13731 Py_UCS4 ch = formatchar(v);
13732 if (ch == (Py_UCS4) -1)
13733 return -1;
13734 if (arg->width == -1 && arg->prec == -1) {
13735 /* Fast path */
13736 if (_PyUnicodeWriter_Prepare(writer, 1, ch) == -1)
13737 return -1;
13738 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, ch);
13739 writer->pos += 1;
13740 return 1;
13741 }
13742 *p_str = PyUnicode_FromOrdinal(ch);
13743 break;
13744 }
13745
13746 default:
13747 PyErr_Format(PyExc_ValueError,
13748 "unsupported format character '%c' (0x%x) "
13749 "at index %zd",
13750 (31<=arg->ch && arg->ch<=126) ? (char)arg->ch : '?',
13751 (int)arg->ch,
13752 ctx->fmtpos - 1);
13753 return -1;
13754 }
13755 if (*p_str == NULL)
13756 return -1;
13757 assert (PyUnicode_Check(*p_str));
13758 return 0;
13759}
13760
13761static int
13762unicode_format_arg_output(struct unicode_formatter_t *ctx,
13763 struct unicode_format_arg_t *arg,
13764 PyObject *str)
13765{
13766 Py_ssize_t len;
13767 enum PyUnicode_Kind kind;
13768 void *pbuf;
13769 Py_ssize_t pindex;
13770 Py_UCS4 signchar;
13771 Py_ssize_t buflen;
13772 Py_UCS4 maxchar, bufmaxchar;
13773 Py_ssize_t sublen;
13774 _PyUnicodeWriter *writer = &ctx->writer;
13775 Py_UCS4 fill;
13776
13777 fill = ' ';
13778 if (arg->sign && arg->flags & F_ZERO)
13779 fill = '0';
13780
13781 if (PyUnicode_READY(str) == -1)
13782 return -1;
13783
13784 len = PyUnicode_GET_LENGTH(str);
13785 if ((arg->width == -1 || arg->width <= len)
13786 && (arg->prec == -1 || arg->prec >= len)
13787 && !(arg->flags & (F_SIGN | F_BLANK)))
13788 {
13789 /* Fast path */
13790 if (_PyUnicodeWriter_WriteStr(writer, str) == -1)
13791 return -1;
13792 return 0;
13793 }
13794
13795 /* Truncate the string for "s", "r" and "a" formats
13796 if the precision is set */
13797 if (arg->ch == 's' || arg->ch == 'r' || arg->ch == 'a') {
13798 if (arg->prec >= 0 && len > arg->prec)
13799 len = arg->prec;
13800 }
13801
13802 /* Adjust sign and width */
13803 kind = PyUnicode_KIND(str);
13804 pbuf = PyUnicode_DATA(str);
13805 pindex = 0;
13806 signchar = '\0';
13807 if (arg->sign) {
13808 Py_UCS4 ch = PyUnicode_READ(kind, pbuf, pindex);
13809 if (ch == '-' || ch == '+') {
13810 signchar = ch;
13811 len--;
13812 pindex++;
13813 }
13814 else if (arg->flags & F_SIGN)
13815 signchar = '+';
13816 else if (arg->flags & F_BLANK)
13817 signchar = ' ';
13818 else
13819 arg->sign = 0;
13820 }
13821 if (arg->width < len)
13822 arg->width = len;
13823
13824 /* Prepare the writer */
13825 bufmaxchar = 127;
13826 if (!(arg->flags & F_LJUST)) {
13827 if (arg->sign) {
13828 if ((arg->width-1) > len)
13829 bufmaxchar = MAX_MAXCHAR(bufmaxchar, fill);
13830 }
13831 else {
13832 if (arg->width > len)
13833 bufmaxchar = MAX_MAXCHAR(bufmaxchar, fill);
13834 }
13835 }
13836 maxchar = _PyUnicode_FindMaxChar(str, 0, pindex+len);
13837 bufmaxchar = MAX_MAXCHAR(bufmaxchar, maxchar);
13838 buflen = arg->width;
13839 if (arg->sign && len == arg->width)
13840 buflen++;
13841 if (_PyUnicodeWriter_Prepare(writer, buflen, bufmaxchar) == -1)
13842 return -1;
13843
13844 /* Write the sign if needed */
13845 if (arg->sign) {
13846 if (fill != ' ') {
13847 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
13848 writer->pos += 1;
13849 }
13850 if (arg->width > len)
13851 arg->width--;
13852 }
13853
13854 /* Write the numeric prefix for "x", "X" and "o" formats
13855 if the alternate form is used.
13856 For example, write "0x" for the "%#x" format. */
13857 if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
13858 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
13859 assert(PyUnicode_READ(kind, pbuf, pindex + 1) == arg->ch);
13860 if (fill != ' ') {
13861 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
13862 PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
13863 writer->pos += 2;
13864 pindex += 2;
13865 }
13866 arg->width -= 2;
13867 if (arg->width < 0)
13868 arg->width = 0;
13869 len -= 2;
13870 }
13871
13872 /* Pad left with the fill character if needed */
13873 if (arg->width > len && !(arg->flags & F_LJUST)) {
13874 sublen = arg->width - len;
13875 FILL(writer->kind, writer->data, fill, writer->pos, sublen);
13876 writer->pos += sublen;
13877 arg->width = len;
13878 }
13879
13880 /* If padding with spaces: write sign if needed and/or numeric prefix if
13881 the alternate form is used */
13882 if (fill == ' ') {
13883 if (arg->sign) {
13884 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
13885 writer->pos += 1;
13886 }
13887 if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
13888 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
13889 assert(PyUnicode_READ(kind, pbuf, pindex+1) == arg->ch);
13890 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
13891 PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
13892 writer->pos += 2;
13893 pindex += 2;
13894 }
13895 }
13896
13897 /* Write characters */
13898 if (len) {
13899 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
13900 str, pindex, len);
13901 writer->pos += len;
13902 }
13903
13904 /* Pad right with the fill character if needed */
13905 if (arg->width > len) {
13906 sublen = arg->width - len;
13907 FILL(writer->kind, writer->data, ' ', writer->pos, sublen);
13908 writer->pos += sublen;
13909 }
13910 return 0;
13911}
13912
13913/* Helper of PyUnicode_Format(): format one arg.
13914 Return 0 on success, raise an exception and return -1 on error. */
13915static int
13916unicode_format_arg(struct unicode_formatter_t *ctx)
13917{
13918 struct unicode_format_arg_t arg;
13919 PyObject *str;
13920 int ret;
13921
13922 ret = unicode_format_arg_parse(ctx, &arg);
13923 if (ret == -1)
13924 return -1;
13925
13926 ret = unicode_format_arg_format(ctx, &arg, &str);
13927 if (ret == -1)
13928 return -1;
13929
13930 if (ret != 1) {
13931 ret = unicode_format_arg_output(ctx, &arg, str);
13932 Py_DECREF(str);
13933 if (ret == -1)
13934 return -1;
13935 }
13936
13937 if (ctx->dict && (ctx->argidx < ctx->arglen) && arg.ch != '%') {
13938 PyErr_SetString(PyExc_TypeError,
13939 "not all arguments converted during string formatting");
13940 return -1;
13941 }
13942 return 0;
13943}
13944
Alexander Belopolsky40018472011-02-26 01:02:56 +000013945PyObject *
13946PyUnicode_Format(PyObject *format, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013947{
Victor Stinnera47082312012-10-04 02:19:54 +020013948 struct unicode_formatter_t ctx;
Tim Petersced69f82003-09-16 20:30:58 +000013949
Guido van Rossumd57fd912000-03-10 22:53:23 +000013950 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013951 PyErr_BadInternalCall();
13952 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013953 }
Victor Stinnera47082312012-10-04 02:19:54 +020013954
13955 ctx.fmtstr = PyUnicode_FromObject(format);
13956 if (ctx.fmtstr == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000013957 return NULL;
Victor Stinnera47082312012-10-04 02:19:54 +020013958 if (PyUnicode_READY(ctx.fmtstr) == -1) {
13959 Py_DECREF(ctx.fmtstr);
13960 return NULL;
13961 }
13962 ctx.fmtdata = PyUnicode_DATA(ctx.fmtstr);
13963 ctx.fmtkind = PyUnicode_KIND(ctx.fmtstr);
13964 ctx.fmtcnt = PyUnicode_GET_LENGTH(ctx.fmtstr);
13965 ctx.fmtpos = 0;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013966
Victor Stinnera47082312012-10-04 02:19:54 +020013967 _PyUnicodeWriter_Init(&ctx.writer, ctx.fmtcnt + 100);
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013968
Guido van Rossumd57fd912000-03-10 22:53:23 +000013969 if (PyTuple_Check(args)) {
Victor Stinnera47082312012-10-04 02:19:54 +020013970 ctx.arglen = PyTuple_Size(args);
13971 ctx.argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013972 }
13973 else {
Victor Stinnera47082312012-10-04 02:19:54 +020013974 ctx.arglen = -1;
13975 ctx.argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013976 }
Victor Stinnera47082312012-10-04 02:19:54 +020013977 ctx.args_owned = 0;
Benjamin Peterson28a6cfa2012-08-28 17:55:35 -040013978 if (PyMapping_Check(args) && !PyTuple_Check(args) && !PyUnicode_Check(args))
Victor Stinnera47082312012-10-04 02:19:54 +020013979 ctx.dict = args;
13980 else
13981 ctx.dict = NULL;
13982 ctx.args = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013983
Victor Stinnera47082312012-10-04 02:19:54 +020013984 while (--ctx.fmtcnt >= 0) {
13985 if (PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
13986 Py_ssize_t nonfmtpos, sublen;
13987 Py_UCS4 maxchar;
13988
13989 nonfmtpos = ctx.fmtpos++;
13990 while (ctx.fmtcnt >= 0 &&
13991 PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
13992 ctx.fmtpos++;
13993 ctx.fmtcnt--;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013994 }
Victor Stinnera47082312012-10-04 02:19:54 +020013995 if (ctx.fmtcnt < 0) {
13996 ctx.fmtpos--;
13997 ctx.writer.overallocate = 0;
Victor Stinnera0494432012-10-03 23:03:46 +020013998 }
Victor Stinnera47082312012-10-04 02:19:54 +020013999 sublen = ctx.fmtpos - nonfmtpos;
14000 maxchar = _PyUnicode_FindMaxChar(ctx.fmtstr,
Victor Stinneree4544c2012-05-09 22:24:08 +020014001 nonfmtpos, nonfmtpos + sublen);
Victor Stinnera47082312012-10-04 02:19:54 +020014002 if (_PyUnicodeWriter_Prepare(&ctx.writer, sublen, maxchar) == -1)
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014003 goto onError;
Victor Stinneree4544c2012-05-09 22:24:08 +020014004
Victor Stinnera47082312012-10-04 02:19:54 +020014005 _PyUnicode_FastCopyCharacters(ctx.writer.buffer, ctx.writer.pos,
14006 ctx.fmtstr, nonfmtpos, sublen);
14007 ctx.writer.pos += sublen;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014008 }
14009 else {
Victor Stinnera47082312012-10-04 02:19:54 +020014010 ctx.fmtpos++;
14011 if (unicode_format_arg(&ctx) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000014012 goto onError;
Victor Stinnera47082312012-10-04 02:19:54 +020014013 }
14014 }
Victor Stinneraff3cc62012-04-30 05:19:21 +020014015
Victor Stinnera47082312012-10-04 02:19:54 +020014016 if (ctx.argidx < ctx.arglen && !ctx.dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014017 PyErr_SetString(PyExc_TypeError,
14018 "not all arguments converted during string formatting");
14019 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014020 }
14021
Victor Stinnera47082312012-10-04 02:19:54 +020014022 if (ctx.args_owned) {
14023 Py_DECREF(ctx.args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014024 }
Victor Stinnera47082312012-10-04 02:19:54 +020014025 Py_DECREF(ctx.fmtstr);
14026 return _PyUnicodeWriter_Finish(&ctx.writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014027
Benjamin Peterson29060642009-01-31 22:14:21 +000014028 onError:
Victor Stinnera47082312012-10-04 02:19:54 +020014029 Py_DECREF(ctx.fmtstr);
14030 _PyUnicodeWriter_Dealloc(&ctx.writer);
14031 if (ctx.args_owned) {
14032 Py_DECREF(ctx.args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014033 }
14034 return NULL;
14035}
14036
Jeremy Hylton938ace62002-07-17 16:30:39 +000014037static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +000014038unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
14039
Tim Peters6d6c1a32001-08-02 04:15:00 +000014040static PyObject *
14041unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
14042{
Benjamin Peterson29060642009-01-31 22:14:21 +000014043 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014044 static char *kwlist[] = {"object", "encoding", "errors", 0};
14045 char *encoding = NULL;
14046 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000014047
Benjamin Peterson14339b62009-01-31 16:36:08 +000014048 if (type != &PyUnicode_Type)
14049 return unicode_subtype_new(type, args, kwds);
14050 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +000014051 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +000014052 return NULL;
Victor Stinner382955f2011-12-11 21:44:00 +010014053 if (x == NULL) {
14054 Py_INCREF(unicode_empty);
14055 return unicode_empty;
14056 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000014057 if (encoding == NULL && errors == NULL)
14058 return PyObject_Str(x);
14059 else
Benjamin Peterson29060642009-01-31 22:14:21 +000014060 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +000014061}
14062
Guido van Rossume023fe02001-08-30 03:12:59 +000014063static PyObject *
14064unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
14065{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014066 PyObject *unicode, *self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014067 Py_ssize_t length, char_size;
14068 int share_wstr, share_utf8;
14069 unsigned int kind;
14070 void *data;
Guido van Rossume023fe02001-08-30 03:12:59 +000014071
Benjamin Peterson14339b62009-01-31 16:36:08 +000014072 assert(PyType_IsSubtype(type, &PyUnicode_Type));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014073
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014074 unicode = unicode_new(&PyUnicode_Type, args, kwds);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014075 if (unicode == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000014076 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020014077 assert(_PyUnicode_CHECK(unicode));
Benjamin Petersonbac79492012-01-14 13:34:47 -050014078 if (PyUnicode_READY(unicode) == -1) {
Benjamin Peterson22a29702012-01-02 09:00:30 -060014079 Py_DECREF(unicode);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014080 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060014081 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014082
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014083 self = type->tp_alloc(type, 0);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014084 if (self == NULL) {
14085 Py_DECREF(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014086 return NULL;
14087 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014088 kind = PyUnicode_KIND(unicode);
14089 length = PyUnicode_GET_LENGTH(unicode);
14090
14091 _PyUnicode_LENGTH(self) = length;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014092#ifdef Py_DEBUG
14093 _PyUnicode_HASH(self) = -1;
14094#else
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014095 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014096#endif
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014097 _PyUnicode_STATE(self).interned = 0;
14098 _PyUnicode_STATE(self).kind = kind;
14099 _PyUnicode_STATE(self).compact = 0;
Victor Stinner3cf46372011-10-03 14:42:15 +020014100 _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014101 _PyUnicode_STATE(self).ready = 1;
14102 _PyUnicode_WSTR(self) = NULL;
14103 _PyUnicode_UTF8_LENGTH(self) = 0;
14104 _PyUnicode_UTF8(self) = NULL;
14105 _PyUnicode_WSTR_LENGTH(self) = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +020014106 _PyUnicode_DATA_ANY(self) = NULL;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014107
14108 share_utf8 = 0;
14109 share_wstr = 0;
14110 if (kind == PyUnicode_1BYTE_KIND) {
14111 char_size = 1;
14112 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
14113 share_utf8 = 1;
14114 }
14115 else if (kind == PyUnicode_2BYTE_KIND) {
14116 char_size = 2;
14117 if (sizeof(wchar_t) == 2)
14118 share_wstr = 1;
14119 }
14120 else {
14121 assert(kind == PyUnicode_4BYTE_KIND);
14122 char_size = 4;
14123 if (sizeof(wchar_t) == 4)
14124 share_wstr = 1;
14125 }
14126
14127 /* Ensure we won't overflow the length. */
14128 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
14129 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014130 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014131 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014132 data = PyObject_MALLOC((length + 1) * char_size);
14133 if (data == NULL) {
14134 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014135 goto onError;
14136 }
14137
Victor Stinnerc3c74152011-10-02 20:39:55 +020014138 _PyUnicode_DATA_ANY(self) = data;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014139 if (share_utf8) {
14140 _PyUnicode_UTF8_LENGTH(self) = length;
14141 _PyUnicode_UTF8(self) = data;
14142 }
14143 if (share_wstr) {
14144 _PyUnicode_WSTR_LENGTH(self) = length;
14145 _PyUnicode_WSTR(self) = (wchar_t *)data;
14146 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014147
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014148 Py_MEMCPY(data, PyUnicode_DATA(unicode),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020014149 kind * (length + 1));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020014150 assert(_PyUnicode_CheckConsistency(self, 1));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014151#ifdef Py_DEBUG
14152 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
14153#endif
Victor Stinnerdd18d3a2011-10-22 11:08:10 +020014154 Py_DECREF(unicode);
Victor Stinner7931d9a2011-11-04 00:22:48 +010014155 return self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014156
14157onError:
14158 Py_DECREF(unicode);
14159 Py_DECREF(self);
14160 return NULL;
Guido van Rossume023fe02001-08-30 03:12:59 +000014161}
14162
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000014163PyDoc_STRVAR(unicode_doc,
Nick Coghlan573b1fd2012-08-16 14:13:07 +100014164 "str(object[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +000014165\n\
Nick Coghlan573b1fd2012-08-16 14:13:07 +100014166Create a new string object from the given object. If encoding or\n\
14167errors is specified, then the object must expose a data buffer\n\
14168that will be decoded using the given encoding and error handler.\n\
14169Otherwise, returns the result of object.__str__() (if defined)\n\
14170or repr(object).\n\
14171encoding defaults to sys.getdefaultencoding().\n\
14172errors defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +000014173
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014174static PyObject *unicode_iter(PyObject *seq);
14175
Guido van Rossumd57fd912000-03-10 22:53:23 +000014176PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000014177 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Benjamin Peterson14339b62009-01-31 16:36:08 +000014178 "str", /* tp_name */
14179 sizeof(PyUnicodeObject), /* tp_size */
14180 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014181 /* Slots */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014182 (destructor)unicode_dealloc, /* tp_dealloc */
14183 0, /* tp_print */
14184 0, /* tp_getattr */
14185 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000014186 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014187 unicode_repr, /* tp_repr */
14188 &unicode_as_number, /* tp_as_number */
14189 &unicode_as_sequence, /* tp_as_sequence */
14190 &unicode_as_mapping, /* tp_as_mapping */
14191 (hashfunc) unicode_hash, /* tp_hash*/
14192 0, /* tp_call*/
14193 (reprfunc) unicode_str, /* tp_str */
14194 PyObject_GenericGetAttr, /* tp_getattro */
14195 0, /* tp_setattro */
14196 0, /* tp_as_buffer */
14197 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Benjamin Peterson29060642009-01-31 22:14:21 +000014198 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014199 unicode_doc, /* tp_doc */
14200 0, /* tp_traverse */
14201 0, /* tp_clear */
14202 PyUnicode_RichCompare, /* tp_richcompare */
14203 0, /* tp_weaklistoffset */
14204 unicode_iter, /* tp_iter */
14205 0, /* tp_iternext */
14206 unicode_methods, /* tp_methods */
14207 0, /* tp_members */
14208 0, /* tp_getset */
14209 &PyBaseObject_Type, /* tp_base */
14210 0, /* tp_dict */
14211 0, /* tp_descr_get */
14212 0, /* tp_descr_set */
14213 0, /* tp_dictoffset */
14214 0, /* tp_init */
14215 0, /* tp_alloc */
14216 unicode_new, /* tp_new */
14217 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014218};
14219
14220/* Initialize the Unicode implementation */
14221
Victor Stinner3a50e702011-10-18 21:21:00 +020014222int _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014223{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014224 int i;
14225
Thomas Wouters477c8d52006-05-27 19:21:47 +000014226 /* XXX - move this array to unicodectype.c ? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014227 Py_UCS2 linebreak[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +000014228 0x000A, /* LINE FEED */
14229 0x000D, /* CARRIAGE RETURN */
14230 0x001C, /* FILE SEPARATOR */
14231 0x001D, /* GROUP SEPARATOR */
14232 0x001E, /* RECORD SEPARATOR */
14233 0x0085, /* NEXT LINE */
14234 0x2028, /* LINE SEPARATOR */
14235 0x2029, /* PARAGRAPH SEPARATOR */
14236 };
14237
Fred Drakee4315f52000-05-09 19:53:39 +000014238 /* Init the implementation */
Victor Stinnera464fc12011-10-02 20:39:30 +020014239 unicode_empty = PyUnicode_New(0, 0);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014240 if (!unicode_empty)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014241 Py_FatalError("Can't create empty string");
Victor Stinnerd3df8ab2011-11-22 01:22:34 +010014242 assert(_PyUnicode_CheckConsistency(unicode_empty, 1));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014243
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014244 for (i = 0; i < 256; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +000014245 unicode_latin1[i] = NULL;
Guido van Rossumcacfc072002-05-24 19:01:59 +000014246 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000014247 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +000014248
14249 /* initialize the linebreak bloom filter */
14250 bloom_linebreak = make_bloom_mask(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014251 PyUnicode_2BYTE_KIND, linebreak,
Victor Stinner63941882011-09-29 00:42:28 +020014252 Py_ARRAY_LENGTH(linebreak));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014253
14254 PyType_Ready(&EncodingMapType);
Victor Stinner3a50e702011-10-18 21:21:00 +020014255
14256#ifdef HAVE_MBCS
14257 winver.dwOSVersionInfoSize = sizeof(winver);
14258 if (!GetVersionEx((OSVERSIONINFO*)&winver)) {
14259 PyErr_SetFromWindowsErr(0);
14260 return -1;
14261 }
14262#endif
14263 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014264}
14265
14266/* Finalize the Unicode implementation */
14267
Christian Heimesa156e092008-02-16 07:38:31 +000014268int
14269PyUnicode_ClearFreeList(void)
14270{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014271 return 0;
Christian Heimesa156e092008-02-16 07:38:31 +000014272}
14273
Guido van Rossumd57fd912000-03-10 22:53:23 +000014274void
Thomas Wouters78890102000-07-22 19:25:51 +000014275_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014276{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014277 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014278
Guido van Rossum4ae8ef82000-10-03 18:09:04 +000014279 Py_XDECREF(unicode_empty);
14280 unicode_empty = NULL;
Barry Warsaw5b4c2282000-10-03 20:45:26 +000014281
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014282 for (i = 0; i < 256; i++) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014283 if (unicode_latin1[i]) {
14284 Py_DECREF(unicode_latin1[i]);
14285 unicode_latin1[i] = NULL;
14286 }
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014287 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020014288 _PyUnicode_ClearStaticStrings();
Christian Heimesa156e092008-02-16 07:38:31 +000014289 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +000014290}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000014291
Walter Dörwald16807132007-05-25 13:52:07 +000014292void
14293PyUnicode_InternInPlace(PyObject **p)
14294{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014295 register PyObject *s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014296 PyObject *t;
Victor Stinner4fae54c2011-10-03 02:01:52 +020014297#ifdef Py_DEBUG
14298 assert(s != NULL);
14299 assert(_PyUnicode_CHECK(s));
14300#else
Benjamin Peterson14339b62009-01-31 16:36:08 +000014301 if (s == NULL || !PyUnicode_Check(s))
Victor Stinner4fae54c2011-10-03 02:01:52 +020014302 return;
14303#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000014304 /* If it's a subclass, we don't really know what putting
14305 it in the interned dict might do. */
14306 if (!PyUnicode_CheckExact(s))
14307 return;
14308 if (PyUnicode_CHECK_INTERNED(s))
14309 return;
14310 if (interned == NULL) {
14311 interned = PyDict_New();
14312 if (interned == NULL) {
14313 PyErr_Clear(); /* Don't leave an exception */
14314 return;
14315 }
14316 }
14317 /* It might be that the GetItem call fails even
14318 though the key is present in the dictionary,
14319 namely when this happens during a stack overflow. */
14320 Py_ALLOW_RECURSION
Victor Stinner7931d9a2011-11-04 00:22:48 +010014321 t = PyDict_GetItem(interned, s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014322 Py_END_ALLOW_RECURSION
Martin v. Löwis5b222132007-06-10 09:51:05 +000014323
Benjamin Peterson29060642009-01-31 22:14:21 +000014324 if (t) {
14325 Py_INCREF(t);
14326 Py_DECREF(*p);
14327 *p = t;
14328 return;
14329 }
Walter Dörwald16807132007-05-25 13:52:07 +000014330
Benjamin Peterson14339b62009-01-31 16:36:08 +000014331 PyThreadState_GET()->recursion_critical = 1;
Victor Stinner7931d9a2011-11-04 00:22:48 +010014332 if (PyDict_SetItem(interned, s, s) < 0) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014333 PyErr_Clear();
14334 PyThreadState_GET()->recursion_critical = 0;
14335 return;
14336 }
14337 PyThreadState_GET()->recursion_critical = 0;
14338 /* The two references in interned are not counted by refcnt.
14339 The deallocator will take care of this */
14340 Py_REFCNT(s) -= 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014341 _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000014342}
14343
14344void
14345PyUnicode_InternImmortal(PyObject **p)
14346{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014347 PyUnicode_InternInPlace(p);
14348 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
Victor Stinneraf9e4b82011-10-23 20:07:00 +020014349 _PyUnicode_STATE(*p).interned = SSTATE_INTERNED_IMMORTAL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014350 Py_INCREF(*p);
14351 }
Walter Dörwald16807132007-05-25 13:52:07 +000014352}
14353
14354PyObject *
14355PyUnicode_InternFromString(const char *cp)
14356{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014357 PyObject *s = PyUnicode_FromString(cp);
14358 if (s == NULL)
14359 return NULL;
14360 PyUnicode_InternInPlace(&s);
14361 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000014362}
14363
Alexander Belopolsky40018472011-02-26 01:02:56 +000014364void
14365_Py_ReleaseInternedUnicodeStrings(void)
Walter Dörwald16807132007-05-25 13:52:07 +000014366{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014367 PyObject *keys;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014368 PyObject *s;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014369 Py_ssize_t i, n;
14370 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000014371
Benjamin Peterson14339b62009-01-31 16:36:08 +000014372 if (interned == NULL || !PyDict_Check(interned))
14373 return;
14374 keys = PyDict_Keys(interned);
14375 if (keys == NULL || !PyList_Check(keys)) {
14376 PyErr_Clear();
14377 return;
14378 }
Walter Dörwald16807132007-05-25 13:52:07 +000014379
Benjamin Peterson14339b62009-01-31 16:36:08 +000014380 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
14381 detector, interned unicode strings are not forcibly deallocated;
14382 rather, we give them their stolen references back, and then clear
14383 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000014384
Benjamin Peterson14339b62009-01-31 16:36:08 +000014385 n = PyList_GET_SIZE(keys);
14386 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000014387 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014388 for (i = 0; i < n; i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014389 s = PyList_GET_ITEM(keys, i);
Victor Stinner6b56a7f2011-10-04 20:04:52 +020014390 if (PyUnicode_READY(s) == -1) {
14391 assert(0 && "could not ready string");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014392 fprintf(stderr, "could not ready string\n");
Victor Stinner6b56a7f2011-10-04 20:04:52 +020014393 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014394 switch (PyUnicode_CHECK_INTERNED(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014395 case SSTATE_NOT_INTERNED:
14396 /* XXX Shouldn't happen */
14397 break;
14398 case SSTATE_INTERNED_IMMORTAL:
14399 Py_REFCNT(s) += 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014400 immortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014401 break;
14402 case SSTATE_INTERNED_MORTAL:
14403 Py_REFCNT(s) += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014404 mortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014405 break;
14406 default:
14407 Py_FatalError("Inconsistent interned string state.");
14408 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014409 _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014410 }
14411 fprintf(stderr, "total size of all interned strings: "
14412 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
14413 "mortal/immortal\n", mortal_size, immortal_size);
14414 Py_DECREF(keys);
14415 PyDict_Clear(interned);
14416 Py_DECREF(interned);
14417 interned = NULL;
Walter Dörwald16807132007-05-25 13:52:07 +000014418}
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014419
14420
14421/********************* Unicode Iterator **************************/
14422
14423typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014424 PyObject_HEAD
14425 Py_ssize_t it_index;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014426 PyObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014427} unicodeiterobject;
14428
14429static void
14430unicodeiter_dealloc(unicodeiterobject *it)
14431{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014432 _PyObject_GC_UNTRACK(it);
14433 Py_XDECREF(it->it_seq);
14434 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014435}
14436
14437static int
14438unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
14439{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014440 Py_VISIT(it->it_seq);
14441 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014442}
14443
14444static PyObject *
14445unicodeiter_next(unicodeiterobject *it)
14446{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014447 PyObject *seq, *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014448
Benjamin Peterson14339b62009-01-31 16:36:08 +000014449 assert(it != NULL);
14450 seq = it->it_seq;
14451 if (seq == NULL)
14452 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020014453 assert(_PyUnicode_CHECK(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014454
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014455 if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
14456 int kind = PyUnicode_KIND(seq);
14457 void *data = PyUnicode_DATA(seq);
14458 Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
14459 item = PyUnicode_FromOrdinal(chr);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014460 if (item != NULL)
14461 ++it->it_index;
14462 return item;
14463 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014464
Benjamin Peterson14339b62009-01-31 16:36:08 +000014465 Py_DECREF(seq);
14466 it->it_seq = NULL;
14467 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014468}
14469
14470static PyObject *
14471unicodeiter_len(unicodeiterobject *it)
14472{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014473 Py_ssize_t len = 0;
14474 if (it->it_seq)
Victor Stinnerc4f281e2011-10-11 22:11:42 +020014475 len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014476 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014477}
14478
14479PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
14480
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000014481static PyObject *
14482unicodeiter_reduce(unicodeiterobject *it)
14483{
14484 if (it->it_seq != NULL) {
Antoine Pitroua7013882012-04-05 00:04:20 +020014485 return Py_BuildValue("N(O)n", _PyObject_GetBuiltin("iter"),
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000014486 it->it_seq, it->it_index);
14487 } else {
14488 PyObject *u = PyUnicode_FromUnicode(NULL, 0);
14489 if (u == NULL)
14490 return NULL;
Antoine Pitroua7013882012-04-05 00:04:20 +020014491 return Py_BuildValue("N(N)", _PyObject_GetBuiltin("iter"), u);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000014492 }
14493}
14494
14495PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
14496
14497static PyObject *
14498unicodeiter_setstate(unicodeiterobject *it, PyObject *state)
14499{
14500 Py_ssize_t index = PyLong_AsSsize_t(state);
14501 if (index == -1 && PyErr_Occurred())
14502 return NULL;
14503 if (index < 0)
14504 index = 0;
14505 it->it_index = index;
14506 Py_RETURN_NONE;
14507}
14508
14509PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
14510
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014511static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014512 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000014513 length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000014514 {"__reduce__", (PyCFunction)unicodeiter_reduce, METH_NOARGS,
14515 reduce_doc},
14516 {"__setstate__", (PyCFunction)unicodeiter_setstate, METH_O,
14517 setstate_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000014518 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014519};
14520
14521PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014522 PyVarObject_HEAD_INIT(&PyType_Type, 0)
14523 "str_iterator", /* tp_name */
14524 sizeof(unicodeiterobject), /* tp_basicsize */
14525 0, /* tp_itemsize */
14526 /* methods */
14527 (destructor)unicodeiter_dealloc, /* tp_dealloc */
14528 0, /* tp_print */
14529 0, /* tp_getattr */
14530 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000014531 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014532 0, /* tp_repr */
14533 0, /* tp_as_number */
14534 0, /* tp_as_sequence */
14535 0, /* tp_as_mapping */
14536 0, /* tp_hash */
14537 0, /* tp_call */
14538 0, /* tp_str */
14539 PyObject_GenericGetAttr, /* tp_getattro */
14540 0, /* tp_setattro */
14541 0, /* tp_as_buffer */
14542 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
14543 0, /* tp_doc */
14544 (traverseproc)unicodeiter_traverse, /* tp_traverse */
14545 0, /* tp_clear */
14546 0, /* tp_richcompare */
14547 0, /* tp_weaklistoffset */
14548 PyObject_SelfIter, /* tp_iter */
14549 (iternextfunc)unicodeiter_next, /* tp_iternext */
14550 unicodeiter_methods, /* tp_methods */
14551 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014552};
14553
14554static PyObject *
14555unicode_iter(PyObject *seq)
14556{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014557 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014558
Benjamin Peterson14339b62009-01-31 16:36:08 +000014559 if (!PyUnicode_Check(seq)) {
14560 PyErr_BadInternalCall();
14561 return NULL;
14562 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014563 if (PyUnicode_READY(seq) == -1)
14564 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014565 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
14566 if (it == NULL)
14567 return NULL;
14568 it->it_index = 0;
14569 Py_INCREF(seq);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014570 it->it_seq = seq;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014571 _PyObject_GC_TRACK(it);
14572 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014573}
14574
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010014575
14576size_t
14577Py_UNICODE_strlen(const Py_UNICODE *u)
14578{
14579 int res = 0;
14580 while(*u++)
14581 res++;
14582 return res;
14583}
14584
14585Py_UNICODE*
14586Py_UNICODE_strcpy(Py_UNICODE *s1, const Py_UNICODE *s2)
14587{
14588 Py_UNICODE *u = s1;
14589 while ((*u++ = *s2++));
14590 return s1;
14591}
14592
14593Py_UNICODE*
14594Py_UNICODE_strncpy(Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
14595{
14596 Py_UNICODE *u = s1;
14597 while ((*u++ = *s2++))
14598 if (n-- == 0)
14599 break;
14600 return s1;
14601}
14602
14603Py_UNICODE*
14604Py_UNICODE_strcat(Py_UNICODE *s1, const Py_UNICODE *s2)
14605{
14606 Py_UNICODE *u1 = s1;
14607 u1 += Py_UNICODE_strlen(u1);
14608 Py_UNICODE_strcpy(u1, s2);
14609 return s1;
14610}
14611
14612int
14613Py_UNICODE_strcmp(const Py_UNICODE *s1, const Py_UNICODE *s2)
14614{
14615 while (*s1 && *s2 && *s1 == *s2)
14616 s1++, s2++;
14617 if (*s1 && *s2)
14618 return (*s1 < *s2) ? -1 : +1;
14619 if (*s1)
14620 return 1;
14621 if (*s2)
14622 return -1;
14623 return 0;
14624}
14625
14626int
14627Py_UNICODE_strncmp(const Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
14628{
14629 register Py_UNICODE u1, u2;
14630 for (; n != 0; n--) {
14631 u1 = *s1;
14632 u2 = *s2;
14633 if (u1 != u2)
14634 return (u1 < u2) ? -1 : +1;
14635 if (u1 == '\0')
14636 return 0;
14637 s1++;
14638 s2++;
14639 }
14640 return 0;
14641}
14642
14643Py_UNICODE*
14644Py_UNICODE_strchr(const Py_UNICODE *s, Py_UNICODE c)
14645{
14646 const Py_UNICODE *p;
14647 for (p = s; *p; p++)
14648 if (*p == c)
14649 return (Py_UNICODE*)p;
14650 return NULL;
14651}
14652
14653Py_UNICODE*
14654Py_UNICODE_strrchr(const Py_UNICODE *s, Py_UNICODE c)
14655{
14656 const Py_UNICODE *p;
14657 p = s + Py_UNICODE_strlen(s);
14658 while (p != s) {
14659 p--;
14660 if (*p == c)
14661 return (Py_UNICODE*)p;
14662 }
14663 return NULL;
14664}
Victor Stinner331ea922010-08-10 16:37:20 +000014665
Victor Stinner71133ff2010-09-01 23:43:53 +000014666Py_UNICODE*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014667PyUnicode_AsUnicodeCopy(PyObject *unicode)
Victor Stinner71133ff2010-09-01 23:43:53 +000014668{
Victor Stinner577db2c2011-10-11 22:12:48 +020014669 Py_UNICODE *u, *copy;
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014670 Py_ssize_t len, size;
Victor Stinner71133ff2010-09-01 23:43:53 +000014671
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014672 if (!PyUnicode_Check(unicode)) {
14673 PyErr_BadArgument();
14674 return NULL;
14675 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014676 u = PyUnicode_AsUnicodeAndSize(unicode, &len);
Victor Stinner577db2c2011-10-11 22:12:48 +020014677 if (u == NULL)
14678 return NULL;
Victor Stinner71133ff2010-09-01 23:43:53 +000014679 /* Ensure we won't overflow the size. */
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014680 if (len > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
Victor Stinner71133ff2010-09-01 23:43:53 +000014681 PyErr_NoMemory();
14682 return NULL;
14683 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014684 size = len + 1; /* copy the null character */
Victor Stinner71133ff2010-09-01 23:43:53 +000014685 size *= sizeof(Py_UNICODE);
14686 copy = PyMem_Malloc(size);
14687 if (copy == NULL) {
14688 PyErr_NoMemory();
14689 return NULL;
14690 }
Victor Stinner577db2c2011-10-11 22:12:48 +020014691 memcpy(copy, u, size);
Victor Stinner71133ff2010-09-01 23:43:53 +000014692 return copy;
14693}
Martin v. Löwis5b222132007-06-10 09:51:05 +000014694
Georg Brandl66c221e2010-10-14 07:04:07 +000014695/* A _string module, to export formatter_parser and formatter_field_name_split
14696 to the string.Formatter class implemented in Python. */
14697
14698static PyMethodDef _string_methods[] = {
14699 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
14700 METH_O, PyDoc_STR("split the argument as a field name")},
14701 {"formatter_parser", (PyCFunction) formatter_parser,
14702 METH_O, PyDoc_STR("parse the argument as a format string")},
14703 {NULL, NULL}
14704};
14705
14706static struct PyModuleDef _string_module = {
14707 PyModuleDef_HEAD_INIT,
14708 "_string",
14709 PyDoc_STR("string helper module"),
14710 0,
14711 _string_methods,
14712 NULL,
14713 NULL,
14714 NULL,
14715 NULL
14716};
14717
14718PyMODINIT_FUNC
14719PyInit__string(void)
14720{
14721 return PyModule_Create(&_string_module);
14722}
14723
14724
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000014725#ifdef __cplusplus
14726}
14727#endif