blob: 16d59292eff2e0586ae1a4df8967c20680a79ffe [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
415 assert(Py_REFCNT(unicode) == 1);
416
417 len = _PyUnicode_WSTR_LENGTH(unicode);
418 if (len == 0) {
419 Py_INCREF(unicode_empty);
420 Py_DECREF(unicode);
421 return unicode_empty;
422 }
423
424 if (len == 1) {
425 wchar_t ch = _PyUnicode_WSTR(unicode)[0];
426 if (ch < 256) {
427 PyObject *latin1_char = get_latin1_char((unsigned char)ch);
428 Py_DECREF(unicode);
429 return latin1_char;
430 }
431 }
432
433 if (_PyUnicode_Ready(unicode) < 0) {
434 Py_XDECREF(unicode);
435 return NULL;
436 }
437#else
438 /* don't make the result ready in debug mode to ensure that the caller
439 makes the string ready before using it */
440 assert(_PyUnicode_CheckConsistency(unicode, 1));
441#endif
442 return unicode;
443}
444
445static PyObject*
446unicode_result_ready(PyObject *unicode)
447{
448 Py_ssize_t length;
449
450 length = PyUnicode_GET_LENGTH(unicode);
451 if (length == 0) {
452 if (unicode != unicode_empty) {
453 Py_INCREF(unicode_empty);
454 Py_DECREF(unicode);
455 }
456 return unicode_empty;
457 }
458
459 if (length == 1) {
460 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, 0);
461 if (ch < 256) {
462 PyObject *latin1_char = unicode_latin1[ch];
463 if (latin1_char != NULL) {
464 if (unicode != latin1_char) {
465 Py_INCREF(latin1_char);
466 Py_DECREF(unicode);
467 }
468 return latin1_char;
469 }
470 else {
471 assert(_PyUnicode_CheckConsistency(unicode, 1));
472 Py_INCREF(unicode);
473 unicode_latin1[ch] = unicode;
474 return unicode;
475 }
476 }
477 }
478
479 assert(_PyUnicode_CheckConsistency(unicode, 1));
480 return unicode;
481}
482
483static PyObject*
484unicode_result(PyObject *unicode)
485{
486 assert(_PyUnicode_CHECK(unicode));
487 if (PyUnicode_IS_READY(unicode))
488 return unicode_result_ready(unicode);
489 else
490 return unicode_result_wchar(unicode);
491}
492
Victor Stinnerc4b49542011-12-11 22:44:26 +0100493static PyObject*
494unicode_result_unchanged(PyObject *unicode)
495{
496 if (PyUnicode_CheckExact(unicode)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -0500497 if (PyUnicode_READY(unicode) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +0100498 return NULL;
499 Py_INCREF(unicode);
500 return unicode;
501 }
502 else
503 /* Subtype -- return genuine unicode string with the same value. */
Victor Stinnerbf6e5602011-12-12 01:53:47 +0100504 return _PyUnicode_Copy(unicode);
Victor Stinnerc4b49542011-12-11 22:44:26 +0100505}
506
Victor Stinner3a50e702011-10-18 21:21:00 +0200507#ifdef HAVE_MBCS
508static OSVERSIONINFOEX winver;
509#endif
510
Thomas Wouters477c8d52006-05-27 19:21:47 +0000511/* --- Bloom Filters ----------------------------------------------------- */
512
513/* stuff to implement simple "bloom filters" for Unicode characters.
514 to keep things simple, we use a single bitmask, using the least 5
515 bits from each unicode characters as the bit index. */
516
517/* the linebreak mask is set up by Unicode_Init below */
518
Antoine Pitrouf068f942010-01-13 14:19:12 +0000519#if LONG_BIT >= 128
520#define BLOOM_WIDTH 128
521#elif LONG_BIT >= 64
522#define BLOOM_WIDTH 64
523#elif LONG_BIT >= 32
524#define BLOOM_WIDTH 32
525#else
526#error "LONG_BIT is smaller than 32"
527#endif
528
Thomas Wouters477c8d52006-05-27 19:21:47 +0000529#define BLOOM_MASK unsigned long
530
531static BLOOM_MASK bloom_linebreak;
532
Antoine Pitrouf068f942010-01-13 14:19:12 +0000533#define BLOOM_ADD(mask, ch) ((mask |= (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
534#define BLOOM(mask, ch) ((mask & (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000535
Benjamin Peterson29060642009-01-31 22:14:21 +0000536#define BLOOM_LINEBREAK(ch) \
537 ((ch) < 128U ? ascii_linebreak[(ch)] : \
538 (BLOOM(bloom_linebreak, (ch)) && Py_UNICODE_ISLINEBREAK(ch)))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000539
Alexander Belopolsky40018472011-02-26 01:02:56 +0000540Py_LOCAL_INLINE(BLOOM_MASK)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200541make_bloom_mask(int kind, void* ptr, Py_ssize_t len)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000542{
543 /* calculate simple bloom-style bitmask for a given unicode string */
544
Antoine Pitrouf068f942010-01-13 14:19:12 +0000545 BLOOM_MASK mask;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000546 Py_ssize_t i;
547
548 mask = 0;
549 for (i = 0; i < len; i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200550 BLOOM_ADD(mask, PyUnicode_READ(kind, ptr, i));
Thomas Wouters477c8d52006-05-27 19:21:47 +0000551
552 return mask;
553}
554
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200555#define BLOOM_MEMBER(mask, chr, str) \
556 (BLOOM(mask, chr) \
557 && (PyUnicode_FindChar(str, chr, 0, PyUnicode_GET_LENGTH(str), 1) >= 0))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000558
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200559/* Compilation of templated routines */
560
561#include "stringlib/asciilib.h"
562#include "stringlib/fastsearch.h"
563#include "stringlib/partition.h"
564#include "stringlib/split.h"
565#include "stringlib/count.h"
566#include "stringlib/find.h"
567#include "stringlib/find_max_char.h"
568#include "stringlib/localeutil.h"
569#include "stringlib/undef.h"
570
571#include "stringlib/ucs1lib.h"
572#include "stringlib/fastsearch.h"
573#include "stringlib/partition.h"
574#include "stringlib/split.h"
575#include "stringlib/count.h"
576#include "stringlib/find.h"
577#include "stringlib/find_max_char.h"
578#include "stringlib/localeutil.h"
579#include "stringlib/undef.h"
580
581#include "stringlib/ucs2lib.h"
582#include "stringlib/fastsearch.h"
583#include "stringlib/partition.h"
584#include "stringlib/split.h"
585#include "stringlib/count.h"
586#include "stringlib/find.h"
587#include "stringlib/find_max_char.h"
588#include "stringlib/localeutil.h"
589#include "stringlib/undef.h"
590
591#include "stringlib/ucs4lib.h"
592#include "stringlib/fastsearch.h"
593#include "stringlib/partition.h"
594#include "stringlib/split.h"
595#include "stringlib/count.h"
596#include "stringlib/find.h"
597#include "stringlib/find_max_char.h"
598#include "stringlib/localeutil.h"
599#include "stringlib/undef.h"
600
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200601#include "stringlib/unicodedefs.h"
602#include "stringlib/fastsearch.h"
603#include "stringlib/count.h"
604#include "stringlib/find.h"
Antoine Pitrou0a3229d2011-11-21 20:39:13 +0100605#include "stringlib/undef.h"
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200606
Guido van Rossumd57fd912000-03-10 22:53:23 +0000607/* --- Unicode Object ----------------------------------------------------- */
608
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200609static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +0200610fixup(PyObject *self, Py_UCS4 (*fixfct)(PyObject *s));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200611
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200612Py_LOCAL_INLINE(Py_ssize_t) findchar(void *s, int kind,
613 Py_ssize_t size, Py_UCS4 ch,
614 int direction)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200615{
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200616 int mode = (direction == 1) ? FAST_SEARCH : FAST_RSEARCH;
617
618 switch (kind) {
619 case PyUnicode_1BYTE_KIND:
620 {
621 Py_UCS1 ch1 = (Py_UCS1) ch;
622 if (ch1 == ch)
623 return ucs1lib_fastsearch((Py_UCS1 *) s, size, &ch1, 1, 0, mode);
624 else
625 return -1;
626 }
627 case PyUnicode_2BYTE_KIND:
628 {
629 Py_UCS2 ch2 = (Py_UCS2) ch;
630 if (ch2 == ch)
631 return ucs2lib_fastsearch((Py_UCS2 *) s, size, &ch2, 1, 0, mode);
632 else
633 return -1;
634 }
635 case PyUnicode_4BYTE_KIND:
636 return ucs4lib_fastsearch((Py_UCS4 *) s, size, &ch, 1, 0, mode);
637 default:
638 assert(0);
639 return -1;
Victor Stinner9e7a1bc2011-10-13 00:18:12 +0200640 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200641}
642
Victor Stinnerfe226c02011-10-03 03:52:20 +0200643static PyObject*
644resize_compact(PyObject *unicode, Py_ssize_t length)
645{
646 Py_ssize_t char_size;
647 Py_ssize_t struct_size;
648 Py_ssize_t new_size;
649 int share_wstr;
Victor Stinner84def372011-12-11 20:04:56 +0100650 PyObject *new_unicode;
Victor Stinner79891572012-05-03 13:43:07 +0200651 assert(unicode_modifiable(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200652 assert(PyUnicode_IS_READY(unicode));
Victor Stinner488fa492011-12-12 00:01:39 +0100653 assert(PyUnicode_IS_COMPACT(unicode));
654
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200655 char_size = PyUnicode_KIND(unicode);
Victor Stinner488fa492011-12-12 00:01:39 +0100656 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerfe226c02011-10-03 03:52:20 +0200657 struct_size = sizeof(PyASCIIObject);
658 else
659 struct_size = sizeof(PyCompactUnicodeObject);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200660 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200661
Victor Stinnerfe226c02011-10-03 03:52:20 +0200662 if (length > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1)) {
663 PyErr_NoMemory();
664 return NULL;
665 }
666 new_size = (struct_size + (length + 1) * char_size);
667
Victor Stinner84def372011-12-11 20:04:56 +0100668 _Py_DEC_REFTOTAL;
669 _Py_ForgetReference(unicode);
670
671 new_unicode = (PyObject *)PyObject_REALLOC((char *)unicode, new_size);
672 if (new_unicode == NULL) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +0100673 _Py_NewReference(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200674 PyErr_NoMemory();
675 return NULL;
676 }
Victor Stinner84def372011-12-11 20:04:56 +0100677 unicode = new_unicode;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200678 _Py_NewReference(unicode);
Victor Stinner84def372011-12-11 20:04:56 +0100679
Victor Stinnerfe226c02011-10-03 03:52:20 +0200680 _PyUnicode_LENGTH(unicode) = length;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200681 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200682 _PyUnicode_WSTR(unicode) = PyUnicode_DATA(unicode);
Victor Stinner488fa492011-12-12 00:01:39 +0100683 if (!PyUnicode_IS_ASCII(unicode))
Victor Stinnerc379ead2011-10-03 12:52:27 +0200684 _PyUnicode_WSTR_LENGTH(unicode) = length;
685 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200686 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
687 length, 0);
Victor Stinner79891572012-05-03 13:43:07 +0200688 assert(_PyUnicode_CheckConsistency(unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200689 return unicode;
690}
691
Alexander Belopolsky40018472011-02-26 01:02:56 +0000692static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200693resize_inplace(PyObject *unicode, Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000694{
Victor Stinner95663112011-10-04 01:03:50 +0200695 wchar_t *wstr;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100696 Py_ssize_t new_size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200697 assert(!PyUnicode_IS_COMPACT(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200698 assert(Py_REFCNT(unicode) == 1);
Tim Petersced69f82003-09-16 20:30:58 +0000699
Victor Stinnerfe226c02011-10-03 03:52:20 +0200700 if (PyUnicode_IS_READY(unicode)) {
701 Py_ssize_t char_size;
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200702 int share_wstr, share_utf8;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200703 void *data;
704
705 data = _PyUnicode_DATA_ANY(unicode);
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200706 char_size = PyUnicode_KIND(unicode);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200707 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
708 share_utf8 = _PyUnicode_SHARE_UTF8(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200709
710 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
711 PyErr_NoMemory();
712 return -1;
713 }
714 new_size = (length + 1) * char_size;
715
Victor Stinner7a9105a2011-12-12 00:13:42 +0100716 if (!share_utf8 && _PyUnicode_HAS_UTF8_MEMORY(unicode))
717 {
718 PyObject_DEL(_PyUnicode_UTF8(unicode));
719 _PyUnicode_UTF8(unicode) = NULL;
720 _PyUnicode_UTF8_LENGTH(unicode) = 0;
721 }
722
Victor Stinnerfe226c02011-10-03 03:52:20 +0200723 data = (PyObject *)PyObject_REALLOC(data, new_size);
724 if (data == NULL) {
725 PyErr_NoMemory();
726 return -1;
727 }
728 _PyUnicode_DATA_ANY(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200729 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200730 _PyUnicode_WSTR(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200731 _PyUnicode_WSTR_LENGTH(unicode) = length;
732 }
733 if (share_utf8) {
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200734 _PyUnicode_UTF8(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200735 _PyUnicode_UTF8_LENGTH(unicode) = length;
736 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200737 _PyUnicode_LENGTH(unicode) = length;
738 PyUnicode_WRITE(PyUnicode_KIND(unicode), data, length, 0);
Victor Stinner95663112011-10-04 01:03:50 +0200739 if (share_wstr || _PyUnicode_WSTR(unicode) == NULL) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200740 assert(_PyUnicode_CheckConsistency(unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200741 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200742 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200743 }
Victor Stinner95663112011-10-04 01:03:50 +0200744 assert(_PyUnicode_WSTR(unicode) != NULL);
745
746 /* check for integer overflow */
747 if (length > PY_SSIZE_T_MAX / sizeof(wchar_t) - 1) {
748 PyErr_NoMemory();
749 return -1;
750 }
Victor Stinner7a9105a2011-12-12 00:13:42 +0100751 new_size = sizeof(wchar_t) * (length + 1);
Victor Stinner95663112011-10-04 01:03:50 +0200752 wstr = _PyUnicode_WSTR(unicode);
Victor Stinner7a9105a2011-12-12 00:13:42 +0100753 wstr = PyObject_REALLOC(wstr, new_size);
Victor Stinner95663112011-10-04 01:03:50 +0200754 if (!wstr) {
755 PyErr_NoMemory();
756 return -1;
757 }
758 _PyUnicode_WSTR(unicode) = wstr;
759 _PyUnicode_WSTR(unicode)[length] = 0;
760 _PyUnicode_WSTR_LENGTH(unicode) = length;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200761 assert(_PyUnicode_CheckConsistency(unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +0000762 return 0;
763}
764
Victor Stinnerfe226c02011-10-03 03:52:20 +0200765static PyObject*
766resize_copy(PyObject *unicode, Py_ssize_t length)
767{
768 Py_ssize_t copy_length;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100769 if (_PyUnicode_KIND(unicode) != PyUnicode_WCHAR_KIND) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200770 PyObject *copy;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100771
Benjamin Petersonbac79492012-01-14 13:34:47 -0500772 if (PyUnicode_READY(unicode) == -1)
Victor Stinner7a9105a2011-12-12 00:13:42 +0100773 return NULL;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200774
775 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
776 if (copy == NULL)
777 return NULL;
778
779 copy_length = Py_MIN(length, PyUnicode_GET_LENGTH(unicode));
Victor Stinnerd3f08822012-05-29 12:57:52 +0200780 _PyUnicode_FastCopyCharacters(copy, 0, unicode, 0, copy_length);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200781 return copy;
Victor Stinner8cfcbed2011-10-03 23:19:21 +0200782 }
783 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200784 PyObject *w;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100785
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200786 w = (PyObject*)_PyUnicode_New(length);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200787 if (w == NULL)
788 return NULL;
789 copy_length = _PyUnicode_WSTR_LENGTH(unicode);
790 copy_length = Py_MIN(copy_length, length);
791 Py_UNICODE_COPY(_PyUnicode_WSTR(w), _PyUnicode_WSTR(unicode),
792 copy_length);
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200793 return w;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200794 }
795}
796
Guido van Rossumd57fd912000-03-10 22:53:23 +0000797/* We allocate one more byte to make sure the string is
Martin v. Löwis47383402007-08-15 07:32:56 +0000798 Ux0000 terminated; some code (e.g. new_identifier)
799 relies on that.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000800
801 XXX This allocator could further be enhanced by assuring that the
Benjamin Peterson29060642009-01-31 22:14:21 +0000802 free list never reduces its size below 1.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000803
804*/
805
Alexander Belopolsky40018472011-02-26 01:02:56 +0000806static PyUnicodeObject *
807_PyUnicode_New(Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000808{
809 register PyUnicodeObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200810 size_t new_size;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000811
Thomas Wouters477c8d52006-05-27 19:21:47 +0000812 /* Optimization for empty strings */
Guido van Rossumd57fd912000-03-10 22:53:23 +0000813 if (length == 0 && unicode_empty != NULL) {
814 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +0200815 return (PyUnicodeObject*)unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000816 }
817
Neal Norwitz3ce5d922008-08-24 07:08:55 +0000818 /* Ensure we won't overflow the size. */
819 if (length > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
820 return (PyUnicodeObject *)PyErr_NoMemory();
821 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200822 if (length < 0) {
823 PyErr_SetString(PyExc_SystemError,
824 "Negative size passed to _PyUnicode_New");
825 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000826 }
827
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200828 unicode = PyObject_New(PyUnicodeObject, &PyUnicode_Type);
829 if (unicode == NULL)
830 return NULL;
831 new_size = sizeof(Py_UNICODE) * ((size_t)length + 1);
832 _PyUnicode_WSTR(unicode) = (Py_UNICODE*) PyObject_MALLOC(new_size);
833 if (!_PyUnicode_WSTR(unicode)) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +0100834 Py_DECREF(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +0000835 PyErr_NoMemory();
Victor Stinnerb0a82a62011-12-12 13:08:33 +0100836 return NULL;
Guido van Rossum3c1bb802000-04-27 20:13:50 +0000837 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200838
Jeremy Hyltond8082792003-09-16 19:41:39 +0000839 /* Initialize the first element to guard against cases where
Tim Petersced69f82003-09-16 20:30:58 +0000840 * the caller fails before initializing str -- unicode_resize()
841 * reads str[0], and the Keep-Alive optimization can keep memory
842 * allocated for str alive across a call to unicode_dealloc(unicode).
843 * We don't want unicode_resize to read uninitialized memory in
844 * that case.
845 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200846 _PyUnicode_WSTR(unicode)[0] = 0;
847 _PyUnicode_WSTR(unicode)[length] = 0;
848 _PyUnicode_WSTR_LENGTH(unicode) = length;
849 _PyUnicode_HASH(unicode) = -1;
850 _PyUnicode_STATE(unicode).interned = 0;
851 _PyUnicode_STATE(unicode).kind = 0;
852 _PyUnicode_STATE(unicode).compact = 0;
853 _PyUnicode_STATE(unicode).ready = 0;
854 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +0200855 _PyUnicode_DATA_ANY(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200856 _PyUnicode_LENGTH(unicode) = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200857 _PyUnicode_UTF8(unicode) = NULL;
858 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner7931d9a2011-11-04 00:22:48 +0100859 assert(_PyUnicode_CheckConsistency((PyObject *)unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +0000860 return unicode;
861}
862
Victor Stinnerf42dc442011-10-02 23:33:16 +0200863static const char*
864unicode_kind_name(PyObject *unicode)
865{
Victor Stinner42dfd712011-10-03 14:41:45 +0200866 /* don't check consistency: unicode_kind_name() is called from
867 _PyUnicode_Dump() */
Victor Stinnerf42dc442011-10-02 23:33:16 +0200868 if (!PyUnicode_IS_COMPACT(unicode))
869 {
870 if (!PyUnicode_IS_READY(unicode))
871 return "wstr";
Benjamin Petersonead6b532011-12-20 17:23:42 -0600872 switch (PyUnicode_KIND(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200873 {
874 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200875 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200876 return "legacy ascii";
877 else
878 return "legacy latin1";
879 case PyUnicode_2BYTE_KIND:
880 return "legacy UCS2";
881 case PyUnicode_4BYTE_KIND:
882 return "legacy UCS4";
883 default:
884 return "<legacy invalid kind>";
885 }
886 }
887 assert(PyUnicode_IS_READY(unicode));
Benjamin Petersonead6b532011-12-20 17:23:42 -0600888 switch (PyUnicode_KIND(unicode)) {
Victor Stinnerf42dc442011-10-02 23:33:16 +0200889 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200890 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200891 return "ascii";
892 else
Victor Stinnera3b334d2011-10-03 13:53:37 +0200893 return "latin1";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200894 case PyUnicode_2BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200895 return "UCS2";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200896 case PyUnicode_4BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200897 return "UCS4";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200898 default:
899 return "<invalid compact kind>";
900 }
901}
902
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200903#ifdef Py_DEBUG
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200904/* Functions wrapping macros for use in debugger */
905char *_PyUnicode_utf8(void *unicode){
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200906 return PyUnicode_UTF8(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200907}
908
909void *_PyUnicode_compact_data(void *unicode) {
910 return _PyUnicode_COMPACT_DATA(unicode);
911}
912void *_PyUnicode_data(void *unicode){
913 printf("obj %p\n", unicode);
914 printf("compact %d\n", PyUnicode_IS_COMPACT(unicode));
915 printf("compact ascii %d\n", PyUnicode_IS_COMPACT_ASCII(unicode));
916 printf("ascii op %p\n", ((void*)((PyASCIIObject*)(unicode) + 1)));
917 printf("compact op %p\n", ((void*)((PyCompactUnicodeObject*)(unicode) + 1)));
918 printf("compact data %p\n", _PyUnicode_COMPACT_DATA(unicode));
919 return PyUnicode_DATA(unicode);
920}
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200921
922void
923_PyUnicode_Dump(PyObject *op)
924{
925 PyASCIIObject *ascii = (PyASCIIObject *)op;
Victor Stinnera849a4b2011-10-03 12:12:11 +0200926 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
927 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
928 void *data;
Victor Stinner0d60e872011-10-23 19:47:19 +0200929
Victor Stinnera849a4b2011-10-03 12:12:11 +0200930 if (ascii->state.compact)
Victor Stinner0d60e872011-10-23 19:47:19 +0200931 {
932 if (ascii->state.ascii)
933 data = (ascii + 1);
934 else
935 data = (compact + 1);
936 }
Victor Stinnera849a4b2011-10-03 12:12:11 +0200937 else
938 data = unicode->data.any;
Victor Stinner0d60e872011-10-23 19:47:19 +0200939 printf("%s: len=%zu, ",unicode_kind_name(op), ascii->length);
940
Victor Stinnera849a4b2011-10-03 12:12:11 +0200941 if (ascii->wstr == data)
942 printf("shared ");
943 printf("wstr=%p", ascii->wstr);
Victor Stinner0d60e872011-10-23 19:47:19 +0200944
Victor Stinnera3b334d2011-10-03 13:53:37 +0200945 if (!(ascii->state.ascii == 1 && ascii->state.compact == 1)) {
Victor Stinnera849a4b2011-10-03 12:12:11 +0200946 printf(" (%zu), ", compact->wstr_length);
947 if (!ascii->state.compact && compact->utf8 == unicode->data.any)
948 printf("shared ");
949 printf("utf8=%p (%zu)", compact->utf8, compact->utf8_length);
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200950 }
Victor Stinnera849a4b2011-10-03 12:12:11 +0200951 printf(", data=%p\n", data);
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200952}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200953#endif
954
955PyObject *
956PyUnicode_New(Py_ssize_t size, Py_UCS4 maxchar)
957{
958 PyObject *obj;
959 PyCompactUnicodeObject *unicode;
960 void *data;
Victor Stinner8f825062012-04-27 13:55:39 +0200961 enum PyUnicode_Kind kind;
Victor Stinner9e9d6892011-10-04 01:02:02 +0200962 int is_sharing, is_ascii;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200963 Py_ssize_t char_size;
964 Py_ssize_t struct_size;
965
966 /* Optimization for empty strings */
967 if (size == 0 && unicode_empty != NULL) {
968 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +0200969 return unicode_empty;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200970 }
971
Victor Stinner9e9d6892011-10-04 01:02:02 +0200972 is_ascii = 0;
973 is_sharing = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200974 struct_size = sizeof(PyCompactUnicodeObject);
975 if (maxchar < 128) {
Victor Stinner8f825062012-04-27 13:55:39 +0200976 kind = PyUnicode_1BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200977 char_size = 1;
978 is_ascii = 1;
979 struct_size = sizeof(PyASCIIObject);
980 }
981 else if (maxchar < 256) {
Victor Stinner8f825062012-04-27 13:55:39 +0200982 kind = PyUnicode_1BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200983 char_size = 1;
984 }
985 else if (maxchar < 65536) {
Victor Stinner8f825062012-04-27 13:55:39 +0200986 kind = PyUnicode_2BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200987 char_size = 2;
988 if (sizeof(wchar_t) == 2)
989 is_sharing = 1;
990 }
991 else {
Victor Stinnerc9590ad2012-03-04 01:34:37 +0100992 if (maxchar > MAX_UNICODE) {
993 PyErr_SetString(PyExc_SystemError,
994 "invalid maximum character passed to PyUnicode_New");
995 return NULL;
996 }
Victor Stinner8f825062012-04-27 13:55:39 +0200997 kind = PyUnicode_4BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200998 char_size = 4;
999 if (sizeof(wchar_t) == 4)
1000 is_sharing = 1;
1001 }
1002
1003 /* Ensure we won't overflow the size. */
1004 if (size < 0) {
1005 PyErr_SetString(PyExc_SystemError,
1006 "Negative size passed to PyUnicode_New");
1007 return NULL;
1008 }
1009 if (size > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1))
1010 return PyErr_NoMemory();
1011
1012 /* Duplicated allocation code from _PyObject_New() instead of a call to
1013 * PyObject_New() so we are able to allocate space for the object and
1014 * it's data buffer.
1015 */
1016 obj = (PyObject *) PyObject_MALLOC(struct_size + (size + 1) * char_size);
1017 if (obj == NULL)
1018 return PyErr_NoMemory();
1019 obj = PyObject_INIT(obj, &PyUnicode_Type);
1020 if (obj == NULL)
1021 return NULL;
1022
1023 unicode = (PyCompactUnicodeObject *)obj;
1024 if (is_ascii)
1025 data = ((PyASCIIObject*)obj) + 1;
1026 else
1027 data = unicode + 1;
1028 _PyUnicode_LENGTH(unicode) = size;
1029 _PyUnicode_HASH(unicode) = -1;
1030 _PyUnicode_STATE(unicode).interned = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001031 _PyUnicode_STATE(unicode).kind = kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001032 _PyUnicode_STATE(unicode).compact = 1;
1033 _PyUnicode_STATE(unicode).ready = 1;
1034 _PyUnicode_STATE(unicode).ascii = is_ascii;
1035 if (is_ascii) {
1036 ((char*)data)[size] = 0;
1037 _PyUnicode_WSTR(unicode) = NULL;
1038 }
Victor Stinner8f825062012-04-27 13:55:39 +02001039 else if (kind == PyUnicode_1BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001040 ((char*)data)[size] = 0;
1041 _PyUnicode_WSTR(unicode) = NULL;
1042 _PyUnicode_WSTR_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001043 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001044 unicode->utf8_length = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001045 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001046 else {
1047 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001048 unicode->utf8_length = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001049 if (kind == PyUnicode_2BYTE_KIND)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001050 ((Py_UCS2*)data)[size] = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001051 else /* kind == PyUnicode_4BYTE_KIND */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001052 ((Py_UCS4*)data)[size] = 0;
1053 if (is_sharing) {
1054 _PyUnicode_WSTR_LENGTH(unicode) = size;
1055 _PyUnicode_WSTR(unicode) = (wchar_t *)data;
1056 }
1057 else {
1058 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1059 _PyUnicode_WSTR(unicode) = NULL;
1060 }
1061 }
Victor Stinner8f825062012-04-27 13:55:39 +02001062#ifdef Py_DEBUG
1063 /* Fill the data with invalid characters to detect bugs earlier.
1064 _PyUnicode_CheckConsistency(str, 1) detects invalid characters,
1065 at least for ASCII and UCS-4 strings. U+00FF is invalid in ASCII
1066 and U+FFFFFFFF is an invalid character in Unicode 6.0. */
1067 memset(data, 0xff, size * kind);
1068#endif
Victor Stinner7931d9a2011-11-04 00:22:48 +01001069 assert(_PyUnicode_CheckConsistency((PyObject*)unicode, 0));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001070 return obj;
1071}
1072
1073#if SIZEOF_WCHAR_T == 2
1074/* Helper function to convert a 16-bits wchar_t representation to UCS4, this
1075 will decode surrogate pairs, the other conversions are implemented as macros
Georg Brandl7597add2011-10-05 16:36:47 +02001076 for efficiency.
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001077
1078 This function assumes that unicode can hold one more code point than wstr
1079 characters for a terminating null character. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001080static void
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001081unicode_convert_wchar_to_ucs4(const wchar_t *begin, const wchar_t *end,
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001082 PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001083{
1084 const wchar_t *iter;
1085 Py_UCS4 *ucs4_out;
1086
Victor Stinner910337b2011-10-03 03:20:16 +02001087 assert(unicode != NULL);
1088 assert(_PyUnicode_CHECK(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001089 assert(_PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
1090 ucs4_out = PyUnicode_4BYTE_DATA(unicode);
1091
1092 for (iter = begin; iter < end; ) {
1093 assert(ucs4_out < (PyUnicode_4BYTE_DATA(unicode) +
1094 _PyUnicode_GET_LENGTH(unicode)));
Victor Stinner551ac952011-11-29 22:58:13 +01001095 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1096 && (iter+1) < end
1097 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001098 {
Victor Stinner551ac952011-11-29 22:58:13 +01001099 *ucs4_out++ = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001100 iter += 2;
1101 }
1102 else {
1103 *ucs4_out++ = *iter;
1104 iter++;
1105 }
1106 }
1107 assert(ucs4_out == (PyUnicode_4BYTE_DATA(unicode) +
1108 _PyUnicode_GET_LENGTH(unicode)));
1109
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001110}
1111#endif
1112
Victor Stinnercd9950f2011-10-02 00:34:53 +02001113static int
Victor Stinner488fa492011-12-12 00:01:39 +01001114unicode_check_modifiable(PyObject *unicode)
Victor Stinnercd9950f2011-10-02 00:34:53 +02001115{
Victor Stinner488fa492011-12-12 00:01:39 +01001116 if (!unicode_modifiable(unicode)) {
Victor Stinner01698042011-10-04 00:04:26 +02001117 PyErr_SetString(PyExc_SystemError,
Victor Stinner488fa492011-12-12 00:01:39 +01001118 "Cannot modify a string currently used");
Victor Stinnercd9950f2011-10-02 00:34:53 +02001119 return -1;
1120 }
Victor Stinnercd9950f2011-10-02 00:34:53 +02001121 return 0;
1122}
1123
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001124static int
1125_copy_characters(PyObject *to, Py_ssize_t to_start,
1126 PyObject *from, Py_ssize_t from_start,
1127 Py_ssize_t how_many, int check_maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001128{
Victor Stinnera0702ab2011-09-29 14:14:38 +02001129 unsigned int from_kind, to_kind;
1130 void *from_data, *to_data;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001131
Victor Stinneree4544c2012-05-09 22:24:08 +02001132 assert(0 <= how_many);
1133 assert(0 <= from_start);
1134 assert(0 <= to_start);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001135 assert(PyUnicode_Check(from));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001136 assert(PyUnicode_IS_READY(from));
Victor Stinneree4544c2012-05-09 22:24:08 +02001137 assert(from_start + how_many <= PyUnicode_GET_LENGTH(from));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001138
Victor Stinnerd3f08822012-05-29 12:57:52 +02001139 assert(PyUnicode_Check(to));
1140 assert(PyUnicode_IS_READY(to));
1141 assert(to_start + how_many <= PyUnicode_GET_LENGTH(to));
1142
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001143 if (how_many == 0)
1144 return 0;
1145
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001146 from_kind = PyUnicode_KIND(from);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001147 from_data = PyUnicode_DATA(from);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001148 to_kind = PyUnicode_KIND(to);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001149 to_data = PyUnicode_DATA(to);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001150
Victor Stinnerf1852262012-06-16 16:38:26 +02001151#ifdef Py_DEBUG
1152 if (!check_maxchar
1153 && PyUnicode_MAX_CHAR_VALUE(from) > PyUnicode_MAX_CHAR_VALUE(to))
1154 {
1155 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
1156 Py_UCS4 ch;
1157 Py_ssize_t i;
1158 for (i=0; i < how_many; i++) {
1159 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1160 assert(ch <= to_maxchar);
1161 }
1162 }
1163#endif
1164
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001165 if (from_kind == to_kind) {
Victor Stinnerf1852262012-06-16 16:38:26 +02001166 if (check_maxchar
1167 && !PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to))
1168 {
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001169 /* Writing Latin-1 characters into an ASCII string requires to
1170 check that all written characters are pure ASCII */
Victor Stinnerf1852262012-06-16 16:38:26 +02001171 Py_UCS4 max_char;
1172 max_char = ucs1lib_find_max_char(from_data,
1173 (Py_UCS1*)from_data + how_many);
1174 if (max_char >= 128)
1175 return -1;
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001176 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +02001177 Py_MEMCPY((char*)to_data + to_kind * to_start,
1178 (char*)from_data + from_kind * from_start,
1179 to_kind * how_many);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001180 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001181 else if (from_kind == PyUnicode_1BYTE_KIND
1182 && to_kind == PyUnicode_2BYTE_KIND)
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001183 {
1184 _PyUnicode_CONVERT_BYTES(
1185 Py_UCS1, Py_UCS2,
1186 PyUnicode_1BYTE_DATA(from) + from_start,
1187 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1188 PyUnicode_2BYTE_DATA(to) + to_start
1189 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001190 }
Victor Stinner157f83f2011-09-28 21:41:31 +02001191 else if (from_kind == PyUnicode_1BYTE_KIND
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001192 && to_kind == PyUnicode_4BYTE_KIND)
1193 {
1194 _PyUnicode_CONVERT_BYTES(
1195 Py_UCS1, Py_UCS4,
1196 PyUnicode_1BYTE_DATA(from) + from_start,
1197 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1198 PyUnicode_4BYTE_DATA(to) + to_start
1199 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001200 }
1201 else if (from_kind == PyUnicode_2BYTE_KIND
1202 && to_kind == PyUnicode_4BYTE_KIND)
1203 {
1204 _PyUnicode_CONVERT_BYTES(
1205 Py_UCS2, Py_UCS4,
1206 PyUnicode_2BYTE_DATA(from) + from_start,
1207 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1208 PyUnicode_4BYTE_DATA(to) + to_start
1209 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001210 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001211 else {
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001212 assert (PyUnicode_MAX_CHAR_VALUE(from) > PyUnicode_MAX_CHAR_VALUE(to));
1213
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001214 if (!check_maxchar) {
1215 if (from_kind == PyUnicode_2BYTE_KIND
1216 && to_kind == PyUnicode_1BYTE_KIND)
1217 {
1218 _PyUnicode_CONVERT_BYTES(
1219 Py_UCS2, Py_UCS1,
1220 PyUnicode_2BYTE_DATA(from) + from_start,
1221 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1222 PyUnicode_1BYTE_DATA(to) + to_start
1223 );
1224 }
1225 else if (from_kind == PyUnicode_4BYTE_KIND
1226 && to_kind == PyUnicode_1BYTE_KIND)
1227 {
1228 _PyUnicode_CONVERT_BYTES(
1229 Py_UCS4, Py_UCS1,
1230 PyUnicode_4BYTE_DATA(from) + from_start,
1231 PyUnicode_4BYTE_DATA(from) + from_start + how_many,
1232 PyUnicode_1BYTE_DATA(to) + to_start
1233 );
1234 }
1235 else if (from_kind == PyUnicode_4BYTE_KIND
1236 && to_kind == PyUnicode_2BYTE_KIND)
1237 {
1238 _PyUnicode_CONVERT_BYTES(
1239 Py_UCS4, Py_UCS2,
1240 PyUnicode_4BYTE_DATA(from) + from_start,
1241 PyUnicode_4BYTE_DATA(from) + from_start + how_many,
1242 PyUnicode_2BYTE_DATA(to) + to_start
1243 );
1244 }
1245 else {
1246 assert(0);
1247 return -1;
1248 }
1249 }
Victor Stinnerf1852262012-06-16 16:38:26 +02001250 else {
Victor Stinnera0702ab2011-09-29 14:14:38 +02001251 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001252 Py_UCS4 ch;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001253 Py_ssize_t i;
1254
Victor Stinnera0702ab2011-09-29 14:14:38 +02001255 for (i=0; i < how_many; i++) {
1256 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001257 if (ch > to_maxchar)
1258 return -1;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001259 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1260 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001261 }
1262 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001263 return 0;
1264}
1265
Victor Stinnerd3f08822012-05-29 12:57:52 +02001266void
1267_PyUnicode_FastCopyCharacters(
1268 PyObject *to, Py_ssize_t to_start,
1269 PyObject *from, Py_ssize_t from_start, Py_ssize_t how_many)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001270{
1271 (void)_copy_characters(to, to_start, from, from_start, how_many, 0);
1272}
1273
1274Py_ssize_t
1275PyUnicode_CopyCharacters(PyObject *to, Py_ssize_t to_start,
1276 PyObject *from, Py_ssize_t from_start,
1277 Py_ssize_t how_many)
1278{
1279 int err;
1280
1281 if (!PyUnicode_Check(from) || !PyUnicode_Check(to)) {
1282 PyErr_BadInternalCall();
1283 return -1;
1284 }
1285
Benjamin Petersonbac79492012-01-14 13:34:47 -05001286 if (PyUnicode_READY(from) == -1)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001287 return -1;
Benjamin Petersonbac79492012-01-14 13:34:47 -05001288 if (PyUnicode_READY(to) == -1)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001289 return -1;
1290
Victor Stinnerd3f08822012-05-29 12:57:52 +02001291 if (from_start < 0) {
1292 PyErr_SetString(PyExc_IndexError, "string index out of range");
1293 return -1;
1294 }
1295 if (to_start < 0) {
1296 PyErr_SetString(PyExc_IndexError, "string index out of range");
1297 return -1;
1298 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001299 how_many = Py_MIN(PyUnicode_GET_LENGTH(from), how_many);
1300 if (to_start + how_many > PyUnicode_GET_LENGTH(to)) {
1301 PyErr_Format(PyExc_SystemError,
1302 "Cannot write %zi characters at %zi "
1303 "in a string of %zi characters",
1304 how_many, to_start, PyUnicode_GET_LENGTH(to));
1305 return -1;
1306 }
1307
1308 if (how_many == 0)
1309 return 0;
1310
Victor Stinner488fa492011-12-12 00:01:39 +01001311 if (unicode_check_modifiable(to))
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001312 return -1;
1313
1314 err = _copy_characters(to, to_start, from, from_start, how_many, 1);
1315 if (err) {
1316 PyErr_Format(PyExc_SystemError,
1317 "Cannot copy %s characters "
1318 "into a string of %s characters",
1319 unicode_kind_name(from),
1320 unicode_kind_name(to));
1321 return -1;
1322 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001323 return how_many;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001324}
1325
Victor Stinner17222162011-09-28 22:15:37 +02001326/* Find the maximum code point and count the number of surrogate pairs so a
1327 correct string length can be computed before converting a string to UCS4.
1328 This function counts single surrogates as a character and not as a pair.
1329
1330 Return 0 on success, or -1 on error. */
1331static int
1332find_maxchar_surrogates(const wchar_t *begin, const wchar_t *end,
1333 Py_UCS4 *maxchar, Py_ssize_t *num_surrogates)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001334{
1335 const wchar_t *iter;
Victor Stinner8faf8212011-12-08 22:14:11 +01001336 Py_UCS4 ch;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001337
Victor Stinnerc53be962011-10-02 21:33:54 +02001338 assert(num_surrogates != NULL && maxchar != NULL);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001339 *num_surrogates = 0;
1340 *maxchar = 0;
1341
1342 for (iter = begin; iter < end; ) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001343#if SIZEOF_WCHAR_T == 2
Victor Stinnerca4f2072011-11-22 03:38:40 +01001344 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1345 && (iter+1) < end
1346 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001347 {
Victor Stinner8faf8212011-12-08 22:14:11 +01001348 ch = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001349 ++(*num_surrogates);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001350 iter += 2;
1351 }
1352 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001353#endif
Victor Stinner8faf8212011-12-08 22:14:11 +01001354 {
1355 ch = *iter;
1356 iter++;
1357 }
1358 if (ch > *maxchar) {
1359 *maxchar = ch;
1360 if (*maxchar > MAX_UNICODE) {
1361 PyErr_Format(PyExc_ValueError,
1362 "character U+%x is not in range [U+0000; U+10ffff]",
1363 ch);
1364 return -1;
1365 }
1366 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001367 }
1368 return 0;
1369}
1370
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001371int
1372_PyUnicode_Ready(PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001373{
1374 wchar_t *end;
1375 Py_UCS4 maxchar = 0;
1376 Py_ssize_t num_surrogates;
1377#if SIZEOF_WCHAR_T == 2
1378 Py_ssize_t length_wo_surrogates;
1379#endif
1380
Georg Brandl7597add2011-10-05 16:36:47 +02001381 /* _PyUnicode_Ready() is only intended for old-style API usage where
Victor Stinnerd8f65102011-09-29 19:43:17 +02001382 strings were created using _PyObject_New() and where no canonical
1383 representation (the str field) has been set yet aka strings
1384 which are not yet ready. */
Victor Stinner910337b2011-10-03 03:20:16 +02001385 assert(_PyUnicode_CHECK(unicode));
1386 assert(_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001387 assert(_PyUnicode_WSTR(unicode) != NULL);
Victor Stinnerc3c74152011-10-02 20:39:55 +02001388 assert(_PyUnicode_DATA_ANY(unicode) == NULL);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001389 assert(_PyUnicode_UTF8(unicode) == NULL);
Victor Stinnerd8f65102011-09-29 19:43:17 +02001390 /* Actually, it should neither be interned nor be anything else: */
1391 assert(_PyUnicode_STATE(unicode).interned == SSTATE_NOT_INTERNED);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001392
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001393 end = _PyUnicode_WSTR(unicode) + _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinner17222162011-09-28 22:15:37 +02001394 if (find_maxchar_surrogates(_PyUnicode_WSTR(unicode), end,
Victor Stinnerd8f65102011-09-29 19:43:17 +02001395 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001396 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001397
1398 if (maxchar < 256) {
Victor Stinnerc3c74152011-10-02 20:39:55 +02001399 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(_PyUnicode_WSTR_LENGTH(unicode) + 1);
1400 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001401 PyErr_NoMemory();
1402 return -1;
1403 }
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001404 _PyUnicode_CONVERT_BYTES(wchar_t, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001405 _PyUnicode_WSTR(unicode), end,
1406 PyUnicode_1BYTE_DATA(unicode));
1407 PyUnicode_1BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1408 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1409 _PyUnicode_STATE(unicode).kind = PyUnicode_1BYTE_KIND;
1410 if (maxchar < 128) {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001411 _PyUnicode_STATE(unicode).ascii = 1;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001412 _PyUnicode_UTF8(unicode) = _PyUnicode_DATA_ANY(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001413 _PyUnicode_UTF8_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001414 }
1415 else {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001416 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001417 _PyUnicode_UTF8(unicode) = NULL;
1418 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001419 }
1420 PyObject_FREE(_PyUnicode_WSTR(unicode));
1421 _PyUnicode_WSTR(unicode) = NULL;
1422 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1423 }
1424 /* In this case we might have to convert down from 4-byte native
1425 wchar_t to 2-byte unicode. */
1426 else if (maxchar < 65536) {
1427 assert(num_surrogates == 0 &&
1428 "FindMaxCharAndNumSurrogatePairs() messed up");
1429
Victor Stinner506f5922011-09-28 22:34:18 +02001430#if SIZEOF_WCHAR_T == 2
1431 /* We can share representations and are done. */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001432 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Victor Stinner506f5922011-09-28 22:34:18 +02001433 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1434 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1435 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001436 _PyUnicode_UTF8(unicode) = NULL;
1437 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001438#else
1439 /* sizeof(wchar_t) == 4 */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001440 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(
Victor Stinner506f5922011-09-28 22:34:18 +02001441 2 * (_PyUnicode_WSTR_LENGTH(unicode) + 1));
Victor Stinnerc3c74152011-10-02 20:39:55 +02001442 if (!_PyUnicode_DATA_ANY(unicode)) {
Victor Stinner506f5922011-09-28 22:34:18 +02001443 PyErr_NoMemory();
1444 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001445 }
Victor Stinner506f5922011-09-28 22:34:18 +02001446 _PyUnicode_CONVERT_BYTES(wchar_t, Py_UCS2,
1447 _PyUnicode_WSTR(unicode), end,
1448 PyUnicode_2BYTE_DATA(unicode));
1449 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1450 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1451 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001452 _PyUnicode_UTF8(unicode) = NULL;
1453 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001454 PyObject_FREE(_PyUnicode_WSTR(unicode));
1455 _PyUnicode_WSTR(unicode) = NULL;
1456 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1457#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001458 }
1459 /* maxchar exeeds 16 bit, wee need 4 bytes for unicode characters */
1460 else {
1461#if SIZEOF_WCHAR_T == 2
1462 /* in case the native representation is 2-bytes, we need to allocate a
1463 new normalized 4-byte version. */
1464 length_wo_surrogates = _PyUnicode_WSTR_LENGTH(unicode) - num_surrogates;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001465 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(4 * (length_wo_surrogates + 1));
1466 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001467 PyErr_NoMemory();
1468 return -1;
1469 }
1470 _PyUnicode_LENGTH(unicode) = length_wo_surrogates;
1471 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001472 _PyUnicode_UTF8(unicode) = NULL;
1473 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner126c5592011-10-03 04:17:10 +02001474 /* unicode_convert_wchar_to_ucs4() requires a ready string */
1475 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerc53be962011-10-02 21:33:54 +02001476 unicode_convert_wchar_to_ucs4(_PyUnicode_WSTR(unicode), end, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001477 PyObject_FREE(_PyUnicode_WSTR(unicode));
1478 _PyUnicode_WSTR(unicode) = NULL;
1479 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1480#else
1481 assert(num_surrogates == 0);
1482
Victor Stinnerc3c74152011-10-02 20:39:55 +02001483 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001484 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001485 _PyUnicode_UTF8(unicode) = NULL;
1486 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001487 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
1488#endif
1489 PyUnicode_4BYTE_DATA(unicode)[_PyUnicode_LENGTH(unicode)] = '\0';
1490 }
1491 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001492 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001493 return 0;
1494}
1495
Alexander Belopolsky40018472011-02-26 01:02:56 +00001496static void
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001497unicode_dealloc(register PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001498{
Walter Dörwald16807132007-05-25 13:52:07 +00001499 switch (PyUnicode_CHECK_INTERNED(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001500 case SSTATE_NOT_INTERNED:
1501 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001502
Benjamin Peterson29060642009-01-31 22:14:21 +00001503 case SSTATE_INTERNED_MORTAL:
1504 /* revive dead object temporarily for DelItem */
1505 Py_REFCNT(unicode) = 3;
Victor Stinner7931d9a2011-11-04 00:22:48 +01001506 if (PyDict_DelItem(interned, unicode) != 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00001507 Py_FatalError(
1508 "deletion of interned string failed");
1509 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001510
Benjamin Peterson29060642009-01-31 22:14:21 +00001511 case SSTATE_INTERNED_IMMORTAL:
1512 Py_FatalError("Immortal interned string died.");
Walter Dörwald16807132007-05-25 13:52:07 +00001513
Benjamin Peterson29060642009-01-31 22:14:21 +00001514 default:
1515 Py_FatalError("Inconsistent interned string state.");
Walter Dörwald16807132007-05-25 13:52:07 +00001516 }
1517
Victor Stinner03490912011-10-03 23:45:12 +02001518 if (_PyUnicode_HAS_WSTR_MEMORY(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001519 PyObject_DEL(_PyUnicode_WSTR(unicode));
Victor Stinner829c0ad2011-10-03 01:08:02 +02001520 if (_PyUnicode_HAS_UTF8_MEMORY(unicode))
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001521 PyObject_DEL(_PyUnicode_UTF8(unicode));
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001522 if (!PyUnicode_IS_COMPACT(unicode) && _PyUnicode_DATA_ANY(unicode))
1523 PyObject_DEL(_PyUnicode_DATA_ANY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001524
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001525 Py_TYPE(unicode)->tp_free(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001526}
1527
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001528#ifdef Py_DEBUG
1529static int
1530unicode_is_singleton(PyObject *unicode)
1531{
1532 PyASCIIObject *ascii = (PyASCIIObject *)unicode;
1533 if (unicode == unicode_empty)
1534 return 1;
1535 if (ascii->state.kind != PyUnicode_WCHAR_KIND && ascii->length == 1)
1536 {
1537 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, 0);
1538 if (ch < 256 && unicode_latin1[ch] == unicode)
1539 return 1;
1540 }
1541 return 0;
1542}
1543#endif
1544
Alexander Belopolsky40018472011-02-26 01:02:56 +00001545static int
Victor Stinner488fa492011-12-12 00:01:39 +01001546unicode_modifiable(PyObject *unicode)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001547{
Victor Stinner488fa492011-12-12 00:01:39 +01001548 assert(_PyUnicode_CHECK(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001549 if (Py_REFCNT(unicode) != 1)
1550 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001551 if (_PyUnicode_HASH(unicode) != -1)
1552 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001553 if (PyUnicode_CHECK_INTERNED(unicode))
1554 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001555 if (!PyUnicode_CheckExact(unicode))
1556 return 0;
Victor Stinner77bb47b2011-10-03 20:06:05 +02001557#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001558 /* singleton refcount is greater than 1 */
1559 assert(!unicode_is_singleton(unicode));
Victor Stinner77bb47b2011-10-03 20:06:05 +02001560#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +02001561 return 1;
1562}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001563
Victor Stinnerfe226c02011-10-03 03:52:20 +02001564static int
1565unicode_resize(PyObject **p_unicode, Py_ssize_t length)
1566{
1567 PyObject *unicode;
1568 Py_ssize_t old_length;
1569
1570 assert(p_unicode != NULL);
1571 unicode = *p_unicode;
1572
1573 assert(unicode != NULL);
1574 assert(PyUnicode_Check(unicode));
1575 assert(0 <= length);
1576
Victor Stinner910337b2011-10-03 03:20:16 +02001577 if (_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001578 old_length = PyUnicode_WSTR_LENGTH(unicode);
1579 else
1580 old_length = PyUnicode_GET_LENGTH(unicode);
1581 if (old_length == length)
1582 return 0;
1583
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001584 if (length == 0) {
1585 Py_DECREF(*p_unicode);
1586 *p_unicode = unicode_empty;
1587 Py_INCREF(*p_unicode);
1588 return 0;
1589 }
1590
Victor Stinner488fa492011-12-12 00:01:39 +01001591 if (!unicode_modifiable(unicode)) {
Victor Stinnerfe226c02011-10-03 03:52:20 +02001592 PyObject *copy = resize_copy(unicode, length);
1593 if (copy == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001594 return -1;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001595 Py_DECREF(*p_unicode);
1596 *p_unicode = copy;
Benjamin Peterson29060642009-01-31 22:14:21 +00001597 return 0;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001598 }
1599
Victor Stinnerfe226c02011-10-03 03:52:20 +02001600 if (PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001601 PyObject *new_unicode = resize_compact(unicode, length);
1602 if (new_unicode == NULL)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001603 return -1;
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001604 *p_unicode = new_unicode;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001605 return 0;
Benjamin Peterson4bfce8f2011-10-03 19:35:07 -04001606 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001607 return resize_inplace(unicode, length);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001608}
1609
Alexander Belopolsky40018472011-02-26 01:02:56 +00001610int
Victor Stinnerfe226c02011-10-03 03:52:20 +02001611PyUnicode_Resize(PyObject **p_unicode, Py_ssize_t length)
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001612{
Victor Stinnerfe226c02011-10-03 03:52:20 +02001613 PyObject *unicode;
1614 if (p_unicode == NULL) {
1615 PyErr_BadInternalCall();
1616 return -1;
1617 }
1618 unicode = *p_unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001619 if (unicode == NULL || !PyUnicode_Check(unicode) || length < 0)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001620 {
1621 PyErr_BadInternalCall();
1622 return -1;
1623 }
1624 return unicode_resize(p_unicode, length);
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001625}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001626
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001627static int
Victor Stinner1b487b42012-05-03 12:29:04 +02001628unicode_widen(PyObject **p_unicode, Py_ssize_t length,
1629 unsigned int maxchar)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001630{
1631 PyObject *result;
1632 assert(PyUnicode_IS_READY(*p_unicode));
Victor Stinner1b487b42012-05-03 12:29:04 +02001633 assert(length <= PyUnicode_GET_LENGTH(*p_unicode));
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001634 if (maxchar <= PyUnicode_MAX_CHAR_VALUE(*p_unicode))
1635 return 0;
1636 result = PyUnicode_New(PyUnicode_GET_LENGTH(*p_unicode),
1637 maxchar);
1638 if (result == NULL)
1639 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +02001640 _PyUnicode_FastCopyCharacters(result, 0, *p_unicode, 0, length);
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001641 Py_DECREF(*p_unicode);
1642 *p_unicode = result;
1643 return 0;
1644}
1645
1646static int
1647unicode_putchar(PyObject **p_unicode, Py_ssize_t *pos,
1648 Py_UCS4 ch)
1649{
Victor Stinner15e9ed22012-02-22 13:36:20 +01001650 assert(ch <= MAX_UNICODE);
Victor Stinner1b487b42012-05-03 12:29:04 +02001651 if (unicode_widen(p_unicode, *pos, ch) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001652 return -1;
1653 PyUnicode_WRITE(PyUnicode_KIND(*p_unicode),
1654 PyUnicode_DATA(*p_unicode),
1655 (*pos)++, ch);
1656 return 0;
1657}
1658
Victor Stinnerc5166102012-02-22 13:55:02 +01001659/* Copy a ASCII or latin1 char* string into a Python Unicode string.
Victor Stinnerc5166102012-02-22 13:55:02 +01001660
Victor Stinnerb429d3b2012-02-22 21:22:20 +01001661 WARNING: The function doesn't copy the terminating null character and
1662 doesn't check the maximum character (may write a latin1 character in an
1663 ASCII string). */
Victor Stinner184252a2012-06-16 02:57:41 +02001664static void
1665unicode_write_cstr(PyObject *unicode, Py_ssize_t index,
1666 const char *str, Py_ssize_t len)
Victor Stinnerc5166102012-02-22 13:55:02 +01001667{
1668 enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
1669 void *data = PyUnicode_DATA(unicode);
Victor Stinner184252a2012-06-16 02:57:41 +02001670 const char *end = str + len;
Victor Stinnerc5166102012-02-22 13:55:02 +01001671
1672 switch (kind) {
1673 case PyUnicode_1BYTE_KIND: {
Victor Stinnerc5166102012-02-22 13:55:02 +01001674 assert(index + len <= PyUnicode_GET_LENGTH(unicode));
Antoine Pitrouba6bafc2012-02-22 16:41:50 +01001675 memcpy((char *) data + index, str, len);
Victor Stinner184252a2012-06-16 02:57:41 +02001676 break;
Victor Stinnerc5166102012-02-22 13:55:02 +01001677 }
1678 case PyUnicode_2BYTE_KIND: {
1679 Py_UCS2 *start = (Py_UCS2 *)data + index;
1680 Py_UCS2 *ucs2 = start;
1681 assert(index <= PyUnicode_GET_LENGTH(unicode));
1682
Victor Stinner184252a2012-06-16 02:57:41 +02001683 for (; str < end; ++ucs2, ++str)
Victor Stinnerc5166102012-02-22 13:55:02 +01001684 *ucs2 = (Py_UCS2)*str;
1685
1686 assert((ucs2 - start) <= PyUnicode_GET_LENGTH(unicode));
Victor Stinner184252a2012-06-16 02:57:41 +02001687 break;
Victor Stinnerc5166102012-02-22 13:55:02 +01001688 }
1689 default: {
1690 Py_UCS4 *start = (Py_UCS4 *)data + index;
1691 Py_UCS4 *ucs4 = start;
1692 assert(kind == PyUnicode_4BYTE_KIND);
1693 assert(index <= PyUnicode_GET_LENGTH(unicode));
1694
Victor Stinner184252a2012-06-16 02:57:41 +02001695 for (; str < end; ++ucs4, ++str)
Victor Stinnerc5166102012-02-22 13:55:02 +01001696 *ucs4 = (Py_UCS4)*str;
1697
1698 assert((ucs4 - start) <= PyUnicode_GET_LENGTH(unicode));
Victor Stinnerc5166102012-02-22 13:55:02 +01001699 }
1700 }
1701}
1702
1703
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001704static PyObject*
1705get_latin1_char(unsigned char ch)
1706{
Victor Stinnera464fc12011-10-02 20:39:30 +02001707 PyObject *unicode = unicode_latin1[ch];
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001708 if (!unicode) {
Victor Stinnera464fc12011-10-02 20:39:30 +02001709 unicode = PyUnicode_New(1, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001710 if (!unicode)
1711 return NULL;
1712 PyUnicode_1BYTE_DATA(unicode)[0] = ch;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001713 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001714 unicode_latin1[ch] = unicode;
1715 }
1716 Py_INCREF(unicode);
Victor Stinnera464fc12011-10-02 20:39:30 +02001717 return unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001718}
1719
Alexander Belopolsky40018472011-02-26 01:02:56 +00001720PyObject *
1721PyUnicode_FromUnicode(const Py_UNICODE *u, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001722{
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001723 PyObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001724 Py_UCS4 maxchar = 0;
1725 Py_ssize_t num_surrogates;
1726
1727 if (u == NULL)
1728 return (PyObject*)_PyUnicode_New(size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001729
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001730 /* If the Unicode data is known at construction time, we can apply
1731 some optimizations which share commonly used objects. */
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001732
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001733 /* Optimization for empty strings */
1734 if (size == 0 && unicode_empty != NULL) {
1735 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001736 return unicode_empty;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001737 }
Tim Petersced69f82003-09-16 20:30:58 +00001738
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001739 /* Single character Unicode objects in the Latin-1 range are
1740 shared when using this constructor */
1741 if (size == 1 && *u < 256)
1742 return get_latin1_char((unsigned char)*u);
1743
1744 /* If not empty and not single character, copy the Unicode data
1745 into the new object */
Victor Stinnerd8f65102011-09-29 19:43:17 +02001746 if (find_maxchar_surrogates(u, u + size,
1747 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001748 return NULL;
1749
Victor Stinner8faf8212011-12-08 22:14:11 +01001750 unicode = PyUnicode_New(size - num_surrogates, maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001751 if (!unicode)
1752 return NULL;
1753
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001754 switch (PyUnicode_KIND(unicode)) {
1755 case PyUnicode_1BYTE_KIND:
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001756 _PyUnicode_CONVERT_BYTES(Py_UNICODE, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001757 u, u + size, PyUnicode_1BYTE_DATA(unicode));
1758 break;
1759 case PyUnicode_2BYTE_KIND:
1760#if Py_UNICODE_SIZE == 2
1761 Py_MEMCPY(PyUnicode_2BYTE_DATA(unicode), u, size * 2);
1762#else
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001763 _PyUnicode_CONVERT_BYTES(Py_UNICODE, Py_UCS2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001764 u, u + size, PyUnicode_2BYTE_DATA(unicode));
1765#endif
1766 break;
1767 case PyUnicode_4BYTE_KIND:
1768#if SIZEOF_WCHAR_T == 2
1769 /* This is the only case which has to process surrogates, thus
1770 a simple copy loop is not enough and we need a function. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001771 unicode_convert_wchar_to_ucs4(u, u + size, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001772#else
1773 assert(num_surrogates == 0);
1774 Py_MEMCPY(PyUnicode_4BYTE_DATA(unicode), u, size * 4);
1775#endif
1776 break;
1777 default:
1778 assert(0 && "Impossible state");
1779 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00001780
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001781 return unicode_result(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001782}
1783
Alexander Belopolsky40018472011-02-26 01:02:56 +00001784PyObject *
1785PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size)
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001786{
Benjamin Peterson14339b62009-01-31 16:36:08 +00001787 if (size < 0) {
1788 PyErr_SetString(PyExc_SystemError,
Benjamin Peterson29060642009-01-31 22:14:21 +00001789 "Negative size passed to PyUnicode_FromStringAndSize");
Benjamin Peterson14339b62009-01-31 16:36:08 +00001790 return NULL;
1791 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01001792 if (u != NULL)
1793 return PyUnicode_DecodeUTF8Stateful(u, size, NULL, NULL);
1794 else
1795 return (PyObject *)_PyUnicode_New(size);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001796}
1797
Alexander Belopolsky40018472011-02-26 01:02:56 +00001798PyObject *
1799PyUnicode_FromString(const char *u)
Walter Dörwaldd2034312007-05-18 16:29:38 +00001800{
1801 size_t size = strlen(u);
1802 if (size > PY_SSIZE_T_MAX) {
1803 PyErr_SetString(PyExc_OverflowError, "input too long");
1804 return NULL;
1805 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01001806 return PyUnicode_DecodeUTF8Stateful(u, (Py_ssize_t)size, NULL, NULL);
Walter Dörwaldd2034312007-05-18 16:29:38 +00001807}
1808
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001809PyObject *
1810_PyUnicode_FromId(_Py_Identifier *id)
1811{
1812 if (!id->object) {
Victor Stinnerd1cd99b2012-02-07 23:05:55 +01001813 id->object = PyUnicode_DecodeUTF8Stateful(id->string,
1814 strlen(id->string),
1815 NULL, NULL);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001816 if (!id->object)
1817 return NULL;
1818 PyUnicode_InternInPlace(&id->object);
1819 assert(!id->next);
1820 id->next = static_strings;
1821 static_strings = id;
1822 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001823 return id->object;
1824}
1825
1826void
1827_PyUnicode_ClearStaticStrings()
1828{
Benjamin Peterson0c270a82013-01-09 09:52:01 -06001829 _Py_Identifier *tmp, *s = static_strings;
1830 while (s) {
1831 Py_DECREF(s->object);
1832 s->object = NULL;
1833 tmp = s->next;
1834 s->next = NULL;
1835 s = tmp;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001836 }
Benjamin Peterson0c270a82013-01-09 09:52:01 -06001837 static_strings = NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001838}
1839
Benjamin Peterson0df54292012-03-26 14:50:32 -04001840/* Internal function, doesn't check maximum character */
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001841
Victor Stinnerd3f08822012-05-29 12:57:52 +02001842PyObject*
1843_PyUnicode_FromASCII(const char *buffer, Py_ssize_t size)
Victor Stinner702c7342011-10-05 13:50:52 +02001844{
Victor Stinnerd3f08822012-05-29 12:57:52 +02001845 const unsigned char *s = (const unsigned char *)buffer;
Victor Stinner785938e2011-12-11 20:09:03 +01001846 PyObject *unicode;
Victor Stinnere6b2d442011-12-11 21:54:30 +01001847 if (size == 1) {
Victor Stinner0617b6e2011-10-05 23:26:01 +02001848#ifdef Py_DEBUG
Victor Stinnere6b2d442011-12-11 21:54:30 +01001849 assert(s[0] < 128);
Victor Stinner0617b6e2011-10-05 23:26:01 +02001850#endif
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001851 return get_latin1_char(s[0]);
Victor Stinnere6b2d442011-12-11 21:54:30 +01001852 }
Victor Stinner785938e2011-12-11 20:09:03 +01001853 unicode = PyUnicode_New(size, 127);
1854 if (!unicode)
Victor Stinner702c7342011-10-05 13:50:52 +02001855 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01001856 memcpy(PyUnicode_1BYTE_DATA(unicode), s, size);
1857 assert(_PyUnicode_CheckConsistency(unicode, 1));
1858 return unicode;
Victor Stinner702c7342011-10-05 13:50:52 +02001859}
1860
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001861static Py_UCS4
1862kind_maxchar_limit(unsigned int kind)
1863{
Benjamin Petersonead6b532011-12-20 17:23:42 -06001864 switch (kind) {
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001865 case PyUnicode_1BYTE_KIND:
1866 return 0x80;
1867 case PyUnicode_2BYTE_KIND:
1868 return 0x100;
1869 case PyUnicode_4BYTE_KIND:
1870 return 0x10000;
1871 default:
1872 assert(0 && "invalid kind");
Victor Stinner8faf8212011-12-08 22:14:11 +01001873 return MAX_UNICODE;
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001874 }
1875}
1876
Victor Stinnere6abb482012-05-02 01:15:40 +02001877Py_LOCAL_INLINE(Py_UCS4)
1878align_maxchar(Py_UCS4 maxchar)
1879{
1880 if (maxchar <= 127)
1881 return 127;
1882 else if (maxchar <= 255)
1883 return 255;
1884 else if (maxchar <= 65535)
1885 return 65535;
1886 else
1887 return MAX_UNICODE;
1888}
1889
Victor Stinner702c7342011-10-05 13:50:52 +02001890static PyObject*
Victor Stinnere57b1c02011-09-28 22:20:48 +02001891_PyUnicode_FromUCS1(const unsigned char* u, Py_ssize_t size)
Mark Dickinson081dfee2009-03-18 14:47:41 +00001892{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001893 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001894 unsigned char max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001895
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001896 if (size == 0) {
1897 Py_INCREF(unicode_empty);
1898 return unicode_empty;
1899 }
1900 assert(size > 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001901 if (size == 1)
1902 return get_latin1_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001903
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001904 max_char = ucs1lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001905 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001906 if (!res)
1907 return NULL;
1908 memcpy(PyUnicode_1BYTE_DATA(res), u, size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001909 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001910 return res;
Mark Dickinson081dfee2009-03-18 14:47:41 +00001911}
1912
Victor Stinnere57b1c02011-09-28 22:20:48 +02001913static PyObject*
1914_PyUnicode_FromUCS2(const Py_UCS2 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001915{
1916 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001917 Py_UCS2 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001918
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001919 if (size == 0) {
1920 Py_INCREF(unicode_empty);
1921 return unicode_empty;
1922 }
1923 assert(size > 0);
Victor Stinnerb6cd0142012-05-03 02:17:04 +02001924 if (size == 1) {
1925 Py_UCS4 ch = u[0];
1926 if (ch < 256)
1927 return get_latin1_char((unsigned char)ch);
1928
1929 res = PyUnicode_New(1, ch);
1930 if (res == NULL)
1931 return NULL;
1932 PyUnicode_WRITE(PyUnicode_KIND(res), PyUnicode_DATA(res), 0, ch);
1933 assert(_PyUnicode_CheckConsistency(res, 1));
1934 return res;
1935 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001936
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001937 max_char = ucs2lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001938 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001939 if (!res)
1940 return NULL;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001941 if (max_char >= 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001942 memcpy(PyUnicode_2BYTE_DATA(res), u, sizeof(Py_UCS2)*size);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001943 else {
1944 _PyUnicode_CONVERT_BYTES(
1945 Py_UCS2, Py_UCS1, u, u + size, PyUnicode_1BYTE_DATA(res));
1946 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001947 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001948 return res;
1949}
1950
Victor Stinnere57b1c02011-09-28 22:20:48 +02001951static PyObject*
1952_PyUnicode_FromUCS4(const Py_UCS4 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001953{
1954 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001955 Py_UCS4 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001956
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001957 if (size == 0) {
1958 Py_INCREF(unicode_empty);
1959 return unicode_empty;
1960 }
1961 assert(size > 0);
Victor Stinnerb6cd0142012-05-03 02:17:04 +02001962 if (size == 1) {
1963 Py_UCS4 ch = u[0];
1964 if (ch < 256)
1965 return get_latin1_char((unsigned char)ch);
1966
1967 res = PyUnicode_New(1, ch);
1968 if (res == NULL)
1969 return NULL;
1970 PyUnicode_WRITE(PyUnicode_KIND(res), PyUnicode_DATA(res), 0, ch);
1971 assert(_PyUnicode_CheckConsistency(res, 1));
1972 return res;
1973 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001974
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001975 max_char = ucs4lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001976 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001977 if (!res)
1978 return NULL;
Antoine Pitrou950468e2011-10-11 22:45:48 +02001979 if (max_char < 256)
1980 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, u, u + size,
1981 PyUnicode_1BYTE_DATA(res));
1982 else if (max_char < 0x10000)
1983 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, u, u + size,
1984 PyUnicode_2BYTE_DATA(res));
1985 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001986 memcpy(PyUnicode_4BYTE_DATA(res), u, sizeof(Py_UCS4)*size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001987 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001988 return res;
1989}
1990
1991PyObject*
1992PyUnicode_FromKindAndData(int kind, const void *buffer, Py_ssize_t size)
1993{
Victor Stinnercfed46e2011-11-22 01:29:14 +01001994 if (size < 0) {
1995 PyErr_SetString(PyExc_ValueError, "size must be positive");
1996 return NULL;
1997 }
Benjamin Petersonead6b532011-12-20 17:23:42 -06001998 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001999 case PyUnicode_1BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002000 return _PyUnicode_FromUCS1(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002001 case PyUnicode_2BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002002 return _PyUnicode_FromUCS2(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002003 case PyUnicode_4BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002004 return _PyUnicode_FromUCS4(buffer, size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002005 default:
Victor Stinnerb9275c12011-10-05 14:01:42 +02002006 PyErr_SetString(PyExc_SystemError, "invalid kind");
2007 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002008 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002009}
2010
Victor Stinnerece58de2012-04-23 23:36:38 +02002011Py_UCS4
2012_PyUnicode_FindMaxChar(PyObject *unicode, Py_ssize_t start, Py_ssize_t end)
2013{
2014 enum PyUnicode_Kind kind;
2015 void *startptr, *endptr;
2016
2017 assert(PyUnicode_IS_READY(unicode));
2018 assert(0 <= start);
2019 assert(end <= PyUnicode_GET_LENGTH(unicode));
2020 assert(start <= end);
2021
2022 if (start == 0 && end == PyUnicode_GET_LENGTH(unicode))
2023 return PyUnicode_MAX_CHAR_VALUE(unicode);
2024
2025 if (start == end)
2026 return 127;
2027
Victor Stinner94d558b2012-04-27 22:26:58 +02002028 if (PyUnicode_IS_ASCII(unicode))
2029 return 127;
2030
Victor Stinnerece58de2012-04-23 23:36:38 +02002031 kind = PyUnicode_KIND(unicode);
Benjamin Petersonf3b7d862012-04-23 18:07:01 -04002032 startptr = PyUnicode_DATA(unicode);
Benjamin Petersonb9f4c9d2012-04-23 21:45:40 -04002033 endptr = (char *)startptr + end * kind;
2034 startptr = (char *)startptr + start * kind;
Benjamin Peterson2844a7a2012-04-23 18:00:25 -04002035 switch(kind) {
2036 case PyUnicode_1BYTE_KIND:
2037 return ucs1lib_find_max_char(startptr, endptr);
2038 case PyUnicode_2BYTE_KIND:
2039 return ucs2lib_find_max_char(startptr, endptr);
2040 case PyUnicode_4BYTE_KIND:
2041 return ucs4lib_find_max_char(startptr, endptr);
Victor Stinnerece58de2012-04-23 23:36:38 +02002042 default:
Benjamin Peterson2844a7a2012-04-23 18:00:25 -04002043 assert(0);
2044 return 0;
Victor Stinnerece58de2012-04-23 23:36:38 +02002045 }
2046}
2047
Victor Stinner25a4b292011-10-06 12:31:55 +02002048/* Ensure that a string uses the most efficient storage, if it is not the
2049 case: create a new string with of the right kind. Write NULL into *p_unicode
2050 on error. */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02002051static void
Victor Stinner25a4b292011-10-06 12:31:55 +02002052unicode_adjust_maxchar(PyObject **p_unicode)
2053{
2054 PyObject *unicode, *copy;
2055 Py_UCS4 max_char;
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002056 Py_ssize_t len;
Victor Stinner25a4b292011-10-06 12:31:55 +02002057 unsigned int kind;
2058
2059 assert(p_unicode != NULL);
2060 unicode = *p_unicode;
2061 assert(PyUnicode_IS_READY(unicode));
2062 if (PyUnicode_IS_ASCII(unicode))
2063 return;
2064
2065 len = PyUnicode_GET_LENGTH(unicode);
2066 kind = PyUnicode_KIND(unicode);
2067 if (kind == PyUnicode_1BYTE_KIND) {
2068 const Py_UCS1 *u = PyUnicode_1BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002069 max_char = ucs1lib_find_max_char(u, u + len);
2070 if (max_char >= 128)
2071 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002072 }
2073 else if (kind == PyUnicode_2BYTE_KIND) {
2074 const Py_UCS2 *u = PyUnicode_2BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002075 max_char = ucs2lib_find_max_char(u, u + len);
2076 if (max_char >= 256)
2077 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002078 }
2079 else {
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002080 const Py_UCS4 *u = PyUnicode_4BYTE_DATA(unicode);
Victor Stinner25a4b292011-10-06 12:31:55 +02002081 assert(kind == PyUnicode_4BYTE_KIND);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002082 max_char = ucs4lib_find_max_char(u, u + len);
2083 if (max_char >= 0x10000)
2084 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002085 }
Victor Stinner25a4b292011-10-06 12:31:55 +02002086 copy = PyUnicode_New(len, max_char);
Victor Stinnerca439ee2012-06-16 03:17:34 +02002087 if (copy != NULL)
2088 _PyUnicode_FastCopyCharacters(copy, 0, unicode, 0, len);
Victor Stinner25a4b292011-10-06 12:31:55 +02002089 Py_DECREF(unicode);
2090 *p_unicode = copy;
2091}
2092
Victor Stinner034f6cf2011-09-30 02:26:44 +02002093PyObject*
Victor Stinnerbf6e5602011-12-12 01:53:47 +01002094_PyUnicode_Copy(PyObject *unicode)
Victor Stinner034f6cf2011-09-30 02:26:44 +02002095{
Victor Stinner87af4f22011-11-21 23:03:47 +01002096 Py_ssize_t length;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002097 PyObject *copy;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002098
Victor Stinner034f6cf2011-09-30 02:26:44 +02002099 if (!PyUnicode_Check(unicode)) {
2100 PyErr_BadInternalCall();
2101 return NULL;
2102 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05002103 if (PyUnicode_READY(unicode) == -1)
Victor Stinner034f6cf2011-09-30 02:26:44 +02002104 return NULL;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002105
Victor Stinner87af4f22011-11-21 23:03:47 +01002106 length = PyUnicode_GET_LENGTH(unicode);
2107 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002108 if (!copy)
2109 return NULL;
2110 assert(PyUnicode_KIND(copy) == PyUnicode_KIND(unicode));
2111
Victor Stinner87af4f22011-11-21 23:03:47 +01002112 Py_MEMCPY(PyUnicode_DATA(copy), PyUnicode_DATA(unicode),
2113 length * PyUnicode_KIND(unicode));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002114 assert(_PyUnicode_CheckConsistency(copy, 1));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002115 return copy;
Victor Stinner034f6cf2011-09-30 02:26:44 +02002116}
2117
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002118
Victor Stinnerbc603d12011-10-02 01:00:40 +02002119/* Widen Unicode objects to larger buffers. Don't write terminating null
2120 character. Return NULL on error. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002121
2122void*
2123_PyUnicode_AsKind(PyObject *s, unsigned int kind)
2124{
Victor Stinnerbc603d12011-10-02 01:00:40 +02002125 Py_ssize_t len;
2126 void *result;
2127 unsigned int skind;
2128
Benjamin Petersonbac79492012-01-14 13:34:47 -05002129 if (PyUnicode_READY(s) == -1)
Victor Stinnerbc603d12011-10-02 01:00:40 +02002130 return NULL;
2131
2132 len = PyUnicode_GET_LENGTH(s);
2133 skind = PyUnicode_KIND(s);
2134 if (skind >= kind) {
Victor Stinner01698042011-10-04 00:04:26 +02002135 PyErr_SetString(PyExc_SystemError, "invalid widening attempt");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002136 return NULL;
2137 }
Benjamin Petersonead6b532011-12-20 17:23:42 -06002138 switch (kind) {
Victor Stinnerbc603d12011-10-02 01:00:40 +02002139 case PyUnicode_2BYTE_KIND:
2140 result = PyMem_Malloc(len * sizeof(Py_UCS2));
2141 if (!result)
2142 return PyErr_NoMemory();
2143 assert(skind == PyUnicode_1BYTE_KIND);
2144 _PyUnicode_CONVERT_BYTES(
2145 Py_UCS1, Py_UCS2,
2146 PyUnicode_1BYTE_DATA(s),
2147 PyUnicode_1BYTE_DATA(s) + len,
2148 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002149 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002150 case PyUnicode_4BYTE_KIND:
2151 result = PyMem_Malloc(len * sizeof(Py_UCS4));
2152 if (!result)
2153 return PyErr_NoMemory();
2154 if (skind == PyUnicode_2BYTE_KIND) {
2155 _PyUnicode_CONVERT_BYTES(
2156 Py_UCS2, Py_UCS4,
2157 PyUnicode_2BYTE_DATA(s),
2158 PyUnicode_2BYTE_DATA(s) + len,
2159 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002160 }
Victor Stinnerbc603d12011-10-02 01:00:40 +02002161 else {
2162 assert(skind == PyUnicode_1BYTE_KIND);
2163 _PyUnicode_CONVERT_BYTES(
2164 Py_UCS1, Py_UCS4,
2165 PyUnicode_1BYTE_DATA(s),
2166 PyUnicode_1BYTE_DATA(s) + len,
2167 result);
2168 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002169 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002170 default:
2171 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002172 }
Victor Stinner01698042011-10-04 00:04:26 +02002173 PyErr_SetString(PyExc_SystemError, "invalid kind");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002174 return NULL;
2175}
2176
2177static Py_UCS4*
2178as_ucs4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2179 int copy_null)
2180{
2181 int kind;
2182 void *data;
2183 Py_ssize_t len, targetlen;
2184 if (PyUnicode_READY(string) == -1)
2185 return NULL;
2186 kind = PyUnicode_KIND(string);
2187 data = PyUnicode_DATA(string);
2188 len = PyUnicode_GET_LENGTH(string);
2189 targetlen = len;
2190 if (copy_null)
2191 targetlen++;
2192 if (!target) {
2193 if (PY_SSIZE_T_MAX / sizeof(Py_UCS4) < targetlen) {
2194 PyErr_NoMemory();
2195 return NULL;
2196 }
2197 target = PyMem_Malloc(targetlen * sizeof(Py_UCS4));
2198 if (!target) {
2199 PyErr_NoMemory();
2200 return NULL;
2201 }
2202 }
2203 else {
2204 if (targetsize < targetlen) {
2205 PyErr_Format(PyExc_SystemError,
2206 "string is longer than the buffer");
2207 if (copy_null && 0 < targetsize)
2208 target[0] = 0;
2209 return NULL;
2210 }
2211 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002212 if (kind == PyUnicode_1BYTE_KIND) {
2213 Py_UCS1 *start = (Py_UCS1 *) data;
2214 _PyUnicode_CONVERT_BYTES(Py_UCS1, Py_UCS4, start, start + len, target);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002215 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002216 else if (kind == PyUnicode_2BYTE_KIND) {
2217 Py_UCS2 *start = (Py_UCS2 *) data;
2218 _PyUnicode_CONVERT_BYTES(Py_UCS2, Py_UCS4, start, start + len, target);
2219 }
2220 else {
2221 assert(kind == PyUnicode_4BYTE_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002222 Py_MEMCPY(target, data, len * sizeof(Py_UCS4));
Antoine Pitrou950468e2011-10-11 22:45:48 +02002223 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002224 if (copy_null)
2225 target[len] = 0;
2226 return target;
2227}
2228
2229Py_UCS4*
2230PyUnicode_AsUCS4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2231 int copy_null)
2232{
Antoine Pitroude20b0b2011-11-10 21:47:38 +01002233 if (target == NULL || targetsize < 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002234 PyErr_BadInternalCall();
2235 return NULL;
2236 }
2237 return as_ucs4(string, target, targetsize, copy_null);
2238}
2239
2240Py_UCS4*
2241PyUnicode_AsUCS4Copy(PyObject *string)
2242{
2243 return as_ucs4(string, NULL, 0, 1);
2244}
2245
2246#ifdef HAVE_WCHAR_H
Mark Dickinson081dfee2009-03-18 14:47:41 +00002247
Alexander Belopolsky40018472011-02-26 01:02:56 +00002248PyObject *
2249PyUnicode_FromWideChar(register const wchar_t *w, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002250{
Guido van Rossumd57fd912000-03-10 22:53:23 +00002251 if (w == NULL) {
Victor Stinner382955f2011-12-11 21:44:00 +01002252 if (size == 0) {
2253 Py_INCREF(unicode_empty);
2254 return unicode_empty;
2255 }
Benjamin Peterson29060642009-01-31 22:14:21 +00002256 PyErr_BadInternalCall();
2257 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002258 }
2259
Martin v. Löwis790465f2008-04-05 20:41:37 +00002260 if (size == -1) {
2261 size = wcslen(w);
2262 }
2263
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002264 return PyUnicode_FromUnicode(w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002265}
2266
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002267#endif /* HAVE_WCHAR_H */
Mark Dickinson081dfee2009-03-18 14:47:41 +00002268
Walter Dörwald346737f2007-05-31 10:44:43 +00002269static void
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002270makefmt(char *fmt, int longflag, int longlongflag, int size_tflag,
2271 int zeropad, int width, int precision, char c)
Walter Dörwald346737f2007-05-31 10:44:43 +00002272{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002273 *fmt++ = '%';
2274 if (width) {
2275 if (zeropad)
2276 *fmt++ = '0';
2277 fmt += sprintf(fmt, "%d", width);
2278 }
2279 if (precision)
2280 fmt += sprintf(fmt, ".%d", precision);
2281 if (longflag)
2282 *fmt++ = 'l';
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002283 else if (longlongflag) {
2284 /* longlongflag should only ever be nonzero on machines with
2285 HAVE_LONG_LONG defined */
2286#ifdef HAVE_LONG_LONG
2287 char *f = PY_FORMAT_LONG_LONG;
2288 while (*f)
2289 *fmt++ = *f++;
2290#else
2291 /* we shouldn't ever get here */
2292 assert(0);
2293 *fmt++ = 'l';
2294#endif
2295 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002296 else if (size_tflag) {
2297 char *f = PY_FORMAT_SIZE_T;
2298 while (*f)
2299 *fmt++ = *f++;
2300 }
2301 *fmt++ = c;
2302 *fmt = '\0';
Walter Dörwald346737f2007-05-31 10:44:43 +00002303}
2304
Victor Stinner96865452011-03-01 23:44:09 +00002305/* helper for PyUnicode_FromFormatV() */
2306
2307static const char*
2308parse_format_flags(const char *f,
2309 int *p_width, int *p_precision,
2310 int *p_longflag, int *p_longlongflag, int *p_size_tflag)
2311{
2312 int width, precision, longflag, longlongflag, size_tflag;
2313
2314 /* parse the width.precision part, e.g. "%2.5s" => width=2, precision=5 */
2315 f++;
2316 width = 0;
2317 while (Py_ISDIGIT((unsigned)*f))
2318 width = (width*10) + *f++ - '0';
2319 precision = 0;
2320 if (*f == '.') {
2321 f++;
2322 while (Py_ISDIGIT((unsigned)*f))
2323 precision = (precision*10) + *f++ - '0';
2324 if (*f == '%') {
2325 /* "%.3%s" => f points to "3" */
2326 f--;
2327 }
2328 }
2329 if (*f == '\0') {
2330 /* bogus format "%.1" => go backward, f points to "1" */
2331 f--;
2332 }
2333 if (p_width != NULL)
2334 *p_width = width;
2335 if (p_precision != NULL)
2336 *p_precision = precision;
2337
2338 /* Handle %ld, %lu, %lld and %llu. */
2339 longflag = 0;
2340 longlongflag = 0;
Victor Stinnere7faec12011-03-02 00:01:53 +00002341 size_tflag = 0;
Victor Stinner96865452011-03-01 23:44:09 +00002342
2343 if (*f == 'l') {
Victor Stinner6d970f42011-03-02 00:04:25 +00002344 if (f[1] == 'd' || f[1] == 'u' || f[1] == 'i') {
Victor Stinner96865452011-03-01 23:44:09 +00002345 longflag = 1;
2346 ++f;
2347 }
2348#ifdef HAVE_LONG_LONG
2349 else if (f[1] == 'l' &&
Victor Stinner6d970f42011-03-02 00:04:25 +00002350 (f[2] == 'd' || f[2] == 'u' || f[2] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002351 longlongflag = 1;
2352 f += 2;
2353 }
2354#endif
2355 }
2356 /* handle the size_t flag. */
Victor Stinner6d970f42011-03-02 00:04:25 +00002357 else if (*f == 'z' && (f[1] == 'd' || f[1] == 'u' || f[1] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002358 size_tflag = 1;
2359 ++f;
2360 }
2361 if (p_longflag != NULL)
2362 *p_longflag = longflag;
2363 if (p_longlongflag != NULL)
2364 *p_longlongflag = longlongflag;
2365 if (p_size_tflag != NULL)
2366 *p_size_tflag = size_tflag;
2367 return f;
2368}
2369
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002370/* maximum number of characters required for output of %ld. 21 characters
2371 allows for 64-bit integers (in decimal) and an optional sign. */
2372#define MAX_LONG_CHARS 21
2373/* maximum number of characters required for output of %lld.
2374 We need at most ceil(log10(256)*SIZEOF_LONG_LONG) digits,
2375 plus 1 for the sign. 53/22 is an upper bound for log10(256). */
2376#define MAX_LONG_LONG_CHARS (2 + (SIZEOF_LONG_LONG*53-1) / 22)
2377
Walter Dörwaldd2034312007-05-18 16:29:38 +00002378PyObject *
2379PyUnicode_FromFormatV(const char *format, va_list vargs)
2380{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002381 va_list count;
2382 Py_ssize_t callcount = 0;
2383 PyObject **callresults = NULL;
2384 PyObject **callresult = NULL;
2385 Py_ssize_t n = 0;
2386 int width = 0;
2387 int precision = 0;
2388 int zeropad;
2389 const char* f;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002390 PyObject *string;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002391 /* used by sprintf */
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002392 char fmt[61]; /* should be enough for %0width.precisionlld */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002393 Py_UCS4 maxchar = 127; /* result is ASCII by default */
2394 Py_UCS4 argmaxchar;
2395 Py_ssize_t numbersize = 0;
2396 char *numberresults = NULL;
2397 char *numberresult = NULL;
2398 Py_ssize_t i;
2399 int kind;
2400 void *data;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002401
Victor Stinner4a2b7a12010-08-13 14:03:48 +00002402 Py_VA_COPY(count, vargs);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002403 /* step 1: count the number of %S/%R/%A/%s format specifications
2404 * (we call PyObject_Str()/PyObject_Repr()/PyObject_ASCII()/
2405 * PyUnicode_DecodeUTF8() for these objects once during step 3 and put the
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002406 * result in an array)
Georg Brandl7597add2011-10-05 16:36:47 +02002407 * also estimate a upper bound for all the number formats in the string,
2408 * numbers will be formatted in step 3 and be kept in a '\0'-separated
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002409 * buffer before putting everything together. */
Benjamin Peterson14339b62009-01-31 16:36:08 +00002410 for (f = format; *f; f++) {
2411 if (*f == '%') {
Victor Stinner96865452011-03-01 23:44:09 +00002412 int longlongflag;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002413 /* skip width or width.precision (eg. "1.2" of "%1.2f") */
2414 f = parse_format_flags(f, &width, NULL, NULL, &longlongflag, NULL);
2415 if (*f == 's' || *f=='S' || *f=='R' || *f=='A' || *f=='V')
2416 ++callcount;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002417
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002418 else if (*f == 'd' || *f=='u' || *f=='i' || *f=='x' || *f=='p') {
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002419#ifdef HAVE_LONG_LONG
2420 if (longlongflag) {
2421 if (width < MAX_LONG_LONG_CHARS)
2422 width = MAX_LONG_LONG_CHARS;
2423 }
2424 else
2425#endif
2426 /* MAX_LONG_CHARS is enough to hold a 64-bit integer,
2427 including sign. Decimal takes the most space. This
2428 isn't enough for octal. If a width is specified we
2429 need more (which we allocate later). */
2430 if (width < MAX_LONG_CHARS)
2431 width = MAX_LONG_CHARS;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002432
2433 /* account for the size + '\0' to separate numbers
2434 inside of the numberresults buffer */
2435 numbersize += (width + 1);
2436 }
2437 }
2438 else if ((unsigned char)*f > 127) {
2439 PyErr_Format(PyExc_ValueError,
2440 "PyUnicode_FromFormatV() expects an ASCII-encoded format "
2441 "string, got a non-ASCII byte: 0x%02x",
2442 (unsigned char)*f);
2443 return NULL;
2444 }
2445 }
2446 /* step 2: allocate memory for the results of
2447 * PyObject_Str()/PyObject_Repr()/PyUnicode_DecodeUTF8() calls */
2448 if (callcount) {
2449 callresults = PyObject_Malloc(sizeof(PyObject *) * callcount);
2450 if (!callresults) {
2451 PyErr_NoMemory();
2452 return NULL;
2453 }
2454 callresult = callresults;
2455 }
2456 /* step 2.5: allocate memory for the results of formating numbers */
2457 if (numbersize) {
2458 numberresults = PyObject_Malloc(numbersize);
2459 if (!numberresults) {
2460 PyErr_NoMemory();
2461 goto fail;
2462 }
2463 numberresult = numberresults;
2464 }
2465
2466 /* step 3: format numbers and figure out how large a buffer we need */
2467 for (f = format; *f; f++) {
2468 if (*f == '%') {
2469 const char* p;
2470 int longflag;
2471 int longlongflag;
2472 int size_tflag;
2473 int numprinted;
2474
2475 p = f;
2476 zeropad = (f[1] == '0');
2477 f = parse_format_flags(f, &width, &precision,
2478 &longflag, &longlongflag, &size_tflag);
2479 switch (*f) {
2480 case 'c':
2481 {
2482 Py_UCS4 ordinal = va_arg(count, int);
Victor Stinnere6abb482012-05-02 01:15:40 +02002483 maxchar = MAX_MAXCHAR(maxchar, ordinal);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002484 n++;
2485 break;
2486 }
2487 case '%':
2488 n++;
2489 break;
2490 case 'i':
2491 case 'd':
2492 makefmt(fmt, longflag, longlongflag, size_tflag, zeropad,
2493 width, precision, *f);
2494 if (longflag)
2495 numprinted = sprintf(numberresult, fmt,
2496 va_arg(count, long));
2497#ifdef HAVE_LONG_LONG
2498 else if (longlongflag)
2499 numprinted = sprintf(numberresult, fmt,
2500 va_arg(count, PY_LONG_LONG));
2501#endif
2502 else if (size_tflag)
2503 numprinted = sprintf(numberresult, fmt,
2504 va_arg(count, Py_ssize_t));
2505 else
2506 numprinted = sprintf(numberresult, fmt,
2507 va_arg(count, int));
2508 n += numprinted;
2509 /* advance by +1 to skip over the '\0' */
2510 numberresult += (numprinted + 1);
2511 assert(*(numberresult - 1) == '\0');
2512 assert(*(numberresult - 2) != '\0');
2513 assert(numprinted >= 0);
2514 assert(numberresult <= numberresults + numbersize);
2515 break;
2516 case 'u':
2517 makefmt(fmt, longflag, longlongflag, size_tflag, zeropad,
2518 width, precision, 'u');
2519 if (longflag)
2520 numprinted = sprintf(numberresult, fmt,
2521 va_arg(count, unsigned long));
2522#ifdef HAVE_LONG_LONG
2523 else if (longlongflag)
2524 numprinted = sprintf(numberresult, fmt,
2525 va_arg(count, unsigned PY_LONG_LONG));
2526#endif
2527 else if (size_tflag)
2528 numprinted = sprintf(numberresult, fmt,
2529 va_arg(count, size_t));
2530 else
2531 numprinted = sprintf(numberresult, fmt,
2532 va_arg(count, unsigned int));
2533 n += numprinted;
2534 numberresult += (numprinted + 1);
2535 assert(*(numberresult - 1) == '\0');
2536 assert(*(numberresult - 2) != '\0');
2537 assert(numprinted >= 0);
2538 assert(numberresult <= numberresults + numbersize);
2539 break;
2540 case 'x':
2541 makefmt(fmt, 0, 0, 0, zeropad, width, precision, 'x');
2542 numprinted = sprintf(numberresult, fmt, va_arg(count, int));
2543 n += numprinted;
2544 numberresult += (numprinted + 1);
2545 assert(*(numberresult - 1) == '\0');
2546 assert(*(numberresult - 2) != '\0');
2547 assert(numprinted >= 0);
2548 assert(numberresult <= numberresults + numbersize);
2549 break;
2550 case 'p':
2551 numprinted = sprintf(numberresult, "%p", va_arg(count, void*));
2552 /* %p is ill-defined: ensure leading 0x. */
2553 if (numberresult[1] == 'X')
2554 numberresult[1] = 'x';
2555 else if (numberresult[1] != 'x') {
2556 memmove(numberresult + 2, numberresult,
2557 strlen(numberresult) + 1);
2558 numberresult[0] = '0';
2559 numberresult[1] = 'x';
2560 numprinted += 2;
2561 }
2562 n += numprinted;
2563 numberresult += (numprinted + 1);
2564 assert(*(numberresult - 1) == '\0');
2565 assert(*(numberresult - 2) != '\0');
2566 assert(numprinted >= 0);
2567 assert(numberresult <= numberresults + numbersize);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002568 break;
2569 case 's':
2570 {
2571 /* UTF-8 */
Georg Brandl780b2a62009-05-05 09:19:59 +00002572 const char *s = va_arg(count, const char*);
Victor Stinnera1d12bb2011-12-11 21:53:09 +01002573 PyObject *str = PyUnicode_DecodeUTF8Stateful(s, strlen(s), "replace", NULL);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002574 if (!str)
2575 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002576 /* since PyUnicode_DecodeUTF8 returns already flexible
2577 unicode objects, there is no need to call ready on them */
2578 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str);
Victor Stinnere6abb482012-05-02 01:15:40 +02002579 maxchar = MAX_MAXCHAR(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002580 n += PyUnicode_GET_LENGTH(str);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002581 /* Remember the str and switch to the next slot */
2582 *callresult++ = str;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002583 break;
2584 }
2585 case 'U':
2586 {
2587 PyObject *obj = va_arg(count, PyObject *);
Victor Stinner910337b2011-10-03 03:20:16 +02002588 assert(obj && _PyUnicode_CHECK(obj));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002589 if (PyUnicode_READY(obj) == -1)
2590 goto fail;
2591 argmaxchar = PyUnicode_MAX_CHAR_VALUE(obj);
Victor Stinnere6abb482012-05-02 01:15:40 +02002592 maxchar = MAX_MAXCHAR(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002593 n += PyUnicode_GET_LENGTH(obj);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002594 break;
2595 }
2596 case 'V':
2597 {
2598 PyObject *obj = va_arg(count, PyObject *);
2599 const char *str = va_arg(count, const char *);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002600 PyObject *str_obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002601 assert(obj || str);
Victor Stinner910337b2011-10-03 03:20:16 +02002602 assert(!obj || _PyUnicode_CHECK(obj));
Victor Stinner2512a8b2011-03-01 22:46:52 +00002603 if (obj) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002604 if (PyUnicode_READY(obj) == -1)
2605 goto fail;
2606 argmaxchar = PyUnicode_MAX_CHAR_VALUE(obj);
Victor Stinnere6abb482012-05-02 01:15:40 +02002607 maxchar = MAX_MAXCHAR(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002608 n += PyUnicode_GET_LENGTH(obj);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002609 *callresult++ = NULL;
2610 }
2611 else {
Victor Stinnera1d12bb2011-12-11 21:53:09 +01002612 str_obj = PyUnicode_DecodeUTF8Stateful(str, strlen(str), "replace", NULL);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002613 if (!str_obj)
2614 goto fail;
Benjamin Petersonbac79492012-01-14 13:34:47 -05002615 if (PyUnicode_READY(str_obj) == -1) {
Victor Stinnere1335c72011-10-04 20:53:03 +02002616 Py_DECREF(str_obj);
2617 goto fail;
2618 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002619 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str_obj);
Victor Stinnere6abb482012-05-02 01:15:40 +02002620 maxchar = MAX_MAXCHAR(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002621 n += PyUnicode_GET_LENGTH(str_obj);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002622 *callresult++ = str_obj;
2623 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002624 break;
2625 }
2626 case 'S':
2627 {
2628 PyObject *obj = va_arg(count, PyObject *);
2629 PyObject *str;
2630 assert(obj);
2631 str = PyObject_Str(obj);
Benjamin Petersonc8d8b882012-01-14 13:37:31 -05002632 if (!str)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002633 goto fail;
Benjamin Petersonc8d8b882012-01-14 13:37:31 -05002634 if (PyUnicode_READY(str) == -1) {
2635 Py_DECREF(str);
2636 goto fail;
2637 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002638 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str);
Victor Stinnere6abb482012-05-02 01:15:40 +02002639 maxchar = MAX_MAXCHAR(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002640 n += PyUnicode_GET_LENGTH(str);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002641 /* Remember the str and switch to the next slot */
2642 *callresult++ = str;
2643 break;
2644 }
2645 case 'R':
2646 {
2647 PyObject *obj = va_arg(count, PyObject *);
2648 PyObject *repr;
2649 assert(obj);
2650 repr = PyObject_Repr(obj);
Benjamin Petersonc8d8b882012-01-14 13:37:31 -05002651 if (!repr)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002652 goto fail;
Benjamin Petersonc8d8b882012-01-14 13:37:31 -05002653 if (PyUnicode_READY(repr) == -1) {
2654 Py_DECREF(repr);
2655 goto fail;
2656 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002657 argmaxchar = PyUnicode_MAX_CHAR_VALUE(repr);
Victor Stinnere6abb482012-05-02 01:15:40 +02002658 maxchar = MAX_MAXCHAR(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002659 n += PyUnicode_GET_LENGTH(repr);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002660 /* Remember the repr and switch to the next slot */
2661 *callresult++ = repr;
2662 break;
2663 }
2664 case 'A':
2665 {
2666 PyObject *obj = va_arg(count, PyObject *);
2667 PyObject *ascii;
2668 assert(obj);
2669 ascii = PyObject_ASCII(obj);
Benjamin Petersonc8d8b882012-01-14 13:37:31 -05002670 if (!ascii)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002671 goto fail;
Benjamin Petersonc8d8b882012-01-14 13:37:31 -05002672 if (PyUnicode_READY(ascii) == -1) {
2673 Py_DECREF(ascii);
2674 goto fail;
2675 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002676 argmaxchar = PyUnicode_MAX_CHAR_VALUE(ascii);
Victor Stinnere6abb482012-05-02 01:15:40 +02002677 maxchar = MAX_MAXCHAR(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002678 n += PyUnicode_GET_LENGTH(ascii);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002679 /* Remember the repr and switch to the next slot */
2680 *callresult++ = ascii;
2681 break;
2682 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002683 default:
2684 /* if we stumble upon an unknown
2685 formatting code, copy the rest of
2686 the format string to the output
2687 string. (we cannot just skip the
2688 code, since there's no way to know
2689 what's in the argument list) */
2690 n += strlen(p);
2691 goto expand;
2692 }
2693 } else
2694 n++;
2695 }
Benjamin Peterson29060642009-01-31 22:14:21 +00002696 expand:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002697 /* step 4: fill the buffer */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002698 /* Since we've analyzed how much space we need,
Benjamin Peterson14339b62009-01-31 16:36:08 +00002699 we don't have to resize the string.
2700 There can be no errors beyond this point. */
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002701 string = PyUnicode_New(n, maxchar);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002702 if (!string)
2703 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002704 kind = PyUnicode_KIND(string);
2705 data = PyUnicode_DATA(string);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002706 callresult = callresults;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002707 numberresult = numberresults;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002708
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002709 for (i = 0, f = format; *f; f++) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00002710 if (*f == '%') {
Victor Stinner96865452011-03-01 23:44:09 +00002711 const char* p;
Victor Stinner96865452011-03-01 23:44:09 +00002712
2713 p = f;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002714 f = parse_format_flags(f, NULL, NULL, NULL, NULL, NULL);
2715 /* checking for == because the last argument could be a empty
2716 string, which causes i to point to end, the assert at the end of
2717 the loop */
2718 assert(i <= PyUnicode_GET_LENGTH(string));
Walter Dörwaldd2034312007-05-18 16:29:38 +00002719
Benjamin Peterson14339b62009-01-31 16:36:08 +00002720 switch (*f) {
2721 case 'c':
Victor Stinner5ed8b2c2011-02-21 21:13:44 +00002722 {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002723 const int ordinal = va_arg(vargs, int);
2724 PyUnicode_WRITE(kind, data, i++, ordinal);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002725 break;
Victor Stinner5ed8b2c2011-02-21 21:13:44 +00002726 }
Victor Stinner6d970f42011-03-02 00:04:25 +00002727 case 'i':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002728 case 'd':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002729 case 'u':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002730 case 'x':
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002731 case 'p':
Victor Stinnerc5166102012-02-22 13:55:02 +01002732 {
Victor Stinner184252a2012-06-16 02:57:41 +02002733 Py_ssize_t len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002734 /* unused, since we already have the result */
2735 if (*f == 'p')
2736 (void) va_arg(vargs, void *);
2737 else
2738 (void) va_arg(vargs, int);
2739 /* extract the result from numberresults and append. */
Victor Stinner184252a2012-06-16 02:57:41 +02002740 len = strlen(numberresult);
2741 unicode_write_cstr(string, i, numberresult, len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002742 /* skip over the separating '\0' */
Victor Stinner184252a2012-06-16 02:57:41 +02002743 i += len;
2744 numberresult += len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002745 assert(*numberresult == '\0');
2746 numberresult++;
2747 assert(numberresult <= numberresults + numbersize);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002748 break;
Victor Stinnerc5166102012-02-22 13:55:02 +01002749 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002750 case 's':
2751 {
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002752 /* unused, since we already have the result */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002753 Py_ssize_t size;
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002754 (void) va_arg(vargs, char *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002755 size = PyUnicode_GET_LENGTH(*callresult);
2756 assert(PyUnicode_KIND(*callresult) <= PyUnicode_KIND(string));
Victor Stinnerd3f08822012-05-29 12:57:52 +02002757 _PyUnicode_FastCopyCharacters(string, i, *callresult, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002758 i += size;
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002759 /* We're done with the unicode()/repr() => forget it */
2760 Py_DECREF(*callresult);
2761 /* switch to next unicode()/repr() result */
2762 ++callresult;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002763 break;
2764 }
2765 case 'U':
2766 {
2767 PyObject *obj = va_arg(vargs, PyObject *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002768 Py_ssize_t size;
2769 assert(PyUnicode_KIND(obj) <= PyUnicode_KIND(string));
2770 size = PyUnicode_GET_LENGTH(obj);
Victor Stinnerd3f08822012-05-29 12:57:52 +02002771 _PyUnicode_FastCopyCharacters(string, i, obj, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002772 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002773 break;
2774 }
2775 case 'V':
2776 {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002777 Py_ssize_t size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002778 PyObject *obj = va_arg(vargs, PyObject *);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002779 va_arg(vargs, const char *);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002780 if (obj) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002781 size = PyUnicode_GET_LENGTH(obj);
2782 assert(PyUnicode_KIND(obj) <= PyUnicode_KIND(string));
Victor Stinnerd3f08822012-05-29 12:57:52 +02002783 _PyUnicode_FastCopyCharacters(string, i, obj, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002784 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002785 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002786 size = PyUnicode_GET_LENGTH(*callresult);
2787 assert(PyUnicode_KIND(*callresult) <=
2788 PyUnicode_KIND(string));
Victor Stinnerd3f08822012-05-29 12:57:52 +02002789 _PyUnicode_FastCopyCharacters(string, i, *callresult, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002790 i += size;
Victor Stinner2512a8b2011-03-01 22:46:52 +00002791 Py_DECREF(*callresult);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002792 }
Victor Stinner2512a8b2011-03-01 22:46:52 +00002793 ++callresult;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002794 break;
2795 }
2796 case 'S':
2797 case 'R':
Victor Stinner9a909002010-10-18 20:59:24 +00002798 case 'A':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002799 {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002800 Py_ssize_t size = PyUnicode_GET_LENGTH(*callresult);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002801 /* unused, since we already have the result */
2802 (void) va_arg(vargs, PyObject *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002803 assert(PyUnicode_KIND(*callresult) <= PyUnicode_KIND(string));
Victor Stinnerd3f08822012-05-29 12:57:52 +02002804 _PyUnicode_FastCopyCharacters(string, i, *callresult, 0, size);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002805 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002806 /* We're done with the unicode()/repr() => forget it */
2807 Py_DECREF(*callresult);
2808 /* switch to next unicode()/repr() result */
2809 ++callresult;
2810 break;
2811 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002812 case '%':
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002813 PyUnicode_WRITE(kind, data, i++, '%');
Benjamin Peterson14339b62009-01-31 16:36:08 +00002814 break;
2815 default:
Victor Stinner184252a2012-06-16 02:57:41 +02002816 {
2817 Py_ssize_t len = strlen(p);
2818 unicode_write_cstr(string, i, p, len);
2819 i += len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002820 assert(i == PyUnicode_GET_LENGTH(string));
Benjamin Peterson14339b62009-01-31 16:36:08 +00002821 goto end;
2822 }
Victor Stinner184252a2012-06-16 02:57:41 +02002823 }
Victor Stinner1205f272010-09-11 00:54:47 +00002824 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002825 else {
2826 assert(i < PyUnicode_GET_LENGTH(string));
2827 PyUnicode_WRITE(kind, data, i++, *f);
2828 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002829 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002830 assert(i == PyUnicode_GET_LENGTH(string));
Walter Dörwaldd2034312007-05-18 16:29:38 +00002831
Benjamin Peterson29060642009-01-31 22:14:21 +00002832 end:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002833 if (callresults)
2834 PyObject_Free(callresults);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002835 if (numberresults)
2836 PyObject_Free(numberresults);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002837 return unicode_result(string);
Benjamin Peterson29060642009-01-31 22:14:21 +00002838 fail:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002839 if (callresults) {
2840 PyObject **callresult2 = callresults;
2841 while (callresult2 < callresult) {
Victor Stinner2512a8b2011-03-01 22:46:52 +00002842 Py_XDECREF(*callresult2);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002843 ++callresult2;
2844 }
2845 PyObject_Free(callresults);
2846 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002847 if (numberresults)
2848 PyObject_Free(numberresults);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002849 return NULL;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002850}
2851
Walter Dörwaldd2034312007-05-18 16:29:38 +00002852PyObject *
2853PyUnicode_FromFormat(const char *format, ...)
2854{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002855 PyObject* ret;
2856 va_list vargs;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002857
2858#ifdef HAVE_STDARG_PROTOTYPES
Benjamin Peterson14339b62009-01-31 16:36:08 +00002859 va_start(vargs, format);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002860#else
Benjamin Peterson14339b62009-01-31 16:36:08 +00002861 va_start(vargs);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002862#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00002863 ret = PyUnicode_FromFormatV(format, vargs);
2864 va_end(vargs);
2865 return ret;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002866}
2867
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002868#ifdef HAVE_WCHAR_H
2869
Victor Stinner5593d8a2010-10-02 11:11:27 +00002870/* Helper function for PyUnicode_AsWideChar() and PyUnicode_AsWideCharString():
2871 convert a Unicode object to a wide character string.
2872
Victor Stinnerd88d9832011-09-06 02:00:05 +02002873 - If w is NULL: return the number of wide characters (including the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002874 character) required to convert the unicode object. Ignore size argument.
2875
Victor Stinnerd88d9832011-09-06 02:00:05 +02002876 - Otherwise: return the number of wide characters (excluding the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002877 character) written into w. Write at most size wide characters (including
Victor Stinnerd88d9832011-09-06 02:00:05 +02002878 the null character). */
Victor Stinner5593d8a2010-10-02 11:11:27 +00002879static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002880unicode_aswidechar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002881 wchar_t *w,
2882 Py_ssize_t size)
2883{
Victor Stinner5593d8a2010-10-02 11:11:27 +00002884 Py_ssize_t res;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002885 const wchar_t *wstr;
2886
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002887 wstr = PyUnicode_AsUnicodeAndSize(unicode, &res);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002888 if (wstr == NULL)
2889 return -1;
2890
Victor Stinner5593d8a2010-10-02 11:11:27 +00002891 if (w != NULL) {
Victor Stinner5593d8a2010-10-02 11:11:27 +00002892 if (size > res)
2893 size = res + 1;
2894 else
2895 res = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002896 Py_MEMCPY(w, wstr, size * sizeof(wchar_t));
Victor Stinner5593d8a2010-10-02 11:11:27 +00002897 return res;
2898 }
2899 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002900 return res + 1;
Victor Stinner137c34c2010-09-29 10:25:54 +00002901}
2902
2903Py_ssize_t
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002904PyUnicode_AsWideChar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002905 wchar_t *w,
2906 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002907{
2908 if (unicode == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002909 PyErr_BadInternalCall();
2910 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002911 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002912 return unicode_aswidechar(unicode, w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002913}
2914
Victor Stinner137c34c2010-09-29 10:25:54 +00002915wchar_t*
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00002916PyUnicode_AsWideCharString(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002917 Py_ssize_t *size)
2918{
2919 wchar_t* buffer;
2920 Py_ssize_t buflen;
2921
2922 if (unicode == NULL) {
2923 PyErr_BadInternalCall();
2924 return NULL;
2925 }
2926
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002927 buflen = unicode_aswidechar(unicode, NULL, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002928 if (buflen == -1)
2929 return NULL;
Victor Stinner5593d8a2010-10-02 11:11:27 +00002930 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < buflen) {
Victor Stinner137c34c2010-09-29 10:25:54 +00002931 PyErr_NoMemory();
2932 return NULL;
2933 }
2934
Victor Stinner137c34c2010-09-29 10:25:54 +00002935 buffer = PyMem_MALLOC(buflen * sizeof(wchar_t));
2936 if (buffer == NULL) {
2937 PyErr_NoMemory();
2938 return NULL;
2939 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002940 buflen = unicode_aswidechar(unicode, buffer, buflen);
Stefan Krah8528c312012-08-19 21:52:43 +02002941 if (buflen == -1) {
2942 PyMem_FREE(buffer);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002943 return NULL;
Stefan Krah8528c312012-08-19 21:52:43 +02002944 }
Victor Stinner5593d8a2010-10-02 11:11:27 +00002945 if (size != NULL)
2946 *size = buflen;
Victor Stinner137c34c2010-09-29 10:25:54 +00002947 return buffer;
2948}
2949
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002950#endif /* HAVE_WCHAR_H */
Guido van Rossumd57fd912000-03-10 22:53:23 +00002951
Alexander Belopolsky40018472011-02-26 01:02:56 +00002952PyObject *
2953PyUnicode_FromOrdinal(int ordinal)
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002954{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002955 PyObject *v;
Victor Stinner8faf8212011-12-08 22:14:11 +01002956 if (ordinal < 0 || ordinal > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002957 PyErr_SetString(PyExc_ValueError,
2958 "chr() arg not in range(0x110000)");
2959 return NULL;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002960 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00002961
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002962 if (ordinal < 256)
2963 return get_latin1_char(ordinal);
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002964
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002965 v = PyUnicode_New(1, ordinal);
2966 if (v == NULL)
2967 return NULL;
2968 PyUnicode_WRITE(PyUnicode_KIND(v), PyUnicode_DATA(v), 0, ordinal);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002969 assert(_PyUnicode_CheckConsistency(v, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002970 return v;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002971}
2972
Alexander Belopolsky40018472011-02-26 01:02:56 +00002973PyObject *
2974PyUnicode_FromObject(register PyObject *obj)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002975{
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002976 /* XXX Perhaps we should make this API an alias of
Benjamin Peterson29060642009-01-31 22:14:21 +00002977 PyObject_Str() instead ?! */
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002978 if (PyUnicode_CheckExact(obj)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -05002979 if (PyUnicode_READY(obj) == -1)
Victor Stinnerd3a83d52011-10-01 03:09:33 +02002980 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +00002981 Py_INCREF(obj);
2982 return obj;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002983 }
2984 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002985 /* For a Unicode subtype that's not a Unicode object,
2986 return a true Unicode object with the same data. */
Victor Stinnerbf6e5602011-12-12 01:53:47 +01002987 return _PyUnicode_Copy(obj);
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002988 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00002989 PyErr_Format(PyExc_TypeError,
2990 "Can't convert '%.100s' object to str implicitly",
Christian Heimes90aa7642007-12-19 02:45:37 +00002991 Py_TYPE(obj)->tp_name);
Guido van Rossum98297ee2007-11-06 21:34:58 +00002992 return NULL;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002993}
2994
Alexander Belopolsky40018472011-02-26 01:02:56 +00002995PyObject *
2996PyUnicode_FromEncodedObject(register PyObject *obj,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002997 const char *encoding,
2998 const char *errors)
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002999{
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003000 Py_buffer buffer;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003001 PyObject *v;
Tim Petersced69f82003-09-16 20:30:58 +00003002
Guido van Rossumd57fd912000-03-10 22:53:23 +00003003 if (obj == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003004 PyErr_BadInternalCall();
3005 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003006 }
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003007
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003008 /* Decoding bytes objects is the most common case and should be fast */
3009 if (PyBytes_Check(obj)) {
3010 if (PyBytes_GET_SIZE(obj) == 0) {
3011 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02003012 v = unicode_empty;
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003013 }
3014 else {
3015 v = PyUnicode_Decode(
3016 PyBytes_AS_STRING(obj), PyBytes_GET_SIZE(obj),
3017 encoding, errors);
3018 }
3019 return v;
3020 }
3021
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003022 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003023 PyErr_SetString(PyExc_TypeError,
3024 "decoding str is not supported");
3025 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +00003026 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003027
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003028 /* Retrieve a bytes buffer view through the PEP 3118 buffer interface */
3029 if (PyObject_GetBuffer(obj, &buffer, PyBUF_SIMPLE) < 0) {
3030 PyErr_Format(PyExc_TypeError,
3031 "coercing to str: need bytes, bytearray "
3032 "or buffer-like object, %.80s found",
3033 Py_TYPE(obj)->tp_name);
3034 return NULL;
Marc-André Lemburg6871f6a2001-09-20 12:53:16 +00003035 }
Tim Petersced69f82003-09-16 20:30:58 +00003036
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003037 if (buffer.len == 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003038 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02003039 v = unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003040 }
Tim Petersced69f82003-09-16 20:30:58 +00003041 else
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003042 v = PyUnicode_Decode((char*) buffer.buf, buffer.len, encoding, errors);
Marc-André Lemburgad7c98e2001-01-17 17:09:53 +00003043
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003044 PyBuffer_Release(&buffer);
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003045 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003046}
3047
Victor Stinner600d3be2010-06-10 12:00:55 +00003048/* Convert encoding to lower case and replace '_' with '-' in order to
Victor Stinner37296e82010-06-10 13:36:23 +00003049 catch e.g. UTF_8. Return 0 on error (encoding is longer than lower_len-1),
3050 1 on success. */
Victor Stinner20b654a2013-01-03 01:08:58 +01003051int
3052_Py_normalize_encoding(const char *encoding,
Victor Stinner37296e82010-06-10 13:36:23 +00003053 char *lower,
3054 size_t lower_len)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003055{
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003056 const char *e;
Victor Stinner600d3be2010-06-10 12:00:55 +00003057 char *l;
3058 char *l_end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003059
Benjamin Peterson7a6debe2011-10-15 09:25:28 -04003060 if (encoding == NULL) {
3061 strcpy(lower, "utf-8");
3062 return 1;
3063 }
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003064 e = encoding;
3065 l = lower;
Victor Stinner600d3be2010-06-10 12:00:55 +00003066 l_end = &lower[lower_len - 1];
Victor Stinner37296e82010-06-10 13:36:23 +00003067 while (*e) {
3068 if (l == l_end)
3069 return 0;
David Malcolm96960882010-11-05 17:23:41 +00003070 if (Py_ISUPPER(*e)) {
3071 *l++ = Py_TOLOWER(*e++);
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003072 }
3073 else if (*e == '_') {
3074 *l++ = '-';
3075 e++;
3076 }
3077 else {
3078 *l++ = *e++;
3079 }
3080 }
3081 *l = '\0';
Victor Stinner37296e82010-06-10 13:36:23 +00003082 return 1;
Victor Stinner600d3be2010-06-10 12:00:55 +00003083}
3084
Alexander Belopolsky40018472011-02-26 01:02:56 +00003085PyObject *
3086PyUnicode_Decode(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003087 Py_ssize_t size,
3088 const char *encoding,
3089 const char *errors)
Victor Stinner600d3be2010-06-10 12:00:55 +00003090{
3091 PyObject *buffer = NULL, *unicode;
3092 Py_buffer info;
3093 char lower[11]; /* Enough for any encoding shortcut */
3094
Fred Drakee4315f52000-05-09 19:53:39 +00003095 /* Shortcuts for common default encodings */
Victor Stinner20b654a2013-01-03 01:08:58 +01003096 if (_Py_normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003097 if ((strcmp(lower, "utf-8") == 0) ||
3098 (strcmp(lower, "utf8") == 0))
Victor Stinnera1d12bb2011-12-11 21:53:09 +01003099 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
Victor Stinner37296e82010-06-10 13:36:23 +00003100 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003101 (strcmp(lower, "latin1") == 0) ||
Victor Stinner37296e82010-06-10 13:36:23 +00003102 (strcmp(lower, "iso-8859-1") == 0))
3103 return PyUnicode_DecodeLatin1(s, size, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02003104#ifdef HAVE_MBCS
Victor Stinner37296e82010-06-10 13:36:23 +00003105 else if (strcmp(lower, "mbcs") == 0)
3106 return PyUnicode_DecodeMBCS(s, size, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003107#endif
Victor Stinner37296e82010-06-10 13:36:23 +00003108 else if (strcmp(lower, "ascii") == 0)
3109 return PyUnicode_DecodeASCII(s, size, errors);
3110 else if (strcmp(lower, "utf-16") == 0)
3111 return PyUnicode_DecodeUTF16(s, size, errors, 0);
3112 else if (strcmp(lower, "utf-32") == 0)
3113 return PyUnicode_DecodeUTF32(s, size, errors, 0);
3114 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003115
3116 /* Decode via the codec registry */
Guido van Rossumbe801ac2007-10-08 03:32:34 +00003117 buffer = NULL;
Antoine Pitrouc3b39242009-01-03 16:59:18 +00003118 if (PyBuffer_FillInfo(&info, NULL, (void *)s, size, 1, PyBUF_FULL_RO) < 0)
Guido van Rossumbe801ac2007-10-08 03:32:34 +00003119 goto onError;
Antoine Pitrouee58fa42008-08-19 18:22:14 +00003120 buffer = PyMemoryView_FromBuffer(&info);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003121 if (buffer == NULL)
3122 goto onError;
3123 unicode = PyCodec_Decode(buffer, encoding, errors);
3124 if (unicode == NULL)
3125 goto onError;
3126 if (!PyUnicode_Check(unicode)) {
3127 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00003128 "decoder did not return a str object (type=%.400s)",
Christian Heimes90aa7642007-12-19 02:45:37 +00003129 Py_TYPE(unicode)->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003130 Py_DECREF(unicode);
3131 goto onError;
3132 }
3133 Py_DECREF(buffer);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003134 return unicode_result(unicode);
Tim Petersced69f82003-09-16 20:30:58 +00003135
Benjamin Peterson29060642009-01-31 22:14:21 +00003136 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003137 Py_XDECREF(buffer);
3138 return NULL;
3139}
3140
Alexander Belopolsky40018472011-02-26 01:02:56 +00003141PyObject *
3142PyUnicode_AsDecodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003143 const char *encoding,
3144 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003145{
3146 PyObject *v;
3147
3148 if (!PyUnicode_Check(unicode)) {
3149 PyErr_BadArgument();
3150 goto onError;
3151 }
3152
3153 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003154 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003155
3156 /* Decode via the codec registry */
3157 v = PyCodec_Decode(unicode, encoding, errors);
3158 if (v == NULL)
3159 goto onError;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003160 return unicode_result(v);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003161
Benjamin Peterson29060642009-01-31 22:14:21 +00003162 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003163 return NULL;
3164}
3165
Alexander Belopolsky40018472011-02-26 01:02:56 +00003166PyObject *
3167PyUnicode_AsDecodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003168 const char *encoding,
3169 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003170{
3171 PyObject *v;
3172
3173 if (!PyUnicode_Check(unicode)) {
3174 PyErr_BadArgument();
3175 goto onError;
3176 }
3177
3178 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003179 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003180
3181 /* Decode via the codec registry */
3182 v = PyCodec_Decode(unicode, encoding, errors);
3183 if (v == NULL)
3184 goto onError;
3185 if (!PyUnicode_Check(v)) {
3186 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00003187 "decoder did not return a str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003188 Py_TYPE(v)->tp_name);
3189 Py_DECREF(v);
3190 goto onError;
3191 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003192 return unicode_result(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003193
Benjamin Peterson29060642009-01-31 22:14:21 +00003194 onError:
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003195 return NULL;
3196}
3197
Alexander Belopolsky40018472011-02-26 01:02:56 +00003198PyObject *
3199PyUnicode_Encode(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003200 Py_ssize_t size,
3201 const char *encoding,
3202 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003203{
3204 PyObject *v, *unicode;
Tim Petersced69f82003-09-16 20:30:58 +00003205
Guido van Rossumd57fd912000-03-10 22:53:23 +00003206 unicode = PyUnicode_FromUnicode(s, size);
3207 if (unicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003208 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003209 v = PyUnicode_AsEncodedString(unicode, encoding, errors);
3210 Py_DECREF(unicode);
3211 return v;
3212}
3213
Alexander Belopolsky40018472011-02-26 01:02:56 +00003214PyObject *
3215PyUnicode_AsEncodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003216 const char *encoding,
3217 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003218{
3219 PyObject *v;
3220
3221 if (!PyUnicode_Check(unicode)) {
3222 PyErr_BadArgument();
3223 goto onError;
3224 }
3225
3226 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003227 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003228
3229 /* Encode via the codec registry */
3230 v = PyCodec_Encode(unicode, encoding, errors);
3231 if (v == NULL)
3232 goto onError;
3233 return v;
3234
Benjamin Peterson29060642009-01-31 22:14:21 +00003235 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003236 return NULL;
3237}
3238
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003239static size_t
3240wcstombs_errorpos(const wchar_t *wstr)
3241{
3242 size_t len;
3243#if SIZEOF_WCHAR_T == 2
3244 wchar_t buf[3];
3245#else
3246 wchar_t buf[2];
3247#endif
3248 char outbuf[MB_LEN_MAX];
3249 const wchar_t *start, *previous;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003250
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003251#if SIZEOF_WCHAR_T == 2
3252 buf[2] = 0;
3253#else
3254 buf[1] = 0;
3255#endif
3256 start = wstr;
3257 while (*wstr != L'\0')
3258 {
3259 previous = wstr;
3260#if SIZEOF_WCHAR_T == 2
3261 if (Py_UNICODE_IS_HIGH_SURROGATE(wstr[0])
3262 && Py_UNICODE_IS_LOW_SURROGATE(wstr[1]))
3263 {
3264 buf[0] = wstr[0];
3265 buf[1] = wstr[1];
3266 wstr += 2;
3267 }
3268 else {
3269 buf[0] = *wstr;
3270 buf[1] = 0;
3271 wstr++;
3272 }
3273#else
3274 buf[0] = *wstr;
3275 wstr++;
3276#endif
3277 len = wcstombs(outbuf, buf, sizeof(outbuf));
Victor Stinner2f197072011-12-17 07:08:30 +01003278 if (len == (size_t)-1)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003279 return previous - start;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003280 }
3281
3282 /* failed to find the unencodable character */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003283 return 0;
3284}
3285
Victor Stinner1b579672011-12-17 05:47:23 +01003286static int
3287locale_error_handler(const char *errors, int *surrogateescape)
3288{
3289 if (errors == NULL) {
3290 *surrogateescape = 0;
3291 return 0;
3292 }
3293
3294 if (strcmp(errors, "strict") == 0) {
3295 *surrogateescape = 0;
3296 return 0;
3297 }
3298 if (strcmp(errors, "surrogateescape") == 0) {
3299 *surrogateescape = 1;
3300 return 0;
3301 }
3302 PyErr_Format(PyExc_ValueError,
3303 "only 'strict' and 'surrogateescape' error handlers "
3304 "are supported, not '%s'",
3305 errors);
3306 return -1;
3307}
3308
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003309PyObject *
Victor Stinner1b579672011-12-17 05:47:23 +01003310PyUnicode_EncodeLocale(PyObject *unicode, const char *errors)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003311{
3312 Py_ssize_t wlen, wlen2;
3313 wchar_t *wstr;
3314 PyObject *bytes = NULL;
3315 char *errmsg;
Victor Stinner1f33f2b2011-12-17 04:45:09 +01003316 PyObject *reason;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003317 PyObject *exc;
3318 size_t error_pos;
Victor Stinner1b579672011-12-17 05:47:23 +01003319 int surrogateescape;
3320
3321 if (locale_error_handler(errors, &surrogateescape) < 0)
3322 return NULL;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003323
3324 wstr = PyUnicode_AsWideCharString(unicode, &wlen);
3325 if (wstr == NULL)
3326 return NULL;
3327
3328 wlen2 = wcslen(wstr);
3329 if (wlen2 != wlen) {
3330 PyMem_Free(wstr);
3331 PyErr_SetString(PyExc_TypeError, "embedded null character");
3332 return NULL;
3333 }
3334
3335 if (surrogateescape) {
3336 /* locale encoding with surrogateescape */
3337 char *str;
3338
3339 str = _Py_wchar2char(wstr, &error_pos);
3340 if (str == NULL) {
3341 if (error_pos == (size_t)-1) {
3342 PyErr_NoMemory();
3343 PyMem_Free(wstr);
3344 return NULL;
3345 }
3346 else {
3347 goto encode_error;
3348 }
3349 }
3350 PyMem_Free(wstr);
3351
3352 bytes = PyBytes_FromString(str);
3353 PyMem_Free(str);
3354 }
3355 else {
3356 size_t len, len2;
3357
3358 len = wcstombs(NULL, wstr, 0);
3359 if (len == (size_t)-1) {
Victor Stinner2f197072011-12-17 07:08:30 +01003360 error_pos = (size_t)-1;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003361 goto encode_error;
3362 }
3363
3364 bytes = PyBytes_FromStringAndSize(NULL, len);
3365 if (bytes == NULL) {
3366 PyMem_Free(wstr);
3367 return NULL;
3368 }
3369
3370 len2 = wcstombs(PyBytes_AS_STRING(bytes), wstr, len+1);
3371 if (len2 == (size_t)-1 || len2 > len) {
Victor Stinner2f197072011-12-17 07:08:30 +01003372 error_pos = (size_t)-1;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003373 goto encode_error;
3374 }
3375 PyMem_Free(wstr);
3376 }
3377 return bytes;
3378
3379encode_error:
3380 errmsg = strerror(errno);
3381 assert(errmsg != NULL);
Victor Stinner2f197072011-12-17 07:08:30 +01003382
3383 if (error_pos == (size_t)-1)
3384 error_pos = wcstombs_errorpos(wstr);
3385
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003386 PyMem_Free(wstr);
3387 Py_XDECREF(bytes);
3388
Victor Stinner2f197072011-12-17 07:08:30 +01003389 if (errmsg != NULL) {
3390 size_t errlen;
3391 wstr = _Py_char2wchar(errmsg, &errlen);
3392 if (wstr != NULL) {
3393 reason = PyUnicode_FromWideChar(wstr, errlen);
3394 PyMem_Free(wstr);
3395 } else
3396 errmsg = NULL;
3397 }
3398 if (errmsg == NULL)
Victor Stinner1f33f2b2011-12-17 04:45:09 +01003399 reason = PyUnicode_FromString(
3400 "wcstombs() encountered an unencodable "
3401 "wide character");
3402 if (reason == NULL)
3403 return NULL;
3404
3405 exc = PyObject_CallFunction(PyExc_UnicodeEncodeError, "sOnnO",
3406 "locale", unicode,
3407 (Py_ssize_t)error_pos,
3408 (Py_ssize_t)(error_pos+1),
3409 reason);
3410 Py_DECREF(reason);
3411 if (exc != NULL) {
3412 PyCodec_StrictErrors(exc);
3413 Py_XDECREF(exc);
3414 }
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003415 return NULL;
3416}
3417
Victor Stinnerad158722010-10-27 00:25:46 +00003418PyObject *
3419PyUnicode_EncodeFSDefault(PyObject *unicode)
Victor Stinnerae6265f2010-05-15 16:27:27 +00003420{
Victor Stinner99b95382011-07-04 14:23:54 +02003421#ifdef HAVE_MBCS
Victor Stinnerac931b12011-11-20 18:27:03 +01003422 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003423#elif defined(__APPLE__)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003424 return _PyUnicode_AsUTF8String(unicode, "surrogateescape");
Victor Stinnerad158722010-10-27 00:25:46 +00003425#else
Victor Stinner793b5312011-04-27 00:24:21 +02003426 PyInterpreterState *interp = PyThreadState_GET()->interp;
3427 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3428 cannot use it to encode and decode filenames before it is loaded. Load
3429 the Python codec requires to encode at least its own filename. Use the C
3430 version of the locale codec until the codec registry is initialized and
3431 the Python codec is loaded.
3432
3433 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3434 cannot only rely on it: check also interp->fscodec_initialized for
3435 subinterpreters. */
3436 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Victor Stinnerae6265f2010-05-15 16:27:27 +00003437 return PyUnicode_AsEncodedString(unicode,
3438 Py_FileSystemDefaultEncoding,
3439 "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00003440 }
3441 else {
Victor Stinner1b579672011-12-17 05:47:23 +01003442 return PyUnicode_EncodeLocale(unicode, "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00003443 }
Victor Stinnerad158722010-10-27 00:25:46 +00003444#endif
Victor Stinnerae6265f2010-05-15 16:27:27 +00003445}
3446
Alexander Belopolsky40018472011-02-26 01:02:56 +00003447PyObject *
3448PyUnicode_AsEncodedString(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003449 const char *encoding,
3450 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003451{
3452 PyObject *v;
Victor Stinner600d3be2010-06-10 12:00:55 +00003453 char lower[11]; /* Enough for any encoding shortcut */
Tim Petersced69f82003-09-16 20:30:58 +00003454
Guido van Rossumd57fd912000-03-10 22:53:23 +00003455 if (!PyUnicode_Check(unicode)) {
3456 PyErr_BadArgument();
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003457 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003458 }
Fred Drakee4315f52000-05-09 19:53:39 +00003459
Fred Drakee4315f52000-05-09 19:53:39 +00003460 /* Shortcuts for common default encodings */
Victor Stinner20b654a2013-01-03 01:08:58 +01003461 if (_Py_normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003462 if ((strcmp(lower, "utf-8") == 0) ||
3463 (strcmp(lower, "utf8") == 0))
Victor Stinnera5c68c32011-03-02 01:03:14 +00003464 {
Victor Stinner2f283c22011-03-02 01:21:46 +00003465 if (errors == NULL || strcmp(errors, "strict") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003466 return _PyUnicode_AsUTF8String(unicode, NULL);
Victor Stinner2f283c22011-03-02 01:21:46 +00003467 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003468 return _PyUnicode_AsUTF8String(unicode, errors);
Victor Stinnera5c68c32011-03-02 01:03:14 +00003469 }
Victor Stinner37296e82010-06-10 13:36:23 +00003470 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003471 (strcmp(lower, "latin1") == 0) ||
Victor Stinner37296e82010-06-10 13:36:23 +00003472 (strcmp(lower, "iso-8859-1") == 0))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003473 return _PyUnicode_AsLatin1String(unicode, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02003474#ifdef HAVE_MBCS
Victor Stinnerac931b12011-11-20 18:27:03 +01003475 else if (strcmp(lower, "mbcs") == 0)
3476 return PyUnicode_EncodeCodePage(CP_ACP, unicode, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003477#endif
Victor Stinner37296e82010-06-10 13:36:23 +00003478 else if (strcmp(lower, "ascii") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003479 return _PyUnicode_AsASCIIString(unicode, errors);
Victor Stinner37296e82010-06-10 13:36:23 +00003480 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003481
3482 /* Encode via the codec registry */
3483 v = PyCodec_Encode(unicode, encoding, errors);
3484 if (v == NULL)
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003485 return NULL;
3486
3487 /* The normal path */
3488 if (PyBytes_Check(v))
3489 return v;
3490
3491 /* If the codec returns a buffer, raise a warning and convert to bytes */
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003492 if (PyByteArray_Check(v)) {
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003493 int error;
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003494 PyObject *b;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003495
3496 error = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
3497 "encoder %s returned bytearray instead of bytes",
3498 encoding);
3499 if (error) {
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003500 Py_DECREF(v);
3501 return NULL;
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003502 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003503
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003504 b = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(v), Py_SIZE(v));
3505 Py_DECREF(v);
3506 return b;
3507 }
3508
3509 PyErr_Format(PyExc_TypeError,
3510 "encoder did not return a bytes object (type=%.400s)",
3511 Py_TYPE(v)->tp_name);
3512 Py_DECREF(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003513 return NULL;
3514}
3515
Alexander Belopolsky40018472011-02-26 01:02:56 +00003516PyObject *
3517PyUnicode_AsEncodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003518 const char *encoding,
3519 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003520{
3521 PyObject *v;
3522
3523 if (!PyUnicode_Check(unicode)) {
3524 PyErr_BadArgument();
3525 goto onError;
3526 }
3527
3528 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003529 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003530
3531 /* Encode via the codec registry */
3532 v = PyCodec_Encode(unicode, encoding, errors);
3533 if (v == NULL)
3534 goto onError;
3535 if (!PyUnicode_Check(v)) {
3536 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00003537 "encoder did not return an str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003538 Py_TYPE(v)->tp_name);
3539 Py_DECREF(v);
3540 goto onError;
3541 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003542 return v;
Tim Petersced69f82003-09-16 20:30:58 +00003543
Benjamin Peterson29060642009-01-31 22:14:21 +00003544 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003545 return NULL;
3546}
3547
Victor Stinner2f197072011-12-17 07:08:30 +01003548static size_t
3549mbstowcs_errorpos(const char *str, size_t len)
3550{
3551#ifdef HAVE_MBRTOWC
3552 const char *start = str;
3553 mbstate_t mbs;
3554 size_t converted;
3555 wchar_t ch;
3556
3557 memset(&mbs, 0, sizeof mbs);
3558 while (len)
3559 {
3560 converted = mbrtowc(&ch, (char*)str, len, &mbs);
3561 if (converted == 0)
3562 /* Reached end of string */
3563 break;
3564 if (converted == (size_t)-1 || converted == (size_t)-2) {
3565 /* Conversion error or incomplete character */
3566 return str - start;
3567 }
3568 else {
3569 str += converted;
3570 len -= converted;
3571 }
3572 }
3573 /* failed to find the undecodable byte sequence */
3574 return 0;
3575#endif
3576 return 0;
3577}
3578
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003579PyObject*
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003580PyUnicode_DecodeLocaleAndSize(const char *str, Py_ssize_t len,
Victor Stinner1b579672011-12-17 05:47:23 +01003581 const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003582{
3583 wchar_t smallbuf[256];
3584 size_t smallbuf_len = Py_ARRAY_LENGTH(smallbuf);
3585 wchar_t *wstr;
3586 size_t wlen, wlen2;
3587 PyObject *unicode;
Victor Stinner1b579672011-12-17 05:47:23 +01003588 int surrogateescape;
Victor Stinner2f197072011-12-17 07:08:30 +01003589 size_t error_pos;
3590 char *errmsg;
3591 PyObject *reason, *exc;
Victor Stinner1b579672011-12-17 05:47:23 +01003592
3593 if (locale_error_handler(errors, &surrogateescape) < 0)
3594 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003595
3596 if (str[len] != '\0' || len != strlen(str)) {
3597 PyErr_SetString(PyExc_TypeError, "embedded null character");
3598 return NULL;
3599 }
3600
3601 if (surrogateescape)
3602 {
3603 wstr = _Py_char2wchar(str, &wlen);
3604 if (wstr == NULL) {
3605 if (wlen == (size_t)-1)
3606 PyErr_NoMemory();
3607 else
3608 PyErr_SetFromErrno(PyExc_OSError);
3609 return NULL;
3610 }
3611
3612 unicode = PyUnicode_FromWideChar(wstr, wlen);
3613 PyMem_Free(wstr);
3614 }
3615 else {
3616#ifndef HAVE_BROKEN_MBSTOWCS
3617 wlen = mbstowcs(NULL, str, 0);
3618#else
3619 wlen = len;
3620#endif
Victor Stinner2f197072011-12-17 07:08:30 +01003621 if (wlen == (size_t)-1)
3622 goto decode_error;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003623 if (wlen+1 <= smallbuf_len) {
3624 wstr = smallbuf;
3625 }
3626 else {
3627 if (wlen > PY_SSIZE_T_MAX / sizeof(wchar_t) - 1)
3628 return PyErr_NoMemory();
3629
3630 wstr = PyMem_Malloc((wlen+1) * sizeof(wchar_t));
3631 if (!wstr)
3632 return PyErr_NoMemory();
3633 }
3634
3635 /* This shouldn't fail now */
3636 wlen2 = mbstowcs(wstr, str, wlen+1);
3637 if (wlen2 == (size_t)-1) {
3638 if (wstr != smallbuf)
3639 PyMem_Free(wstr);
Victor Stinner2f197072011-12-17 07:08:30 +01003640 goto decode_error;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003641 }
3642#ifdef HAVE_BROKEN_MBSTOWCS
3643 assert(wlen2 == wlen);
3644#endif
3645 unicode = PyUnicode_FromWideChar(wstr, wlen2);
3646 if (wstr != smallbuf)
3647 PyMem_Free(wstr);
3648 }
3649 return unicode;
Victor Stinner2f197072011-12-17 07:08:30 +01003650
3651decode_error:
3652 errmsg = strerror(errno);
3653 assert(errmsg != NULL);
3654
3655 error_pos = mbstowcs_errorpos(str, len);
3656 if (errmsg != NULL) {
3657 size_t errlen;
3658 wstr = _Py_char2wchar(errmsg, &errlen);
3659 if (wstr != NULL) {
3660 reason = PyUnicode_FromWideChar(wstr, errlen);
3661 PyMem_Free(wstr);
3662 } else
3663 errmsg = NULL;
3664 }
3665 if (errmsg == NULL)
3666 reason = PyUnicode_FromString(
3667 "mbstowcs() encountered an invalid multibyte sequence");
3668 if (reason == NULL)
3669 return NULL;
3670
3671 exc = PyObject_CallFunction(PyExc_UnicodeDecodeError, "sy#nnO",
3672 "locale", str, len,
3673 (Py_ssize_t)error_pos,
3674 (Py_ssize_t)(error_pos+1),
3675 reason);
3676 Py_DECREF(reason);
3677 if (exc != NULL) {
3678 PyCodec_StrictErrors(exc);
3679 Py_XDECREF(exc);
3680 }
3681 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003682}
3683
3684PyObject*
Victor Stinner1b579672011-12-17 05:47:23 +01003685PyUnicode_DecodeLocale(const char *str, const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003686{
3687 Py_ssize_t size = (Py_ssize_t)strlen(str);
Victor Stinner1b579672011-12-17 05:47:23 +01003688 return PyUnicode_DecodeLocaleAndSize(str, size, errors);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003689}
3690
3691
3692PyObject*
Christian Heimes5894ba72007-11-04 11:43:14 +00003693PyUnicode_DecodeFSDefault(const char *s) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003694 Py_ssize_t size = (Py_ssize_t)strlen(s);
Christian Heimes5894ba72007-11-04 11:43:14 +00003695 return PyUnicode_DecodeFSDefaultAndSize(s, size);
3696}
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003697
Christian Heimes5894ba72007-11-04 11:43:14 +00003698PyObject*
3699PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
3700{
Victor Stinner99b95382011-07-04 14:23:54 +02003701#ifdef HAVE_MBCS
Victor Stinnerad158722010-10-27 00:25:46 +00003702 return PyUnicode_DecodeMBCS(s, size, NULL);
3703#elif defined(__APPLE__)
Victor Stinnera1d12bb2011-12-11 21:53:09 +01003704 return PyUnicode_DecodeUTF8Stateful(s, size, "surrogateescape", NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003705#else
Victor Stinner793b5312011-04-27 00:24:21 +02003706 PyInterpreterState *interp = PyThreadState_GET()->interp;
3707 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3708 cannot use it to encode and decode filenames before it is loaded. Load
3709 the Python codec requires to encode at least its own filename. Use the C
3710 version of the locale codec until the codec registry is initialized and
3711 the Python codec is loaded.
3712
3713 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3714 cannot only rely on it: check also interp->fscodec_initialized for
3715 subinterpreters. */
3716 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003717 return PyUnicode_Decode(s, size,
3718 Py_FileSystemDefaultEncoding,
Victor Stinnerb9a20ad2010-04-30 16:37:52 +00003719 "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003720 }
3721 else {
Victor Stinner1b579672011-12-17 05:47:23 +01003722 return PyUnicode_DecodeLocaleAndSize(s, size, "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003723 }
Victor Stinnerad158722010-10-27 00:25:46 +00003724#endif
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003725}
3726
Martin v. Löwis011e8422009-05-05 04:43:17 +00003727
3728int
Antoine Pitrou13348842012-01-29 18:36:34 +01003729_PyUnicode_HasNULChars(PyObject* s)
3730{
3731 static PyObject *nul = NULL;
3732
3733 if (nul == NULL)
3734 nul = PyUnicode_FromStringAndSize("\0", 1);
3735 if (nul == NULL)
3736 return -1;
3737 return PyUnicode_Contains(s, nul);
3738}
3739
3740
3741int
Martin v. Löwis011e8422009-05-05 04:43:17 +00003742PyUnicode_FSConverter(PyObject* arg, void* addr)
3743{
3744 PyObject *output = NULL;
3745 Py_ssize_t size;
3746 void *data;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003747 if (arg == NULL) {
3748 Py_DECREF(*(PyObject**)addr);
3749 return 1;
3750 }
Victor Stinnerdcb24032010-04-22 12:08:36 +00003751 if (PyBytes_Check(arg)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00003752 output = arg;
3753 Py_INCREF(output);
3754 }
3755 else {
3756 arg = PyUnicode_FromObject(arg);
3757 if (!arg)
3758 return 0;
Victor Stinnerae6265f2010-05-15 16:27:27 +00003759 output = PyUnicode_EncodeFSDefault(arg);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003760 Py_DECREF(arg);
3761 if (!output)
3762 return 0;
3763 if (!PyBytes_Check(output)) {
3764 Py_DECREF(output);
3765 PyErr_SetString(PyExc_TypeError, "encoder failed to return bytes");
3766 return 0;
3767 }
3768 }
Victor Stinner0ea2a462010-04-30 00:22:08 +00003769 size = PyBytes_GET_SIZE(output);
3770 data = PyBytes_AS_STRING(output);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003771 if (size != strlen(data)) {
Benjamin Peterson7a6b44a2011-08-18 13:51:47 -05003772 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
Martin v. Löwis011e8422009-05-05 04:43:17 +00003773 Py_DECREF(output);
3774 return 0;
3775 }
3776 *(PyObject**)addr = output;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003777 return Py_CLEANUP_SUPPORTED;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003778}
3779
3780
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003781int
3782PyUnicode_FSDecoder(PyObject* arg, void* addr)
3783{
3784 PyObject *output = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003785 if (arg == NULL) {
3786 Py_DECREF(*(PyObject**)addr);
3787 return 1;
3788 }
3789 if (PyUnicode_Check(arg)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -05003790 if (PyUnicode_READY(arg) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003791 return 0;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003792 output = arg;
3793 Py_INCREF(output);
3794 }
3795 else {
3796 arg = PyBytes_FromObject(arg);
3797 if (!arg)
3798 return 0;
3799 output = PyUnicode_DecodeFSDefaultAndSize(PyBytes_AS_STRING(arg),
3800 PyBytes_GET_SIZE(arg));
3801 Py_DECREF(arg);
3802 if (!output)
3803 return 0;
3804 if (!PyUnicode_Check(output)) {
3805 Py_DECREF(output);
3806 PyErr_SetString(PyExc_TypeError, "decoder failed to return unicode");
3807 return 0;
3808 }
3809 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05003810 if (PyUnicode_READY(output) == -1) {
Victor Stinner065836e2011-10-27 01:56:33 +02003811 Py_DECREF(output);
3812 return 0;
3813 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003814 if (findchar(PyUnicode_DATA(output), PyUnicode_KIND(output),
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02003815 PyUnicode_GET_LENGTH(output), 0, 1) >= 0) {
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003816 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
3817 Py_DECREF(output);
3818 return 0;
3819 }
3820 *(PyObject**)addr = output;
3821 return Py_CLEANUP_SUPPORTED;
3822}
3823
3824
Martin v. Löwis5b222132007-06-10 09:51:05 +00003825char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003826PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *psize)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003827{
Christian Heimesf3863112007-11-22 07:46:41 +00003828 PyObject *bytes;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003829
Neal Norwitze0a0a6e2007-08-25 01:04:21 +00003830 if (!PyUnicode_Check(unicode)) {
3831 PyErr_BadArgument();
3832 return NULL;
3833 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003834 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003835 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003836
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003837 if (PyUnicode_UTF8(unicode) == NULL) {
3838 assert(!PyUnicode_IS_COMPACT_ASCII(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003839 bytes = _PyUnicode_AsUTF8String(unicode, "strict");
3840 if (bytes == NULL)
3841 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003842 _PyUnicode_UTF8(unicode) = PyObject_MALLOC(PyBytes_GET_SIZE(bytes) + 1);
3843 if (_PyUnicode_UTF8(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003844 Py_DECREF(bytes);
3845 return NULL;
3846 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003847 _PyUnicode_UTF8_LENGTH(unicode) = PyBytes_GET_SIZE(bytes);
3848 Py_MEMCPY(_PyUnicode_UTF8(unicode),
3849 PyBytes_AS_STRING(bytes),
3850 _PyUnicode_UTF8_LENGTH(unicode) + 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003851 Py_DECREF(bytes);
3852 }
3853
3854 if (psize)
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003855 *psize = PyUnicode_UTF8_LENGTH(unicode);
3856 return PyUnicode_UTF8(unicode);
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003857}
3858
3859char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003860PyUnicode_AsUTF8(PyObject *unicode)
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003861{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003862 return PyUnicode_AsUTF8AndSize(unicode, NULL);
3863}
3864
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003865Py_UNICODE *
3866PyUnicode_AsUnicodeAndSize(PyObject *unicode, Py_ssize_t *size)
3867{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003868 const unsigned char *one_byte;
3869#if SIZEOF_WCHAR_T == 4
3870 const Py_UCS2 *two_bytes;
3871#else
3872 const Py_UCS4 *four_bytes;
3873 const Py_UCS4 *ucs4_end;
3874 Py_ssize_t num_surrogates;
3875#endif
3876 wchar_t *w;
3877 wchar_t *wchar_end;
3878
3879 if (!PyUnicode_Check(unicode)) {
3880 PyErr_BadArgument();
3881 return NULL;
3882 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003883 if (_PyUnicode_WSTR(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003884 /* Non-ASCII compact unicode object */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003885 assert(_PyUnicode_KIND(unicode) != 0);
3886 assert(PyUnicode_IS_READY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003887
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003888 if (PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003889#if SIZEOF_WCHAR_T == 2
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003890 four_bytes = PyUnicode_4BYTE_DATA(unicode);
3891 ucs4_end = four_bytes + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003892 num_surrogates = 0;
3893
3894 for (; four_bytes < ucs4_end; ++four_bytes) {
3895 if (*four_bytes > 0xFFFF)
3896 ++num_surrogates;
3897 }
3898
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003899 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(
3900 sizeof(wchar_t) * (_PyUnicode_LENGTH(unicode) + 1 + num_surrogates));
3901 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003902 PyErr_NoMemory();
3903 return NULL;
3904 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003905 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode) + num_surrogates;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003906
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003907 w = _PyUnicode_WSTR(unicode);
3908 wchar_end = w + _PyUnicode_WSTR_LENGTH(unicode);
3909 four_bytes = PyUnicode_4BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003910 for (; four_bytes < ucs4_end; ++four_bytes, ++w) {
3911 if (*four_bytes > 0xFFFF) {
Victor Stinner8faf8212011-12-08 22:14:11 +01003912 assert(*four_bytes <= MAX_UNICODE);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003913 /* encode surrogate pair in this case */
Victor Stinner551ac952011-11-29 22:58:13 +01003914 *w++ = Py_UNICODE_HIGH_SURROGATE(*four_bytes);
3915 *w = Py_UNICODE_LOW_SURROGATE(*four_bytes);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003916 }
3917 else
3918 *w = *four_bytes;
3919
3920 if (w > wchar_end) {
3921 assert(0 && "Miscalculated string end");
3922 }
3923 }
3924 *w = 0;
3925#else
3926 /* sizeof(wchar_t) == 4 */
3927 Py_FatalError("Impossible unicode object state, wstr and str "
3928 "should share memory already.");
3929 return NULL;
3930#endif
3931 }
3932 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003933 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(sizeof(wchar_t) *
3934 (_PyUnicode_LENGTH(unicode) + 1));
3935 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003936 PyErr_NoMemory();
3937 return NULL;
3938 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003939 if (!PyUnicode_IS_COMPACT_ASCII(unicode))
3940 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode);
3941 w = _PyUnicode_WSTR(unicode);
3942 wchar_end = w + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003943
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003944 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND) {
3945 one_byte = PyUnicode_1BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003946 for (; w < wchar_end; ++one_byte, ++w)
3947 *w = *one_byte;
3948 /* null-terminate the wstr */
3949 *w = 0;
3950 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003951 else if (PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003952#if SIZEOF_WCHAR_T == 4
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003953 two_bytes = PyUnicode_2BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003954 for (; w < wchar_end; ++two_bytes, ++w)
3955 *w = *two_bytes;
3956 /* null-terminate the wstr */
3957 *w = 0;
3958#else
3959 /* sizeof(wchar_t) == 2 */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003960 PyObject_FREE(_PyUnicode_WSTR(unicode));
3961 _PyUnicode_WSTR(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003962 Py_FatalError("Impossible unicode object state, wstr "
3963 "and str should share memory already.");
3964 return NULL;
3965#endif
3966 }
3967 else {
3968 assert(0 && "This should never happen.");
3969 }
3970 }
3971 }
3972 if (size != NULL)
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003973 *size = PyUnicode_WSTR_LENGTH(unicode);
3974 return _PyUnicode_WSTR(unicode);
Martin v. Löwis5b222132007-06-10 09:51:05 +00003975}
3976
Alexander Belopolsky40018472011-02-26 01:02:56 +00003977Py_UNICODE *
3978PyUnicode_AsUnicode(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003979{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003980 return PyUnicode_AsUnicodeAndSize(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003981}
3982
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003983
Alexander Belopolsky40018472011-02-26 01:02:56 +00003984Py_ssize_t
3985PyUnicode_GetSize(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003986{
3987 if (!PyUnicode_Check(unicode)) {
3988 PyErr_BadArgument();
3989 goto onError;
3990 }
3991 return PyUnicode_GET_SIZE(unicode);
3992
Benjamin Peterson29060642009-01-31 22:14:21 +00003993 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003994 return -1;
3995}
3996
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003997Py_ssize_t
3998PyUnicode_GetLength(PyObject *unicode)
3999{
Victor Stinner07621332012-06-16 04:53:46 +02004000 if (!PyUnicode_Check(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004001 PyErr_BadArgument();
4002 return -1;
4003 }
Victor Stinner07621332012-06-16 04:53:46 +02004004 if (PyUnicode_READY(unicode) == -1)
4005 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004006 return PyUnicode_GET_LENGTH(unicode);
4007}
4008
4009Py_UCS4
4010PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
4011{
Victor Stinner2fe5ced2011-10-02 00:25:40 +02004012 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
4013 PyErr_BadArgument();
4014 return (Py_UCS4)-1;
4015 }
Victor Stinnerc4b49542011-12-11 22:44:26 +01004016 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinner2fe5ced2011-10-02 00:25:40 +02004017 PyErr_SetString(PyExc_IndexError, "string index out of range");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004018 return (Py_UCS4)-1;
4019 }
4020 return PyUnicode_READ_CHAR(unicode, index);
4021}
4022
4023int
4024PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 ch)
4025{
4026 if (!PyUnicode_Check(unicode) || !PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02004027 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004028 return -1;
4029 }
Victor Stinner488fa492011-12-12 00:01:39 +01004030 assert(PyUnicode_IS_READY(unicode));
Victor Stinnerc4b49542011-12-11 22:44:26 +01004031 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02004032 PyErr_SetString(PyExc_IndexError, "string index out of range");
4033 return -1;
4034 }
Victor Stinner488fa492011-12-12 00:01:39 +01004035 if (unicode_check_modifiable(unicode))
Victor Stinnercd9950f2011-10-02 00:34:53 +02004036 return -1;
Victor Stinnerc9590ad2012-03-04 01:34:37 +01004037 if (ch > PyUnicode_MAX_CHAR_VALUE(unicode)) {
4038 PyErr_SetString(PyExc_ValueError, "character out of range");
4039 return -1;
4040 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004041 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
4042 index, ch);
4043 return 0;
4044}
4045
Alexander Belopolsky40018472011-02-26 01:02:56 +00004046const char *
4047PyUnicode_GetDefaultEncoding(void)
Fred Drakee4315f52000-05-09 19:53:39 +00004048{
Victor Stinner42cb4622010-09-01 19:39:01 +00004049 return "utf-8";
Fred Drakee4315f52000-05-09 19:53:39 +00004050}
4051
Victor Stinner554f3f02010-06-16 23:33:54 +00004052/* create or adjust a UnicodeDecodeError */
4053static void
4054make_decode_exception(PyObject **exceptionObject,
4055 const char *encoding,
4056 const char *input, Py_ssize_t length,
4057 Py_ssize_t startpos, Py_ssize_t endpos,
4058 const char *reason)
4059{
4060 if (*exceptionObject == NULL) {
4061 *exceptionObject = PyUnicodeDecodeError_Create(
4062 encoding, input, length, startpos, endpos, reason);
4063 }
4064 else {
4065 if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
4066 goto onError;
4067 if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
4068 goto onError;
4069 if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
4070 goto onError;
4071 }
4072 return;
4073
4074onError:
4075 Py_DECREF(*exceptionObject);
4076 *exceptionObject = NULL;
4077}
4078
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004079/* error handling callback helper:
4080 build arguments, call the callback and check the arguments,
Fred Drakedb390c12005-10-28 14:39:47 +00004081 if no exception occurred, copy the replacement to the output
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004082 and adjust various state variables.
4083 return 0 on success, -1 on error
4084*/
4085
Alexander Belopolsky40018472011-02-26 01:02:56 +00004086static int
4087unicode_decode_call_errorhandler(const char *errors, PyObject **errorHandler,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004088 const char *encoding, const char *reason,
4089 const char **input, const char **inend, Py_ssize_t *startinpos,
4090 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004091 PyObject **output, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004092{
Benjamin Peterson142957c2008-07-04 19:55:29 +00004093 static char *argparse = "O!n;decoding error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004094
4095 PyObject *restuple = NULL;
4096 PyObject *repunicode = NULL;
Victor Stinner596a6c42011-11-09 00:02:18 +01004097 Py_ssize_t outsize;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004098 Py_ssize_t insize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004099 Py_ssize_t requiredsize;
4100 Py_ssize_t newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004101 PyObject *inputobj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004102 int res = -1;
4103
Victor Stinner596a6c42011-11-09 00:02:18 +01004104 if (_PyUnicode_KIND(*output) != PyUnicode_WCHAR_KIND)
4105 outsize = PyUnicode_GET_LENGTH(*output);
4106 else
4107 outsize = _PyUnicode_WSTR_LENGTH(*output);
4108
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004109 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004110 *errorHandler = PyCodec_LookupError(errors);
4111 if (*errorHandler == NULL)
4112 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004113 }
4114
Victor Stinner554f3f02010-06-16 23:33:54 +00004115 make_decode_exception(exceptionObject,
4116 encoding,
4117 *input, *inend - *input,
4118 *startinpos, *endinpos,
4119 reason);
4120 if (*exceptionObject == NULL)
4121 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004122
4123 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
4124 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004125 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004126 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00004127 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00004128 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004129 }
4130 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00004131 goto onError;
Benjamin Petersonbac79492012-01-14 13:34:47 -05004132 if (PyUnicode_READY(repunicode) == -1)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004133 goto onError;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004134
4135 /* Copy back the bytes variables, which might have been modified by the
4136 callback */
4137 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4138 if (!inputobj)
4139 goto onError;
Christian Heimes72b710a2008-05-26 13:28:38 +00004140 if (!PyBytes_Check(inputobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004141 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
Walter Dörwalde78178e2007-07-30 13:31:40 +00004142 }
Christian Heimes72b710a2008-05-26 13:28:38 +00004143 *input = PyBytes_AS_STRING(inputobj);
4144 insize = PyBytes_GET_SIZE(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004145 *inend = *input + insize;
Walter Dörwald36f938f2007-08-10 10:11:43 +00004146 /* we can DECREF safely, as the exception has another reference,
4147 so the object won't go away. */
4148 Py_DECREF(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004149
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004150 if (newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004151 newpos = insize+newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004152 if (newpos<0 || newpos>insize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004153 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
4154 goto onError;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004155 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004156
Victor Stinner596a6c42011-11-09 00:02:18 +01004157 if (_PyUnicode_KIND(*output) != PyUnicode_WCHAR_KIND) {
4158 /* need more space? (at least enough for what we
4159 have+the replacement+the rest of the string (starting
4160 at the new input position), so we won't have to check space
4161 when there are no errors in the rest of the string) */
4162 Py_ssize_t replen = PyUnicode_GET_LENGTH(repunicode);
4163 requiredsize = *outpos + replen + insize-newpos;
4164 if (requiredsize > outsize) {
4165 if (requiredsize<2*outsize)
4166 requiredsize = 2*outsize;
4167 if (unicode_resize(output, requiredsize) < 0)
4168 goto onError;
4169 }
Victor Stinner1b487b42012-05-03 12:29:04 +02004170 if (unicode_widen(output, *outpos,
4171 PyUnicode_MAX_CHAR_VALUE(repunicode)) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004172 goto onError;
Victor Stinnerd3f08822012-05-29 12:57:52 +02004173 _PyUnicode_FastCopyCharacters(*output, *outpos, repunicode, 0, replen);
Victor Stinner596a6c42011-11-09 00:02:18 +01004174 *outpos += replen;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004175 }
Victor Stinner596a6c42011-11-09 00:02:18 +01004176 else {
4177 wchar_t *repwstr;
4178 Py_ssize_t repwlen;
4179 repwstr = PyUnicode_AsUnicodeAndSize(repunicode, &repwlen);
4180 if (repwstr == NULL)
4181 goto onError;
4182 /* need more space? (at least enough for what we
4183 have+the replacement+the rest of the string (starting
4184 at the new input position), so we won't have to check space
4185 when there are no errors in the rest of the string) */
4186 requiredsize = *outpos + repwlen + insize-newpos;
4187 if (requiredsize > outsize) {
4188 if (requiredsize < 2*outsize)
4189 requiredsize = 2*outsize;
4190 if (unicode_resize(output, requiredsize) < 0)
4191 goto onError;
4192 }
4193 wcsncpy(_PyUnicode_WSTR(*output) + *outpos, repwstr, repwlen);
4194 *outpos += repwlen;
4195 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004196 *endinpos = newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004197 *inptr = *input + newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004198
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004199 /* we made it! */
4200 res = 0;
4201
Benjamin Peterson29060642009-01-31 22:14:21 +00004202 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004203 Py_XDECREF(restuple);
4204 return res;
4205}
4206
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004207/* --- UTF-7 Codec -------------------------------------------------------- */
4208
Antoine Pitrou244651a2009-05-04 18:56:13 +00004209/* See RFC2152 for details. We encode conservatively and decode liberally. */
4210
4211/* Three simple macros defining base-64. */
4212
4213/* Is c a base-64 character? */
4214
4215#define IS_BASE64(c) \
4216 (((c) >= 'A' && (c) <= 'Z') || \
4217 ((c) >= 'a' && (c) <= 'z') || \
4218 ((c) >= '0' && (c) <= '9') || \
4219 (c) == '+' || (c) == '/')
4220
4221/* given that c is a base-64 character, what is its base-64 value? */
4222
4223#define FROM_BASE64(c) \
4224 (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' : \
4225 ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 : \
4226 ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 : \
4227 (c) == '+' ? 62 : 63)
4228
4229/* What is the base-64 character of the bottom 6 bits of n? */
4230
4231#define TO_BASE64(n) \
4232 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
4233
4234/* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
4235 * decoded as itself. We are permissive on decoding; the only ASCII
4236 * byte not decoding to itself is the + which begins a base64
4237 * string. */
4238
4239#define DECODE_DIRECT(c) \
4240 ((c) <= 127 && (c) != '+')
4241
4242/* The UTF-7 encoder treats ASCII characters differently according to
4243 * whether they are Set D, Set O, Whitespace, or special (i.e. none of
4244 * the above). See RFC2152. This array identifies these different
4245 * sets:
4246 * 0 : "Set D"
4247 * alphanumeric and '(),-./:?
4248 * 1 : "Set O"
4249 * !"#$%&*;<=>@[]^_`{|}
4250 * 2 : "whitespace"
4251 * ht nl cr sp
4252 * 3 : special (must be base64 encoded)
4253 * everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
4254 */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004255
Tim Petersced69f82003-09-16 20:30:58 +00004256static
Antoine Pitrou244651a2009-05-04 18:56:13 +00004257char utf7_category[128] = {
4258/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
4259 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
4260/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
4261 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
4262/* sp ! " # $ % & ' ( ) * + , - . / */
4263 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
4264/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
4265 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
4266/* @ A B C D E F G H I J K L M N O */
4267 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4268/* P Q R S T U V W X Y Z [ \ ] ^ _ */
4269 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
4270/* ` a b c d e f g h i j k l m n o */
4271 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4272/* p q r s t u v w x y z { | } ~ del */
4273 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004274};
4275
Antoine Pitrou244651a2009-05-04 18:56:13 +00004276/* ENCODE_DIRECT: this character should be encoded as itself. The
4277 * answer depends on whether we are encoding set O as itself, and also
4278 * on whether we are encoding whitespace as itself. RFC2152 makes it
4279 * clear that the answers to these questions vary between
4280 * applications, so this code needs to be flexible. */
Marc-André Lemburge115ec82005-10-19 22:33:31 +00004281
Antoine Pitrou244651a2009-05-04 18:56:13 +00004282#define ENCODE_DIRECT(c, directO, directWS) \
4283 ((c) < 128 && (c) > 0 && \
4284 ((utf7_category[(c)] == 0) || \
4285 (directWS && (utf7_category[(c)] == 2)) || \
4286 (directO && (utf7_category[(c)] == 1))))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004287
Alexander Belopolsky40018472011-02-26 01:02:56 +00004288PyObject *
4289PyUnicode_DecodeUTF7(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004290 Py_ssize_t size,
4291 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004292{
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004293 return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
4294}
4295
Antoine Pitrou244651a2009-05-04 18:56:13 +00004296/* The decoder. The only state we preserve is our read position,
4297 * i.e. how many characters we have consumed. So if we end in the
4298 * middle of a shift sequence we have to back off the read position
4299 * and the output to the beginning of the sequence, otherwise we lose
4300 * all the shift state (seen bits, number of bits seen, high
4301 * surrogate). */
4302
Alexander Belopolsky40018472011-02-26 01:02:56 +00004303PyObject *
4304PyUnicode_DecodeUTF7Stateful(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004305 Py_ssize_t size,
4306 const char *errors,
4307 Py_ssize_t *consumed)
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004308{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004309 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004310 Py_ssize_t startinpos;
4311 Py_ssize_t endinpos;
4312 Py_ssize_t outpos;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004313 const char *e;
Victor Stinner7931d9a2011-11-04 00:22:48 +01004314 PyObject *unicode;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004315 const char *errmsg = "";
4316 int inShift = 0;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004317 Py_ssize_t shiftOutStart;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004318 unsigned int base64bits = 0;
4319 unsigned long base64buffer = 0;
Victor Stinner24729f32011-11-10 20:31:37 +01004320 Py_UCS4 surrogate = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004321 PyObject *errorHandler = NULL;
4322 PyObject *exc = NULL;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004323
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004324 /* Start off assuming it's all ASCII. Widen later as necessary. */
4325 unicode = PyUnicode_New(size, 127);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004326 if (!unicode)
4327 return NULL;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004328 if (size == 0) {
4329 if (consumed)
4330 *consumed = 0;
Victor Stinner7931d9a2011-11-04 00:22:48 +01004331 return unicode;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004332 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004333
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004334 shiftOutStart = outpos = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004335 e = s + size;
4336
4337 while (s < e) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004338 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00004339 restart:
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00004340 ch = (unsigned char) *s;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004341
Antoine Pitrou244651a2009-05-04 18:56:13 +00004342 if (inShift) { /* in a base-64 section */
4343 if (IS_BASE64(ch)) { /* consume a base-64 character */
4344 base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
4345 base64bits += 6;
4346 s++;
4347 if (base64bits >= 16) {
4348 /* we have enough bits for a UTF-16 value */
Victor Stinner24729f32011-11-10 20:31:37 +01004349 Py_UCS4 outCh = (Py_UCS4)(base64buffer >> (base64bits-16));
Antoine Pitrou244651a2009-05-04 18:56:13 +00004350 base64bits -= 16;
4351 base64buffer &= (1 << base64bits) - 1; /* clear high bits */
4352 if (surrogate) {
4353 /* expecting a second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004354 if (Py_UNICODE_IS_LOW_SURROGATE(outCh)) {
4355 Py_UCS4 ch2 = Py_UNICODE_JOIN_SURROGATES(surrogate, outCh);
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004356 if (unicode_putchar(&unicode, &outpos, ch2) < 0)
4357 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004358 surrogate = 0;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01004359 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004360 }
4361 else {
Antoine Pitrou78edf752011-11-15 01:44:16 +01004362 if (unicode_putchar(&unicode, &outpos, surrogate) < 0)
4363 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004364 surrogate = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004365 }
4366 }
Victor Stinner551ac952011-11-29 22:58:13 +01004367 if (Py_UNICODE_IS_HIGH_SURROGATE(outCh)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004368 /* first surrogate */
4369 surrogate = outCh;
4370 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004371 else {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004372 if (unicode_putchar(&unicode, &outpos, outCh) < 0)
4373 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004374 }
4375 }
4376 }
4377 else { /* now leaving a base-64 section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004378 inShift = 0;
4379 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004380 if (surrogate) {
Antoine Pitrou78edf752011-11-15 01:44:16 +01004381 if (unicode_putchar(&unicode, &outpos, surrogate) < 0)
4382 goto onError;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01004383 surrogate = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004384 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004385 if (base64bits > 0) { /* left-over bits */
4386 if (base64bits >= 6) {
4387 /* We've seen at least one base-64 character */
4388 errmsg = "partial character in shift sequence";
4389 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004390 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004391 else {
4392 /* Some bits remain; they should be zero */
4393 if (base64buffer != 0) {
4394 errmsg = "non-zero padding bits in shift sequence";
4395 goto utf7Error;
4396 }
4397 }
4398 }
4399 if (ch != '-') {
4400 /* '-' is absorbed; other terminating
4401 characters are preserved */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004402 if (unicode_putchar(&unicode, &outpos, ch) < 0)
4403 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004404 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004405 }
4406 }
4407 else if ( ch == '+' ) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004408 startinpos = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004409 s++; /* consume '+' */
4410 if (s < e && *s == '-') { /* '+-' encodes '+' */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004411 s++;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004412 if (unicode_putchar(&unicode, &outpos, '+') < 0)
4413 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004414 }
4415 else { /* begin base64-encoded section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004416 inShift = 1;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004417 shiftOutStart = outpos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004418 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004419 }
4420 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004421 else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004422 if (unicode_putchar(&unicode, &outpos, ch) < 0)
4423 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004424 s++;
4425 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004426 else {
4427 startinpos = s-starts;
4428 s++;
4429 errmsg = "unexpected special character";
4430 goto utf7Error;
4431 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004432 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004433utf7Error:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004434 endinpos = s-starts;
4435 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00004436 errors, &errorHandler,
4437 "utf7", errmsg,
4438 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004439 &unicode, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00004440 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004441 }
4442
Antoine Pitrou244651a2009-05-04 18:56:13 +00004443 /* end of string */
4444
4445 if (inShift && !consumed) { /* in shift sequence, no more to follow */
4446 /* if we're in an inconsistent state, that's an error */
4447 if (surrogate ||
4448 (base64bits >= 6) ||
4449 (base64bits > 0 && base64buffer != 0)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004450 endinpos = size;
4451 if (unicode_decode_call_errorhandler(
4452 errors, &errorHandler,
4453 "utf7", "unterminated shift sequence",
4454 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004455 &unicode, &outpos))
Antoine Pitrou244651a2009-05-04 18:56:13 +00004456 goto onError;
4457 if (s < e)
4458 goto restart;
4459 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004460 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004461
4462 /* return state */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004463 if (consumed) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004464 if (inShift) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004465 outpos = shiftOutStart; /* back off output */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004466 *consumed = startinpos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004467 }
4468 else {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004469 *consumed = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004470 }
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004471 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004472
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004473 if (unicode_resize(&unicode, outpos) < 0)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004474 goto onError;
4475
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004476 Py_XDECREF(errorHandler);
4477 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01004478 return unicode_result(unicode);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004479
Benjamin Peterson29060642009-01-31 22:14:21 +00004480 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004481 Py_XDECREF(errorHandler);
4482 Py_XDECREF(exc);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004483 Py_DECREF(unicode);
4484 return NULL;
4485}
4486
4487
Alexander Belopolsky40018472011-02-26 01:02:56 +00004488PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004489_PyUnicode_EncodeUTF7(PyObject *str,
4490 int base64SetO,
4491 int base64WhiteSpace,
4492 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004493{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004494 int kind;
4495 void *data;
4496 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004497 PyObject *v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004498 int inShift = 0;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004499 Py_ssize_t i;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004500 unsigned int base64bits = 0;
4501 unsigned long base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004502 char * out;
4503 char * start;
4504
Benjamin Petersonbac79492012-01-14 13:34:47 -05004505 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004506 return NULL;
4507 kind = PyUnicode_KIND(str);
4508 data = PyUnicode_DATA(str);
4509 len = PyUnicode_GET_LENGTH(str);
4510
4511 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004512 return PyBytes_FromStringAndSize(NULL, 0);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004513
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004514 /* It might be possible to tighten this worst case */
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004515 if (len > PY_SSIZE_T_MAX / 8)
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004516 return PyErr_NoMemory();
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004517 v = PyBytes_FromStringAndSize(NULL, len * 8);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004518 if (v == NULL)
4519 return NULL;
4520
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004521 start = out = PyBytes_AS_STRING(v);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004522 for (i = 0; i < len; ++i) {
Victor Stinner0e368262011-11-10 20:12:49 +01004523 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004524
Antoine Pitrou244651a2009-05-04 18:56:13 +00004525 if (inShift) {
4526 if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4527 /* shifting out */
4528 if (base64bits) { /* output remaining bits */
4529 *out++ = TO_BASE64(base64buffer << (6-base64bits));
4530 base64buffer = 0;
4531 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004532 }
4533 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004534 /* Characters not in the BASE64 set implicitly unshift the sequence
4535 so no '-' is required, except if the character is itself a '-' */
4536 if (IS_BASE64(ch) || ch == '-') {
4537 *out++ = '-';
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004538 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004539 *out++ = (char) ch;
4540 }
4541 else {
4542 goto encode_char;
Tim Petersced69f82003-09-16 20:30:58 +00004543 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004544 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004545 else { /* not in a shift sequence */
4546 if (ch == '+') {
4547 *out++ = '+';
4548 *out++ = '-';
4549 }
4550 else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4551 *out++ = (char) ch;
4552 }
4553 else {
4554 *out++ = '+';
4555 inShift = 1;
4556 goto encode_char;
4557 }
4558 }
4559 continue;
4560encode_char:
Antoine Pitrou244651a2009-05-04 18:56:13 +00004561 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01004562 assert(ch <= MAX_UNICODE);
Victor Stinner0d3721d2011-11-22 03:27:53 +01004563
Antoine Pitrou244651a2009-05-04 18:56:13 +00004564 /* code first surrogate */
4565 base64bits += 16;
4566 base64buffer = (base64buffer << 16) | 0xd800 | ((ch-0x10000) >> 10);
4567 while (base64bits >= 6) {
4568 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4569 base64bits -= 6;
4570 }
4571 /* prepare second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004572 ch = Py_UNICODE_LOW_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004573 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004574 base64bits += 16;
4575 base64buffer = (base64buffer << 16) | ch;
4576 while (base64bits >= 6) {
4577 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4578 base64bits -= 6;
4579 }
Hye-Shik Chang1bc09b72004-01-03 19:35:43 +00004580 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004581 if (base64bits)
4582 *out++= TO_BASE64(base64buffer << (6-base64bits) );
4583 if (inShift)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004584 *out++ = '-';
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004585 if (_PyBytes_Resize(&v, out - start) < 0)
4586 return NULL;
4587 return v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004588}
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004589PyObject *
4590PyUnicode_EncodeUTF7(const Py_UNICODE *s,
4591 Py_ssize_t size,
4592 int base64SetO,
4593 int base64WhiteSpace,
4594 const char *errors)
4595{
4596 PyObject *result;
4597 PyObject *tmp = PyUnicode_FromUnicode(s, size);
4598 if (tmp == NULL)
4599 return NULL;
Victor Stinner0e368262011-11-10 20:12:49 +01004600 result = _PyUnicode_EncodeUTF7(tmp, base64SetO,
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004601 base64WhiteSpace, errors);
4602 Py_DECREF(tmp);
4603 return result;
4604}
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004605
Antoine Pitrou244651a2009-05-04 18:56:13 +00004606#undef IS_BASE64
4607#undef FROM_BASE64
4608#undef TO_BASE64
4609#undef DECODE_DIRECT
4610#undef ENCODE_DIRECT
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004611
Guido van Rossumd57fd912000-03-10 22:53:23 +00004612/* --- UTF-8 Codec -------------------------------------------------------- */
4613
Alexander Belopolsky40018472011-02-26 01:02:56 +00004614PyObject *
4615PyUnicode_DecodeUTF8(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004616 Py_ssize_t size,
4617 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004618{
Walter Dörwald69652032004-09-07 20:24:22 +00004619 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
4620}
4621
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004622#include "stringlib/asciilib.h"
4623#include "stringlib/codecs.h"
4624#include "stringlib/undef.h"
4625
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004626#include "stringlib/ucs1lib.h"
4627#include "stringlib/codecs.h"
4628#include "stringlib/undef.h"
4629
4630#include "stringlib/ucs2lib.h"
4631#include "stringlib/codecs.h"
4632#include "stringlib/undef.h"
4633
4634#include "stringlib/ucs4lib.h"
4635#include "stringlib/codecs.h"
4636#include "stringlib/undef.h"
4637
Antoine Pitrouab868312009-01-10 15:40:25 +00004638/* Mask to quickly check whether a C 'long' contains a
4639 non-ASCII, UTF8-encoded char. */
4640#if (SIZEOF_LONG == 8)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004641# define ASCII_CHAR_MASK 0x8080808080808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004642#elif (SIZEOF_LONG == 4)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004643# define ASCII_CHAR_MASK 0x80808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004644#else
4645# error C 'long' size should be either 4 or 8!
4646#endif
4647
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004648static Py_ssize_t
4649ascii_decode(const char *start, const char *end, Py_UCS1 *dest)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004650{
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004651 const char *p = start;
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004652 const char *aligned_end = (const char *) _Py_ALIGN_DOWN(end, SIZEOF_LONG);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004653
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004654#if SIZEOF_LONG <= SIZEOF_VOID_P
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004655 assert(_Py_IS_ALIGNED(dest, SIZEOF_LONG));
4656 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004657 /* Fast path, see in STRINGLIB(utf8_decode) for
4658 an explanation. */
4659 /* Help register allocation */
4660 register const char *_p = p;
4661 register Py_UCS1 * q = dest;
4662 while (_p < aligned_end) {
4663 unsigned long value = *(const unsigned long *) _p;
4664 if (value & ASCII_CHAR_MASK)
Benjamin Peterson29060642009-01-31 22:14:21 +00004665 break;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004666 *((unsigned long *)q) = value;
4667 _p += SIZEOF_LONG;
4668 q += SIZEOF_LONG;
Benjamin Peterson14339b62009-01-31 16:36:08 +00004669 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004670 p = _p;
4671 while (p < end) {
4672 if ((unsigned char)*p & 0x80)
4673 break;
4674 *q++ = *p++;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004675 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004676 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004677 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004678#endif
4679 while (p < end) {
4680 /* Fast path, see in STRINGLIB(utf8_decode) in stringlib/codecs.h
4681 for an explanation. */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004682 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004683 /* Help register allocation */
4684 register const char *_p = p;
4685 while (_p < aligned_end) {
4686 unsigned long value = *(unsigned long *) _p;
4687 if (value & ASCII_CHAR_MASK)
4688 break;
4689 _p += SIZEOF_LONG;
4690 }
4691 p = _p;
4692 if (_p == end)
4693 break;
4694 }
4695 if ((unsigned char)*p & 0x80)
4696 break;
4697 ++p;
4698 }
4699 memcpy(dest, start, p - start);
4700 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004701}
Antoine Pitrouab868312009-01-10 15:40:25 +00004702
Victor Stinner785938e2011-12-11 20:09:03 +01004703PyObject *
4704PyUnicode_DecodeUTF8Stateful(const char *s,
4705 Py_ssize_t size,
4706 const char *errors,
4707 Py_ssize_t *consumed)
4708{
Victor Stinner785938e2011-12-11 20:09:03 +01004709 PyObject *unicode;
Victor Stinner785938e2011-12-11 20:09:03 +01004710 const char *starts = s;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004711 const char *end = s + size;
4712 Py_ssize_t outpos;
4713
4714 Py_ssize_t startinpos;
4715 Py_ssize_t endinpos;
4716 const char *errmsg = "";
4717 PyObject *errorHandler = NULL;
4718 PyObject *exc = NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01004719
4720 if (size == 0) {
4721 if (consumed)
4722 *consumed = 0;
Victor Stinner382955f2011-12-11 21:44:00 +01004723 Py_INCREF(unicode_empty);
4724 return unicode_empty;
Victor Stinner785938e2011-12-11 20:09:03 +01004725 }
4726
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004727 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
4728 if (size == 1 && (unsigned char)s[0] < 128) {
Victor Stinner785938e2011-12-11 20:09:03 +01004729 if (consumed)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004730 *consumed = 1;
4731 return get_latin1_char((unsigned char)s[0]);
Victor Stinner785938e2011-12-11 20:09:03 +01004732 }
4733
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004734 unicode = PyUnicode_New(size, 127);
Victor Stinner785938e2011-12-11 20:09:03 +01004735 if (!unicode)
4736 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01004737
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004738 outpos = ascii_decode(s, end, PyUnicode_1BYTE_DATA(unicode));
4739 s += outpos;
4740 while (s < end) {
4741 Py_UCS4 ch;
4742 int kind = PyUnicode_KIND(unicode);
4743 if (kind == PyUnicode_1BYTE_KIND) {
4744 if (PyUnicode_IS_ASCII(unicode))
4745 ch = asciilib_utf8_decode(&s, end,
4746 PyUnicode_1BYTE_DATA(unicode), &outpos);
4747 else
4748 ch = ucs1lib_utf8_decode(&s, end,
4749 PyUnicode_1BYTE_DATA(unicode), &outpos);
4750 } else if (kind == PyUnicode_2BYTE_KIND) {
4751 ch = ucs2lib_utf8_decode(&s, end,
4752 PyUnicode_2BYTE_DATA(unicode), &outpos);
4753 } else {
4754 assert(kind == PyUnicode_4BYTE_KIND);
4755 ch = ucs4lib_utf8_decode(&s, end,
4756 PyUnicode_4BYTE_DATA(unicode), &outpos);
4757 }
4758
4759 switch (ch) {
4760 case 0:
4761 if (s == end || consumed)
4762 goto End;
4763 errmsg = "unexpected end of data";
4764 startinpos = s - starts;
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004765 endinpos = end - starts;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004766 break;
4767 case 1:
4768 errmsg = "invalid start byte";
4769 startinpos = s - starts;
4770 endinpos = startinpos + 1;
4771 break;
4772 case 2:
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004773 case 3:
4774 case 4:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004775 errmsg = "invalid continuation byte";
4776 startinpos = s - starts;
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004777 endinpos = startinpos + ch - 1;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004778 break;
4779 default:
4780 if (unicode_putchar(&unicode, &outpos, ch) < 0)
4781 goto onError;
4782 continue;
4783 }
4784
4785 if (unicode_decode_call_errorhandler(
4786 errors, &errorHandler,
4787 "utf-8", errmsg,
4788 &starts, &end, &startinpos, &endinpos, &exc, &s,
4789 &unicode, &outpos))
4790 goto onError;
Victor Stinner785938e2011-12-11 20:09:03 +01004791 }
4792
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004793End:
4794 if (unicode_resize(&unicode, outpos) < 0)
4795 goto onError;
4796
4797 if (consumed)
4798 *consumed = s - starts;
4799
4800 Py_XDECREF(errorHandler);
4801 Py_XDECREF(exc);
4802 assert(_PyUnicode_CheckConsistency(unicode, 1));
4803 return unicode;
4804
4805onError:
4806 Py_XDECREF(errorHandler);
4807 Py_XDECREF(exc);
4808 Py_XDECREF(unicode);
4809 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01004810}
4811
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004812#ifdef __APPLE__
4813
4814/* Simplified UTF-8 decoder using surrogateescape error handler,
Victor Stinner27b1ca22012-12-03 12:47:59 +01004815 used to decode the command line arguments on Mac OS X.
4816
4817 Return a pointer to a newly allocated wide character string (use
4818 PyMem_Free() to free the memory), or NULL on memory allocation error. */
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004819
4820wchar_t*
4821_Py_DecodeUTF8_surrogateescape(const char *s, Py_ssize_t size)
4822{
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004823 const char *e;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004824 wchar_t *unicode;
4825 Py_ssize_t outpos;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004826
4827 /* Note: size will always be longer than the resulting Unicode
4828 character count */
Victor Stinner27b1ca22012-12-03 12:47:59 +01004829 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < (size + 1))
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004830 return NULL;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004831 unicode = PyMem_Malloc((size + 1) * sizeof(wchar_t));
4832 if (!unicode)
4833 return NULL;
4834
4835 /* Unpack UTF-8 encoded data */
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004836 e = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004837 outpos = 0;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004838 while (s < e) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004839 Py_UCS4 ch;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004840#if SIZEOF_WCHAR_T == 4
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004841 ch = ucs4lib_utf8_decode(&s, e, (Py_UCS4 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004842#else
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004843 ch = ucs2lib_utf8_decode(&s, e, (Py_UCS2 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004844#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004845 if (ch > 0xFF) {
4846#if SIZEOF_WCHAR_T == 4
4847 assert(0);
4848#else
4849 assert(Py_UNICODE_IS_SURROGATE(ch));
4850 /* compute and append the two surrogates: */
4851 unicode[outpos++] = (wchar_t)Py_UNICODE_HIGH_SURROGATE(ch);
4852 unicode[outpos++] = (wchar_t)Py_UNICODE_LOW_SURROGATE(ch);
4853#endif
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004854 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004855 else {
4856 if (!ch && s == e)
4857 break;
4858 /* surrogateescape */
4859 unicode[outpos++] = 0xDC00 + (unsigned char)*s++;
4860 }
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004861 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004862 unicode[outpos] = L'\0';
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004863 return unicode;
4864}
4865
4866#endif /* __APPLE__ */
Antoine Pitrouab868312009-01-10 15:40:25 +00004867
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004868/* Primary internal function which creates utf8 encoded bytes objects.
4869
4870 Allocation strategy: if the string is short, convert into a stack buffer
Tim Peters602f7402002-04-27 18:03:26 +00004871 and allocate exactly as much space needed at the end. Else allocate the
4872 maximum possible needed (4 result bytes per Unicode character), and return
4873 the excess memory at the end.
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004874*/
Tim Peters7e3d9612002-04-21 03:26:37 +00004875PyObject *
Victor Stinner7931d9a2011-11-04 00:22:48 +01004876_PyUnicode_AsUTF8String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004877{
Victor Stinner6099a032011-12-18 14:22:26 +01004878 enum PyUnicode_Kind kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004879 void *data;
4880 Py_ssize_t size;
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00004881
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004882 if (!PyUnicode_Check(unicode)) {
4883 PyErr_BadArgument();
4884 return NULL;
4885 }
4886
4887 if (PyUnicode_READY(unicode) == -1)
4888 return NULL;
4889
Victor Stinnere90fe6a2011-10-01 16:48:13 +02004890 if (PyUnicode_UTF8(unicode))
4891 return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode),
4892 PyUnicode_UTF8_LENGTH(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004893
4894 kind = PyUnicode_KIND(unicode);
4895 data = PyUnicode_DATA(unicode);
4896 size = PyUnicode_GET_LENGTH(unicode);
4897
Benjamin Petersonead6b532011-12-20 17:23:42 -06004898 switch (kind) {
Victor Stinner6099a032011-12-18 14:22:26 +01004899 default:
4900 assert(0);
4901 case PyUnicode_1BYTE_KIND:
4902 /* the string cannot be ASCII, or PyUnicode_UTF8() would be set */
4903 assert(!PyUnicode_IS_ASCII(unicode));
4904 return ucs1lib_utf8_encoder(unicode, data, size, errors);
4905 case PyUnicode_2BYTE_KIND:
4906 return ucs2lib_utf8_encoder(unicode, data, size, errors);
4907 case PyUnicode_4BYTE_KIND:
4908 return ucs4lib_utf8_encoder(unicode, data, size, errors);
Tim Peters602f7402002-04-27 18:03:26 +00004909 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004910}
4911
Alexander Belopolsky40018472011-02-26 01:02:56 +00004912PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004913PyUnicode_EncodeUTF8(const Py_UNICODE *s,
4914 Py_ssize_t size,
4915 const char *errors)
4916{
4917 PyObject *v, *unicode;
4918
4919 unicode = PyUnicode_FromUnicode(s, size);
4920 if (unicode == NULL)
4921 return NULL;
4922 v = _PyUnicode_AsUTF8String(unicode, errors);
4923 Py_DECREF(unicode);
4924 return v;
4925}
4926
4927PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00004928PyUnicode_AsUTF8String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004929{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004930 return _PyUnicode_AsUTF8String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004931}
4932
Walter Dörwald41980ca2007-08-16 21:55:45 +00004933/* --- UTF-32 Codec ------------------------------------------------------- */
4934
4935PyObject *
4936PyUnicode_DecodeUTF32(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004937 Py_ssize_t size,
4938 const char *errors,
4939 int *byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004940{
4941 return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
4942}
4943
4944PyObject *
4945PyUnicode_DecodeUTF32Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004946 Py_ssize_t size,
4947 const char *errors,
4948 int *byteorder,
4949 Py_ssize_t *consumed)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004950{
4951 const char *starts = s;
4952 Py_ssize_t startinpos;
4953 Py_ssize_t endinpos;
4954 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01004955 PyObject *unicode;
Mark Dickinson7db923c2010-06-12 09:10:14 +00004956 const unsigned char *q, *e;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004957 int bo = 0; /* assume native ordering by default */
4958 const char *errmsg = "";
Walter Dörwald41980ca2007-08-16 21:55:45 +00004959 /* Offsets from q for retrieving bytes in the right order. */
4960#ifdef BYTEORDER_IS_LITTLE_ENDIAN
4961 int iorder[] = {0, 1, 2, 3};
4962#else
4963 int iorder[] = {3, 2, 1, 0};
4964#endif
4965 PyObject *errorHandler = NULL;
4966 PyObject *exc = NULL;
Victor Stinner313a1202010-06-11 23:56:51 +00004967
Walter Dörwald41980ca2007-08-16 21:55:45 +00004968 q = (unsigned char *)s;
4969 e = q + size;
4970
4971 if (byteorder)
4972 bo = *byteorder;
4973
4974 /* Check for BOM marks (U+FEFF) in the input and adjust current
4975 byte order setting accordingly. In native mode, the leading BOM
4976 mark is skipped, in all other modes, it is copied to the output
4977 stream as-is (giving a ZWNBSP character). */
4978 if (bo == 0) {
4979 if (size >= 4) {
4980 const Py_UCS4 bom = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
Benjamin Peterson29060642009-01-31 22:14:21 +00004981 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00004982#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Benjamin Peterson29060642009-01-31 22:14:21 +00004983 if (bom == 0x0000FEFF) {
4984 q += 4;
4985 bo = -1;
4986 }
4987 else if (bom == 0xFFFE0000) {
4988 q += 4;
4989 bo = 1;
4990 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004991#else
Benjamin Peterson29060642009-01-31 22:14:21 +00004992 if (bom == 0x0000FEFF) {
4993 q += 4;
4994 bo = 1;
4995 }
4996 else if (bom == 0xFFFE0000) {
4997 q += 4;
4998 bo = -1;
4999 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00005000#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00005001 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00005002 }
5003
5004 if (bo == -1) {
5005 /* force LE */
5006 iorder[0] = 0;
5007 iorder[1] = 1;
5008 iorder[2] = 2;
5009 iorder[3] = 3;
5010 }
5011 else if (bo == 1) {
5012 /* force BE */
5013 iorder[0] = 3;
5014 iorder[1] = 2;
5015 iorder[2] = 1;
5016 iorder[3] = 0;
5017 }
5018
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005019 /* This might be one to much, because of a BOM */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005020 unicode = PyUnicode_New((size+3)/4, 127);
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005021 if (!unicode)
5022 return NULL;
5023 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01005024 return unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005025 outpos = 0;
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005026
Walter Dörwald41980ca2007-08-16 21:55:45 +00005027 while (q < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005028 Py_UCS4 ch;
5029 /* remaining bytes at the end? (size should be divisible by 4) */
5030 if (e-q<4) {
5031 if (consumed)
5032 break;
5033 errmsg = "truncated data";
5034 startinpos = ((const char *)q)-starts;
5035 endinpos = ((const char *)e)-starts;
5036 goto utf32Error;
5037 /* The remaining input chars are ignored if the callback
5038 chooses to skip the input */
5039 }
5040 ch = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
5041 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00005042
Benjamin Peterson29060642009-01-31 22:14:21 +00005043 if (ch >= 0x110000)
5044 {
5045 errmsg = "codepoint not in range(0x110000)";
5046 startinpos = ((const char *)q)-starts;
5047 endinpos = startinpos+4;
5048 goto utf32Error;
5049 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005050 if (unicode_putchar(&unicode, &outpos, ch) < 0)
5051 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005052 q += 4;
5053 continue;
5054 utf32Error:
Benjamin Peterson29060642009-01-31 22:14:21 +00005055 if (unicode_decode_call_errorhandler(
5056 errors, &errorHandler,
5057 "utf32", errmsg,
5058 &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005059 &unicode, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00005060 goto onError;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005061 }
5062
5063 if (byteorder)
5064 *byteorder = bo;
5065
5066 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005067 *consumed = (const char *)q-starts;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005068
5069 /* Adjust length */
Victor Stinner16e6a802011-12-12 13:24:15 +01005070 if (unicode_resize(&unicode, outpos) < 0)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005071 goto onError;
5072
5073 Py_XDECREF(errorHandler);
5074 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01005075 return unicode_result(unicode);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005076
Benjamin Peterson29060642009-01-31 22:14:21 +00005077 onError:
Walter Dörwald41980ca2007-08-16 21:55:45 +00005078 Py_DECREF(unicode);
5079 Py_XDECREF(errorHandler);
5080 Py_XDECREF(exc);
5081 return NULL;
5082}
5083
5084PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005085_PyUnicode_EncodeUTF32(PyObject *str,
5086 const char *errors,
5087 int byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005088{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005089 int kind;
5090 void *data;
5091 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005092 PyObject *v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005093 unsigned char *p;
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01005094 Py_ssize_t nsize, i;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005095 /* Offsets from p for storing byte pairs in the right order. */
5096#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5097 int iorder[] = {0, 1, 2, 3};
5098#else
5099 int iorder[] = {3, 2, 1, 0};
5100#endif
5101
Benjamin Peterson29060642009-01-31 22:14:21 +00005102#define STORECHAR(CH) \
5103 do { \
5104 p[iorder[3]] = ((CH) >> 24) & 0xff; \
5105 p[iorder[2]] = ((CH) >> 16) & 0xff; \
5106 p[iorder[1]] = ((CH) >> 8) & 0xff; \
5107 p[iorder[0]] = (CH) & 0xff; \
5108 p += 4; \
Walter Dörwald41980ca2007-08-16 21:55:45 +00005109 } while(0)
5110
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005111 if (!PyUnicode_Check(str)) {
5112 PyErr_BadArgument();
5113 return NULL;
5114 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005115 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005116 return NULL;
5117 kind = PyUnicode_KIND(str);
5118 data = PyUnicode_DATA(str);
5119 len = PyUnicode_GET_LENGTH(str);
5120
5121 nsize = len + (byteorder == 0);
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01005122 if (nsize > PY_SSIZE_T_MAX / 4)
Benjamin Peterson29060642009-01-31 22:14:21 +00005123 return PyErr_NoMemory();
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01005124 v = PyBytes_FromStringAndSize(NULL, nsize * 4);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005125 if (v == NULL)
5126 return NULL;
5127
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005128 p = (unsigned char *)PyBytes_AS_STRING(v);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005129 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005130 STORECHAR(0xFEFF);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005131 if (len == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005132 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005133
5134 if (byteorder == -1) {
5135 /* force LE */
5136 iorder[0] = 0;
5137 iorder[1] = 1;
5138 iorder[2] = 2;
5139 iorder[3] = 3;
5140 }
5141 else if (byteorder == 1) {
5142 /* force BE */
5143 iorder[0] = 3;
5144 iorder[1] = 2;
5145 iorder[2] = 1;
5146 iorder[3] = 0;
5147 }
5148
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005149 for (i = 0; i < len; i++)
5150 STORECHAR(PyUnicode_READ(kind, data, i));
Guido van Rossum98297ee2007-11-06 21:34:58 +00005151
5152 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005153 return v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005154#undef STORECHAR
5155}
5156
Alexander Belopolsky40018472011-02-26 01:02:56 +00005157PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005158PyUnicode_EncodeUTF32(const Py_UNICODE *s,
5159 Py_ssize_t size,
5160 const char *errors,
5161 int byteorder)
5162{
5163 PyObject *result;
5164 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5165 if (tmp == NULL)
5166 return NULL;
5167 result = _PyUnicode_EncodeUTF32(tmp, errors, byteorder);
5168 Py_DECREF(tmp);
5169 return result;
5170}
5171
5172PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005173PyUnicode_AsUTF32String(PyObject *unicode)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005174{
Victor Stinnerb960b342011-11-20 19:12:52 +01005175 return _PyUnicode_EncodeUTF32(unicode, NULL, 0);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005176}
5177
Guido van Rossumd57fd912000-03-10 22:53:23 +00005178/* --- UTF-16 Codec ------------------------------------------------------- */
5179
Tim Peters772747b2001-08-09 22:21:55 +00005180PyObject *
5181PyUnicode_DecodeUTF16(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005182 Py_ssize_t size,
5183 const char *errors,
5184 int *byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005185{
Walter Dörwald69652032004-09-07 20:24:22 +00005186 return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
5187}
5188
5189PyObject *
5190PyUnicode_DecodeUTF16Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005191 Py_ssize_t size,
5192 const char *errors,
5193 int *byteorder,
5194 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00005195{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005196 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005197 Py_ssize_t startinpos;
5198 Py_ssize_t endinpos;
5199 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01005200 PyObject *unicode;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005201 const unsigned char *q, *e;
Tim Peters772747b2001-08-09 22:21:55 +00005202 int bo = 0; /* assume native ordering by default */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005203 int native_ordering;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00005204 const char *errmsg = "";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005205 PyObject *errorHandler = NULL;
5206 PyObject *exc = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005207
Tim Peters772747b2001-08-09 22:21:55 +00005208 q = (unsigned char *)s;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005209 e = q + size;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005210
5211 if (byteorder)
Tim Peters772747b2001-08-09 22:21:55 +00005212 bo = *byteorder;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005213
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005214 /* Check for BOM marks (U+FEFF) in the input and adjust current
5215 byte order setting accordingly. In native mode, the leading BOM
5216 mark is skipped, in all other modes, it is copied to the output
5217 stream as-is (giving a ZWNBSP character). */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005218 if (bo == 0 && size >= 2) {
5219 const Py_UCS4 bom = (q[1] << 8) | q[0];
5220 if (bom == 0xFEFF) {
5221 q += 2;
5222 bo = -1;
Benjamin Peterson29060642009-01-31 22:14:21 +00005223 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005224 else if (bom == 0xFFFE) {
5225 q += 2;
5226 bo = 1;
5227 }
5228 if (byteorder)
5229 *byteorder = bo;
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005230 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005231
Antoine Pitrou63065d72012-05-15 23:48:04 +02005232 if (q == e) {
5233 if (consumed)
5234 *consumed = size;
5235 Py_INCREF(unicode_empty);
5236 return unicode_empty;
Tim Peters772747b2001-08-09 22:21:55 +00005237 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005238
Antoine Pitrouab868312009-01-10 15:40:25 +00005239#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Antoine Pitrou63065d72012-05-15 23:48:04 +02005240 native_ordering = bo <= 0;
Antoine Pitrouab868312009-01-10 15:40:25 +00005241#else
Antoine Pitrou63065d72012-05-15 23:48:04 +02005242 native_ordering = bo >= 0;
Antoine Pitrouab868312009-01-10 15:40:25 +00005243#endif
Tim Peters772747b2001-08-09 22:21:55 +00005244
Antoine Pitrou63065d72012-05-15 23:48:04 +02005245 /* Note: size will always be longer than the resulting Unicode
5246 character count */
5247 unicode = PyUnicode_New((e - q + 1) / 2, 127);
5248 if (!unicode)
5249 return NULL;
5250
5251 outpos = 0;
5252 while (1) {
5253 Py_UCS4 ch = 0;
5254 if (e - q >= 2) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005255 int kind = PyUnicode_KIND(unicode);
Antoine Pitrou63065d72012-05-15 23:48:04 +02005256 if (kind == PyUnicode_1BYTE_KIND) {
5257 if (PyUnicode_IS_ASCII(unicode))
5258 ch = asciilib_utf16_decode(&q, e,
5259 PyUnicode_1BYTE_DATA(unicode), &outpos,
5260 native_ordering);
5261 else
5262 ch = ucs1lib_utf16_decode(&q, e,
5263 PyUnicode_1BYTE_DATA(unicode), &outpos,
5264 native_ordering);
5265 } else if (kind == PyUnicode_2BYTE_KIND) {
5266 ch = ucs2lib_utf16_decode(&q, e,
5267 PyUnicode_2BYTE_DATA(unicode), &outpos,
5268 native_ordering);
5269 } else {
5270 assert(kind == PyUnicode_4BYTE_KIND);
5271 ch = ucs4lib_utf16_decode(&q, e,
5272 PyUnicode_4BYTE_DATA(unicode), &outpos,
5273 native_ordering);
Antoine Pitrouab868312009-01-10 15:40:25 +00005274 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005275 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005276
Antoine Pitrou63065d72012-05-15 23:48:04 +02005277 switch (ch)
5278 {
5279 case 0:
5280 /* remaining byte at the end? (size should be even) */
5281 if (q == e || consumed)
5282 goto End;
5283 errmsg = "truncated data";
5284 startinpos = ((const char *)q) - starts;
5285 endinpos = ((const char *)e) - starts;
5286 break;
5287 /* The remaining input chars are ignored if the callback
5288 chooses to skip the input */
5289 case 1:
Serhiy Storchaka48e188e2013-01-08 23:14:24 +02005290 q -= 2;
5291 if (consumed)
Serhiy Storchakaae3b32a2013-01-08 23:40:52 +02005292 goto End;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005293 errmsg = "unexpected end of data";
Serhiy Storchaka48e188e2013-01-08 23:14:24 +02005294 startinpos = ((const char *)q) - starts;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005295 endinpos = ((const char *)e) - starts;
5296 break;
5297 case 2:
5298 errmsg = "illegal encoding";
5299 startinpos = ((const char *)q) - 2 - starts;
5300 endinpos = startinpos + 2;
5301 break;
5302 case 3:
5303 errmsg = "illegal UTF-16 surrogate";
5304 startinpos = ((const char *)q) - 4 - starts;
5305 endinpos = startinpos + 2;
5306 break;
5307 default:
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005308 if (unicode_putchar(&unicode, &outpos, ch) < 0)
5309 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005310 continue;
5311 }
5312
Benjamin Peterson29060642009-01-31 22:14:21 +00005313 if (unicode_decode_call_errorhandler(
Antoine Pitrouab868312009-01-10 15:40:25 +00005314 errors,
5315 &errorHandler,
5316 "utf16", errmsg,
5317 &starts,
5318 (const char **)&e,
5319 &startinpos,
5320 &endinpos,
5321 &exc,
5322 (const char **)&q,
5323 &unicode,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005324 &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00005325 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005326 }
5327
Antoine Pitrou63065d72012-05-15 23:48:04 +02005328End:
Walter Dörwald69652032004-09-07 20:24:22 +00005329 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005330 *consumed = (const char *)q-starts;
Walter Dörwald69652032004-09-07 20:24:22 +00005331
Guido van Rossumd57fd912000-03-10 22:53:23 +00005332 /* Adjust length */
Victor Stinner16e6a802011-12-12 13:24:15 +01005333 if (unicode_resize(&unicode, outpos) < 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005334 goto onError;
5335
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005336 Py_XDECREF(errorHandler);
5337 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01005338 return unicode_result(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005339
Benjamin Peterson29060642009-01-31 22:14:21 +00005340 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00005341 Py_DECREF(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005342 Py_XDECREF(errorHandler);
5343 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005344 return NULL;
5345}
5346
Tim Peters772747b2001-08-09 22:21:55 +00005347PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005348_PyUnicode_EncodeUTF16(PyObject *str,
5349 const char *errors,
5350 int byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005351{
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005352 enum PyUnicode_Kind kind;
5353 const void *data;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005354 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005355 PyObject *v;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005356 unsigned short *out;
5357 Py_ssize_t bytesize;
5358 Py_ssize_t pairs;
5359#ifdef WORDS_BIGENDIAN
5360 int native_ordering = byteorder >= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005361#else
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005362 int native_ordering = byteorder <= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005363#endif
5364
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005365 if (!PyUnicode_Check(str)) {
5366 PyErr_BadArgument();
5367 return NULL;
5368 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005369 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005370 return NULL;
5371 kind = PyUnicode_KIND(str);
5372 data = PyUnicode_DATA(str);
5373 len = PyUnicode_GET_LENGTH(str);
Victor Stinner0e368262011-11-10 20:12:49 +01005374
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005375 pairs = 0;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005376 if (kind == PyUnicode_4BYTE_KIND) {
5377 const Py_UCS4 *in = (const Py_UCS4 *)data;
5378 const Py_UCS4 *end = in + len;
5379 while (in < end)
5380 if (*in++ >= 0x10000)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005381 pairs++;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005382 }
5383 if (len > PY_SSIZE_T_MAX / 2 - pairs - (byteorder == 0))
Benjamin Peterson29060642009-01-31 22:14:21 +00005384 return PyErr_NoMemory();
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005385 bytesize = (len + pairs + (byteorder == 0)) * 2;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005386 v = PyBytes_FromStringAndSize(NULL, bytesize);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005387 if (v == NULL)
5388 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005389
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005390 /* output buffer is 2-bytes aligned */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02005391 assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 2));
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005392 out = (unsigned short *)PyBytes_AS_STRING(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005393 if (byteorder == 0)
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005394 *out++ = 0xFEFF;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005395 if (len == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005396 goto done;
Tim Peters772747b2001-08-09 22:21:55 +00005397
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005398 switch (kind) {
5399 case PyUnicode_1BYTE_KIND: {
5400 ucs1lib_utf16_encode(out, (const Py_UCS1 *)data, len, native_ordering);
5401 break;
Tim Peters772747b2001-08-09 22:21:55 +00005402 }
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005403 case PyUnicode_2BYTE_KIND: {
5404 ucs2lib_utf16_encode(out, (const Py_UCS2 *)data, len, native_ordering);
5405 break;
Tim Peters772747b2001-08-09 22:21:55 +00005406 }
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005407 case PyUnicode_4BYTE_KIND: {
5408 ucs4lib_utf16_encode(out, (const Py_UCS4 *)data, len, native_ordering);
5409 break;
5410 }
5411 default:
5412 assert(0);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005413 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005414
5415 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005416 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005417}
5418
Alexander Belopolsky40018472011-02-26 01:02:56 +00005419PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005420PyUnicode_EncodeUTF16(const Py_UNICODE *s,
5421 Py_ssize_t size,
5422 const char *errors,
5423 int byteorder)
5424{
5425 PyObject *result;
5426 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5427 if (tmp == NULL)
5428 return NULL;
5429 result = _PyUnicode_EncodeUTF16(tmp, errors, byteorder);
5430 Py_DECREF(tmp);
5431 return result;
5432}
5433
5434PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005435PyUnicode_AsUTF16String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005436{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005437 return _PyUnicode_EncodeUTF16(unicode, NULL, 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005438}
5439
5440/* --- Unicode Escape Codec ----------------------------------------------- */
5441
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005442/* Helper function for PyUnicode_DecodeUnicodeEscape, determines
5443 if all the escapes in the string make it still a valid ASCII string.
5444 Returns -1 if any escapes were found which cause the string to
5445 pop out of ASCII range. Otherwise returns the length of the
5446 required buffer to hold the string.
5447 */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02005448static Py_ssize_t
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005449length_of_escaped_ascii_string(const char *s, Py_ssize_t size)
5450{
5451 const unsigned char *p = (const unsigned char *)s;
5452 const unsigned char *end = p + size;
5453 Py_ssize_t length = 0;
5454
5455 if (size < 0)
5456 return -1;
5457
5458 for (; p < end; ++p) {
5459 if (*p > 127) {
5460 /* Non-ASCII */
5461 return -1;
5462 }
5463 else if (*p != '\\') {
5464 /* Normal character */
5465 ++length;
5466 }
5467 else {
5468 /* Backslash-escape, check next char */
5469 ++p;
5470 /* Escape sequence reaches till end of string or
5471 non-ASCII follow-up. */
5472 if (p >= end || *p > 127)
5473 return -1;
5474 switch (*p) {
5475 case '\n':
5476 /* backslash + \n result in zero characters */
5477 break;
5478 case '\\': case '\'': case '\"':
5479 case 'b': case 'f': case 't':
5480 case 'n': case 'r': case 'v': case 'a':
5481 ++length;
5482 break;
5483 case '0': case '1': case '2': case '3':
5484 case '4': case '5': case '6': case '7':
5485 case 'x': case 'u': case 'U': case 'N':
5486 /* these do not guarantee ASCII characters */
5487 return -1;
5488 default:
5489 /* count the backslash + the other character */
5490 length += 2;
5491 }
5492 }
5493 }
5494 return length;
5495}
5496
Fredrik Lundh06d12682001-01-24 07:59:11 +00005497static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
Marc-André Lemburg0f774e32000-06-28 16:43:35 +00005498
Alexander Belopolsky40018472011-02-26 01:02:56 +00005499PyObject *
5500PyUnicode_DecodeUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005501 Py_ssize_t size,
Victor Stinnerc17f5402011-09-29 00:16:58 +02005502 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005503{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005504 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005505 Py_ssize_t startinpos;
5506 Py_ssize_t endinpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005507 int j;
Victor Stinner7931d9a2011-11-04 00:22:48 +01005508 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005509 const char *end;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005510 char* message;
5511 Py_UCS4 chr = 0xffffffff; /* in case 'getcode' messes up */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005512 PyObject *errorHandler = NULL;
5513 PyObject *exc = NULL;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005514 Py_ssize_t len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005515 Py_ssize_t i;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005516
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005517 len = length_of_escaped_ascii_string(s, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005518
5519 /* After length_of_escaped_ascii_string() there are two alternatives,
5520 either the string is pure ASCII with named escapes like \n, etc.
5521 and we determined it's exact size (common case)
5522 or it contains \x, \u, ... escape sequences. then we create a
5523 legacy wchar string and resize it at the end of this function. */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005524 if (len >= 0) {
5525 v = PyUnicode_New(len, 127);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005526 if (!v)
5527 goto onError;
5528 assert(PyUnicode_KIND(v) == PyUnicode_1BYTE_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005529 }
5530 else {
5531 /* Escaped strings will always be longer than the resulting
5532 Unicode string, so we start with size here and then reduce the
5533 length after conversion to the true value.
5534 (but if the error callback returns a long replacement string
5535 we'll have to allocate more space) */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005536 v = PyUnicode_New(size, 127);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005537 if (!v)
5538 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005539 len = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005540 }
5541
Guido van Rossumd57fd912000-03-10 22:53:23 +00005542 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01005543 return v;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005544 i = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005545 end = s + size;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005546
Guido van Rossumd57fd912000-03-10 22:53:23 +00005547 while (s < end) {
5548 unsigned char c;
Victor Stinner24729f32011-11-10 20:31:37 +01005549 Py_UCS4 x;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005550 int digits;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005551
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005552 /* The only case in which i == ascii_length is a backslash
5553 followed by a newline. */
5554 assert(i <= len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005555
Guido van Rossumd57fd912000-03-10 22:53:23 +00005556 /* Non-escape characters are interpreted as Unicode ordinals */
5557 if (*s != '\\') {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005558 if (unicode_putchar(&v, &i, (unsigned char) *s++) < 0)
5559 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005560 continue;
5561 }
5562
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005563 startinpos = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005564 /* \ - Escapes */
5565 s++;
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005566 c = *s++;
5567 if (s > end)
5568 c = '\0'; /* Invalid after \ */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005569
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005570 /* The only case in which i == ascii_length is a backslash
5571 followed by a newline. */
5572 assert(i < len || (i == len && c == '\n'));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005573
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005574 switch (c) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005575
Benjamin Peterson29060642009-01-31 22:14:21 +00005576 /* \x escapes */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005577#define WRITECHAR(ch) \
5578 do { \
5579 if (unicode_putchar(&v, &i, ch) < 0) \
5580 goto onError; \
5581 }while(0)
5582
Guido van Rossumd57fd912000-03-10 22:53:23 +00005583 case '\n': break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005584 case '\\': WRITECHAR('\\'); break;
5585 case '\'': WRITECHAR('\''); break;
5586 case '\"': WRITECHAR('\"'); break;
5587 case 'b': WRITECHAR('\b'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005588 /* FF */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005589 case 'f': WRITECHAR('\014'); break;
5590 case 't': WRITECHAR('\t'); break;
5591 case 'n': WRITECHAR('\n'); break;
5592 case 'r': WRITECHAR('\r'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005593 /* VT */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005594 case 'v': WRITECHAR('\013'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005595 /* BEL, not classic C */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005596 case 'a': WRITECHAR('\007'); break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005597
Benjamin Peterson29060642009-01-31 22:14:21 +00005598 /* \OOO (octal) escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005599 case '0': case '1': case '2': case '3':
5600 case '4': case '5': case '6': case '7':
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005601 x = s[-1] - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005602 if (s < end && '0' <= *s && *s <= '7') {
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005603 x = (x<<3) + *s++ - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005604 if (s < end && '0' <= *s && *s <= '7')
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005605 x = (x<<3) + *s++ - '0';
Guido van Rossumd57fd912000-03-10 22:53:23 +00005606 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005607 WRITECHAR(x);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005608 break;
5609
Benjamin Peterson29060642009-01-31 22:14:21 +00005610 /* hex escapes */
5611 /* \xXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005612 case 'x':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005613 digits = 2;
5614 message = "truncated \\xXX escape";
5615 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005616
Benjamin Peterson29060642009-01-31 22:14:21 +00005617 /* \uXXXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005618 case 'u':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005619 digits = 4;
5620 message = "truncated \\uXXXX escape";
5621 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005622
Benjamin Peterson29060642009-01-31 22:14:21 +00005623 /* \UXXXXXXXX */
Fredrik Lundhdf846752000-09-03 11:29:49 +00005624 case 'U':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005625 digits = 8;
5626 message = "truncated \\UXXXXXXXX escape";
5627 hexescape:
5628 chr = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005629 if (s+digits>end) {
5630 endinpos = size;
5631 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005632 errors, &errorHandler,
5633 "unicodeescape", "end of string in escape sequence",
5634 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005635 &v, &i))
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005636 goto onError;
5637 goto nextByte;
5638 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005639 for (j = 0; j < digits; ++j) {
5640 c = (unsigned char) s[j];
David Malcolm96960882010-11-05 17:23:41 +00005641 if (!Py_ISXDIGIT(c)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005642 endinpos = (s+j+1)-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005643 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005644 errors, &errorHandler,
5645 "unicodeescape", message,
5646 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005647 &v, &i))
Fredrik Lundhdf846752000-09-03 11:29:49 +00005648 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005649 len = PyUnicode_GET_LENGTH(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005650 goto nextByte;
Fredrik Lundhdf846752000-09-03 11:29:49 +00005651 }
5652 chr = (chr<<4) & ~0xF;
5653 if (c >= '0' && c <= '9')
5654 chr += c - '0';
5655 else if (c >= 'a' && c <= 'f')
5656 chr += 10 + c - 'a';
5657 else
5658 chr += 10 + c - 'A';
5659 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005660 s += j;
Jeremy Hylton504de6b2003-10-06 05:08:26 +00005661 if (chr == 0xffffffff && PyErr_Occurred())
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005662 /* _decoding_error will have already written into the
5663 target buffer. */
5664 break;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005665 store:
Fredrik Lundhdf846752000-09-03 11:29:49 +00005666 /* when we get here, chr is a 32-bit unicode character */
Victor Stinner8faf8212011-12-08 22:14:11 +01005667 if (chr <= MAX_UNICODE) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005668 WRITECHAR(chr);
Fredrik Lundhdf846752000-09-03 11:29:49 +00005669 } else {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005670 endinpos = s-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005671 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005672 errors, &errorHandler,
5673 "unicodeescape", "illegal Unicode character",
5674 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005675 &v, &i))
Fredrik Lundhdf846752000-09-03 11:29:49 +00005676 goto onError;
5677 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00005678 break;
5679
Benjamin Peterson29060642009-01-31 22:14:21 +00005680 /* \N{name} */
Fredrik Lundhccc74732001-02-18 22:13:49 +00005681 case 'N':
5682 message = "malformed \\N character escape";
5683 if (ucnhash_CAPI == NULL) {
5684 /* load the unicode data module */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005685 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
5686 PyUnicodeData_CAPSULE_NAME, 1);
Fredrik Lundhccc74732001-02-18 22:13:49 +00005687 if (ucnhash_CAPI == NULL)
5688 goto ucnhashError;
5689 }
5690 if (*s == '{') {
5691 const char *start = s+1;
5692 /* look for the closing brace */
5693 while (*s != '}' && s < end)
5694 s++;
5695 if (s > start && s < end && *s == '}') {
5696 /* found a name. look it up in the unicode database */
5697 message = "unknown Unicode character name";
5698 s++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005699 if (ucnhash_CAPI->getcode(NULL, start, (int)(s-start-1),
Ezio Melotti931b8aa2011-10-21 21:57:36 +03005700 &chr, 0))
Fredrik Lundhccc74732001-02-18 22:13:49 +00005701 goto store;
5702 }
5703 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005704 endinpos = s-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005705 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005706 errors, &errorHandler,
5707 "unicodeescape", message,
5708 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005709 &v, &i))
Fredrik Lundhccc74732001-02-18 22:13:49 +00005710 goto onError;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005711 break;
5712
5713 default:
Walter Dörwald8c077222002-03-25 11:16:18 +00005714 if (s > end) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005715 message = "\\ at end of string";
5716 s--;
5717 endinpos = s-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005718 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005719 errors, &errorHandler,
5720 "unicodeescape", message,
5721 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005722 &v, &i))
Walter Dörwald8c077222002-03-25 11:16:18 +00005723 goto onError;
5724 }
5725 else {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005726 WRITECHAR('\\');
5727 WRITECHAR(s[-1]);
Walter Dörwald8c077222002-03-25 11:16:18 +00005728 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00005729 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005730 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005731 nextByte:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005732 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005733 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005734#undef WRITECHAR
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005735
Victor Stinner16e6a802011-12-12 13:24:15 +01005736 if (unicode_resize(&v, i) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005737 goto onError;
Walter Dörwaldd4ade082003-08-15 15:00:26 +00005738 Py_XDECREF(errorHandler);
5739 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01005740 return unicode_result(v);
Walter Dörwald8c077222002-03-25 11:16:18 +00005741
Benjamin Peterson29060642009-01-31 22:14:21 +00005742 ucnhashError:
Fredrik Lundh06d12682001-01-24 07:59:11 +00005743 PyErr_SetString(
5744 PyExc_UnicodeError,
5745 "\\N escapes not supported (can't load unicodedata module)"
5746 );
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00005747 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005748 Py_XDECREF(errorHandler);
5749 Py_XDECREF(exc);
Fredrik Lundhf6056062001-01-20 11:15:25 +00005750 return NULL;
5751
Benjamin Peterson29060642009-01-31 22:14:21 +00005752 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00005753 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005754 Py_XDECREF(errorHandler);
5755 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005756 return NULL;
5757}
5758
5759/* Return a Unicode-Escape string version of the Unicode object.
5760
5761 If quotes is true, the string is enclosed in u"" or u'' quotes as
5762 appropriate.
5763
5764*/
5765
Alexander Belopolsky40018472011-02-26 01:02:56 +00005766PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005767PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005768{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005769 Py_ssize_t i, len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005770 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005771 char *p;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005772 int kind;
5773 void *data;
5774 Py_ssize_t expandsize = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005775
Ezio Melottie7f90372012-10-05 03:33:31 +03005776 /* Initial allocation is based on the longest-possible character
Thomas Wouters89f507f2006-12-13 04:49:30 +00005777 escape.
5778
Ezio Melottie7f90372012-10-05 03:33:31 +03005779 For UCS1 strings it's '\xxx', 4 bytes per source character.
5780 For UCS2 strings it's '\uxxxx', 6 bytes per source character.
5781 For UCS4 strings it's '\U00xxxxxx', 10 bytes per source character.
Thomas Wouters89f507f2006-12-13 04:49:30 +00005782 */
5783
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005784 if (!PyUnicode_Check(unicode)) {
5785 PyErr_BadArgument();
5786 return NULL;
5787 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005788 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005789 return NULL;
5790 len = PyUnicode_GET_LENGTH(unicode);
5791 kind = PyUnicode_KIND(unicode);
5792 data = PyUnicode_DATA(unicode);
Benjamin Petersonead6b532011-12-20 17:23:42 -06005793 switch (kind) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005794 case PyUnicode_1BYTE_KIND: expandsize = 4; break;
5795 case PyUnicode_2BYTE_KIND: expandsize = 6; break;
5796 case PyUnicode_4BYTE_KIND: expandsize = 10; break;
5797 }
5798
5799 if (len == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005800 return PyBytes_FromStringAndSize(NULL, 0);
5801
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005802 if (len > (PY_SSIZE_T_MAX - 2 - 1) / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005803 return PyErr_NoMemory();
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005804
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005805 repr = PyBytes_FromStringAndSize(NULL,
Benjamin Peterson29060642009-01-31 22:14:21 +00005806 2
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005807 + expandsize*len
Benjamin Peterson29060642009-01-31 22:14:21 +00005808 + 1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005809 if (repr == NULL)
5810 return NULL;
5811
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005812 p = PyBytes_AS_STRING(repr);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005813
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005814 for (i = 0; i < len; i++) {
Victor Stinner3326cb62011-11-10 20:15:25 +01005815 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005816
Walter Dörwald79e913e2007-05-12 11:08:06 +00005817 /* Escape backslashes */
5818 if (ch == '\\') {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005819 *p++ = '\\';
5820 *p++ = (char) ch;
Walter Dörwald79e913e2007-05-12 11:08:06 +00005821 continue;
Tim Petersced69f82003-09-16 20:30:58 +00005822 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005823
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005824 /* Map 21-bit characters to '\U00xxxxxx' */
5825 else if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01005826 assert(ch <= MAX_UNICODE);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005827 *p++ = '\\';
5828 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005829 *p++ = Py_hexdigits[(ch >> 28) & 0x0000000F];
5830 *p++ = Py_hexdigits[(ch >> 24) & 0x0000000F];
5831 *p++ = Py_hexdigits[(ch >> 20) & 0x0000000F];
5832 *p++ = Py_hexdigits[(ch >> 16) & 0x0000000F];
5833 *p++ = Py_hexdigits[(ch >> 12) & 0x0000000F];
5834 *p++ = Py_hexdigits[(ch >> 8) & 0x0000000F];
5835 *p++ = Py_hexdigits[(ch >> 4) & 0x0000000F];
5836 *p++ = Py_hexdigits[ch & 0x0000000F];
Benjamin Peterson29060642009-01-31 22:14:21 +00005837 continue;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005838 }
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005839
Guido van Rossumd57fd912000-03-10 22:53:23 +00005840 /* Map 16-bit characters to '\uxxxx' */
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005841 if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005842 *p++ = '\\';
5843 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005844 *p++ = Py_hexdigits[(ch >> 12) & 0x000F];
5845 *p++ = Py_hexdigits[(ch >> 8) & 0x000F];
5846 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
5847 *p++ = Py_hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00005848 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005849
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005850 /* Map special whitespace to '\t', \n', '\r' */
5851 else if (ch == '\t') {
5852 *p++ = '\\';
5853 *p++ = 't';
5854 }
5855 else if (ch == '\n') {
5856 *p++ = '\\';
5857 *p++ = 'n';
5858 }
5859 else if (ch == '\r') {
5860 *p++ = '\\';
5861 *p++ = 'r';
5862 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005863
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005864 /* Map non-printable US ASCII to '\xhh' */
Marc-André Lemburg11326de2001-11-28 12:56:20 +00005865 else if (ch < ' ' || ch >= 0x7F) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005866 *p++ = '\\';
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005867 *p++ = 'x';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005868 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
5869 *p++ = Py_hexdigits[ch & 0x000F];
Tim Petersced69f82003-09-16 20:30:58 +00005870 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005871
Guido van Rossumd57fd912000-03-10 22:53:23 +00005872 /* Copy everything else as-is */
5873 else
5874 *p++ = (char) ch;
5875 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005876
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005877 assert(p - PyBytes_AS_STRING(repr) > 0);
5878 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0)
5879 return NULL;
5880 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005881}
5882
Alexander Belopolsky40018472011-02-26 01:02:56 +00005883PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005884PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
5885 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005886{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005887 PyObject *result;
5888 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5889 if (tmp == NULL)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005890 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005891 result = PyUnicode_AsUnicodeEscapeString(tmp);
5892 Py_DECREF(tmp);
5893 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005894}
5895
5896/* --- Raw Unicode Escape Codec ------------------------------------------- */
5897
Alexander Belopolsky40018472011-02-26 01:02:56 +00005898PyObject *
5899PyUnicode_DecodeRawUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005900 Py_ssize_t size,
5901 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005902{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005903 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005904 Py_ssize_t startinpos;
5905 Py_ssize_t endinpos;
5906 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01005907 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005908 const char *end;
5909 const char *bs;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005910 PyObject *errorHandler = NULL;
5911 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00005912
Guido van Rossumd57fd912000-03-10 22:53:23 +00005913 /* Escaped strings will always be longer than the resulting
5914 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005915 length after conversion to the true value. (But decoding error
5916 handler might have to resize the string) */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005917 v = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005918 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005919 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005920 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01005921 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005922 outpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005923 end = s + size;
5924 while (s < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005925 unsigned char c;
5926 Py_UCS4 x;
5927 int i;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00005928 int count;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005929
Benjamin Peterson29060642009-01-31 22:14:21 +00005930 /* Non-escape characters are interpreted as Unicode ordinals */
5931 if (*s != '\\') {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005932 if (unicode_putchar(&v, &outpos, (unsigned char)*s++) < 0)
5933 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005934 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00005935 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005936 startinpos = s-starts;
5937
5938 /* \u-escapes are only interpreted iff the number of leading
5939 backslashes if odd */
5940 bs = s;
5941 for (;s < end;) {
5942 if (*s != '\\')
5943 break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005944 if (unicode_putchar(&v, &outpos, (unsigned char)*s++) < 0)
5945 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005946 }
5947 if (((s - bs) & 1) == 0 ||
5948 s >= end ||
5949 (*s != 'u' && *s != 'U')) {
5950 continue;
5951 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005952 outpos--;
Benjamin Peterson29060642009-01-31 22:14:21 +00005953 count = *s=='u' ? 4 : 8;
5954 s++;
5955
5956 /* \uXXXX with 4 hex digits, \Uxxxxxxxx with 8 */
Benjamin Peterson29060642009-01-31 22:14:21 +00005957 for (x = 0, i = 0; i < count; ++i, ++s) {
5958 c = (unsigned char)*s;
David Malcolm96960882010-11-05 17:23:41 +00005959 if (!Py_ISXDIGIT(c)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005960 endinpos = s-starts;
5961 if (unicode_decode_call_errorhandler(
5962 errors, &errorHandler,
5963 "rawunicodeescape", "truncated \\uXXXX",
5964 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005965 &v, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00005966 goto onError;
5967 goto nextByte;
5968 }
5969 x = (x<<4) & ~0xF;
5970 if (c >= '0' && c <= '9')
5971 x += c - '0';
5972 else if (c >= 'a' && c <= 'f')
5973 x += 10 + c - 'a';
5974 else
5975 x += 10 + c - 'A';
5976 }
Victor Stinner8faf8212011-12-08 22:14:11 +01005977 if (x <= MAX_UNICODE) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005978 if (unicode_putchar(&v, &outpos, x) < 0)
5979 goto onError;
Christian Heimesfe337bf2008-03-23 21:54:12 +00005980 } else {
5981 endinpos = s-starts;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00005982 if (unicode_decode_call_errorhandler(
5983 errors, &errorHandler,
5984 "rawunicodeescape", "\\Uxxxxxxxx out of range",
Benjamin Peterson29060642009-01-31 22:14:21 +00005985 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005986 &v, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00005987 goto onError;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00005988 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005989 nextByte:
5990 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005991 }
Victor Stinner16e6a802011-12-12 13:24:15 +01005992 if (unicode_resize(&v, outpos) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005993 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005994 Py_XDECREF(errorHandler);
5995 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01005996 return unicode_result(v);
Tim Petersced69f82003-09-16 20:30:58 +00005997
Benjamin Peterson29060642009-01-31 22:14:21 +00005998 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00005999 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006000 Py_XDECREF(errorHandler);
6001 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006002 return NULL;
6003}
6004
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006005
Alexander Belopolsky40018472011-02-26 01:02:56 +00006006PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006007PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006008{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006009 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006010 char *p;
6011 char *q;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006012 Py_ssize_t expandsize, pos;
6013 int kind;
6014 void *data;
6015 Py_ssize_t len;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006016
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006017 if (!PyUnicode_Check(unicode)) {
6018 PyErr_BadArgument();
6019 return NULL;
6020 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05006021 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006022 return NULL;
6023 kind = PyUnicode_KIND(unicode);
6024 data = PyUnicode_DATA(unicode);
6025 len = PyUnicode_GET_LENGTH(unicode);
Benjamin Peterson1518e872011-11-23 10:44:52 -06006026 /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6
6027 bytes, and 1 byte characters 4. */
6028 expandsize = kind * 2 + 2;
Victor Stinner0e368262011-11-10 20:12:49 +01006029
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006030 if (len > PY_SSIZE_T_MAX / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00006031 return PyErr_NoMemory();
Benjamin Peterson14339b62009-01-31 16:36:08 +00006032
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006033 repr = PyBytes_FromStringAndSize(NULL, expandsize * len);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006034 if (repr == NULL)
6035 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006036 if (len == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006037 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006038
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006039 p = q = PyBytes_AS_STRING(repr);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006040 for (pos = 0; pos < len; pos++) {
6041 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Benjamin Peterson29060642009-01-31 22:14:21 +00006042 /* Map 32-bit characters to '\Uxxxxxxxx' */
6043 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01006044 assert(ch <= MAX_UNICODE);
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006045 *p++ = '\\';
6046 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006047 *p++ = Py_hexdigits[(ch >> 28) & 0xf];
6048 *p++ = Py_hexdigits[(ch >> 24) & 0xf];
6049 *p++ = Py_hexdigits[(ch >> 20) & 0xf];
6050 *p++ = Py_hexdigits[(ch >> 16) & 0xf];
6051 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6052 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6053 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6054 *p++ = Py_hexdigits[ch & 15];
Tim Petersced69f82003-09-16 20:30:58 +00006055 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006056 /* Map 16-bit characters to '\uxxxx' */
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006057 else if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006058 *p++ = '\\';
6059 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006060 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6061 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6062 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6063 *p++ = Py_hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006064 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006065 /* Copy everything else as-is */
6066 else
Guido van Rossumd57fd912000-03-10 22:53:23 +00006067 *p++ = (char) ch;
6068 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00006069
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006070 assert(p > q);
6071 if (_PyBytes_Resize(&repr, p - q) < 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006072 return NULL;
6073 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006074}
6075
Alexander Belopolsky40018472011-02-26 01:02:56 +00006076PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006077PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
6078 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006079{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006080 PyObject *result;
6081 PyObject *tmp = PyUnicode_FromUnicode(s, size);
6082 if (tmp == NULL)
Walter Dörwald711005d2007-05-12 12:03:26 +00006083 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006084 result = PyUnicode_AsRawUnicodeEscapeString(tmp);
6085 Py_DECREF(tmp);
6086 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006087}
6088
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006089/* --- Unicode Internal Codec ------------------------------------------- */
6090
Alexander Belopolsky40018472011-02-26 01:02:56 +00006091PyObject *
6092_PyUnicode_DecodeUnicodeInternal(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006093 Py_ssize_t size,
6094 const char *errors)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006095{
6096 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006097 Py_ssize_t startinpos;
6098 Py_ssize_t endinpos;
6099 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01006100 PyObject *v;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006101 const char *end;
6102 const char *reason;
6103 PyObject *errorHandler = NULL;
6104 PyObject *exc = NULL;
6105
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006106 if (PyErr_WarnEx(PyExc_DeprecationWarning,
Ezio Melotti11060a42011-11-16 09:39:10 +02006107 "unicode_internal codec has been deprecated",
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006108 1))
6109 return NULL;
6110
Thomas Wouters89f507f2006-12-13 04:49:30 +00006111 /* XXX overflow detection missing */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006112 v = PyUnicode_New((size+Py_UNICODE_SIZE-1)/ Py_UNICODE_SIZE, 127);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006113 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006114 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006115 if (PyUnicode_GET_LENGTH(v) == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01006116 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006117 outpos = 0;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006118 end = s + size;
6119
6120 while (s < end) {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006121 Py_UNICODE uch;
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006122 Py_UCS4 ch;
6123 /* We copy the raw representation one byte at a time because the
6124 pointer may be unaligned (see test_codeccallbacks). */
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006125 ((char *) &uch)[0] = s[0];
6126 ((char *) &uch)[1] = s[1];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006127#ifdef Py_UNICODE_WIDE
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006128 ((char *) &uch)[2] = s[2];
6129 ((char *) &uch)[3] = s[3];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006130#endif
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006131 ch = uch;
6132
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006133 /* We have to sanity check the raw data, otherwise doom looms for
6134 some malformed UCS-4 data. */
6135 if (
Benjamin Peterson29060642009-01-31 22:14:21 +00006136#ifdef Py_UNICODE_WIDE
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006137 ch > 0x10ffff ||
Benjamin Peterson29060642009-01-31 22:14:21 +00006138#endif
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006139 end-s < Py_UNICODE_SIZE
6140 )
Benjamin Peterson29060642009-01-31 22:14:21 +00006141 {
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006142 startinpos = s - starts;
6143 if (end-s < Py_UNICODE_SIZE) {
6144 endinpos = end-starts;
6145 reason = "truncated input";
6146 }
6147 else {
6148 endinpos = s - starts + Py_UNICODE_SIZE;
6149 reason = "illegal code point (> 0x10FFFF)";
6150 }
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006151 if (unicode_decode_call_errorhandler(
6152 errors, &errorHandler,
6153 "unicode_internal", reason,
Walter Dörwalde78178e2007-07-30 13:31:40 +00006154 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006155 &v, &outpos))
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006156 goto onError;
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006157 continue;
6158 }
6159
6160 s += Py_UNICODE_SIZE;
6161#ifndef Py_UNICODE_WIDE
Victor Stinner551ac952011-11-29 22:58:13 +01006162 if (Py_UNICODE_IS_HIGH_SURROGATE(ch) && s < end)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006163 {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006164 Py_UNICODE uch2;
6165 ((char *) &uch2)[0] = s[0];
6166 ((char *) &uch2)[1] = s[1];
Victor Stinner551ac952011-11-29 22:58:13 +01006167 if (Py_UNICODE_IS_LOW_SURROGATE(uch2))
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006168 {
Victor Stinner551ac952011-11-29 22:58:13 +01006169 ch = Py_UNICODE_JOIN_SURROGATES(uch, uch2);
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006170 s += Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006171 }
6172 }
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006173#endif
6174
6175 if (unicode_putchar(&v, &outpos, ch) < 0)
6176 goto onError;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006177 }
6178
Victor Stinner16e6a802011-12-12 13:24:15 +01006179 if (unicode_resize(&v, outpos) < 0)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006180 goto onError;
6181 Py_XDECREF(errorHandler);
6182 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006183 return unicode_result(v);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006184
Benjamin Peterson29060642009-01-31 22:14:21 +00006185 onError:
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006186 Py_XDECREF(v);
6187 Py_XDECREF(errorHandler);
6188 Py_XDECREF(exc);
6189 return NULL;
6190}
6191
Guido van Rossumd57fd912000-03-10 22:53:23 +00006192/* --- Latin-1 Codec ------------------------------------------------------ */
6193
Alexander Belopolsky40018472011-02-26 01:02:56 +00006194PyObject *
6195PyUnicode_DecodeLatin1(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006196 Py_ssize_t size,
6197 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006198{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006199 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Victor Stinnere57b1c02011-09-28 22:20:48 +02006200 return _PyUnicode_FromUCS1((unsigned char*)s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006201}
6202
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006203/* create or adjust a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006204static void
6205make_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006206 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006207 PyObject *unicode,
6208 Py_ssize_t startpos, Py_ssize_t endpos,
6209 const char *reason)
6210{
6211 if (*exceptionObject == NULL) {
6212 *exceptionObject = PyObject_CallFunction(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006213 PyExc_UnicodeEncodeError, "sOnns",
Martin v. Löwis9e816682011-11-02 12:45:42 +01006214 encoding, unicode, startpos, endpos, reason);
6215 }
6216 else {
6217 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
6218 goto onError;
6219 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
6220 goto onError;
6221 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
6222 goto onError;
6223 return;
6224 onError:
6225 Py_DECREF(*exceptionObject);
6226 *exceptionObject = NULL;
6227 }
6228}
6229
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006230/* raises a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006231static void
6232raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006233 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006234 PyObject *unicode,
6235 Py_ssize_t startpos, Py_ssize_t endpos,
6236 const char *reason)
6237{
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006238 make_encode_exception(exceptionObject,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006239 encoding, unicode, startpos, endpos, reason);
6240 if (*exceptionObject != NULL)
6241 PyCodec_StrictErrors(*exceptionObject);
6242}
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006243
6244/* error handling callback helper:
6245 build arguments, call the callback and check the arguments,
6246 put the result into newpos and return the replacement string, which
6247 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006248static PyObject *
6249unicode_encode_call_errorhandler(const char *errors,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006250 PyObject **errorHandler,
6251 const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006252 PyObject *unicode, PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006253 Py_ssize_t startpos, Py_ssize_t endpos,
6254 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006255{
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006256 static char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006257 Py_ssize_t len;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006258 PyObject *restuple;
6259 PyObject *resunicode;
6260
6261 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006262 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006263 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006264 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006265 }
6266
Benjamin Petersonbac79492012-01-14 13:34:47 -05006267 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006268 return NULL;
6269 len = PyUnicode_GET_LENGTH(unicode);
6270
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006271 make_encode_exception(exceptionObject,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006272 encoding, unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006273 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006274 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006275
6276 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00006277 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006278 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006279 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006280 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006281 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00006282 Py_DECREF(restuple);
6283 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006284 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006285 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00006286 &resunicode, newpos)) {
6287 Py_DECREF(restuple);
6288 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006289 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006290 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
6291 PyErr_SetString(PyExc_TypeError, &argparse[3]);
6292 Py_DECREF(restuple);
6293 return NULL;
6294 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006295 if (*newpos<0)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006296 *newpos = len + *newpos;
6297 if (*newpos<0 || *newpos>len) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006298 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
6299 Py_DECREF(restuple);
6300 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00006301 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006302 Py_INCREF(resunicode);
6303 Py_DECREF(restuple);
6304 return resunicode;
6305}
6306
Alexander Belopolsky40018472011-02-26 01:02:56 +00006307static PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006308unicode_encode_ucs1(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006309 const char *errors,
Victor Stinnerfcd96532011-11-04 00:28:50 +01006310 unsigned int limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006311{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006312 /* input state */
6313 Py_ssize_t pos=0, size;
6314 int kind;
6315 void *data;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006316 /* output object */
6317 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006318 /* pointer into the output */
6319 char *str;
6320 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00006321 Py_ssize_t ressize;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006322 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
6323 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006324 PyObject *errorHandler = NULL;
6325 PyObject *exc = NULL;
6326 /* the following variable is used for caching string comparisons
6327 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
6328 int known_errorHandler = -1;
6329
Benjamin Petersonbac79492012-01-14 13:34:47 -05006330 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006331 return NULL;
6332 size = PyUnicode_GET_LENGTH(unicode);
6333 kind = PyUnicode_KIND(unicode);
6334 data = PyUnicode_DATA(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006335 /* allocate enough for a simple encoding without
6336 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00006337 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00006338 return PyBytes_FromStringAndSize(NULL, 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006339 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006340 if (res == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00006341 return NULL;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006342 str = PyBytes_AS_STRING(res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006343 ressize = size;
6344
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006345 while (pos < size) {
6346 Py_UCS4 c = PyUnicode_READ(kind, data, pos);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006347
Benjamin Peterson29060642009-01-31 22:14:21 +00006348 /* can we encode this? */
6349 if (c<limit) {
6350 /* no overflow check, because we know that the space is enough */
6351 *str++ = (char)c;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006352 ++pos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006353 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006354 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006355 Py_ssize_t requiredsize;
6356 PyObject *repunicode;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006357 Py_ssize_t repsize, newpos, respos, i;
Benjamin Peterson29060642009-01-31 22:14:21 +00006358 /* startpos for collecting unencodable chars */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006359 Py_ssize_t collstart = pos;
6360 Py_ssize_t collend = pos;
Benjamin Peterson29060642009-01-31 22:14:21 +00006361 /* find all unecodable characters */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006362 while ((collend < size) && (PyUnicode_READ(kind, data, collend)>=limit))
Benjamin Peterson29060642009-01-31 22:14:21 +00006363 ++collend;
6364 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
6365 if (known_errorHandler==-1) {
6366 if ((errors==NULL) || (!strcmp(errors, "strict")))
6367 known_errorHandler = 1;
6368 else if (!strcmp(errors, "replace"))
6369 known_errorHandler = 2;
6370 else if (!strcmp(errors, "ignore"))
6371 known_errorHandler = 3;
6372 else if (!strcmp(errors, "xmlcharrefreplace"))
6373 known_errorHandler = 4;
6374 else
6375 known_errorHandler = 0;
6376 }
6377 switch (known_errorHandler) {
6378 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006379 raise_encode_exception(&exc, encoding, unicode, collstart, collend, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006380 goto onError;
6381 case 2: /* replace */
6382 while (collstart++<collend)
6383 *str++ = '?'; /* fall through */
6384 case 3: /* ignore */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006385 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006386 break;
6387 case 4: /* xmlcharrefreplace */
6388 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006389 /* determine replacement size */
6390 for (i = collstart, repsize = 0; i < collend; ++i) {
6391 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
6392 if (ch < 10)
Benjamin Peterson29060642009-01-31 22:14:21 +00006393 repsize += 2+1+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006394 else if (ch < 100)
Benjamin Peterson29060642009-01-31 22:14:21 +00006395 repsize += 2+2+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006396 else if (ch < 1000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006397 repsize += 2+3+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006398 else if (ch < 10000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006399 repsize += 2+4+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006400 else if (ch < 100000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006401 repsize += 2+5+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006402 else if (ch < 1000000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006403 repsize += 2+6+1;
Victor Stinner0d3721d2011-11-22 03:27:53 +01006404 else {
Victor Stinner8faf8212011-12-08 22:14:11 +01006405 assert(ch <= MAX_UNICODE);
Benjamin Peterson29060642009-01-31 22:14:21 +00006406 repsize += 2+7+1;
Victor Stinner0d3721d2011-11-22 03:27:53 +01006407 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006408 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006409 requiredsize = respos+repsize+(size-collend);
Benjamin Peterson29060642009-01-31 22:14:21 +00006410 if (requiredsize > ressize) {
6411 if (requiredsize<2*ressize)
6412 requiredsize = 2*ressize;
6413 if (_PyBytes_Resize(&res, requiredsize))
6414 goto onError;
6415 str = PyBytes_AS_STRING(res) + respos;
6416 ressize = requiredsize;
6417 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006418 /* generate replacement */
6419 for (i = collstart; i < collend; ++i) {
6420 str += sprintf(str, "&#%d;", PyUnicode_READ(kind, data, i));
Benjamin Peterson29060642009-01-31 22:14:21 +00006421 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006422 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006423 break;
6424 default:
6425 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006426 encoding, reason, unicode, &exc,
6427 collstart, collend, &newpos);
6428 if (repunicode == NULL || (PyUnicode_Check(repunicode) &&
Benjamin Petersonbac79492012-01-14 13:34:47 -05006429 PyUnicode_READY(repunicode) == -1))
Benjamin Peterson29060642009-01-31 22:14:21 +00006430 goto onError;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006431 if (PyBytes_Check(repunicode)) {
6432 /* Directly copy bytes result to output. */
6433 repsize = PyBytes_Size(repunicode);
6434 if (repsize > 1) {
6435 /* Make room for all additional bytes. */
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006436 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006437 if (_PyBytes_Resize(&res, ressize+repsize-1)) {
6438 Py_DECREF(repunicode);
6439 goto onError;
6440 }
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006441 str = PyBytes_AS_STRING(res) + respos;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006442 ressize += repsize-1;
6443 }
6444 memcpy(str, PyBytes_AsString(repunicode), repsize);
6445 str += repsize;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006446 pos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006447 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006448 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006449 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006450 /* need more space? (at least enough for what we
6451 have+the replacement+the rest of the string, so
6452 we won't have to check space for encodable characters) */
6453 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006454 repsize = PyUnicode_GET_LENGTH(repunicode);
6455 requiredsize = respos+repsize+(size-collend);
Benjamin Peterson29060642009-01-31 22:14:21 +00006456 if (requiredsize > ressize) {
6457 if (requiredsize<2*ressize)
6458 requiredsize = 2*ressize;
6459 if (_PyBytes_Resize(&res, requiredsize)) {
6460 Py_DECREF(repunicode);
6461 goto onError;
6462 }
6463 str = PyBytes_AS_STRING(res) + respos;
6464 ressize = requiredsize;
6465 }
6466 /* check if there is anything unencodable in the replacement
6467 and copy it to the output */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006468 for (i = 0; repsize-->0; ++i, ++str) {
6469 c = PyUnicode_READ_CHAR(repunicode, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00006470 if (c >= limit) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006471 raise_encode_exception(&exc, encoding, unicode,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006472 pos, pos+1, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006473 Py_DECREF(repunicode);
6474 goto onError;
6475 }
6476 *str = (char)c;
6477 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006478 pos = newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006479 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006480 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00006481 }
6482 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006483 /* Resize if we allocated to much */
6484 size = str - PyBytes_AS_STRING(res);
6485 if (size < ressize) { /* If this falls res will be NULL */
Alexandre Vassalottibad1b922008-12-27 09:49:09 +00006486 assert(size >= 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006487 if (_PyBytes_Resize(&res, size) < 0)
6488 goto onError;
6489 }
6490
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006491 Py_XDECREF(errorHandler);
6492 Py_XDECREF(exc);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006493 return res;
6494
6495 onError:
6496 Py_XDECREF(res);
6497 Py_XDECREF(errorHandler);
6498 Py_XDECREF(exc);
6499 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006500}
6501
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006502/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006503PyObject *
6504PyUnicode_EncodeLatin1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006505 Py_ssize_t size,
6506 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006507{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006508 PyObject *result;
6509 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6510 if (unicode == NULL)
6511 return NULL;
6512 result = unicode_encode_ucs1(unicode, errors, 256);
6513 Py_DECREF(unicode);
6514 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006515}
6516
Alexander Belopolsky40018472011-02-26 01:02:56 +00006517PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006518_PyUnicode_AsLatin1String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006519{
6520 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006521 PyErr_BadArgument();
6522 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006523 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006524 if (PyUnicode_READY(unicode) == -1)
6525 return NULL;
6526 /* Fast path: if it is a one-byte string, construct
6527 bytes object directly. */
6528 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND)
6529 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6530 PyUnicode_GET_LENGTH(unicode));
6531 /* Non-Latin-1 characters present. Defer to above function to
6532 raise the exception. */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006533 return unicode_encode_ucs1(unicode, errors, 256);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006534}
6535
6536PyObject*
6537PyUnicode_AsLatin1String(PyObject *unicode)
6538{
6539 return _PyUnicode_AsLatin1String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006540}
6541
6542/* --- 7-bit ASCII Codec -------------------------------------------------- */
6543
Alexander Belopolsky40018472011-02-26 01:02:56 +00006544PyObject *
6545PyUnicode_DecodeASCII(const char *s,
6546 Py_ssize_t size,
6547 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006548{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006549 const char *starts = s;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006550 PyObject *unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006551 int kind;
6552 void *data;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006553 Py_ssize_t startinpos;
6554 Py_ssize_t endinpos;
6555 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006556 const char *e;
6557 PyObject *errorHandler = NULL;
6558 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006559
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006560 if (size == 0) {
6561 Py_INCREF(unicode_empty);
6562 return unicode_empty;
6563 }
6564
Guido van Rossumd57fd912000-03-10 22:53:23 +00006565 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Victor Stinner702c7342011-10-05 13:50:52 +02006566 if (size == 1 && (unsigned char)s[0] < 128)
6567 return get_latin1_char((unsigned char)s[0]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006568
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006569 unicode = PyUnicode_New(size, 127);
6570 if (unicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006571 goto onError;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006572
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006573 e = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006574 data = PyUnicode_1BYTE_DATA(unicode);
6575 outpos = ascii_decode(s, e, (Py_UCS1 *)data);
6576 if (outpos == size)
6577 return unicode;
6578
6579 s += outpos;
6580 kind = PyUnicode_1BYTE_KIND;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006581 while (s < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006582 register unsigned char c = (unsigned char)*s;
6583 if (c < 128) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006584 PyUnicode_WRITE(kind, data, outpos++, c);
Benjamin Peterson29060642009-01-31 22:14:21 +00006585 ++s;
6586 }
6587 else {
6588 startinpos = s-starts;
6589 endinpos = startinpos + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00006590 if (unicode_decode_call_errorhandler(
6591 errors, &errorHandler,
6592 "ascii", "ordinal not in range(128)",
6593 &starts, &e, &startinpos, &endinpos, &exc, &s,
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006594 &unicode, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00006595 goto onError;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006596 kind = PyUnicode_KIND(unicode);
6597 data = PyUnicode_DATA(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00006598 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006599 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006600 if (unicode_resize(&unicode, outpos) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006601 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006602 Py_XDECREF(errorHandler);
6603 Py_XDECREF(exc);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006604 assert(_PyUnicode_CheckConsistency(unicode, 1));
6605 return unicode;
Tim Petersced69f82003-09-16 20:30:58 +00006606
Benjamin Peterson29060642009-01-31 22:14:21 +00006607 onError:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006608 Py_XDECREF(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006609 Py_XDECREF(errorHandler);
6610 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006611 return NULL;
6612}
6613
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006614/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006615PyObject *
6616PyUnicode_EncodeASCII(const Py_UNICODE *p,
6617 Py_ssize_t size,
6618 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006619{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006620 PyObject *result;
6621 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6622 if (unicode == NULL)
6623 return NULL;
6624 result = unicode_encode_ucs1(unicode, errors, 128);
6625 Py_DECREF(unicode);
6626 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006627}
6628
Alexander Belopolsky40018472011-02-26 01:02:56 +00006629PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006630_PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006631{
6632 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006633 PyErr_BadArgument();
6634 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006635 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006636 if (PyUnicode_READY(unicode) == -1)
6637 return NULL;
6638 /* Fast path: if it is an ASCII-only string, construct bytes object
6639 directly. Else defer to above function to raise the exception. */
6640 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
6641 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6642 PyUnicode_GET_LENGTH(unicode));
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006643 return unicode_encode_ucs1(unicode, errors, 128);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006644}
6645
6646PyObject *
6647PyUnicode_AsASCIIString(PyObject *unicode)
6648{
6649 return _PyUnicode_AsASCIIString(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006650}
6651
Victor Stinner99b95382011-07-04 14:23:54 +02006652#ifdef HAVE_MBCS
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006653
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006654/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006655
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00006656#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006657#define NEED_RETRY
6658#endif
6659
Victor Stinner3a50e702011-10-18 21:21:00 +02006660#ifndef WC_ERR_INVALID_CHARS
6661# define WC_ERR_INVALID_CHARS 0x0080
6662#endif
6663
6664static char*
6665code_page_name(UINT code_page, PyObject **obj)
6666{
6667 *obj = NULL;
6668 if (code_page == CP_ACP)
6669 return "mbcs";
6670 if (code_page == CP_UTF7)
6671 return "CP_UTF7";
6672 if (code_page == CP_UTF8)
6673 return "CP_UTF8";
6674
6675 *obj = PyBytes_FromFormat("cp%u", code_page);
6676 if (*obj == NULL)
6677 return NULL;
6678 return PyBytes_AS_STRING(*obj);
6679}
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006680
Alexander Belopolsky40018472011-02-26 01:02:56 +00006681static int
Victor Stinner3a50e702011-10-18 21:21:00 +02006682is_dbcs_lead_byte(UINT code_page, const char *s, int offset)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006683{
6684 const char *curr = s + offset;
Victor Stinner3a50e702011-10-18 21:21:00 +02006685 const char *prev;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006686
Victor Stinner3a50e702011-10-18 21:21:00 +02006687 if (!IsDBCSLeadByteEx(code_page, *curr))
6688 return 0;
6689
6690 prev = CharPrevExA(code_page, s, curr, 0);
6691 if (prev == curr)
6692 return 1;
6693 /* FIXME: This code is limited to "true" double-byte encodings,
6694 as it assumes an incomplete character consists of a single
6695 byte. */
6696 if (curr - prev == 2)
6697 return 1;
6698 if (!IsDBCSLeadByteEx(code_page, *prev))
6699 return 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006700 return 0;
6701}
6702
Victor Stinner3a50e702011-10-18 21:21:00 +02006703static DWORD
6704decode_code_page_flags(UINT code_page)
6705{
6706 if (code_page == CP_UTF7) {
6707 /* The CP_UTF7 decoder only supports flags=0 */
6708 return 0;
6709 }
6710 else
6711 return MB_ERR_INVALID_CHARS;
6712}
6713
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006714/*
Victor Stinner3a50e702011-10-18 21:21:00 +02006715 * Decode a byte string from a Windows code page into unicode object in strict
6716 * mode.
6717 *
6718 * Returns consumed size if succeed, returns -2 on decode error, or raise a
6719 * WindowsError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006720 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006721static int
Victor Stinner3a50e702011-10-18 21:21:00 +02006722decode_code_page_strict(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01006723 PyObject **v,
Victor Stinner3a50e702011-10-18 21:21:00 +02006724 const char *in,
6725 int insize)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006726{
Victor Stinner3a50e702011-10-18 21:21:00 +02006727 const DWORD flags = decode_code_page_flags(code_page);
Victor Stinner24729f32011-11-10 20:31:37 +01006728 wchar_t *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02006729 DWORD outsize;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006730
6731 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02006732 assert(insize > 0);
6733 outsize = MultiByteToWideChar(code_page, flags, in, insize, NULL, 0);
6734 if (outsize <= 0)
6735 goto error;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006736
6737 if (*v == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006738 /* Create unicode object */
Victor Stinnerab595942011-12-17 04:59:06 +01006739 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01006740 *v = (PyObject*)_PyUnicode_New(outsize);
Benjamin Peterson29060642009-01-31 22:14:21 +00006741 if (*v == NULL)
6742 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02006743 out = PyUnicode_AS_UNICODE(*v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006744 }
6745 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006746 /* Extend unicode object */
Victor Stinner3a50e702011-10-18 21:21:00 +02006747 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
Victor Stinner16e6a802011-12-12 13:24:15 +01006748 if (unicode_resize(v, n + outsize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006749 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02006750 out = PyUnicode_AS_UNICODE(*v) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006751 }
6752
6753 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02006754 outsize = MultiByteToWideChar(code_page, flags, in, insize, out, outsize);
6755 if (outsize <= 0)
6756 goto error;
6757 return insize;
Victor Stinner554f3f02010-06-16 23:33:54 +00006758
Victor Stinner3a50e702011-10-18 21:21:00 +02006759error:
6760 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
6761 return -2;
6762 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00006763 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006764}
6765
Victor Stinner3a50e702011-10-18 21:21:00 +02006766/*
6767 * Decode a byte string from a code page into unicode object with an error
6768 * handler.
6769 *
6770 * Returns consumed size if succeed, or raise a WindowsError or
6771 * UnicodeDecodeError exception and returns -1 on error.
6772 */
6773static int
6774decode_code_page_errors(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01006775 PyObject **v,
6776 const char *in, const int size,
Victor Stinner3a50e702011-10-18 21:21:00 +02006777 const char *errors)
6778{
6779 const char *startin = in;
6780 const char *endin = in + size;
6781 const DWORD flags = decode_code_page_flags(code_page);
6782 /* Ideally, we should get reason from FormatMessage. This is the Windows
6783 2000 English version of the message. */
6784 const char *reason = "No mapping for the Unicode character exists "
6785 "in the target code page.";
6786 /* each step cannot decode more than 1 character, but a character can be
6787 represented as a surrogate pair */
6788 wchar_t buffer[2], *startout, *out;
6789 int insize, outsize;
6790 PyObject *errorHandler = NULL;
6791 PyObject *exc = NULL;
6792 PyObject *encoding_obj = NULL;
6793 char *encoding;
6794 DWORD err;
6795 int ret = -1;
6796
6797 assert(size > 0);
6798
6799 encoding = code_page_name(code_page, &encoding_obj);
6800 if (encoding == NULL)
6801 return -1;
6802
6803 if (errors == NULL || strcmp(errors, "strict") == 0) {
6804 /* The last error was ERROR_NO_UNICODE_TRANSLATION, then we raise a
6805 UnicodeDecodeError. */
6806 make_decode_exception(&exc, encoding, in, size, 0, 0, reason);
6807 if (exc != NULL) {
6808 PyCodec_StrictErrors(exc);
6809 Py_CLEAR(exc);
6810 }
6811 goto error;
6812 }
6813
6814 if (*v == NULL) {
6815 /* Create unicode object */
6816 if (size > PY_SSIZE_T_MAX / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
6817 PyErr_NoMemory();
6818 goto error;
6819 }
Victor Stinnerab595942011-12-17 04:59:06 +01006820 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01006821 *v = (PyObject*)_PyUnicode_New(size * Py_ARRAY_LENGTH(buffer));
Victor Stinner3a50e702011-10-18 21:21:00 +02006822 if (*v == NULL)
6823 goto error;
6824 startout = PyUnicode_AS_UNICODE(*v);
6825 }
6826 else {
6827 /* Extend unicode object */
6828 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
6829 if (size > (PY_SSIZE_T_MAX - n) / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
6830 PyErr_NoMemory();
6831 goto error;
6832 }
Victor Stinner16e6a802011-12-12 13:24:15 +01006833 if (unicode_resize(v, n + size * Py_ARRAY_LENGTH(buffer)) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02006834 goto error;
6835 startout = PyUnicode_AS_UNICODE(*v) + n;
6836 }
6837
6838 /* Decode the byte string character per character */
6839 out = startout;
6840 while (in < endin)
6841 {
6842 /* Decode a character */
6843 insize = 1;
6844 do
6845 {
6846 outsize = MultiByteToWideChar(code_page, flags,
6847 in, insize,
6848 buffer, Py_ARRAY_LENGTH(buffer));
6849 if (outsize > 0)
6850 break;
6851 err = GetLastError();
6852 if (err != ERROR_NO_UNICODE_TRANSLATION
6853 && err != ERROR_INSUFFICIENT_BUFFER)
6854 {
6855 PyErr_SetFromWindowsErr(0);
6856 goto error;
6857 }
6858 insize++;
6859 }
6860 /* 4=maximum length of a UTF-8 sequence */
6861 while (insize <= 4 && (in + insize) <= endin);
6862
6863 if (outsize <= 0) {
6864 Py_ssize_t startinpos, endinpos, outpos;
6865
6866 startinpos = in - startin;
6867 endinpos = startinpos + 1;
6868 outpos = out - PyUnicode_AS_UNICODE(*v);
6869 if (unicode_decode_call_errorhandler(
6870 errors, &errorHandler,
6871 encoding, reason,
6872 &startin, &endin, &startinpos, &endinpos, &exc, &in,
Victor Stinner596a6c42011-11-09 00:02:18 +01006873 v, &outpos))
Victor Stinner3a50e702011-10-18 21:21:00 +02006874 {
6875 goto error;
6876 }
Victor Stinner596a6c42011-11-09 00:02:18 +01006877 out = PyUnicode_AS_UNICODE(*v) + outpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02006878 }
6879 else {
6880 in += insize;
6881 memcpy(out, buffer, outsize * sizeof(wchar_t));
6882 out += outsize;
6883 }
6884 }
6885
6886 /* write a NUL character at the end */
6887 *out = 0;
6888
6889 /* Extend unicode object */
6890 outsize = out - startout;
6891 assert(outsize <= PyUnicode_WSTR_LENGTH(*v));
Victor Stinner16e6a802011-12-12 13:24:15 +01006892 if (unicode_resize(v, outsize) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02006893 goto error;
Victor Stinner76a31a62011-11-04 00:05:13 +01006894 ret = size;
Victor Stinner3a50e702011-10-18 21:21:00 +02006895
6896error:
6897 Py_XDECREF(encoding_obj);
6898 Py_XDECREF(errorHandler);
6899 Py_XDECREF(exc);
6900 return ret;
6901}
6902
Victor Stinner3a50e702011-10-18 21:21:00 +02006903static PyObject *
6904decode_code_page_stateful(int code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01006905 const char *s, Py_ssize_t size,
6906 const char *errors, Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006907{
Victor Stinner76a31a62011-11-04 00:05:13 +01006908 PyObject *v = NULL;
6909 int chunk_size, final, converted, done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006910
Victor Stinner3a50e702011-10-18 21:21:00 +02006911 if (code_page < 0) {
6912 PyErr_SetString(PyExc_ValueError, "invalid code page number");
6913 return NULL;
6914 }
6915
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006916 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00006917 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006918
Victor Stinner76a31a62011-11-04 00:05:13 +01006919 do
6920 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006921#ifdef NEED_RETRY
Victor Stinner76a31a62011-11-04 00:05:13 +01006922 if (size > INT_MAX) {
6923 chunk_size = INT_MAX;
6924 final = 0;
6925 done = 0;
6926 }
6927 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006928#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01006929 {
6930 chunk_size = (int)size;
6931 final = (consumed == NULL);
6932 done = 1;
6933 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006934
Victor Stinner76a31a62011-11-04 00:05:13 +01006935 /* Skip trailing lead-byte unless 'final' is set */
6936 if (!final && is_dbcs_lead_byte(code_page, s, chunk_size - 1))
6937 --chunk_size;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006938
Victor Stinner76a31a62011-11-04 00:05:13 +01006939 if (chunk_size == 0 && done) {
6940 if (v != NULL)
6941 break;
6942 Py_INCREF(unicode_empty);
6943 return unicode_empty;
6944 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006945
Victor Stinner76a31a62011-11-04 00:05:13 +01006946
6947 converted = decode_code_page_strict(code_page, &v,
6948 s, chunk_size);
6949 if (converted == -2)
6950 converted = decode_code_page_errors(code_page, &v,
6951 s, chunk_size,
6952 errors);
6953 assert(converted != 0);
6954
6955 if (converted < 0) {
6956 Py_XDECREF(v);
6957 return NULL;
6958 }
6959
6960 if (consumed)
6961 *consumed += converted;
6962
6963 s += converted;
6964 size -= converted;
6965 } while (!done);
Victor Stinner3a50e702011-10-18 21:21:00 +02006966
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006967 return unicode_result(v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006968}
6969
Alexander Belopolsky40018472011-02-26 01:02:56 +00006970PyObject *
Victor Stinner3a50e702011-10-18 21:21:00 +02006971PyUnicode_DecodeCodePageStateful(int code_page,
6972 const char *s,
6973 Py_ssize_t size,
6974 const char *errors,
6975 Py_ssize_t *consumed)
6976{
6977 return decode_code_page_stateful(code_page, s, size, errors, consumed);
6978}
6979
6980PyObject *
6981PyUnicode_DecodeMBCSStateful(const char *s,
6982 Py_ssize_t size,
6983 const char *errors,
6984 Py_ssize_t *consumed)
6985{
6986 return decode_code_page_stateful(CP_ACP, s, size, errors, consumed);
6987}
6988
6989PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00006990PyUnicode_DecodeMBCS(const char *s,
6991 Py_ssize_t size,
6992 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006993{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006994 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
6995}
6996
Victor Stinner3a50e702011-10-18 21:21:00 +02006997static DWORD
6998encode_code_page_flags(UINT code_page, const char *errors)
6999{
7000 if (code_page == CP_UTF8) {
7001 if (winver.dwMajorVersion >= 6)
7002 /* CP_UTF8 supports WC_ERR_INVALID_CHARS on Windows Vista
7003 and later */
7004 return WC_ERR_INVALID_CHARS;
7005 else
7006 /* CP_UTF8 only supports flags=0 on Windows older than Vista */
7007 return 0;
7008 }
7009 else if (code_page == CP_UTF7) {
7010 /* CP_UTF7 only supports flags=0 */
7011 return 0;
7012 }
7013 else {
7014 if (errors != NULL && strcmp(errors, "replace") == 0)
7015 return 0;
7016 else
7017 return WC_NO_BEST_FIT_CHARS;
7018 }
7019}
7020
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007021/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007022 * Encode a Unicode string to a Windows code page into a byte string in strict
7023 * mode.
7024 *
7025 * Returns consumed characters if succeed, returns -2 on encode error, or raise
7026 * a WindowsError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007027 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007028static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007029encode_code_page_strict(UINT code_page, PyObject **outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007030 PyObject *unicode, Py_ssize_t offset, int len,
Victor Stinner3a50e702011-10-18 21:21:00 +02007031 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007032{
Victor Stinner554f3f02010-06-16 23:33:54 +00007033 BOOL usedDefaultChar = FALSE;
Victor Stinner3a50e702011-10-18 21:21:00 +02007034 BOOL *pusedDefaultChar = &usedDefaultChar;
7035 int outsize;
Victor Stinner554f3f02010-06-16 23:33:54 +00007036 PyObject *exc = NULL;
Victor Stinner24729f32011-11-10 20:31:37 +01007037 wchar_t *p;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007038 Py_ssize_t size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007039 const DWORD flags = encode_code_page_flags(code_page, NULL);
7040 char *out;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007041 /* Create a substring so that we can get the UTF-16 representation
7042 of just the slice under consideration. */
7043 PyObject *substring;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007044
Martin v. Löwis3d325192011-11-04 18:23:06 +01007045 assert(len > 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007046
Victor Stinner3a50e702011-10-18 21:21:00 +02007047 if (code_page != CP_UTF8 && code_page != CP_UTF7)
Victor Stinner554f3f02010-06-16 23:33:54 +00007048 pusedDefaultChar = &usedDefaultChar;
Victor Stinner3a50e702011-10-18 21:21:00 +02007049 else
Victor Stinner554f3f02010-06-16 23:33:54 +00007050 pusedDefaultChar = NULL;
Victor Stinner554f3f02010-06-16 23:33:54 +00007051
Victor Stinner2fc507f2011-11-04 20:06:39 +01007052 substring = PyUnicode_Substring(unicode, offset, offset+len);
7053 if (substring == NULL)
7054 return -1;
7055 p = PyUnicode_AsUnicodeAndSize(substring, &size);
7056 if (p == NULL) {
7057 Py_DECREF(substring);
7058 return -1;
7059 }
Martin v. Löwis3d325192011-11-04 18:23:06 +01007060
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007061 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007062 outsize = WideCharToMultiByte(code_page, flags,
7063 p, size,
7064 NULL, 0,
7065 NULL, pusedDefaultChar);
7066 if (outsize <= 0)
7067 goto error;
7068 /* If we used a default char, then we failed! */
Victor Stinner2fc507f2011-11-04 20:06:39 +01007069 if (pusedDefaultChar && *pusedDefaultChar) {
7070 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007071 return -2;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007072 }
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007073
Victor Stinner3a50e702011-10-18 21:21:00 +02007074 if (*outbytes == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007075 /* Create string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007076 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007077 if (*outbytes == NULL) {
7078 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007079 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007080 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007081 out = PyBytes_AS_STRING(*outbytes);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007082 }
7083 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007084 /* Extend string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007085 const Py_ssize_t n = PyBytes_Size(*outbytes);
7086 if (outsize > PY_SSIZE_T_MAX - n) {
7087 PyErr_NoMemory();
Victor Stinner2fc507f2011-11-04 20:06:39 +01007088 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007089 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007090 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007091 if (_PyBytes_Resize(outbytes, n + outsize) < 0) {
7092 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007093 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007094 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007095 out = PyBytes_AS_STRING(*outbytes) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007096 }
7097
7098 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007099 outsize = WideCharToMultiByte(code_page, flags,
7100 p, size,
7101 out, outsize,
7102 NULL, pusedDefaultChar);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007103 Py_CLEAR(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007104 if (outsize <= 0)
7105 goto error;
7106 if (pusedDefaultChar && *pusedDefaultChar)
7107 return -2;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007108 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00007109
Victor Stinner3a50e702011-10-18 21:21:00 +02007110error:
Victor Stinner2fc507f2011-11-04 20:06:39 +01007111 Py_XDECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007112 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7113 return -2;
7114 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007115 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007116}
7117
Victor Stinner3a50e702011-10-18 21:21:00 +02007118/*
7119 * Encode a Unicode string to a Windows code page into a byte string using a
7120 * error handler.
7121 *
7122 * Returns consumed characters if succeed, or raise a WindowsError and returns
7123 * -1 on other error.
7124 */
7125static int
7126encode_code_page_errors(UINT code_page, PyObject **outbytes,
Victor Stinner7581cef2011-11-03 22:32:33 +01007127 PyObject *unicode, Py_ssize_t unicode_offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007128 Py_ssize_t insize, const char* errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007129{
Victor Stinner3a50e702011-10-18 21:21:00 +02007130 const DWORD flags = encode_code_page_flags(code_page, errors);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007131 Py_ssize_t pos = unicode_offset;
7132 Py_ssize_t endin = unicode_offset + insize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007133 /* Ideally, we should get reason from FormatMessage. This is the Windows
7134 2000 English version of the message. */
7135 const char *reason = "invalid character";
7136 /* 4=maximum length of a UTF-8 sequence */
7137 char buffer[4];
7138 BOOL usedDefaultChar = FALSE, *pusedDefaultChar;
7139 Py_ssize_t outsize;
7140 char *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007141 PyObject *errorHandler = NULL;
7142 PyObject *exc = NULL;
7143 PyObject *encoding_obj = NULL;
7144 char *encoding;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007145 Py_ssize_t newpos, newoutsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007146 PyObject *rep;
7147 int ret = -1;
7148
7149 assert(insize > 0);
7150
7151 encoding = code_page_name(code_page, &encoding_obj);
7152 if (encoding == NULL)
7153 return -1;
7154
7155 if (errors == NULL || strcmp(errors, "strict") == 0) {
7156 /* The last error was ERROR_NO_UNICODE_TRANSLATION,
7157 then we raise a UnicodeEncodeError. */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007158 make_encode_exception(&exc, encoding, unicode, 0, 0, reason);
Victor Stinner3a50e702011-10-18 21:21:00 +02007159 if (exc != NULL) {
7160 PyCodec_StrictErrors(exc);
7161 Py_DECREF(exc);
7162 }
7163 Py_XDECREF(encoding_obj);
7164 return -1;
7165 }
7166
7167 if (code_page != CP_UTF8 && code_page != CP_UTF7)
7168 pusedDefaultChar = &usedDefaultChar;
7169 else
7170 pusedDefaultChar = NULL;
7171
7172 if (Py_ARRAY_LENGTH(buffer) > PY_SSIZE_T_MAX / insize) {
7173 PyErr_NoMemory();
7174 goto error;
7175 }
7176 outsize = insize * Py_ARRAY_LENGTH(buffer);
7177
7178 if (*outbytes == NULL) {
7179 /* Create string object */
7180 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
7181 if (*outbytes == NULL)
7182 goto error;
7183 out = PyBytes_AS_STRING(*outbytes);
7184 }
7185 else {
7186 /* Extend string object */
7187 Py_ssize_t n = PyBytes_Size(*outbytes);
7188 if (n > PY_SSIZE_T_MAX - outsize) {
7189 PyErr_NoMemory();
7190 goto error;
7191 }
7192 if (_PyBytes_Resize(outbytes, n + outsize) < 0)
7193 goto error;
7194 out = PyBytes_AS_STRING(*outbytes) + n;
7195 }
7196
7197 /* Encode the string character per character */
Martin v. Löwis3d325192011-11-04 18:23:06 +01007198 while (pos < endin)
Victor Stinner3a50e702011-10-18 21:21:00 +02007199 {
Victor Stinner2fc507f2011-11-04 20:06:39 +01007200 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, pos);
7201 wchar_t chars[2];
7202 int charsize;
7203 if (ch < 0x10000) {
7204 chars[0] = (wchar_t)ch;
7205 charsize = 1;
7206 }
7207 else {
7208 ch -= 0x10000;
7209 chars[0] = 0xd800 + (ch >> 10);
7210 chars[1] = 0xdc00 + (ch & 0x3ff);
7211 charsize = 2;
7212 }
7213
Victor Stinner3a50e702011-10-18 21:21:00 +02007214 outsize = WideCharToMultiByte(code_page, flags,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007215 chars, charsize,
Victor Stinner3a50e702011-10-18 21:21:00 +02007216 buffer, Py_ARRAY_LENGTH(buffer),
7217 NULL, pusedDefaultChar);
7218 if (outsize > 0) {
7219 if (pusedDefaultChar == NULL || !(*pusedDefaultChar))
7220 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007221 pos++;
Victor Stinner3a50e702011-10-18 21:21:00 +02007222 memcpy(out, buffer, outsize);
7223 out += outsize;
7224 continue;
7225 }
7226 }
7227 else if (GetLastError() != ERROR_NO_UNICODE_TRANSLATION) {
7228 PyErr_SetFromWindowsErr(0);
7229 goto error;
7230 }
7231
Victor Stinner3a50e702011-10-18 21:21:00 +02007232 rep = unicode_encode_call_errorhandler(
7233 errors, &errorHandler, encoding, reason,
Victor Stinner7581cef2011-11-03 22:32:33 +01007234 unicode, &exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007235 pos, pos + 1, &newpos);
Victor Stinner3a50e702011-10-18 21:21:00 +02007236 if (rep == NULL)
7237 goto error;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007238 pos = newpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007239
7240 if (PyBytes_Check(rep)) {
7241 outsize = PyBytes_GET_SIZE(rep);
7242 if (outsize != 1) {
7243 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7244 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7245 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7246 Py_DECREF(rep);
7247 goto error;
7248 }
7249 out = PyBytes_AS_STRING(*outbytes) + offset;
7250 }
7251 memcpy(out, PyBytes_AS_STRING(rep), outsize);
7252 out += outsize;
7253 }
7254 else {
7255 Py_ssize_t i;
7256 enum PyUnicode_Kind kind;
7257 void *data;
7258
Benjamin Petersonbac79492012-01-14 13:34:47 -05007259 if (PyUnicode_READY(rep) == -1) {
Victor Stinner3a50e702011-10-18 21:21:00 +02007260 Py_DECREF(rep);
7261 goto error;
7262 }
7263
7264 outsize = PyUnicode_GET_LENGTH(rep);
7265 if (outsize != 1) {
7266 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7267 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7268 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7269 Py_DECREF(rep);
7270 goto error;
7271 }
7272 out = PyBytes_AS_STRING(*outbytes) + offset;
7273 }
7274 kind = PyUnicode_KIND(rep);
7275 data = PyUnicode_DATA(rep);
7276 for (i=0; i < outsize; i++) {
7277 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7278 if (ch > 127) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007279 raise_encode_exception(&exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007280 encoding, unicode,
7281 pos, pos + 1,
Victor Stinner3a50e702011-10-18 21:21:00 +02007282 "unable to encode error handler result to ASCII");
7283 Py_DECREF(rep);
7284 goto error;
7285 }
7286 *out = (unsigned char)ch;
7287 out++;
7288 }
7289 }
7290 Py_DECREF(rep);
7291 }
7292 /* write a NUL byte */
7293 *out = 0;
7294 outsize = out - PyBytes_AS_STRING(*outbytes);
7295 assert(outsize <= PyBytes_GET_SIZE(*outbytes));
7296 if (_PyBytes_Resize(outbytes, outsize) < 0)
7297 goto error;
7298 ret = 0;
7299
7300error:
7301 Py_XDECREF(encoding_obj);
7302 Py_XDECREF(errorHandler);
7303 Py_XDECREF(exc);
7304 return ret;
7305}
7306
Victor Stinner3a50e702011-10-18 21:21:00 +02007307static PyObject *
7308encode_code_page(int code_page,
Victor Stinner7581cef2011-11-03 22:32:33 +01007309 PyObject *unicode,
Victor Stinner3a50e702011-10-18 21:21:00 +02007310 const char *errors)
7311{
Martin v. Löwis3d325192011-11-04 18:23:06 +01007312 Py_ssize_t len;
Victor Stinner3a50e702011-10-18 21:21:00 +02007313 PyObject *outbytes = NULL;
Victor Stinner7581cef2011-11-03 22:32:33 +01007314 Py_ssize_t offset;
Victor Stinner76a31a62011-11-04 00:05:13 +01007315 int chunk_len, ret, done;
Victor Stinner7581cef2011-11-03 22:32:33 +01007316
Benjamin Petersonbac79492012-01-14 13:34:47 -05007317 if (PyUnicode_READY(unicode) == -1)
Victor Stinner2fc507f2011-11-04 20:06:39 +01007318 return NULL;
7319 len = PyUnicode_GET_LENGTH(unicode);
Guido van Rossum03e29f12000-05-04 15:52:20 +00007320
Victor Stinner3a50e702011-10-18 21:21:00 +02007321 if (code_page < 0) {
7322 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7323 return NULL;
7324 }
7325
Martin v. Löwis3d325192011-11-04 18:23:06 +01007326 if (len == 0)
Victor Stinner76a31a62011-11-04 00:05:13 +01007327 return PyBytes_FromStringAndSize(NULL, 0);
7328
Victor Stinner7581cef2011-11-03 22:32:33 +01007329 offset = 0;
7330 do
7331 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007332#ifdef NEED_RETRY
Victor Stinner2fc507f2011-11-04 20:06:39 +01007333 /* UTF-16 encoding may double the size, so use only INT_MAX/2
Martin v. Löwis3d325192011-11-04 18:23:06 +01007334 chunks. */
7335 if (len > INT_MAX/2) {
7336 chunk_len = INT_MAX/2;
Victor Stinner76a31a62011-11-04 00:05:13 +01007337 done = 0;
7338 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007339 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007340#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007341 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007342 chunk_len = (int)len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007343 done = 1;
7344 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007345
Victor Stinner76a31a62011-11-04 00:05:13 +01007346 ret = encode_code_page_strict(code_page, &outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007347 unicode, offset, chunk_len,
Victor Stinner76a31a62011-11-04 00:05:13 +01007348 errors);
7349 if (ret == -2)
7350 ret = encode_code_page_errors(code_page, &outbytes,
7351 unicode, offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007352 chunk_len, errors);
Victor Stinner7581cef2011-11-03 22:32:33 +01007353 if (ret < 0) {
7354 Py_XDECREF(outbytes);
7355 return NULL;
7356 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007357
Victor Stinner7581cef2011-11-03 22:32:33 +01007358 offset += chunk_len;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007359 len -= chunk_len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007360 } while (!done);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007361
Victor Stinner3a50e702011-10-18 21:21:00 +02007362 return outbytes;
7363}
7364
7365PyObject *
7366PyUnicode_EncodeMBCS(const Py_UNICODE *p,
7367 Py_ssize_t size,
7368 const char *errors)
7369{
Victor Stinner7581cef2011-11-03 22:32:33 +01007370 PyObject *unicode, *res;
7371 unicode = PyUnicode_FromUnicode(p, size);
7372 if (unicode == NULL)
7373 return NULL;
7374 res = encode_code_page(CP_ACP, unicode, errors);
7375 Py_DECREF(unicode);
7376 return res;
Victor Stinner3a50e702011-10-18 21:21:00 +02007377}
7378
7379PyObject *
7380PyUnicode_EncodeCodePage(int code_page,
7381 PyObject *unicode,
7382 const char *errors)
7383{
Victor Stinner7581cef2011-11-03 22:32:33 +01007384 return encode_code_page(code_page, unicode, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007385}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007386
Alexander Belopolsky40018472011-02-26 01:02:56 +00007387PyObject *
7388PyUnicode_AsMBCSString(PyObject *unicode)
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007389{
7390 if (!PyUnicode_Check(unicode)) {
7391 PyErr_BadArgument();
7392 return NULL;
7393 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007394 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007395}
7396
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007397#undef NEED_RETRY
7398
Victor Stinner99b95382011-07-04 14:23:54 +02007399#endif /* HAVE_MBCS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007400
Guido van Rossumd57fd912000-03-10 22:53:23 +00007401/* --- Character Mapping Codec -------------------------------------------- */
7402
Alexander Belopolsky40018472011-02-26 01:02:56 +00007403PyObject *
7404PyUnicode_DecodeCharmap(const char *s,
7405 Py_ssize_t size,
7406 PyObject *mapping,
7407 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007408{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007409 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007410 Py_ssize_t startinpos;
7411 Py_ssize_t endinpos;
7412 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007413 const char *e;
Victor Stinner7931d9a2011-11-04 00:22:48 +01007414 PyObject *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007415 Py_ssize_t extrachars = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007416 PyObject *errorHandler = NULL;
7417 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00007418
Guido van Rossumd57fd912000-03-10 22:53:23 +00007419 /* Default to Latin-1 */
7420 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007421 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007422
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007423 v = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007424 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007425 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007426 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01007427 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007428 outpos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007429 e = s + size;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007430 if (PyUnicode_CheckExact(mapping)) {
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007431 Py_ssize_t maplen;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007432 enum PyUnicode_Kind mapkind;
7433 void *mapdata;
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007434 Py_UCS4 x;
7435
Benjamin Petersonbac79492012-01-14 13:34:47 -05007436 if (PyUnicode_READY(mapping) == -1)
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007437 return NULL;
7438
7439 maplen = PyUnicode_GET_LENGTH(mapping);
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007440 mapdata = PyUnicode_DATA(mapping);
7441 mapkind = PyUnicode_KIND(mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00007442 while (s < e) {
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007443 unsigned char ch;
7444 if (mapkind == PyUnicode_2BYTE_KIND && maplen >= 256) {
7445 enum PyUnicode_Kind outkind = PyUnicode_KIND(v);
7446 if (outkind == PyUnicode_1BYTE_KIND) {
7447 void *outdata = PyUnicode_DATA(v);
7448 Py_UCS4 maxchar = PyUnicode_MAX_CHAR_VALUE(v);
7449 while (s < e) {
7450 unsigned char ch = *s;
7451 x = PyUnicode_READ(PyUnicode_2BYTE_KIND, mapdata, ch);
7452 if (x > maxchar)
7453 goto Error;
7454 PyUnicode_WRITE(PyUnicode_1BYTE_KIND, outdata, outpos++, x);
7455 ++s;
7456 }
7457 break;
7458 }
7459 else if (outkind == PyUnicode_2BYTE_KIND) {
7460 void *outdata = PyUnicode_DATA(v);
7461 while (s < e) {
7462 unsigned char ch = *s;
7463 x = PyUnicode_READ(PyUnicode_2BYTE_KIND, mapdata, ch);
7464 if (x == 0xFFFE)
7465 goto Error;
7466 PyUnicode_WRITE(PyUnicode_2BYTE_KIND, outdata, outpos++, x);
7467 ++s;
7468 }
7469 break;
7470 }
7471 }
7472 ch = *s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007473
Benjamin Peterson29060642009-01-31 22:14:21 +00007474 if (ch < maplen)
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007475 x = PyUnicode_READ(mapkind, mapdata, ch);
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007476 else
7477 x = 0xfffe; /* invalid value */
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007478Error:
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007479 if (x == 0xfffe)
7480 {
Benjamin Peterson29060642009-01-31 22:14:21 +00007481 /* undefined mapping */
Benjamin Peterson29060642009-01-31 22:14:21 +00007482 startinpos = s-starts;
7483 endinpos = startinpos+1;
7484 if (unicode_decode_call_errorhandler(
7485 errors, &errorHandler,
7486 "charmap", "character maps to <undefined>",
7487 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007488 &v, &outpos)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007489 goto onError;
7490 }
7491 continue;
7492 }
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007493
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007494 if (unicode_putchar(&v, &outpos, x) < 0)
7495 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00007496 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007497 }
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007498 }
7499 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007500 while (s < e) {
7501 unsigned char ch = *s;
7502 PyObject *w, *x;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007503
Benjamin Peterson29060642009-01-31 22:14:21 +00007504 /* Get mapping (char ordinal -> integer, Unicode char or None) */
7505 w = PyLong_FromLong((long)ch);
7506 if (w == NULL)
7507 goto onError;
7508 x = PyObject_GetItem(mapping, w);
7509 Py_DECREF(w);
7510 if (x == NULL) {
7511 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7512 /* No mapping found means: mapping is undefined. */
7513 PyErr_Clear();
7514 x = Py_None;
7515 Py_INCREF(x);
7516 } else
7517 goto onError;
7518 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007519
Benjamin Peterson29060642009-01-31 22:14:21 +00007520 /* Apply mapping */
7521 if (PyLong_Check(x)) {
7522 long value = PyLong_AS_LONG(x);
Antoine Pitroua1f76552012-09-23 20:00:04 +02007523 if (value < 0 || value > MAX_UNICODE) {
7524 PyErr_Format(PyExc_TypeError,
7525 "character mapping must be in range(0x%lx)",
7526 (unsigned long)MAX_UNICODE + 1);
Benjamin Peterson29060642009-01-31 22:14:21 +00007527 Py_DECREF(x);
7528 goto onError;
7529 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007530 if (unicode_putchar(&v, &outpos, value) < 0)
7531 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00007532 }
7533 else if (x == Py_None) {
7534 /* undefined mapping */
Benjamin Peterson29060642009-01-31 22:14:21 +00007535 startinpos = s-starts;
7536 endinpos = startinpos+1;
7537 if (unicode_decode_call_errorhandler(
7538 errors, &errorHandler,
7539 "charmap", "character maps to <undefined>",
7540 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007541 &v, &outpos)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007542 Py_DECREF(x);
7543 goto onError;
7544 }
7545 Py_DECREF(x);
7546 continue;
7547 }
7548 else if (PyUnicode_Check(x)) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007549 Py_ssize_t targetsize;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007550
Benjamin Petersonbac79492012-01-14 13:34:47 -05007551 if (PyUnicode_READY(x) == -1)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007552 goto onError;
7553 targetsize = PyUnicode_GET_LENGTH(x);
7554
7555 if (targetsize == 1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007556 /* 1-1 mapping */
Victor Stinner62aa4d02011-11-09 00:03:45 +01007557 if (unicode_putchar(&v, &outpos,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007558 PyUnicode_READ_CHAR(x, 0)) < 0)
7559 goto onError;
7560 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007561 else if (targetsize > 1) {
7562 /* 1-n mapping */
7563 if (targetsize > extrachars) {
7564 /* resize first */
Benjamin Peterson29060642009-01-31 22:14:21 +00007565 Py_ssize_t needed = (targetsize - extrachars) + \
7566 (targetsize << 2);
7567 extrachars += needed;
7568 /* XXX overflow detection missing */
Victor Stinner16e6a802011-12-12 13:24:15 +01007569 if (unicode_resize(&v,
7570 PyUnicode_GET_LENGTH(v) + needed) < 0)
7571 {
Benjamin Peterson29060642009-01-31 22:14:21 +00007572 Py_DECREF(x);
7573 goto onError;
7574 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007575 }
Victor Stinner1b487b42012-05-03 12:29:04 +02007576 if (unicode_widen(&v, outpos, PyUnicode_MAX_CHAR_VALUE(x)) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007577 goto onError;
7578 PyUnicode_CopyCharacters(v, outpos, x, 0, targetsize);
7579 outpos += targetsize;
Benjamin Peterson29060642009-01-31 22:14:21 +00007580 extrachars -= targetsize;
7581 }
7582 /* 1-0 mapping: skip the character */
7583 }
7584 else {
7585 /* wrong return value */
7586 PyErr_SetString(PyExc_TypeError,
7587 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00007588 Py_DECREF(x);
7589 goto onError;
7590 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007591 Py_DECREF(x);
7592 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007593 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00007594 }
Victor Stinner16e6a802011-12-12 13:24:15 +01007595 if (unicode_resize(&v, outpos) < 0)
Antoine Pitroua8f63c02011-11-08 18:37:16 +01007596 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007597 Py_XDECREF(errorHandler);
7598 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01007599 return unicode_result(v);
Tim Petersced69f82003-09-16 20:30:58 +00007600
Benjamin Peterson29060642009-01-31 22:14:21 +00007601 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007602 Py_XDECREF(errorHandler);
7603 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007604 Py_XDECREF(v);
7605 return NULL;
7606}
7607
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007608/* Charmap encoding: the lookup table */
7609
Alexander Belopolsky40018472011-02-26 01:02:56 +00007610struct encoding_map {
Benjamin Peterson29060642009-01-31 22:14:21 +00007611 PyObject_HEAD
7612 unsigned char level1[32];
7613 int count2, count3;
7614 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007615};
7616
7617static PyObject*
7618encoding_map_size(PyObject *obj, PyObject* args)
7619{
7620 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007621 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00007622 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007623}
7624
7625static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007626 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00007627 PyDoc_STR("Return the size (in bytes) of this object") },
7628 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007629};
7630
7631static void
7632encoding_map_dealloc(PyObject* o)
7633{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007634 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007635}
7636
7637static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007638 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007639 "EncodingMap", /*tp_name*/
7640 sizeof(struct encoding_map), /*tp_basicsize*/
7641 0, /*tp_itemsize*/
7642 /* methods */
7643 encoding_map_dealloc, /*tp_dealloc*/
7644 0, /*tp_print*/
7645 0, /*tp_getattr*/
7646 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00007647 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00007648 0, /*tp_repr*/
7649 0, /*tp_as_number*/
7650 0, /*tp_as_sequence*/
7651 0, /*tp_as_mapping*/
7652 0, /*tp_hash*/
7653 0, /*tp_call*/
7654 0, /*tp_str*/
7655 0, /*tp_getattro*/
7656 0, /*tp_setattro*/
7657 0, /*tp_as_buffer*/
7658 Py_TPFLAGS_DEFAULT, /*tp_flags*/
7659 0, /*tp_doc*/
7660 0, /*tp_traverse*/
7661 0, /*tp_clear*/
7662 0, /*tp_richcompare*/
7663 0, /*tp_weaklistoffset*/
7664 0, /*tp_iter*/
7665 0, /*tp_iternext*/
7666 encoding_map_methods, /*tp_methods*/
7667 0, /*tp_members*/
7668 0, /*tp_getset*/
7669 0, /*tp_base*/
7670 0, /*tp_dict*/
7671 0, /*tp_descr_get*/
7672 0, /*tp_descr_set*/
7673 0, /*tp_dictoffset*/
7674 0, /*tp_init*/
7675 0, /*tp_alloc*/
7676 0, /*tp_new*/
7677 0, /*tp_free*/
7678 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007679};
7680
7681PyObject*
7682PyUnicode_BuildEncodingMap(PyObject* string)
7683{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007684 PyObject *result;
7685 struct encoding_map *mresult;
7686 int i;
7687 int need_dict = 0;
7688 unsigned char level1[32];
7689 unsigned char level2[512];
7690 unsigned char *mlevel1, *mlevel2, *mlevel3;
7691 int count2 = 0, count3 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007692 int kind;
7693 void *data;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007694 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007695 Py_UCS4 ch;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007696
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007697 if (!PyUnicode_Check(string) || !PyUnicode_GET_LENGTH(string)) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007698 PyErr_BadArgument();
7699 return NULL;
7700 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007701 kind = PyUnicode_KIND(string);
7702 data = PyUnicode_DATA(string);
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007703 length = PyUnicode_GET_LENGTH(string);
7704 length = Py_MIN(length, 256);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007705 memset(level1, 0xFF, sizeof level1);
7706 memset(level2, 0xFF, sizeof level2);
7707
7708 /* If there isn't a one-to-one mapping of NULL to \0,
7709 or if there are non-BMP characters, we need to use
7710 a mapping dictionary. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007711 if (PyUnicode_READ(kind, data, 0) != 0)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007712 need_dict = 1;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007713 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007714 int l1, l2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007715 ch = PyUnicode_READ(kind, data, i);
7716 if (ch == 0 || ch > 0xFFFF) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007717 need_dict = 1;
7718 break;
7719 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007720 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007721 /* unmapped character */
7722 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007723 l1 = ch >> 11;
7724 l2 = ch >> 7;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007725 if (level1[l1] == 0xFF)
7726 level1[l1] = count2++;
7727 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00007728 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007729 }
7730
7731 if (count2 >= 0xFF || count3 >= 0xFF)
7732 need_dict = 1;
7733
7734 if (need_dict) {
7735 PyObject *result = PyDict_New();
7736 PyObject *key, *value;
7737 if (!result)
7738 return NULL;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007739 for (i = 0; i < length; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007740 key = PyLong_FromLong(PyUnicode_READ(kind, data, i));
Christian Heimes217cfd12007-12-02 14:31:20 +00007741 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007742 if (!key || !value)
7743 goto failed1;
7744 if (PyDict_SetItem(result, key, value) == -1)
7745 goto failed1;
7746 Py_DECREF(key);
7747 Py_DECREF(value);
7748 }
7749 return result;
7750 failed1:
7751 Py_XDECREF(key);
7752 Py_XDECREF(value);
7753 Py_DECREF(result);
7754 return NULL;
7755 }
7756
7757 /* Create a three-level trie */
7758 result = PyObject_MALLOC(sizeof(struct encoding_map) +
7759 16*count2 + 128*count3 - 1);
7760 if (!result)
7761 return PyErr_NoMemory();
7762 PyObject_Init(result, &EncodingMapType);
7763 mresult = (struct encoding_map*)result;
7764 mresult->count2 = count2;
7765 mresult->count3 = count3;
7766 mlevel1 = mresult->level1;
7767 mlevel2 = mresult->level23;
7768 mlevel3 = mresult->level23 + 16*count2;
7769 memcpy(mlevel1, level1, 32);
7770 memset(mlevel2, 0xFF, 16*count2);
7771 memset(mlevel3, 0, 128*count3);
7772 count3 = 0;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007773 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007774 int o1, o2, o3, i2, i3;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007775 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7776 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007777 /* unmapped character */
7778 continue;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007779 o1 = ch>>11;
7780 o2 = (ch>>7) & 0xF;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007781 i2 = 16*mlevel1[o1] + o2;
7782 if (mlevel2[i2] == 0xFF)
7783 mlevel2[i2] = count3++;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007784 o3 = ch & 0x7F;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007785 i3 = 128*mlevel2[i2] + o3;
7786 mlevel3[i3] = i;
7787 }
7788 return result;
7789}
7790
7791static int
Victor Stinner22168992011-11-20 17:09:18 +01007792encoding_map_lookup(Py_UCS4 c, PyObject *mapping)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007793{
7794 struct encoding_map *map = (struct encoding_map*)mapping;
7795 int l1 = c>>11;
7796 int l2 = (c>>7) & 0xF;
7797 int l3 = c & 0x7F;
7798 int i;
7799
Victor Stinner22168992011-11-20 17:09:18 +01007800 if (c > 0xFFFF)
Benjamin Peterson29060642009-01-31 22:14:21 +00007801 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007802 if (c == 0)
7803 return 0;
7804 /* level 1*/
7805 i = map->level1[l1];
7806 if (i == 0xFF) {
7807 return -1;
7808 }
7809 /* level 2*/
7810 i = map->level23[16*i+l2];
7811 if (i == 0xFF) {
7812 return -1;
7813 }
7814 /* level 3 */
7815 i = map->level23[16*map->count2 + 128*i + l3];
7816 if (i == 0) {
7817 return -1;
7818 }
7819 return i;
7820}
7821
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007822/* Lookup the character ch in the mapping. If the character
7823 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00007824 error occurred). */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007825static PyObject *
Victor Stinner22168992011-11-20 17:09:18 +01007826charmapencode_lookup(Py_UCS4 c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007827{
Christian Heimes217cfd12007-12-02 14:31:20 +00007828 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007829 PyObject *x;
7830
7831 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007832 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007833 x = PyObject_GetItem(mapping, w);
7834 Py_DECREF(w);
7835 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007836 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7837 /* No mapping found means: mapping is undefined. */
7838 PyErr_Clear();
7839 x = Py_None;
7840 Py_INCREF(x);
7841 return x;
7842 } else
7843 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007844 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00007845 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00007846 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00007847 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007848 long value = PyLong_AS_LONG(x);
7849 if (value < 0 || value > 255) {
7850 PyErr_SetString(PyExc_TypeError,
7851 "character mapping must be in range(256)");
7852 Py_DECREF(x);
7853 return NULL;
7854 }
7855 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007856 }
Christian Heimes72b710a2008-05-26 13:28:38 +00007857 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00007858 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007859 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007860 /* wrong return value */
7861 PyErr_Format(PyExc_TypeError,
7862 "character mapping must return integer, bytes or None, not %.400s",
7863 x->ob_type->tp_name);
7864 Py_DECREF(x);
7865 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007866 }
7867}
7868
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007869static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00007870charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007871{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007872 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
7873 /* exponentially overallocate to minimize reallocations */
7874 if (requiredsize < 2*outsize)
7875 requiredsize = 2*outsize;
7876 if (_PyBytes_Resize(outobj, requiredsize))
7877 return -1;
7878 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007879}
7880
Benjamin Peterson14339b62009-01-31 16:36:08 +00007881typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00007882 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Alexander Belopolsky40018472011-02-26 01:02:56 +00007883} charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007884/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00007885 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007886 space is available. Return a new reference to the object that
7887 was put in the output buffer, or Py_None, if the mapping was undefined
7888 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00007889 reallocation error occurred. The caller must decref the result */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007890static charmapencode_result
Victor Stinner22168992011-11-20 17:09:18 +01007891charmapencode_output(Py_UCS4 c, PyObject *mapping,
Alexander Belopolsky40018472011-02-26 01:02:56 +00007892 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007893{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007894 PyObject *rep;
7895 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00007896 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007897
Christian Heimes90aa7642007-12-19 02:45:37 +00007898 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007899 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00007900 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007901 if (res == -1)
7902 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00007903 if (outsize<requiredsize)
7904 if (charmapencode_resize(outobj, outpos, requiredsize))
7905 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00007906 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00007907 outstart[(*outpos)++] = (char)res;
7908 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007909 }
7910
7911 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007912 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007913 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007914 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007915 Py_DECREF(rep);
7916 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007917 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007918 if (PyLong_Check(rep)) {
7919 Py_ssize_t requiredsize = *outpos+1;
7920 if (outsize<requiredsize)
7921 if (charmapencode_resize(outobj, outpos, requiredsize)) {
7922 Py_DECREF(rep);
7923 return enc_EXCEPTION;
7924 }
Christian Heimes72b710a2008-05-26 13:28:38 +00007925 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00007926 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00007927 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007928 else {
7929 const char *repchars = PyBytes_AS_STRING(rep);
7930 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
7931 Py_ssize_t requiredsize = *outpos+repsize;
7932 if (outsize<requiredsize)
7933 if (charmapencode_resize(outobj, outpos, requiredsize)) {
7934 Py_DECREF(rep);
7935 return enc_EXCEPTION;
7936 }
Christian Heimes72b710a2008-05-26 13:28:38 +00007937 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00007938 memcpy(outstart + *outpos, repchars, repsize);
7939 *outpos += repsize;
7940 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007941 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007942 Py_DECREF(rep);
7943 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007944}
7945
7946/* handle an error in PyUnicode_EncodeCharmap
7947 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007948static int
7949charmap_encoding_error(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007950 PyObject *unicode, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007951 PyObject **exceptionObject,
Walter Dörwalde5402fb2003-08-14 20:25:29 +00007952 int *known_errorHandler, PyObject **errorHandler, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00007953 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007954{
7955 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007956 Py_ssize_t size, repsize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007957 Py_ssize_t newpos;
Victor Stinnerae4f7c82011-11-20 18:28:55 +01007958 enum PyUnicode_Kind kind;
7959 void *data;
7960 Py_ssize_t index;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007961 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00007962 Py_ssize_t collstartpos = *inpos;
7963 Py_ssize_t collendpos = *inpos+1;
7964 Py_ssize_t collpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007965 char *encoding = "charmap";
7966 char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007967 charmapencode_result x;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007968 Py_UCS4 ch;
Brian Curtin2787ea42011-11-02 15:09:37 -05007969 int val;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007970
Benjamin Petersonbac79492012-01-14 13:34:47 -05007971 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007972 return -1;
7973 size = PyUnicode_GET_LENGTH(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007974 /* find all unencodable characters */
7975 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007976 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00007977 if (Py_TYPE(mapping) == &EncodingMapType) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007978 ch = PyUnicode_READ_CHAR(unicode, collendpos);
Brian Curtin2787ea42011-11-02 15:09:37 -05007979 val = encoding_map_lookup(ch, mapping);
7980 if (val != -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00007981 break;
7982 ++collendpos;
7983 continue;
7984 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007985
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007986 ch = PyUnicode_READ_CHAR(unicode, collendpos);
7987 rep = charmapencode_lookup(ch, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00007988 if (rep==NULL)
7989 return -1;
7990 else if (rep!=Py_None) {
7991 Py_DECREF(rep);
7992 break;
7993 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007994 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00007995 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007996 }
7997 /* cache callback name lookup
7998 * (if not done yet, i.e. it's the first error) */
7999 if (*known_errorHandler==-1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008000 if ((errors==NULL) || (!strcmp(errors, "strict")))
8001 *known_errorHandler = 1;
8002 else if (!strcmp(errors, "replace"))
8003 *known_errorHandler = 2;
8004 else if (!strcmp(errors, "ignore"))
8005 *known_errorHandler = 3;
8006 else if (!strcmp(errors, "xmlcharrefreplace"))
8007 *known_errorHandler = 4;
8008 else
8009 *known_errorHandler = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008010 }
8011 switch (*known_errorHandler) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008012 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008013 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008014 return -1;
8015 case 2: /* replace */
8016 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008017 x = charmapencode_output('?', mapping, res, respos);
8018 if (x==enc_EXCEPTION) {
8019 return -1;
8020 }
8021 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008022 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008023 return -1;
8024 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008025 }
8026 /* fall through */
8027 case 3: /* ignore */
8028 *inpos = collendpos;
8029 break;
8030 case 4: /* xmlcharrefreplace */
8031 /* generate replacement (temporarily (mis)uses p) */
8032 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008033 char buffer[2+29+1+1];
8034 char *cp;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008035 sprintf(buffer, "&#%d;", (int)PyUnicode_READ_CHAR(unicode, collpos));
Benjamin Peterson29060642009-01-31 22:14:21 +00008036 for (cp = buffer; *cp; ++cp) {
8037 x = charmapencode_output(*cp, mapping, res, respos);
8038 if (x==enc_EXCEPTION)
8039 return -1;
8040 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008041 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008042 return -1;
8043 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008044 }
8045 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008046 *inpos = collendpos;
8047 break;
8048 default:
8049 repunicode = unicode_encode_call_errorhandler(errors, errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008050 encoding, reason, unicode, exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00008051 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008052 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008053 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00008054 if (PyBytes_Check(repunicode)) {
8055 /* Directly copy bytes result to output. */
8056 Py_ssize_t outsize = PyBytes_Size(*res);
8057 Py_ssize_t requiredsize;
8058 repsize = PyBytes_Size(repunicode);
8059 requiredsize = *respos + repsize;
8060 if (requiredsize > outsize)
8061 /* Make room for all additional bytes. */
8062 if (charmapencode_resize(res, respos, requiredsize)) {
8063 Py_DECREF(repunicode);
8064 return -1;
8065 }
8066 memcpy(PyBytes_AsString(*res) + *respos,
8067 PyBytes_AsString(repunicode), repsize);
8068 *respos += repsize;
8069 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008070 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00008071 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008072 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008073 /* generate replacement */
Benjamin Petersonbac79492012-01-14 13:34:47 -05008074 if (PyUnicode_READY(repunicode) == -1) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008075 Py_DECREF(repunicode);
8076 return -1;
8077 }
Victor Stinner9e30aa52011-11-21 02:49:52 +01008078 repsize = PyUnicode_GET_LENGTH(repunicode);
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008079 data = PyUnicode_DATA(repunicode);
8080 kind = PyUnicode_KIND(repunicode);
8081 for (index = 0; index < repsize; index++) {
8082 Py_UCS4 repch = PyUnicode_READ(kind, data, index);
8083 x = charmapencode_output(repch, mapping, res, respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008084 if (x==enc_EXCEPTION) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008085 Py_DECREF(repunicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00008086 return -1;
8087 }
8088 else if (x==enc_FAILED) {
8089 Py_DECREF(repunicode);
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008090 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008091 return -1;
8092 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008093 }
8094 *inpos = newpos;
8095 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008096 }
8097 return 0;
8098}
8099
Alexander Belopolsky40018472011-02-26 01:02:56 +00008100PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008101_PyUnicode_EncodeCharmap(PyObject *unicode,
8102 PyObject *mapping,
8103 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008104{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008105 /* output object */
8106 PyObject *res = NULL;
8107 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008108 Py_ssize_t inpos = 0;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008109 Py_ssize_t size;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008110 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008111 Py_ssize_t respos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008112 PyObject *errorHandler = NULL;
8113 PyObject *exc = NULL;
8114 /* the following variable is used for caching string comparisons
8115 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8116 * 3=ignore, 4=xmlcharrefreplace */
8117 int known_errorHandler = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008118
Benjamin Petersonbac79492012-01-14 13:34:47 -05008119 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008120 return NULL;
8121 size = PyUnicode_GET_LENGTH(unicode);
8122
Guido van Rossumd57fd912000-03-10 22:53:23 +00008123 /* Default to Latin-1 */
8124 if (mapping == NULL)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008125 return unicode_encode_ucs1(unicode, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008126
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008127 /* allocate enough for a simple encoding without
8128 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00008129 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008130 if (res == NULL)
8131 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00008132 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008133 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008134
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008135 while (inpos<size) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008136 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, inpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008137 /* try to encode it */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008138 charmapencode_result x = charmapencode_output(ch, mapping, &res, &respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008139 if (x==enc_EXCEPTION) /* error */
8140 goto onError;
8141 if (x==enc_FAILED) { /* unencodable character */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008142 if (charmap_encoding_error(unicode, &inpos, mapping,
Benjamin Peterson29060642009-01-31 22:14:21 +00008143 &exc,
8144 &known_errorHandler, &errorHandler, errors,
8145 &res, &respos)) {
8146 goto onError;
8147 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008148 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008149 else
8150 /* done with this character => adjust input position */
8151 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008152 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008153
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008154 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00008155 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00008156 if (_PyBytes_Resize(&res, respos) < 0)
8157 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00008158
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008159 Py_XDECREF(exc);
8160 Py_XDECREF(errorHandler);
8161 return res;
8162
Benjamin Peterson29060642009-01-31 22:14:21 +00008163 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008164 Py_XDECREF(res);
8165 Py_XDECREF(exc);
8166 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008167 return NULL;
8168}
8169
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008170/* Deprecated */
8171PyObject *
8172PyUnicode_EncodeCharmap(const Py_UNICODE *p,
8173 Py_ssize_t size,
8174 PyObject *mapping,
8175 const char *errors)
8176{
8177 PyObject *result;
8178 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8179 if (unicode == NULL)
8180 return NULL;
8181 result = _PyUnicode_EncodeCharmap(unicode, mapping, errors);
8182 Py_DECREF(unicode);
Victor Stinnerfc026c92011-11-04 00:24:51 +01008183 return result;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008184}
8185
Alexander Belopolsky40018472011-02-26 01:02:56 +00008186PyObject *
8187PyUnicode_AsCharmapString(PyObject *unicode,
8188 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008189{
8190 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008191 PyErr_BadArgument();
8192 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008193 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008194 return _PyUnicode_EncodeCharmap(unicode, mapping, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008195}
8196
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008197/* create or adjust a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008198static void
8199make_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008200 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008201 Py_ssize_t startpos, Py_ssize_t endpos,
8202 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008203{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008204 if (*exceptionObject == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008205 *exceptionObject = _PyUnicodeTranslateError_Create(
8206 unicode, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008207 }
8208 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008209 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
8210 goto onError;
8211 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
8212 goto onError;
8213 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
8214 goto onError;
8215 return;
8216 onError:
8217 Py_DECREF(*exceptionObject);
8218 *exceptionObject = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008219 }
8220}
8221
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008222/* raises a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008223static void
8224raise_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008225 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008226 Py_ssize_t startpos, Py_ssize_t endpos,
8227 const char *reason)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008228{
8229 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008230 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008231 if (*exceptionObject != NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008232 PyCodec_StrictErrors(*exceptionObject);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008233}
8234
8235/* error handling callback helper:
8236 build arguments, call the callback and check the arguments,
8237 put the result into newpos and return the replacement string, which
8238 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008239static PyObject *
8240unicode_translate_call_errorhandler(const char *errors,
8241 PyObject **errorHandler,
8242 const char *reason,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008243 PyObject *unicode, PyObject **exceptionObject,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008244 Py_ssize_t startpos, Py_ssize_t endpos,
8245 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008246{
Benjamin Peterson142957c2008-07-04 19:55:29 +00008247 static char *argparse = "O!n;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008248
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008249 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008250 PyObject *restuple;
8251 PyObject *resunicode;
8252
8253 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008254 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008255 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008256 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008257 }
8258
8259 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008260 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008261 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008262 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008263
8264 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00008265 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008266 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008267 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008268 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00008269 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00008270 Py_DECREF(restuple);
8271 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008272 }
8273 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type,
Benjamin Peterson29060642009-01-31 22:14:21 +00008274 &resunicode, &i_newpos)) {
8275 Py_DECREF(restuple);
8276 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008277 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00008278 if (i_newpos<0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008279 *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008280 else
8281 *newpos = i_newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008282 if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008283 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
8284 Py_DECREF(restuple);
8285 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00008286 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008287 Py_INCREF(resunicode);
8288 Py_DECREF(restuple);
8289 return resunicode;
8290}
8291
8292/* Lookup the character ch in the mapping and put the result in result,
8293 which must be decrefed by the caller.
8294 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008295static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008296charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008297{
Christian Heimes217cfd12007-12-02 14:31:20 +00008298 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008299 PyObject *x;
8300
8301 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008302 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008303 x = PyObject_GetItem(mapping, w);
8304 Py_DECREF(w);
8305 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008306 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8307 /* No mapping found means: use 1:1 mapping. */
8308 PyErr_Clear();
8309 *result = NULL;
8310 return 0;
8311 } else
8312 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008313 }
8314 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008315 *result = x;
8316 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008317 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008318 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008319 long value = PyLong_AS_LONG(x);
8320 long max = PyUnicode_GetMax();
8321 if (value < 0 || value > max) {
8322 PyErr_Format(PyExc_TypeError,
Guido van Rossum5a2f7e602007-10-24 21:13:09 +00008323 "character mapping must be in range(0x%x)", max+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00008324 Py_DECREF(x);
8325 return -1;
8326 }
8327 *result = x;
8328 return 0;
8329 }
8330 else if (PyUnicode_Check(x)) {
8331 *result = x;
8332 return 0;
8333 }
8334 else {
8335 /* wrong return value */
8336 PyErr_SetString(PyExc_TypeError,
8337 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00008338 Py_DECREF(x);
8339 return -1;
8340 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008341}
8342/* ensure that *outobj is at least requiredsize characters long,
Benjamin Peterson29060642009-01-31 22:14:21 +00008343 if not reallocate and adjust various state variables.
8344 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008345static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008346charmaptranslate_makespace(Py_UCS4 **outobj, Py_ssize_t *psize,
Benjamin Peterson29060642009-01-31 22:14:21 +00008347 Py_ssize_t requiredsize)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008348{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008349 Py_ssize_t oldsize = *psize;
Kristjan Valur Jonsson85634d72012-05-31 09:37:31 +00008350 Py_UCS4 *new_outobj;
Walter Dörwald4894c302003-10-24 14:25:28 +00008351 if (requiredsize > oldsize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008352 /* exponentially overallocate to minimize reallocations */
8353 if (requiredsize < 2 * oldsize)
8354 requiredsize = 2 * oldsize;
Kristjan Valur Jonsson85634d72012-05-31 09:37:31 +00008355 new_outobj = PyMem_Realloc(*outobj, requiredsize * sizeof(Py_UCS4));
8356 if (new_outobj == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008357 return -1;
Kristjan Valur Jonsson85634d72012-05-31 09:37:31 +00008358 *outobj = new_outobj;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008359 *psize = requiredsize;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008360 }
8361 return 0;
8362}
8363/* lookup the character, put the result in the output string and adjust
8364 various state variables. Return a new reference to the object that
8365 was put in the output buffer in *result, or Py_None, if the mapping was
8366 undefined (in which case no character was written).
8367 The called must decref result.
8368 Return 0 on success, -1 on error. */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008369static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008370charmaptranslate_output(PyObject *input, Py_ssize_t ipos,
8371 PyObject *mapping, Py_UCS4 **output,
8372 Py_ssize_t *osize, Py_ssize_t *opos,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008373 PyObject **res)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008374{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008375 Py_UCS4 curinp = PyUnicode_READ_CHAR(input, ipos);
8376 if (charmaptranslate_lookup(curinp, mapping, res))
Benjamin Peterson29060642009-01-31 22:14:21 +00008377 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008378 if (*res==NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008379 /* not found => default to 1:1 mapping */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008380 (*output)[(*opos)++] = curinp;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008381 }
8382 else if (*res==Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008383 ;
Christian Heimes217cfd12007-12-02 14:31:20 +00008384 else if (PyLong_Check(*res)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008385 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008386 (*output)[(*opos)++] = (Py_UCS4)PyLong_AS_LONG(*res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008387 }
8388 else if (PyUnicode_Check(*res)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008389 Py_ssize_t repsize;
8390 if (PyUnicode_READY(*res) == -1)
8391 return -1;
8392 repsize = PyUnicode_GET_LENGTH(*res);
Benjamin Peterson29060642009-01-31 22:14:21 +00008393 if (repsize==1) {
8394 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008395 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +00008396 }
8397 else if (repsize!=0) {
8398 /* more than one character */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008399 Py_ssize_t requiredsize = *opos +
8400 (PyUnicode_GET_LENGTH(input) - ipos) +
Benjamin Peterson29060642009-01-31 22:14:21 +00008401 repsize - 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008402 Py_ssize_t i;
8403 if (charmaptranslate_makespace(output, osize, requiredsize))
Benjamin Peterson29060642009-01-31 22:14:21 +00008404 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008405 for(i = 0; i < repsize; i++)
8406 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00008407 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008408 }
8409 else
Benjamin Peterson29060642009-01-31 22:14:21 +00008410 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008411 return 0;
8412}
8413
Alexander Belopolsky40018472011-02-26 01:02:56 +00008414PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008415_PyUnicode_TranslateCharmap(PyObject *input,
8416 PyObject *mapping,
8417 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008418{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008419 /* input object */
8420 char *idata;
8421 Py_ssize_t size, i;
8422 int kind;
8423 /* output buffer */
8424 Py_UCS4 *output = NULL;
8425 Py_ssize_t osize;
8426 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008427 /* current output position */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008428 Py_ssize_t opos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008429 char *reason = "character maps to <undefined>";
8430 PyObject *errorHandler = NULL;
8431 PyObject *exc = NULL;
8432 /* the following variable is used for caching string comparisons
8433 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8434 * 3=ignore, 4=xmlcharrefreplace */
8435 int known_errorHandler = -1;
8436
Guido van Rossumd57fd912000-03-10 22:53:23 +00008437 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008438 PyErr_BadArgument();
8439 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008440 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008441
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008442 if (PyUnicode_READY(input) == -1)
8443 return NULL;
8444 idata = (char*)PyUnicode_DATA(input);
8445 kind = PyUnicode_KIND(input);
8446 size = PyUnicode_GET_LENGTH(input);
8447 i = 0;
8448
8449 if (size == 0) {
8450 Py_INCREF(input);
8451 return input;
8452 }
8453
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008454 /* allocate enough for a simple 1:1 translation without
8455 replacements, if we need more, we'll resize */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008456 osize = size;
8457 output = PyMem_Malloc(osize * sizeof(Py_UCS4));
8458 opos = 0;
8459 if (output == NULL) {
8460 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00008461 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008462 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008463
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008464 while (i<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008465 /* try to encode it */
8466 PyObject *x = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008467 if (charmaptranslate_output(input, i, mapping,
8468 &output, &osize, &opos, &x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008469 Py_XDECREF(x);
8470 goto onError;
8471 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008472 Py_XDECREF(x);
Benjamin Peterson29060642009-01-31 22:14:21 +00008473 if (x!=Py_None) /* it worked => adjust input pointer */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008474 ++i;
Benjamin Peterson29060642009-01-31 22:14:21 +00008475 else { /* untranslatable character */
8476 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
8477 Py_ssize_t repsize;
8478 Py_ssize_t newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008479 Py_ssize_t uni2;
Benjamin Peterson29060642009-01-31 22:14:21 +00008480 /* startpos for collecting untranslatable chars */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008481 Py_ssize_t collstart = i;
8482 Py_ssize_t collend = i+1;
8483 Py_ssize_t coll;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008484
Benjamin Peterson29060642009-01-31 22:14:21 +00008485 /* find all untranslatable characters */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008486 while (collend < size) {
8487 if (charmaptranslate_lookup(PyUnicode_READ(kind,idata, collend), mapping, &x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008488 goto onError;
8489 Py_XDECREF(x);
8490 if (x!=Py_None)
8491 break;
8492 ++collend;
8493 }
8494 /* cache callback name lookup
8495 * (if not done yet, i.e. it's the first error) */
8496 if (known_errorHandler==-1) {
8497 if ((errors==NULL) || (!strcmp(errors, "strict")))
8498 known_errorHandler = 1;
8499 else if (!strcmp(errors, "replace"))
8500 known_errorHandler = 2;
8501 else if (!strcmp(errors, "ignore"))
8502 known_errorHandler = 3;
8503 else if (!strcmp(errors, "xmlcharrefreplace"))
8504 known_errorHandler = 4;
8505 else
8506 known_errorHandler = 0;
8507 }
8508 switch (known_errorHandler) {
8509 case 1: /* strict */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008510 raise_translate_exception(&exc, input, collstart,
8511 collend, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008512 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00008513 case 2: /* replace */
8514 /* No need to check for space, this is a 1:1 replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008515 for (coll = collstart; coll<collend; coll++)
8516 output[opos++] = '?';
Benjamin Peterson29060642009-01-31 22:14:21 +00008517 /* fall through */
8518 case 3: /* ignore */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008519 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008520 break;
8521 case 4: /* xmlcharrefreplace */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008522 /* generate replacement (temporarily (mis)uses i) */
8523 for (i = collstart; i < collend; ++i) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008524 char buffer[2+29+1+1];
8525 char *cp;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008526 sprintf(buffer, "&#%d;", PyUnicode_READ(kind, idata, i));
8527 if (charmaptranslate_makespace(&output, &osize,
8528 opos+strlen(buffer)+(size-collend)))
Benjamin Peterson29060642009-01-31 22:14:21 +00008529 goto onError;
8530 for (cp = buffer; *cp; ++cp)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008531 output[opos++] = *cp;
Benjamin Peterson29060642009-01-31 22:14:21 +00008532 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008533 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008534 break;
8535 default:
8536 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008537 reason, input, &exc,
8538 collstart, collend, &newpos);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008539 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008540 goto onError;
Benjamin Peterson9ca3ffa2012-01-01 16:04:29 -06008541 if (PyUnicode_READY(repunicode) == -1) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008542 Py_DECREF(repunicode);
8543 goto onError;
8544 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008545 /* generate replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008546 repsize = PyUnicode_GET_LENGTH(repunicode);
8547 if (charmaptranslate_makespace(&output, &osize,
8548 opos+repsize+(size-collend))) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008549 Py_DECREF(repunicode);
8550 goto onError;
8551 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008552 for (uni2 = 0; repsize-->0; ++uni2)
8553 output[opos++] = PyUnicode_READ_CHAR(repunicode, uni2);
8554 i = newpos;
Benjamin Peterson29060642009-01-31 22:14:21 +00008555 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008556 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008557 }
8558 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008559 res = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND, output, opos);
8560 if (!res)
8561 goto onError;
8562 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008563 Py_XDECREF(exc);
8564 Py_XDECREF(errorHandler);
8565 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008566
Benjamin Peterson29060642009-01-31 22:14:21 +00008567 onError:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008568 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008569 Py_XDECREF(exc);
8570 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008571 return NULL;
8572}
8573
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008574/* Deprecated. Use PyUnicode_Translate instead. */
8575PyObject *
8576PyUnicode_TranslateCharmap(const Py_UNICODE *p,
8577 Py_ssize_t size,
8578 PyObject *mapping,
8579 const char *errors)
8580{
Christian Heimes5f520f42012-09-11 14:03:25 +02008581 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008582 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8583 if (!unicode)
8584 return NULL;
Christian Heimes5f520f42012-09-11 14:03:25 +02008585 result = _PyUnicode_TranslateCharmap(unicode, mapping, errors);
8586 Py_DECREF(unicode);
8587 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008588}
8589
Alexander Belopolsky40018472011-02-26 01:02:56 +00008590PyObject *
8591PyUnicode_Translate(PyObject *str,
8592 PyObject *mapping,
8593 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008594{
8595 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +00008596
Guido van Rossumd57fd912000-03-10 22:53:23 +00008597 str = PyUnicode_FromObject(str);
8598 if (str == NULL)
Christian Heimes5f520f42012-09-11 14:03:25 +02008599 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008600 result = _PyUnicode_TranslateCharmap(str, mapping, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008601 Py_DECREF(str);
8602 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008603}
Tim Petersced69f82003-09-16 20:30:58 +00008604
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008605static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02008606fix_decimal_and_space_to_ascii(PyObject *self)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008607{
8608 /* No need to call PyUnicode_READY(self) because this function is only
8609 called as a callback from fixup() which does it already. */
8610 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
8611 const int kind = PyUnicode_KIND(self);
8612 void *data = PyUnicode_DATA(self);
Victor Stinnere6abb482012-05-02 01:15:40 +02008613 Py_UCS4 maxchar = 127, ch, fixed;
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008614 int modified = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008615 Py_ssize_t i;
8616
8617 for (i = 0; i < len; ++i) {
8618 ch = PyUnicode_READ(kind, data, i);
8619 fixed = 0;
8620 if (ch > 127) {
8621 if (Py_UNICODE_ISSPACE(ch))
8622 fixed = ' ';
8623 else {
8624 const int decimal = Py_UNICODE_TODECIMAL(ch);
8625 if (decimal >= 0)
8626 fixed = '0' + decimal;
8627 }
8628 if (fixed != 0) {
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008629 modified = 1;
Victor Stinnere6abb482012-05-02 01:15:40 +02008630 maxchar = MAX_MAXCHAR(maxchar, fixed);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008631 PyUnicode_WRITE(kind, data, i, fixed);
8632 }
Victor Stinnere6abb482012-05-02 01:15:40 +02008633 else
8634 maxchar = MAX_MAXCHAR(maxchar, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008635 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008636 }
8637
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008638 return (modified) ? maxchar : 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008639}
8640
8641PyObject *
8642_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
8643{
8644 if (!PyUnicode_Check(unicode)) {
8645 PyErr_BadInternalCall();
8646 return NULL;
8647 }
8648 if (PyUnicode_READY(unicode) == -1)
8649 return NULL;
8650 if (PyUnicode_MAX_CHAR_VALUE(unicode) <= 127) {
8651 /* If the string is already ASCII, just return the same string */
8652 Py_INCREF(unicode);
8653 return unicode;
8654 }
Victor Stinner9310abb2011-10-05 00:59:23 +02008655 return fixup(unicode, fix_decimal_and_space_to_ascii);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008656}
8657
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008658PyObject *
8659PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
8660 Py_ssize_t length)
8661{
Victor Stinnerf0124502011-11-21 23:12:56 +01008662 PyObject *decimal;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008663 Py_ssize_t i;
Victor Stinnerf0124502011-11-21 23:12:56 +01008664 Py_UCS4 maxchar;
8665 enum PyUnicode_Kind kind;
8666 void *data;
8667
Victor Stinner99d7ad02012-02-22 13:37:39 +01008668 maxchar = 127;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008669 for (i = 0; i < length; i++) {
Victor Stinnerf0124502011-11-21 23:12:56 +01008670 Py_UNICODE ch = s[i];
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008671 if (ch > 127) {
8672 int decimal = Py_UNICODE_TODECIMAL(ch);
8673 if (decimal >= 0)
Victor Stinnerf0124502011-11-21 23:12:56 +01008674 ch = '0' + decimal;
Victor Stinnere6abb482012-05-02 01:15:40 +02008675 maxchar = MAX_MAXCHAR(maxchar, ch);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008676 }
8677 }
Victor Stinnerf0124502011-11-21 23:12:56 +01008678
8679 /* Copy to a new string */
8680 decimal = PyUnicode_New(length, maxchar);
8681 if (decimal == NULL)
8682 return decimal;
8683 kind = PyUnicode_KIND(decimal);
8684 data = PyUnicode_DATA(decimal);
8685 /* Iterate over code points */
8686 for (i = 0; i < length; i++) {
8687 Py_UNICODE ch = s[i];
8688 if (ch > 127) {
8689 int decimal = Py_UNICODE_TODECIMAL(ch);
8690 if (decimal >= 0)
8691 ch = '0' + decimal;
8692 }
8693 PyUnicode_WRITE(kind, data, i, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008694 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008695 return unicode_result(decimal);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008696}
Guido van Rossum9e896b32000-04-05 20:11:21 +00008697/* --- Decimal Encoder ---------------------------------------------------- */
8698
Alexander Belopolsky40018472011-02-26 01:02:56 +00008699int
8700PyUnicode_EncodeDecimal(Py_UNICODE *s,
8701 Py_ssize_t length,
8702 char *output,
8703 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00008704{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008705 PyObject *unicode;
Victor Stinner6345be92011-11-25 20:09:01 +01008706 Py_ssize_t i;
Victor Stinner42bf7752011-11-21 22:52:58 +01008707 enum PyUnicode_Kind kind;
8708 void *data;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008709
8710 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008711 PyErr_BadArgument();
8712 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008713 }
8714
Victor Stinner42bf7752011-11-21 22:52:58 +01008715 unicode = PyUnicode_FromUnicode(s, length);
8716 if (unicode == NULL)
8717 return -1;
8718
Benjamin Petersonbac79492012-01-14 13:34:47 -05008719 if (PyUnicode_READY(unicode) == -1) {
Victor Stinner6345be92011-11-25 20:09:01 +01008720 Py_DECREF(unicode);
8721 return -1;
8722 }
Victor Stinner42bf7752011-11-21 22:52:58 +01008723 kind = PyUnicode_KIND(unicode);
8724 data = PyUnicode_DATA(unicode);
8725
Victor Stinnerb84d7232011-11-22 01:50:07 +01008726 for (i=0; i < length; ) {
Victor Stinner6345be92011-11-25 20:09:01 +01008727 PyObject *exc;
8728 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00008729 int decimal;
Victor Stinner6345be92011-11-25 20:09:01 +01008730 Py_ssize_t startpos;
8731
8732 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +00008733
Benjamin Peterson29060642009-01-31 22:14:21 +00008734 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008735 *output++ = ' ';
Victor Stinnerb84d7232011-11-22 01:50:07 +01008736 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00008737 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008738 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008739 decimal = Py_UNICODE_TODECIMAL(ch);
8740 if (decimal >= 0) {
8741 *output++ = '0' + decimal;
Victor Stinnerb84d7232011-11-22 01:50:07 +01008742 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00008743 continue;
8744 }
8745 if (0 < ch && ch < 256) {
8746 *output++ = (char)ch;
Victor Stinnerb84d7232011-11-22 01:50:07 +01008747 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00008748 continue;
8749 }
Victor Stinner6345be92011-11-25 20:09:01 +01008750
Victor Stinner42bf7752011-11-21 22:52:58 +01008751 startpos = i;
Victor Stinner6345be92011-11-25 20:09:01 +01008752 exc = NULL;
8753 raise_encode_exception(&exc, "decimal", unicode,
8754 startpos, startpos+1,
8755 "invalid decimal Unicode string");
8756 Py_XDECREF(exc);
8757 Py_DECREF(unicode);
8758 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008759 }
8760 /* 0-terminate the output string */
8761 *output++ = '\0';
Victor Stinner42bf7752011-11-21 22:52:58 +01008762 Py_DECREF(unicode);
Guido van Rossum9e896b32000-04-05 20:11:21 +00008763 return 0;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008764}
8765
Guido van Rossumd57fd912000-03-10 22:53:23 +00008766/* --- Helpers ------------------------------------------------------------ */
8767
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008768static Py_ssize_t
Victor Stinner794d5672011-10-10 03:21:36 +02008769any_find_slice(int direction, PyObject* s1, PyObject* s2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008770 Py_ssize_t start,
8771 Py_ssize_t end)
8772{
8773 int kind1, kind2, kind;
8774 void *buf1, *buf2;
8775 Py_ssize_t len1, len2, result;
8776
8777 kind1 = PyUnicode_KIND(s1);
8778 kind2 = PyUnicode_KIND(s2);
8779 kind = kind1 > kind2 ? kind1 : kind2;
8780 buf1 = PyUnicode_DATA(s1);
8781 buf2 = PyUnicode_DATA(s2);
8782 if (kind1 != kind)
8783 buf1 = _PyUnicode_AsKind(s1, kind);
8784 if (!buf1)
8785 return -2;
8786 if (kind2 != kind)
8787 buf2 = _PyUnicode_AsKind(s2, kind);
8788 if (!buf2) {
8789 if (kind1 != kind) PyMem_Free(buf1);
8790 return -2;
8791 }
8792 len1 = PyUnicode_GET_LENGTH(s1);
8793 len2 = PyUnicode_GET_LENGTH(s2);
8794
Victor Stinner794d5672011-10-10 03:21:36 +02008795 if (direction > 0) {
Benjamin Petersonead6b532011-12-20 17:23:42 -06008796 switch (kind) {
Victor Stinner794d5672011-10-10 03:21:36 +02008797 case PyUnicode_1BYTE_KIND:
8798 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
8799 result = asciilib_find_slice(buf1, len1, buf2, len2, start, end);
8800 else
8801 result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end);
8802 break;
8803 case PyUnicode_2BYTE_KIND:
8804 result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end);
8805 break;
8806 case PyUnicode_4BYTE_KIND:
8807 result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end);
8808 break;
8809 default:
8810 assert(0); result = -2;
8811 }
8812 }
8813 else {
Benjamin Petersonead6b532011-12-20 17:23:42 -06008814 switch (kind) {
Victor Stinner794d5672011-10-10 03:21:36 +02008815 case PyUnicode_1BYTE_KIND:
8816 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
8817 result = asciilib_rfind_slice(buf1, len1, buf2, len2, start, end);
8818 else
8819 result = ucs1lib_rfind_slice(buf1, len1, buf2, len2, start, end);
8820 break;
8821 case PyUnicode_2BYTE_KIND:
8822 result = ucs2lib_rfind_slice(buf1, len1, buf2, len2, start, end);
8823 break;
8824 case PyUnicode_4BYTE_KIND:
8825 result = ucs4lib_rfind_slice(buf1, len1, buf2, len2, start, end);
8826 break;
8827 default:
8828 assert(0); result = -2;
8829 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008830 }
8831
8832 if (kind1 != kind)
8833 PyMem_Free(buf1);
8834 if (kind2 != kind)
8835 PyMem_Free(buf2);
8836
8837 return result;
8838}
8839
8840Py_ssize_t
Victor Stinner41a863c2012-02-24 00:37:51 +01008841_PyUnicode_InsertThousandsGrouping(
8842 PyObject *unicode, Py_ssize_t index,
8843 Py_ssize_t n_buffer,
8844 void *digits, Py_ssize_t n_digits,
8845 Py_ssize_t min_width,
8846 const char *grouping, PyObject *thousands_sep,
8847 Py_UCS4 *maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008848{
Victor Stinner41a863c2012-02-24 00:37:51 +01008849 unsigned int kind, thousands_sep_kind;
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008850 char *data, *thousands_sep_data;
Victor Stinner41a863c2012-02-24 00:37:51 +01008851 Py_ssize_t thousands_sep_len;
8852 Py_ssize_t len;
8853
8854 if (unicode != NULL) {
8855 kind = PyUnicode_KIND(unicode);
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008856 data = (char *) PyUnicode_DATA(unicode) + index * kind;
Victor Stinner41a863c2012-02-24 00:37:51 +01008857 }
8858 else {
8859 kind = PyUnicode_1BYTE_KIND;
8860 data = NULL;
8861 }
8862 thousands_sep_kind = PyUnicode_KIND(thousands_sep);
8863 thousands_sep_data = PyUnicode_DATA(thousands_sep);
8864 thousands_sep_len = PyUnicode_GET_LENGTH(thousands_sep);
8865 if (unicode != NULL && thousands_sep_kind != kind) {
Victor Stinner90f50d42012-02-24 01:44:47 +01008866 if (thousands_sep_kind < kind) {
8867 thousands_sep_data = _PyUnicode_AsKind(thousands_sep, kind);
8868 if (!thousands_sep_data)
8869 return -1;
8870 }
8871 else {
8872 data = _PyUnicode_AsKind(unicode, thousands_sep_kind);
8873 if (!data)
8874 return -1;
8875 }
Victor Stinner41a863c2012-02-24 00:37:51 +01008876 }
8877
Benjamin Petersonead6b532011-12-20 17:23:42 -06008878 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008879 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02008880 if (unicode != NULL && PyUnicode_IS_ASCII(unicode))
Victor Stinner41a863c2012-02-24 00:37:51 +01008881 len = asciilib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008882 (Py_UCS1 *) data, n_buffer, (Py_UCS1 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01008883 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008884 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinnerc3cec782011-10-05 21:24:08 +02008885 else
Victor Stinner41a863c2012-02-24 00:37:51 +01008886 len = ucs1lib_InsertThousandsGrouping(
Victor Stinnerc3cec782011-10-05 21:24:08 +02008887 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01008888 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008889 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01008890 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008891 case PyUnicode_2BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01008892 len = ucs2lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008893 (Py_UCS2 *) data, n_buffer, (Py_UCS2 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01008894 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008895 (Py_UCS2 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01008896 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008897 case PyUnicode_4BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01008898 len = ucs4lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008899 (Py_UCS4 *) data, n_buffer, (Py_UCS4 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01008900 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008901 (Py_UCS4 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01008902 break;
8903 default:
8904 assert(0);
8905 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008906 }
Victor Stinner90f50d42012-02-24 01:44:47 +01008907 if (unicode != NULL && thousands_sep_kind != kind) {
8908 if (thousands_sep_kind < kind)
8909 PyMem_Free(thousands_sep_data);
8910 else
8911 PyMem_Free(data);
8912 }
Victor Stinner41a863c2012-02-24 00:37:51 +01008913 if (unicode == NULL) {
8914 *maxchar = 127;
8915 if (len != n_digits) {
Victor Stinnere6abb482012-05-02 01:15:40 +02008916 *maxchar = MAX_MAXCHAR(*maxchar,
8917 PyUnicode_MAX_CHAR_VALUE(thousands_sep));
Victor Stinner41a863c2012-02-24 00:37:51 +01008918 }
8919 }
8920 return len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008921}
8922
8923
Thomas Wouters477c8d52006-05-27 19:21:47 +00008924/* helper macro to fixup start/end slice values */
Antoine Pitrouf2c54842010-01-13 08:07:53 +00008925#define ADJUST_INDICES(start, end, len) \
8926 if (end > len) \
8927 end = len; \
8928 else if (end < 0) { \
8929 end += len; \
8930 if (end < 0) \
8931 end = 0; \
8932 } \
8933 if (start < 0) { \
8934 start += len; \
8935 if (start < 0) \
8936 start = 0; \
8937 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00008938
Alexander Belopolsky40018472011-02-26 01:02:56 +00008939Py_ssize_t
8940PyUnicode_Count(PyObject *str,
8941 PyObject *substr,
8942 Py_ssize_t start,
8943 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008944{
Martin v. Löwis18e16552006-02-15 17:27:45 +00008945 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02008946 PyObject* str_obj;
8947 PyObject* sub_obj;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008948 int kind1, kind2, kind;
8949 void *buf1 = NULL, *buf2 = NULL;
8950 Py_ssize_t len1, len2;
Tim Petersced69f82003-09-16 20:30:58 +00008951
Victor Stinner9db1a8b2011-10-23 20:04:37 +02008952 str_obj = PyUnicode_FromObject(str);
Benjamin Peterson22a29702012-01-02 09:00:30 -06008953 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +00008954 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02008955 sub_obj = PyUnicode_FromObject(substr);
Benjamin Peterson22a29702012-01-02 09:00:30 -06008956 if (!sub_obj) {
8957 Py_DECREF(str_obj);
8958 return -1;
8959 }
Benjamin Peterson4c13a4a2012-01-02 09:07:38 -06008960 if (PyUnicode_READY(sub_obj) == -1 || PyUnicode_READY(str_obj) == -1) {
Benjamin Peterson5e458f52012-01-02 10:12:13 -06008961 Py_DECREF(sub_obj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008962 Py_DECREF(str_obj);
8963 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008964 }
Tim Petersced69f82003-09-16 20:30:58 +00008965
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008966 kind1 = PyUnicode_KIND(str_obj);
8967 kind2 = PyUnicode_KIND(sub_obj);
Antoine Pitroue45c0c52012-05-12 15:49:07 +02008968 kind = kind1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008969 buf1 = PyUnicode_DATA(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008970 buf2 = PyUnicode_DATA(sub_obj);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -05008971 if (kind2 != kind) {
Antoine Pitrou758153b2012-05-12 15:51:51 +02008972 if (kind2 > kind) {
8973 Py_DECREF(sub_obj);
8974 Py_DECREF(str_obj);
Antoine Pitroue45c0c52012-05-12 15:49:07 +02008975 return 0;
Antoine Pitrou758153b2012-05-12 15:51:51 +02008976 }
Victor Stinner7931d9a2011-11-04 00:22:48 +01008977 buf2 = _PyUnicode_AsKind(sub_obj, kind);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -05008978 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008979 if (!buf2)
8980 goto onError;
8981 len1 = PyUnicode_GET_LENGTH(str_obj);
8982 len2 = PyUnicode_GET_LENGTH(sub_obj);
8983
8984 ADJUST_INDICES(start, end, len1);
Benjamin Petersonead6b532011-12-20 17:23:42 -06008985 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008986 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02008987 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sub_obj))
8988 result = asciilib_count(
8989 ((Py_UCS1*)buf1) + start, end - start,
8990 buf2, len2, PY_SSIZE_T_MAX
8991 );
8992 else
8993 result = ucs1lib_count(
8994 ((Py_UCS1*)buf1) + start, end - start,
8995 buf2, len2, PY_SSIZE_T_MAX
8996 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008997 break;
8998 case PyUnicode_2BYTE_KIND:
8999 result = ucs2lib_count(
9000 ((Py_UCS2*)buf1) + start, end - start,
9001 buf2, len2, PY_SSIZE_T_MAX
9002 );
9003 break;
9004 case PyUnicode_4BYTE_KIND:
9005 result = ucs4lib_count(
9006 ((Py_UCS4*)buf1) + start, end - start,
9007 buf2, len2, PY_SSIZE_T_MAX
9008 );
9009 break;
9010 default:
9011 assert(0); result = 0;
9012 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009013
9014 Py_DECREF(sub_obj);
9015 Py_DECREF(str_obj);
9016
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009017 if (kind2 != kind)
9018 PyMem_Free(buf2);
9019
Guido van Rossumd57fd912000-03-10 22:53:23 +00009020 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009021 onError:
9022 Py_DECREF(sub_obj);
9023 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009024 if (kind2 != kind && buf2)
9025 PyMem_Free(buf2);
9026 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009027}
9028
Alexander Belopolsky40018472011-02-26 01:02:56 +00009029Py_ssize_t
9030PyUnicode_Find(PyObject *str,
9031 PyObject *sub,
9032 Py_ssize_t start,
9033 Py_ssize_t end,
9034 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009035{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009036 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009037
Guido van Rossumd57fd912000-03-10 22:53:23 +00009038 str = PyUnicode_FromObject(str);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009039 if (!str)
Benjamin Peterson29060642009-01-31 22:14:21 +00009040 return -2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009041 sub = PyUnicode_FromObject(sub);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009042 if (!sub) {
9043 Py_DECREF(str);
9044 return -2;
9045 }
9046 if (PyUnicode_READY(sub) == -1 || PyUnicode_READY(str) == -1) {
9047 Py_DECREF(sub);
Benjamin Peterson29060642009-01-31 22:14:21 +00009048 Py_DECREF(str);
9049 return -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009050 }
Tim Petersced69f82003-09-16 20:30:58 +00009051
Victor Stinner794d5672011-10-10 03:21:36 +02009052 result = any_find_slice(direction,
9053 str, sub, start, end
9054 );
Thomas Wouters477c8d52006-05-27 19:21:47 +00009055
Guido van Rossumd57fd912000-03-10 22:53:23 +00009056 Py_DECREF(str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009057 Py_DECREF(sub);
9058
Guido van Rossumd57fd912000-03-10 22:53:23 +00009059 return result;
9060}
9061
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009062Py_ssize_t
9063PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
9064 Py_ssize_t start, Py_ssize_t end,
9065 int direction)
9066{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009067 int kind;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009068 Py_ssize_t result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009069 if (PyUnicode_READY(str) == -1)
9070 return -2;
Victor Stinner267aa242011-10-02 01:08:37 +02009071 if (start < 0 || end < 0) {
9072 PyErr_SetString(PyExc_IndexError, "string index out of range");
9073 return -2;
9074 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009075 if (end > PyUnicode_GET_LENGTH(str))
9076 end = PyUnicode_GET_LENGTH(str);
9077 kind = PyUnicode_KIND(str);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009078 result = findchar(PyUnicode_1BYTE_DATA(str) + kind*start,
9079 kind, end-start, ch, direction);
9080 if (result == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009081 return -1;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009082 else
9083 return start + result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009084}
9085
Alexander Belopolsky40018472011-02-26 01:02:56 +00009086static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009087tailmatch(PyObject *self,
9088 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009089 Py_ssize_t start,
9090 Py_ssize_t end,
9091 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009092{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009093 int kind_self;
9094 int kind_sub;
9095 void *data_self;
9096 void *data_sub;
9097 Py_ssize_t offset;
9098 Py_ssize_t i;
9099 Py_ssize_t end_sub;
9100
9101 if (PyUnicode_READY(self) == -1 ||
9102 PyUnicode_READY(substring) == -1)
9103 return 0;
9104
9105 if (PyUnicode_GET_LENGTH(substring) == 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009106 return 1;
9107
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009108 ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
9109 end -= PyUnicode_GET_LENGTH(substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009110 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00009111 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009112
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009113 kind_self = PyUnicode_KIND(self);
9114 data_self = PyUnicode_DATA(self);
9115 kind_sub = PyUnicode_KIND(substring);
9116 data_sub = PyUnicode_DATA(substring);
9117 end_sub = PyUnicode_GET_LENGTH(substring) - 1;
9118
9119 if (direction > 0)
9120 offset = end;
9121 else
9122 offset = start;
9123
9124 if (PyUnicode_READ(kind_self, data_self, offset) ==
9125 PyUnicode_READ(kind_sub, data_sub, 0) &&
9126 PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
9127 PyUnicode_READ(kind_sub, data_sub, end_sub)) {
9128 /* If both are of the same kind, memcmp is sufficient */
9129 if (kind_self == kind_sub) {
9130 return ! memcmp((char *)data_self +
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009131 (offset * PyUnicode_KIND(substring)),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009132 data_sub,
9133 PyUnicode_GET_LENGTH(substring) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009134 PyUnicode_KIND(substring));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009135 }
9136 /* otherwise we have to compare each character by first accesing it */
9137 else {
9138 /* We do not need to compare 0 and len(substring)-1 because
9139 the if statement above ensured already that they are equal
9140 when we end up here. */
Antoine Pitrou057119b2012-09-02 17:56:33 +02009141 /* TODO: honor direction and do a forward or backwards search */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009142 for (i = 1; i < end_sub; ++i) {
9143 if (PyUnicode_READ(kind_self, data_self, offset + i) !=
9144 PyUnicode_READ(kind_sub, data_sub, i))
9145 return 0;
9146 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009147 return 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009148 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009149 }
9150
9151 return 0;
9152}
9153
Alexander Belopolsky40018472011-02-26 01:02:56 +00009154Py_ssize_t
9155PyUnicode_Tailmatch(PyObject *str,
9156 PyObject *substr,
9157 Py_ssize_t start,
9158 Py_ssize_t end,
9159 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009160{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009161 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009162
Guido van Rossumd57fd912000-03-10 22:53:23 +00009163 str = PyUnicode_FromObject(str);
9164 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009165 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009166 substr = PyUnicode_FromObject(substr);
9167 if (substr == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009168 Py_DECREF(str);
9169 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009170 }
Tim Petersced69f82003-09-16 20:30:58 +00009171
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009172 result = tailmatch(str, substr,
Benjamin Peterson29060642009-01-31 22:14:21 +00009173 start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009174 Py_DECREF(str);
9175 Py_DECREF(substr);
9176 return result;
9177}
9178
Guido van Rossumd57fd912000-03-10 22:53:23 +00009179/* Apply fixfct filter to the Unicode object self and return a
9180 reference to the modified object */
9181
Alexander Belopolsky40018472011-02-26 01:02:56 +00009182static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009183fixup(PyObject *self,
9184 Py_UCS4 (*fixfct)(PyObject *s))
Guido van Rossumd57fd912000-03-10 22:53:23 +00009185{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009186 PyObject *u;
9187 Py_UCS4 maxchar_old, maxchar_new = 0;
Victor Stinnereaab6042011-12-11 22:22:39 +01009188 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009189
Victor Stinnerbf6e5602011-12-12 01:53:47 +01009190 u = _PyUnicode_Copy(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009191 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009192 return NULL;
Victor Stinner87af4f22011-11-21 23:03:47 +01009193 maxchar_old = PyUnicode_MAX_CHAR_VALUE(u);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009194
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009195 /* fix functions return the new maximum character in a string,
9196 if the kind of the resulting unicode object does not change,
9197 everything is fine. Otherwise we need to change the string kind
9198 and re-run the fix function. */
Victor Stinner9310abb2011-10-05 00:59:23 +02009199 maxchar_new = fixfct(u);
Victor Stinnereaab6042011-12-11 22:22:39 +01009200
9201 if (maxchar_new == 0) {
9202 /* no changes */;
9203 if (PyUnicode_CheckExact(self)) {
9204 Py_DECREF(u);
9205 Py_INCREF(self);
9206 return self;
9207 }
9208 else
9209 return u;
9210 }
9211
Victor Stinnere6abb482012-05-02 01:15:40 +02009212 maxchar_new = align_maxchar(maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009213
Victor Stinnereaab6042011-12-11 22:22:39 +01009214 if (maxchar_new == maxchar_old)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009215 return u;
Victor Stinnereaab6042011-12-11 22:22:39 +01009216
9217 /* In case the maximum character changed, we need to
9218 convert the string to the new category. */
9219 v = PyUnicode_New(PyUnicode_GET_LENGTH(self), maxchar_new);
9220 if (v == NULL) {
9221 Py_DECREF(u);
9222 return NULL;
9223 }
9224 if (maxchar_new > maxchar_old) {
9225 /* If the maxchar increased so that the kind changed, not all
9226 characters are representable anymore and we need to fix the
9227 string again. This only happens in very few cases. */
Victor Stinnerd3f08822012-05-29 12:57:52 +02009228 _PyUnicode_FastCopyCharacters(v, 0,
9229 self, 0, PyUnicode_GET_LENGTH(self));
Victor Stinnereaab6042011-12-11 22:22:39 +01009230 maxchar_old = fixfct(v);
9231 assert(maxchar_old > 0 && maxchar_old <= maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009232 }
9233 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02009234 _PyUnicode_FastCopyCharacters(v, 0,
9235 u, 0, PyUnicode_GET_LENGTH(self));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009236 }
Victor Stinnereaab6042011-12-11 22:22:39 +01009237 Py_DECREF(u);
9238 assert(_PyUnicode_CheckConsistency(v, 1));
9239 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009240}
9241
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009242static PyObject *
9243ascii_upper_or_lower(PyObject *self, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009244{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009245 Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9246 char *resdata, *data = PyUnicode_DATA(self);
9247 PyObject *res;
Tim Petersced69f82003-09-16 20:30:58 +00009248
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009249 res = PyUnicode_New(len, 127);
9250 if (res == NULL)
9251 return NULL;
9252 resdata = PyUnicode_DATA(res);
9253 if (lower)
9254 _Py_bytes_lower(resdata, data, len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009255 else
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009256 _Py_bytes_upper(resdata, data, len);
9257 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009258}
9259
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009260static Py_UCS4
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009261handle_capital_sigma(int kind, void *data, Py_ssize_t length, Py_ssize_t i)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009262{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009263 Py_ssize_t j;
9264 int final_sigma;
9265 Py_UCS4 c;
9266 /* U+03A3 is in the Final_Sigma context when, it is found like this:
Tim Petersced69f82003-09-16 20:30:58 +00009267
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009268 \p{cased}\p{case-ignorable}*U+03A3!(\p{case-ignorable}*\p{cased})
9269
9270 where ! is a negation and \p{xxx} is a character with property xxx.
9271 */
9272 for (j = i - 1; j >= 0; j--) {
9273 c = PyUnicode_READ(kind, data, j);
9274 if (!_PyUnicode_IsCaseIgnorable(c))
9275 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009276 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009277 final_sigma = j >= 0 && _PyUnicode_IsCased(c);
9278 if (final_sigma) {
9279 for (j = i + 1; j < length; j++) {
9280 c = PyUnicode_READ(kind, data, j);
9281 if (!_PyUnicode_IsCaseIgnorable(c))
9282 break;
9283 }
9284 final_sigma = j == length || !_PyUnicode_IsCased(c);
9285 }
9286 return (final_sigma) ? 0x3C2 : 0x3C3;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009287}
9288
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009289static int
9290lower_ucs4(int kind, void *data, Py_ssize_t length, Py_ssize_t i,
9291 Py_UCS4 c, Py_UCS4 *mapped)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009292{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009293 /* Obscure special case. */
9294 if (c == 0x3A3) {
9295 mapped[0] = handle_capital_sigma(kind, data, length, i);
9296 return 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009297 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009298 return _PyUnicode_ToLowerFull(c, mapped);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009299}
9300
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009301static Py_ssize_t
9302do_capitalize(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009303{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009304 Py_ssize_t i, k = 0;
9305 int n_res, j;
9306 Py_UCS4 c, mapped[3];
Tim Petersced69f82003-09-16 20:30:58 +00009307
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009308 c = PyUnicode_READ(kind, data, 0);
9309 n_res = _PyUnicode_ToUpperFull(c, mapped);
9310 for (j = 0; j < n_res; j++) {
Victor Stinnere6abb482012-05-02 01:15:40 +02009311 *maxchar = MAX_MAXCHAR(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009312 res[k++] = mapped[j];
Guido van Rossumd57fd912000-03-10 22:53:23 +00009313 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009314 for (i = 1; i < length; i++) {
9315 c = PyUnicode_READ(kind, data, i);
9316 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9317 for (j = 0; j < n_res; j++) {
Victor Stinnere6abb482012-05-02 01:15:40 +02009318 *maxchar = MAX_MAXCHAR(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009319 res[k++] = mapped[j];
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009320 }
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009321 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009322 return k;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009323}
9324
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009325static Py_ssize_t
9326do_swapcase(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar) {
9327 Py_ssize_t i, k = 0;
9328
9329 for (i = 0; i < length; i++) {
9330 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9331 int n_res, j;
9332 if (Py_UNICODE_ISUPPER(c)) {
9333 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9334 }
9335 else if (Py_UNICODE_ISLOWER(c)) {
9336 n_res = _PyUnicode_ToUpperFull(c, mapped);
9337 }
9338 else {
9339 n_res = 1;
9340 mapped[0] = c;
9341 }
9342 for (j = 0; j < n_res; j++) {
Victor Stinnere6abb482012-05-02 01:15:40 +02009343 *maxchar = MAX_MAXCHAR(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009344 res[k++] = mapped[j];
9345 }
9346 }
9347 return k;
9348}
9349
9350static Py_ssize_t
9351do_upper_or_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res,
9352 Py_UCS4 *maxchar, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009353{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009354 Py_ssize_t i, k = 0;
9355
9356 for (i = 0; i < length; i++) {
9357 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9358 int n_res, j;
9359 if (lower)
9360 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9361 else
9362 n_res = _PyUnicode_ToUpperFull(c, mapped);
9363 for (j = 0; j < n_res; j++) {
Victor Stinnere6abb482012-05-02 01:15:40 +02009364 *maxchar = MAX_MAXCHAR(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009365 res[k++] = mapped[j];
9366 }
9367 }
9368 return k;
9369}
9370
9371static Py_ssize_t
9372do_upper(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9373{
9374 return do_upper_or_lower(kind, data, length, res, maxchar, 0);
9375}
9376
9377static Py_ssize_t
9378do_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9379{
9380 return do_upper_or_lower(kind, data, length, res, maxchar, 1);
9381}
9382
Benjamin Petersone51757f2012-01-12 21:10:29 -05009383static Py_ssize_t
Benjamin Petersond5890c82012-01-14 13:23:30 -05009384do_casefold(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9385{
9386 Py_ssize_t i, k = 0;
9387
9388 for (i = 0; i < length; i++) {
9389 Py_UCS4 c = PyUnicode_READ(kind, data, i);
9390 Py_UCS4 mapped[3];
9391 int j, n_res = _PyUnicode_ToFoldedFull(c, mapped);
9392 for (j = 0; j < n_res; j++) {
Victor Stinnere6abb482012-05-02 01:15:40 +02009393 *maxchar = MAX_MAXCHAR(*maxchar, mapped[j]);
Benjamin Petersond5890c82012-01-14 13:23:30 -05009394 res[k++] = mapped[j];
9395 }
9396 }
9397 return k;
9398}
9399
9400static Py_ssize_t
Benjamin Petersone51757f2012-01-12 21:10:29 -05009401do_title(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9402{
9403 Py_ssize_t i, k = 0;
9404 int previous_is_cased;
9405
9406 previous_is_cased = 0;
9407 for (i = 0; i < length; i++) {
9408 const Py_UCS4 c = PyUnicode_READ(kind, data, i);
9409 Py_UCS4 mapped[3];
9410 int n_res, j;
9411
9412 if (previous_is_cased)
9413 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9414 else
9415 n_res = _PyUnicode_ToTitleFull(c, mapped);
9416
9417 for (j = 0; j < n_res; j++) {
Victor Stinnere6abb482012-05-02 01:15:40 +02009418 *maxchar = MAX_MAXCHAR(*maxchar, mapped[j]);
Benjamin Petersone51757f2012-01-12 21:10:29 -05009419 res[k++] = mapped[j];
9420 }
9421
9422 previous_is_cased = _PyUnicode_IsCased(c);
9423 }
9424 return k;
9425}
9426
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009427static PyObject *
9428case_operation(PyObject *self,
9429 Py_ssize_t (*perform)(int, void *, Py_ssize_t, Py_UCS4 *, Py_UCS4 *))
9430{
9431 PyObject *res = NULL;
9432 Py_ssize_t length, newlength = 0;
9433 int kind, outkind;
9434 void *data, *outdata;
9435 Py_UCS4 maxchar = 0, *tmp, *tmpend;
9436
Benjamin Petersoneea48462012-01-16 14:28:50 -05009437 assert(PyUnicode_IS_READY(self));
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009438
9439 kind = PyUnicode_KIND(self);
9440 data = PyUnicode_DATA(self);
9441 length = PyUnicode_GET_LENGTH(self);
9442 tmp = PyMem_MALLOC(sizeof(Py_UCS4) * 3 * length);
9443 if (tmp == NULL)
9444 return PyErr_NoMemory();
9445 newlength = perform(kind, data, length, tmp, &maxchar);
9446 res = PyUnicode_New(newlength, maxchar);
9447 if (res == NULL)
9448 goto leave;
9449 tmpend = tmp + newlength;
9450 outdata = PyUnicode_DATA(res);
9451 outkind = PyUnicode_KIND(res);
9452 switch (outkind) {
9453 case PyUnicode_1BYTE_KIND:
9454 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, tmp, tmpend, outdata);
9455 break;
9456 case PyUnicode_2BYTE_KIND:
9457 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, tmp, tmpend, outdata);
9458 break;
9459 case PyUnicode_4BYTE_KIND:
9460 memcpy(outdata, tmp, sizeof(Py_UCS4) * newlength);
9461 break;
9462 default:
9463 assert(0);
9464 break;
9465 }
9466 leave:
9467 PyMem_FREE(tmp);
9468 return res;
9469}
9470
Tim Peters8ce9f162004-08-27 01:49:32 +00009471PyObject *
9472PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009473{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009474 PyObject *sep = NULL;
Victor Stinnerdd077322011-10-07 17:02:31 +02009475 Py_ssize_t seplen;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009476 PyObject *res = NULL; /* the result */
Tim Peters05eba1f2004-08-27 21:32:02 +00009477 PyObject *fseq; /* PySequence_Fast(seq) */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009478 Py_ssize_t seqlen; /* len(fseq) -- number of items in sequence */
9479 PyObject **items;
Tim Peters8ce9f162004-08-27 01:49:32 +00009480 PyObject *item;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009481 Py_ssize_t sz, i, res_offset;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009482 Py_UCS4 maxchar;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009483 Py_UCS4 item_maxchar;
Victor Stinnerdd077322011-10-07 17:02:31 +02009484 int use_memcpy;
9485 unsigned char *res_data = NULL, *sep_data = NULL;
9486 PyObject *last_obj;
9487 unsigned int kind = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009488
Tim Peters05eba1f2004-08-27 21:32:02 +00009489 fseq = PySequence_Fast(seq, "");
9490 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009491 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00009492 }
9493
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009494 /* NOTE: the following code can't call back into Python code,
9495 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00009496 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009497
Tim Peters05eba1f2004-08-27 21:32:02 +00009498 seqlen = PySequence_Fast_GET_SIZE(fseq);
9499 /* If empty sequence, return u"". */
9500 if (seqlen == 0) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009501 Py_DECREF(fseq);
9502 Py_INCREF(unicode_empty);
9503 res = unicode_empty;
9504 return res;
Tim Peters05eba1f2004-08-27 21:32:02 +00009505 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009506
Tim Peters05eba1f2004-08-27 21:32:02 +00009507 /* If singleton sequence with an exact Unicode, return that. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009508 last_obj = NULL;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009509 items = PySequence_Fast_ITEMS(fseq);
Victor Stinneracf47b82011-10-06 12:32:37 +02009510 if (seqlen == 1) {
9511 if (PyUnicode_CheckExact(items[0])) {
9512 res = items[0];
9513 Py_INCREF(res);
9514 Py_DECREF(fseq);
9515 return res;
9516 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009517 seplen = 0;
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009518 maxchar = 0;
Tim Peters8ce9f162004-08-27 01:49:32 +00009519 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009520 else {
Victor Stinneracf47b82011-10-06 12:32:37 +02009521 /* Set up sep and seplen */
9522 if (separator == NULL) {
9523 /* fall back to a blank space separator */
9524 sep = PyUnicode_FromOrdinal(' ');
9525 if (!sep)
9526 goto onError;
Victor Stinnerdd077322011-10-07 17:02:31 +02009527 seplen = 1;
Victor Stinneracf47b82011-10-06 12:32:37 +02009528 maxchar = 32;
Tim Peters05eba1f2004-08-27 21:32:02 +00009529 }
Victor Stinneracf47b82011-10-06 12:32:37 +02009530 else {
9531 if (!PyUnicode_Check(separator)) {
9532 PyErr_Format(PyExc_TypeError,
9533 "separator: expected str instance,"
9534 " %.80s found",
9535 Py_TYPE(separator)->tp_name);
9536 goto onError;
9537 }
9538 if (PyUnicode_READY(separator))
9539 goto onError;
9540 sep = separator;
9541 seplen = PyUnicode_GET_LENGTH(separator);
9542 maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
9543 /* inc refcount to keep this code path symmetric with the
9544 above case of a blank separator */
9545 Py_INCREF(sep);
9546 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009547 last_obj = sep;
Tim Peters05eba1f2004-08-27 21:32:02 +00009548 }
9549
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009550 /* There are at least two things to join, or else we have a subclass
9551 * of str in the sequence.
9552 * Do a pre-pass to figure out the total amount of space we'll
9553 * need (sz), and see whether all argument are strings.
9554 */
9555 sz = 0;
Victor Stinnerdd077322011-10-07 17:02:31 +02009556#ifdef Py_DEBUG
9557 use_memcpy = 0;
9558#else
9559 use_memcpy = 1;
9560#endif
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009561 for (i = 0; i < seqlen; i++) {
9562 const Py_ssize_t old_sz = sz;
9563 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009564 if (!PyUnicode_Check(item)) {
9565 PyErr_Format(PyExc_TypeError,
9566 "sequence item %zd: expected str instance,"
9567 " %.80s found",
9568 i, Py_TYPE(item)->tp_name);
9569 goto onError;
9570 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009571 if (PyUnicode_READY(item) == -1)
9572 goto onError;
9573 sz += PyUnicode_GET_LENGTH(item);
9574 item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
Victor Stinnere6abb482012-05-02 01:15:40 +02009575 maxchar = MAX_MAXCHAR(maxchar, item_maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009576 if (i != 0)
9577 sz += seplen;
9578 if (sz < old_sz || sz > PY_SSIZE_T_MAX) {
9579 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009580 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009581 goto onError;
9582 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009583 if (use_memcpy && last_obj != NULL) {
9584 if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
9585 use_memcpy = 0;
9586 }
9587 last_obj = item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009588 }
Tim Petersced69f82003-09-16 20:30:58 +00009589
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009590 res = PyUnicode_New(sz, maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009591 if (res == NULL)
9592 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +00009593
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009594 /* Catenate everything. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009595#ifdef Py_DEBUG
9596 use_memcpy = 0;
9597#else
9598 if (use_memcpy) {
9599 res_data = PyUnicode_1BYTE_DATA(res);
9600 kind = PyUnicode_KIND(res);
9601 if (seplen != 0)
9602 sep_data = PyUnicode_1BYTE_DATA(sep);
9603 }
9604#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009605 for (i = 0, res_offset = 0; i < seqlen; ++i) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009606 Py_ssize_t itemlen;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009607 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009608 /* Copy item, and maybe the separator. */
Victor Stinner9ce5a832011-10-03 23:36:02 +02009609 if (i && seplen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009610 if (use_memcpy) {
9611 Py_MEMCPY(res_data,
9612 sep_data,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009613 kind * seplen);
9614 res_data += kind * seplen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009615 }
9616 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02009617 _PyUnicode_FastCopyCharacters(res, res_offset, sep, 0, seplen);
Victor Stinnerdd077322011-10-07 17:02:31 +02009618 res_offset += seplen;
9619 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009620 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009621 itemlen = PyUnicode_GET_LENGTH(item);
9622 if (itemlen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009623 if (use_memcpy) {
9624 Py_MEMCPY(res_data,
9625 PyUnicode_DATA(item),
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009626 kind * itemlen);
9627 res_data += kind * itemlen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009628 }
9629 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02009630 _PyUnicode_FastCopyCharacters(res, res_offset, item, 0, itemlen);
Victor Stinnerdd077322011-10-07 17:02:31 +02009631 res_offset += itemlen;
9632 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009633 }
Tim Peters05eba1f2004-08-27 21:32:02 +00009634 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009635 if (use_memcpy)
9636 assert(res_data == PyUnicode_1BYTE_DATA(res)
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009637 + kind * PyUnicode_GET_LENGTH(res));
Victor Stinnerdd077322011-10-07 17:02:31 +02009638 else
9639 assert(res_offset == PyUnicode_GET_LENGTH(res));
Tim Peters8ce9f162004-08-27 01:49:32 +00009640
Tim Peters05eba1f2004-08-27 21:32:02 +00009641 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009642 Py_XDECREF(sep);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009643 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009644 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009645
Benjamin Peterson29060642009-01-31 22:14:21 +00009646 onError:
Tim Peters05eba1f2004-08-27 21:32:02 +00009647 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009648 Py_XDECREF(sep);
Tim Peters8ce9f162004-08-27 01:49:32 +00009649 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009650 return NULL;
9651}
9652
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009653#define FILL(kind, data, value, start, length) \
9654 do { \
9655 Py_ssize_t i_ = 0; \
9656 assert(kind != PyUnicode_WCHAR_KIND); \
9657 switch ((kind)) { \
9658 case PyUnicode_1BYTE_KIND: { \
9659 unsigned char * to_ = (unsigned char *)((data)) + (start); \
Victor Stinnerf2c76aa2012-05-03 13:10:40 +02009660 memset(to_, (unsigned char)value, (length)); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009661 break; \
9662 } \
9663 case PyUnicode_2BYTE_KIND: { \
9664 Py_UCS2 * to_ = (Py_UCS2 *)((data)) + (start); \
9665 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9666 break; \
9667 } \
Benjamin Petersone157cf12012-01-01 15:56:20 -06009668 case PyUnicode_4BYTE_KIND: { \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009669 Py_UCS4 * to_ = (Py_UCS4 *)((data)) + (start); \
9670 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9671 break; \
Benjamin Petersone157cf12012-01-01 15:56:20 -06009672 default: assert(0); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009673 } \
9674 } \
9675 } while (0)
9676
Victor Stinnerd3f08822012-05-29 12:57:52 +02009677void
9678_PyUnicode_FastFill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
9679 Py_UCS4 fill_char)
9680{
9681 const enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
9682 const void *data = PyUnicode_DATA(unicode);
9683 assert(PyUnicode_IS_READY(unicode));
9684 assert(unicode_modifiable(unicode));
9685 assert(fill_char <= PyUnicode_MAX_CHAR_VALUE(unicode));
9686 assert(start >= 0);
9687 assert(start + length <= PyUnicode_GET_LENGTH(unicode));
9688 FILL(kind, data, fill_char, start, length);
9689}
9690
Victor Stinner3fe55312012-01-04 00:33:50 +01009691Py_ssize_t
9692PyUnicode_Fill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
9693 Py_UCS4 fill_char)
9694{
9695 Py_ssize_t maxlen;
Victor Stinner3fe55312012-01-04 00:33:50 +01009696
9697 if (!PyUnicode_Check(unicode)) {
9698 PyErr_BadInternalCall();
9699 return -1;
9700 }
9701 if (PyUnicode_READY(unicode) == -1)
9702 return -1;
9703 if (unicode_check_modifiable(unicode))
9704 return -1;
9705
Victor Stinnerd3f08822012-05-29 12:57:52 +02009706 if (start < 0) {
9707 PyErr_SetString(PyExc_IndexError, "string index out of range");
9708 return -1;
9709 }
Victor Stinner3fe55312012-01-04 00:33:50 +01009710 if (fill_char > PyUnicode_MAX_CHAR_VALUE(unicode)) {
9711 PyErr_SetString(PyExc_ValueError,
9712 "fill character is bigger than "
9713 "the string maximum character");
9714 return -1;
9715 }
9716
9717 maxlen = PyUnicode_GET_LENGTH(unicode) - start;
9718 length = Py_MIN(maxlen, length);
9719 if (length <= 0)
9720 return 0;
9721
Victor Stinnerd3f08822012-05-29 12:57:52 +02009722 _PyUnicode_FastFill(unicode, start, length, fill_char);
Victor Stinner3fe55312012-01-04 00:33:50 +01009723 return length;
9724}
9725
Victor Stinner9310abb2011-10-05 00:59:23 +02009726static PyObject *
9727pad(PyObject *self,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009728 Py_ssize_t left,
9729 Py_ssize_t right,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009730 Py_UCS4 fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009731{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009732 PyObject *u;
9733 Py_UCS4 maxchar;
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009734 int kind;
9735 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009736
9737 if (left < 0)
9738 left = 0;
9739 if (right < 0)
9740 right = 0;
9741
Victor Stinnerc4b49542011-12-11 22:44:26 +01009742 if (left == 0 && right == 0)
9743 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009744
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009745 if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
9746 right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +00009747 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
9748 return NULL;
9749 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009750 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Victor Stinnere6abb482012-05-02 01:15:40 +02009751 maxchar = MAX_MAXCHAR(maxchar, fill);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009752 u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009753 if (!u)
9754 return NULL;
9755
9756 kind = PyUnicode_KIND(u);
9757 data = PyUnicode_DATA(u);
9758 if (left)
9759 FILL(kind, data, fill, 0, left);
9760 if (right)
9761 FILL(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
Victor Stinnerd3f08822012-05-29 12:57:52 +02009762 _PyUnicode_FastCopyCharacters(u, left, self, 0, _PyUnicode_LENGTH(self));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009763 assert(_PyUnicode_CheckConsistency(u, 1));
9764 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009765}
9766
Alexander Belopolsky40018472011-02-26 01:02:56 +00009767PyObject *
9768PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009769{
Guido van Rossumd57fd912000-03-10 22:53:23 +00009770 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009771
9772 string = PyUnicode_FromObject(string);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009773 if (string == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009774 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -06009775 if (PyUnicode_READY(string) == -1) {
9776 Py_DECREF(string);
9777 return NULL;
9778 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009779
Benjamin Petersonead6b532011-12-20 17:23:42 -06009780 switch (PyUnicode_KIND(string)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009781 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009782 if (PyUnicode_IS_ASCII(string))
9783 list = asciilib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009784 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009785 PyUnicode_GET_LENGTH(string), keepends);
9786 else
9787 list = ucs1lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009788 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009789 PyUnicode_GET_LENGTH(string), keepends);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009790 break;
9791 case PyUnicode_2BYTE_KIND:
9792 list = ucs2lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009793 string, PyUnicode_2BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009794 PyUnicode_GET_LENGTH(string), keepends);
9795 break;
9796 case PyUnicode_4BYTE_KIND:
9797 list = ucs4lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009798 string, PyUnicode_4BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009799 PyUnicode_GET_LENGTH(string), keepends);
9800 break;
9801 default:
9802 assert(0);
9803 list = 0;
9804 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009805 Py_DECREF(string);
9806 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009807}
9808
Alexander Belopolsky40018472011-02-26 01:02:56 +00009809static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009810split(PyObject *self,
9811 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009812 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009813{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009814 int kind1, kind2, kind;
9815 void *buf1, *buf2;
9816 Py_ssize_t len1, len2;
9817 PyObject* out;
9818
Guido van Rossumd57fd912000-03-10 22:53:23 +00009819 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00009820 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009821
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009822 if (PyUnicode_READY(self) == -1)
9823 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009824
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009825 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -06009826 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009827 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009828 if (PyUnicode_IS_ASCII(self))
9829 return asciilib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009830 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009831 PyUnicode_GET_LENGTH(self), maxcount
9832 );
9833 else
9834 return ucs1lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009835 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009836 PyUnicode_GET_LENGTH(self), maxcount
9837 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009838 case PyUnicode_2BYTE_KIND:
9839 return ucs2lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009840 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009841 PyUnicode_GET_LENGTH(self), maxcount
9842 );
9843 case PyUnicode_4BYTE_KIND:
9844 return ucs4lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009845 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009846 PyUnicode_GET_LENGTH(self), maxcount
9847 );
9848 default:
9849 assert(0);
9850 return NULL;
9851 }
9852
9853 if (PyUnicode_READY(substring) == -1)
9854 return NULL;
9855
9856 kind1 = PyUnicode_KIND(self);
9857 kind2 = PyUnicode_KIND(substring);
9858 kind = kind1 > kind2 ? kind1 : kind2;
9859 buf1 = PyUnicode_DATA(self);
9860 buf2 = PyUnicode_DATA(substring);
9861 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009862 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009863 if (!buf1)
9864 return NULL;
9865 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009866 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009867 if (!buf2) {
9868 if (kind1 != kind) PyMem_Free(buf1);
9869 return NULL;
9870 }
9871 len1 = PyUnicode_GET_LENGTH(self);
9872 len2 = PyUnicode_GET_LENGTH(substring);
9873
Benjamin Petersonead6b532011-12-20 17:23:42 -06009874 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009875 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009876 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
9877 out = asciilib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009878 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +02009879 else
9880 out = ucs1lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009881 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009882 break;
9883 case PyUnicode_2BYTE_KIND:
9884 out = ucs2lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009885 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009886 break;
9887 case PyUnicode_4BYTE_KIND:
9888 out = ucs4lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009889 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009890 break;
9891 default:
9892 out = NULL;
9893 }
9894 if (kind1 != kind)
9895 PyMem_Free(buf1);
9896 if (kind2 != kind)
9897 PyMem_Free(buf2);
9898 return out;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009899}
9900
Alexander Belopolsky40018472011-02-26 01:02:56 +00009901static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009902rsplit(PyObject *self,
9903 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009904 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009905{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009906 int kind1, kind2, kind;
9907 void *buf1, *buf2;
9908 Py_ssize_t len1, len2;
9909 PyObject* out;
9910
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009911 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00009912 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009913
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009914 if (PyUnicode_READY(self) == -1)
9915 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009916
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009917 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -06009918 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009919 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009920 if (PyUnicode_IS_ASCII(self))
9921 return asciilib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009922 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009923 PyUnicode_GET_LENGTH(self), maxcount
9924 );
9925 else
9926 return ucs1lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009927 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009928 PyUnicode_GET_LENGTH(self), maxcount
9929 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009930 case PyUnicode_2BYTE_KIND:
9931 return ucs2lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009932 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009933 PyUnicode_GET_LENGTH(self), maxcount
9934 );
9935 case PyUnicode_4BYTE_KIND:
9936 return ucs4lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009937 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009938 PyUnicode_GET_LENGTH(self), maxcount
9939 );
9940 default:
9941 assert(0);
9942 return NULL;
9943 }
9944
9945 if (PyUnicode_READY(substring) == -1)
9946 return NULL;
9947
9948 kind1 = PyUnicode_KIND(self);
9949 kind2 = PyUnicode_KIND(substring);
9950 kind = kind1 > kind2 ? kind1 : kind2;
9951 buf1 = PyUnicode_DATA(self);
9952 buf2 = PyUnicode_DATA(substring);
9953 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009954 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009955 if (!buf1)
9956 return NULL;
9957 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009958 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009959 if (!buf2) {
9960 if (kind1 != kind) PyMem_Free(buf1);
9961 return NULL;
9962 }
9963 len1 = PyUnicode_GET_LENGTH(self);
9964 len2 = PyUnicode_GET_LENGTH(substring);
9965
Benjamin Petersonead6b532011-12-20 17:23:42 -06009966 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009967 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009968 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
9969 out = asciilib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009970 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +02009971 else
9972 out = ucs1lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009973 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009974 break;
9975 case PyUnicode_2BYTE_KIND:
9976 out = ucs2lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009977 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009978 break;
9979 case PyUnicode_4BYTE_KIND:
9980 out = ucs4lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009981 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009982 break;
9983 default:
9984 out = NULL;
9985 }
9986 if (kind1 != kind)
9987 PyMem_Free(buf1);
9988 if (kind2 != kind)
9989 PyMem_Free(buf2);
9990 return out;
9991}
9992
9993static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +02009994anylib_find(int kind, PyObject *str1, void *buf1, Py_ssize_t len1,
9995 PyObject *str2, void *buf2, Py_ssize_t len2, Py_ssize_t offset)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009996{
Benjamin Petersonead6b532011-12-20 17:23:42 -06009997 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009998 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009999 if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
10000 return asciilib_find(buf1, len1, buf2, len2, offset);
10001 else
10002 return ucs1lib_find(buf1, len1, buf2, len2, offset);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010003 case PyUnicode_2BYTE_KIND:
10004 return ucs2lib_find(buf1, len1, buf2, len2, offset);
10005 case PyUnicode_4BYTE_KIND:
10006 return ucs4lib_find(buf1, len1, buf2, len2, offset);
10007 }
10008 assert(0);
10009 return -1;
10010}
10011
10012static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010013anylib_count(int kind, PyObject *sstr, void* sbuf, Py_ssize_t slen,
10014 PyObject *str1, void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010015{
Benjamin Petersonc0b95d12011-12-20 17:24:05 -060010016 switch (kind) {
10017 case PyUnicode_1BYTE_KIND:
10018 if (PyUnicode_IS_ASCII(sstr) && PyUnicode_IS_ASCII(str1))
10019 return asciilib_count(sbuf, slen, buf1, len1, maxcount);
10020 else
10021 return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
10022 case PyUnicode_2BYTE_KIND:
10023 return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
10024 case PyUnicode_4BYTE_KIND:
10025 return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
10026 }
10027 assert(0);
10028 return 0;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010029}
10030
Alexander Belopolsky40018472011-02-26 01:02:56 +000010031static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010032replace(PyObject *self, PyObject *str1,
10033 PyObject *str2, Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010034{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010035 PyObject *u;
10036 char *sbuf = PyUnicode_DATA(self);
10037 char *buf1 = PyUnicode_DATA(str1);
10038 char *buf2 = PyUnicode_DATA(str2);
10039 int srelease = 0, release1 = 0, release2 = 0;
10040 int skind = PyUnicode_KIND(self);
10041 int kind1 = PyUnicode_KIND(str1);
10042 int kind2 = PyUnicode_KIND(str2);
10043 Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
10044 Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
10045 Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010046 int mayshrink;
10047 Py_UCS4 maxchar, maxchar_str2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010048
10049 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010050 maxcount = PY_SSIZE_T_MAX;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010051 else if (maxcount == 0 || slen == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010052 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010053
Victor Stinner59de0ee2011-10-07 10:01:28 +020010054 if (str1 == str2)
10055 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010056 if (skind < kind1)
10057 /* substring too wide to be present */
10058 goto nothing;
10059
Victor Stinner49a0a212011-10-12 23:46:10 +020010060 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
10061 maxchar_str2 = PyUnicode_MAX_CHAR_VALUE(str2);
10062 /* Replacing str1 with str2 may cause a maxchar reduction in the
10063 result string. */
10064 mayshrink = (maxchar_str2 < maxchar);
Victor Stinnere6abb482012-05-02 01:15:40 +020010065 maxchar = MAX_MAXCHAR(maxchar, maxchar_str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010066
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010067 if (len1 == len2) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010068 /* same length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010069 if (len1 == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010070 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010071 if (len1 == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010072 /* replace characters */
Victor Stinner49a0a212011-10-12 23:46:10 +020010073 Py_UCS4 u1, u2;
10074 int rkind;
Victor Stinnerf6441102011-12-18 02:43:08 +010010075 Py_ssize_t index, pos;
10076 char *src;
10077
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010078 u1 = PyUnicode_READ_CHAR(str1, 0);
Victor Stinnerf6441102011-12-18 02:43:08 +010010079 pos = findchar(sbuf, PyUnicode_KIND(self), slen, u1, 1);
10080 if (pos < 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010081 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010082 u2 = PyUnicode_READ_CHAR(str2, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010083 u = PyUnicode_New(slen, maxchar);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010084 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010085 goto error;
Victor Stinnerd3f08822012-05-29 12:57:52 +020010086 _PyUnicode_FastCopyCharacters(u, 0, self, 0, slen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010087 rkind = PyUnicode_KIND(u);
Victor Stinnerf6441102011-12-18 02:43:08 +010010088
10089 PyUnicode_WRITE(rkind, PyUnicode_DATA(u), pos, u2);
10090 index = 0;
10091 src = sbuf;
10092 while (--maxcount)
10093 {
10094 pos++;
10095 src += pos * PyUnicode_KIND(self);
10096 slen -= pos;
10097 index += pos;
10098 pos = findchar(src, PyUnicode_KIND(self), slen, u1, 1);
10099 if (pos < 0)
10100 break;
10101 PyUnicode_WRITE(rkind, PyUnicode_DATA(u), index + pos, u2);
10102 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010103 }
10104 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010105 int rkind = skind;
10106 char *res;
Victor Stinnerf6441102011-12-18 02:43:08 +010010107 Py_ssize_t i;
Victor Stinner25a4b292011-10-06 12:31:55 +020010108
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010109 if (kind1 < rkind) {
10110 /* widen substring */
10111 buf1 = _PyUnicode_AsKind(str1, rkind);
10112 if (!buf1) goto error;
10113 release1 = 1;
10114 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010115 i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010116 if (i < 0)
10117 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010118 if (rkind > kind2) {
10119 /* widen replacement */
10120 buf2 = _PyUnicode_AsKind(str2, rkind);
10121 if (!buf2) goto error;
10122 release2 = 1;
10123 }
10124 else if (rkind < kind2) {
10125 /* widen self and buf1 */
10126 rkind = kind2;
10127 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010128 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010129 sbuf = _PyUnicode_AsKind(self, rkind);
10130 if (!sbuf) goto error;
10131 srelease = 1;
10132 buf1 = _PyUnicode_AsKind(str1, rkind);
10133 if (!buf1) goto error;
10134 release1 = 1;
10135 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010136 u = PyUnicode_New(slen, maxchar);
10137 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010138 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010139 assert(PyUnicode_KIND(u) == rkind);
10140 res = PyUnicode_DATA(u);
Victor Stinner25a4b292011-10-06 12:31:55 +020010141
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010142 memcpy(res, sbuf, rkind * slen);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010143 /* change everything in-place, starting with this one */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010144 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010145 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010146 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010147 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010148
10149 while ( --maxcount > 0) {
Victor Stinnerc3cec782011-10-05 21:24:08 +020010150 i = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010151 sbuf+rkind*i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010152 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010153 if (i == -1)
10154 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010155 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010156 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010157 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010158 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010159 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010160 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010161 }
10162 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010163 Py_ssize_t n, i, j, ires;
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010164 Py_ssize_t new_size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010165 int rkind = skind;
10166 char *res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010167
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010168 if (kind1 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010169 /* widen substring */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010170 buf1 = _PyUnicode_AsKind(str1, rkind);
10171 if (!buf1) goto error;
10172 release1 = 1;
10173 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010174 n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010175 if (n == 0)
10176 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010177 if (kind2 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010178 /* widen replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010179 buf2 = _PyUnicode_AsKind(str2, rkind);
10180 if (!buf2) goto error;
10181 release2 = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010182 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010183 else if (kind2 > rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010184 /* widen self and buf1 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010185 rkind = kind2;
10186 sbuf = _PyUnicode_AsKind(self, rkind);
10187 if (!sbuf) goto error;
10188 srelease = 1;
10189 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010190 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010191 buf1 = _PyUnicode_AsKind(str1, rkind);
10192 if (!buf1) goto error;
10193 release1 = 1;
10194 }
10195 /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
10196 PyUnicode_GET_LENGTH(str1))); */
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010197 if (len2 > len1 && len2 - len1 > (PY_SSIZE_T_MAX - slen) / n) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010198 PyErr_SetString(PyExc_OverflowError,
10199 "replace string is too long");
10200 goto error;
10201 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010202 new_size = slen + n * (len2 - len1);
Victor Stinner49a0a212011-10-12 23:46:10 +020010203 if (new_size == 0) {
10204 Py_INCREF(unicode_empty);
10205 u = unicode_empty;
10206 goto done;
10207 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010208 if (new_size > (PY_SSIZE_T_MAX >> (rkind-1))) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010209 PyErr_SetString(PyExc_OverflowError,
10210 "replace string is too long");
10211 goto error;
10212 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010213 u = PyUnicode_New(new_size, maxchar);
10214 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010215 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010216 assert(PyUnicode_KIND(u) == rkind);
10217 res = PyUnicode_DATA(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010218 ires = i = 0;
10219 if (len1 > 0) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010220 while (n-- > 0) {
10221 /* look for next match */
Victor Stinnerc3cec782011-10-05 21:24:08 +020010222 j = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010223 sbuf + rkind * i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010224 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010225 if (j == -1)
10226 break;
10227 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010228 /* copy unchanged part [i:j] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010229 memcpy(res + rkind * ires,
10230 sbuf + rkind * i,
10231 rkind * (j-i));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010232 ires += j - i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010233 }
10234 /* copy substitution string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010235 if (len2 > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010236 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010237 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010238 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010239 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010240 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010241 i = j + len1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010242 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010243 if (i < slen)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010244 /* copy tail [i:] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010245 memcpy(res + rkind * ires,
10246 sbuf + rkind * i,
10247 rkind * (slen-i));
Victor Stinner49a0a212011-10-12 23:46:10 +020010248 }
10249 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010250 /* interleave */
10251 while (n > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010252 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010253 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010254 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010255 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010256 if (--n <= 0)
10257 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010258 memcpy(res + rkind * ires,
10259 sbuf + rkind * i,
10260 rkind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010261 ires++;
10262 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010263 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010264 memcpy(res + rkind * ires,
10265 sbuf + rkind * i,
10266 rkind * (slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +000010267 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010268 }
10269
10270 if (mayshrink) {
Victor Stinner25a4b292011-10-06 12:31:55 +020010271 unicode_adjust_maxchar(&u);
10272 if (u == NULL)
10273 goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010274 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010275
10276 done:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010277 if (srelease)
10278 PyMem_FREE(sbuf);
10279 if (release1)
10280 PyMem_FREE(buf1);
10281 if (release2)
10282 PyMem_FREE(buf2);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010283 assert(_PyUnicode_CheckConsistency(u, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010284 return u;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010285
Benjamin Peterson29060642009-01-31 22:14:21 +000010286 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +000010287 /* nothing to replace; return original string (when possible) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010288 if (srelease)
10289 PyMem_FREE(sbuf);
10290 if (release1)
10291 PyMem_FREE(buf1);
10292 if (release2)
10293 PyMem_FREE(buf2);
Victor Stinnerc4b49542011-12-11 22:44:26 +010010294 return unicode_result_unchanged(self);
10295
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010296 error:
10297 if (srelease && sbuf)
10298 PyMem_FREE(sbuf);
10299 if (release1 && buf1)
10300 PyMem_FREE(buf1);
10301 if (release2 && buf2)
10302 PyMem_FREE(buf2);
10303 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010304}
10305
10306/* --- Unicode Object Methods --------------------------------------------- */
10307
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010308PyDoc_STRVAR(title__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010309 "S.title() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010310\n\
10311Return a titlecased version of S, i.e. words start with title case\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010312characters, all remaining cased characters have lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010313
10314static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010315unicode_title(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010316{
Benjamin Petersoneea48462012-01-16 14:28:50 -050010317 if (PyUnicode_READY(self) == -1)
10318 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010319 return case_operation(self, do_title);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010320}
10321
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010322PyDoc_STRVAR(capitalize__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010323 "S.capitalize() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010324\n\
10325Return a capitalized version of S, i.e. make the first character\n\
Senthil Kumarane51ee8a2010-07-05 12:00:56 +000010326have upper case and the rest lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010327
10328static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010329unicode_capitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010330{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050010331 if (PyUnicode_READY(self) == -1)
10332 return NULL;
10333 if (PyUnicode_GET_LENGTH(self) == 0)
10334 return unicode_result_unchanged(self);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010335 return case_operation(self, do_capitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010336}
10337
Benjamin Petersond5890c82012-01-14 13:23:30 -050010338PyDoc_STRVAR(casefold__doc__,
10339 "S.casefold() -> str\n\
10340\n\
10341Return a version of S suitable for caseless comparisons.");
10342
10343static PyObject *
10344unicode_casefold(PyObject *self)
10345{
10346 if (PyUnicode_READY(self) == -1)
10347 return NULL;
10348 if (PyUnicode_IS_ASCII(self))
10349 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010350 return case_operation(self, do_casefold);
Benjamin Petersond5890c82012-01-14 13:23:30 -050010351}
10352
10353
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010354/* Argument converter. Coerces to a single unicode character */
10355
10356static int
10357convert_uc(PyObject *obj, void *addr)
10358{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010359 Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010360 PyObject *uniobj;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010361
Benjamin Peterson14339b62009-01-31 16:36:08 +000010362 uniobj = PyUnicode_FromObject(obj);
10363 if (uniobj == NULL) {
10364 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010365 "The fill character cannot be converted to Unicode");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010366 return 0;
10367 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010368 if (PyUnicode_GET_LENGTH(uniobj) != 1) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010369 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010370 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010371 Py_DECREF(uniobj);
10372 return 0;
10373 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010374 *fillcharloc = PyUnicode_READ_CHAR(uniobj, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010375 Py_DECREF(uniobj);
10376 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010377}
10378
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010379PyDoc_STRVAR(center__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010380 "S.center(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010381\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010382Return S centered in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010383done using the specified fill character (default is a space)");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010384
10385static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010386unicode_center(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010387{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010388 Py_ssize_t marg, left;
10389 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010390 Py_UCS4 fillchar = ' ';
10391
Victor Stinnere9a29352011-10-01 02:14:59 +020010392 if (!PyArg_ParseTuple(args, "n|O&:center", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010393 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010394
Benjamin Petersonbac79492012-01-14 13:34:47 -050010395 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010396 return NULL;
10397
Victor Stinnerc4b49542011-12-11 22:44:26 +010010398 if (PyUnicode_GET_LENGTH(self) >= width)
10399 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010400
Victor Stinnerc4b49542011-12-11 22:44:26 +010010401 marg = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010402 left = marg / 2 + (marg & width & 1);
10403
Victor Stinner9310abb2011-10-05 00:59:23 +020010404 return pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010405}
10406
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010407/* This function assumes that str1 and str2 are readied by the caller. */
10408
Marc-André Lemburge5034372000-08-08 08:04:29 +000010409static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010410unicode_compare(PyObject *str1, PyObject *str2)
Marc-André Lemburge5034372000-08-08 08:04:29 +000010411{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010412 int kind1, kind2;
10413 void *data1, *data2;
10414 Py_ssize_t len1, len2, i;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010415
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010416 kind1 = PyUnicode_KIND(str1);
10417 kind2 = PyUnicode_KIND(str2);
10418 data1 = PyUnicode_DATA(str1);
10419 data2 = PyUnicode_DATA(str2);
10420 len1 = PyUnicode_GET_LENGTH(str1);
10421 len2 = PyUnicode_GET_LENGTH(str2);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010422
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010423 for (i = 0; i < len1 && i < len2; ++i) {
10424 Py_UCS4 c1, c2;
10425 c1 = PyUnicode_READ(kind1, data1, i);
10426 c2 = PyUnicode_READ(kind2, data2, i);
Fredrik Lundh45714e92001-06-26 16:39:36 +000010427
10428 if (c1 != c2)
10429 return (c1 < c2) ? -1 : 1;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010430 }
10431
10432 return (len1 < len2) ? -1 : (len1 != len2);
10433}
10434
Alexander Belopolsky40018472011-02-26 01:02:56 +000010435int
10436PyUnicode_Compare(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010437{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010438 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10439 if (PyUnicode_READY(left) == -1 ||
10440 PyUnicode_READY(right) == -1)
10441 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010442 return unicode_compare(left, right);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010443 }
Guido van Rossum09dc34f2007-05-04 04:17:33 +000010444 PyErr_Format(PyExc_TypeError,
10445 "Can't compare %.100s and %.100s",
10446 left->ob_type->tp_name,
10447 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010448 return -1;
10449}
10450
Martin v. Löwis5b222132007-06-10 09:51:05 +000010451int
10452PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
10453{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010454 Py_ssize_t i;
10455 int kind;
10456 void *data;
10457 Py_UCS4 chr;
10458
Victor Stinner910337b2011-10-03 03:20:16 +020010459 assert(_PyUnicode_CHECK(uni));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010460 if (PyUnicode_READY(uni) == -1)
10461 return -1;
10462 kind = PyUnicode_KIND(uni);
10463 data = PyUnicode_DATA(uni);
Martin v. Löwis5b222132007-06-10 09:51:05 +000010464 /* Compare Unicode string and source character set string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010465 for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
10466 if (chr != str[i])
10467 return (chr < (unsigned char)(str[i])) ? -1 : 1;
Benjamin Peterson8667a9b2010-01-09 21:45:28 +000010468 /* This check keeps Python strings that end in '\0' from comparing equal
10469 to C strings identical up to that point. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010470 if (PyUnicode_GET_LENGTH(uni) != i || chr)
Benjamin Peterson29060642009-01-31 22:14:21 +000010471 return 1; /* uni is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010472 if (str[i])
Benjamin Peterson29060642009-01-31 22:14:21 +000010473 return -1; /* str is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010474 return 0;
10475}
10476
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010477
Benjamin Peterson29060642009-01-31 22:14:21 +000010478#define TEST_COND(cond) \
Benjamin Peterson14339b62009-01-31 16:36:08 +000010479 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010480
Alexander Belopolsky40018472011-02-26 01:02:56 +000010481PyObject *
10482PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010483{
10484 int result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010485
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010486 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10487 PyObject *v;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010488 if (PyUnicode_READY(left) == -1 ||
10489 PyUnicode_READY(right) == -1)
10490 return NULL;
10491 if (PyUnicode_GET_LENGTH(left) != PyUnicode_GET_LENGTH(right) ||
10492 PyUnicode_KIND(left) != PyUnicode_KIND(right)) {
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010493 if (op == Py_EQ) {
10494 Py_INCREF(Py_False);
10495 return Py_False;
10496 }
10497 if (op == Py_NE) {
10498 Py_INCREF(Py_True);
10499 return Py_True;
10500 }
10501 }
10502 if (left == right)
10503 result = 0;
10504 else
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010505 result = unicode_compare(left, right);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010506
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010507 /* Convert the return value to a Boolean */
10508 switch (op) {
10509 case Py_EQ:
10510 v = TEST_COND(result == 0);
10511 break;
10512 case Py_NE:
10513 v = TEST_COND(result != 0);
10514 break;
10515 case Py_LE:
10516 v = TEST_COND(result <= 0);
10517 break;
10518 case Py_GE:
10519 v = TEST_COND(result >= 0);
10520 break;
10521 case Py_LT:
10522 v = TEST_COND(result == -1);
10523 break;
10524 case Py_GT:
10525 v = TEST_COND(result == 1);
10526 break;
10527 default:
10528 PyErr_BadArgument();
10529 return NULL;
10530 }
10531 Py_INCREF(v);
10532 return v;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010533 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000010534
Brian Curtindfc80e32011-08-10 20:28:54 -050010535 Py_RETURN_NOTIMPLEMENTED;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010536}
10537
Alexander Belopolsky40018472011-02-26 01:02:56 +000010538int
10539PyUnicode_Contains(PyObject *container, PyObject *element)
Guido van Rossum403d68b2000-03-13 15:55:09 +000010540{
Thomas Wouters477c8d52006-05-27 19:21:47 +000010541 PyObject *str, *sub;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010542 int kind1, kind2, kind;
10543 void *buf1, *buf2;
10544 Py_ssize_t len1, len2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010545 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010546
10547 /* Coerce the two arguments */
Thomas Wouters477c8d52006-05-27 19:21:47 +000010548 sub = PyUnicode_FromObject(element);
10549 if (!sub) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010550 PyErr_Format(PyExc_TypeError,
10551 "'in <string>' requires string as left operand, not %s",
10552 element->ob_type->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010553 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010554 }
10555
Thomas Wouters477c8d52006-05-27 19:21:47 +000010556 str = PyUnicode_FromObject(container);
Benjamin Peterson22a29702012-01-02 09:00:30 -060010557 if (!str) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010558 Py_DECREF(sub);
10559 return -1;
10560 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060010561 if (PyUnicode_READY(sub) == -1 || PyUnicode_READY(str) == -1) {
10562 Py_DECREF(sub);
10563 Py_DECREF(str);
10564 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000010565
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010566 kind1 = PyUnicode_KIND(str);
10567 kind2 = PyUnicode_KIND(sub);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010568 kind = kind1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010569 buf1 = PyUnicode_DATA(str);
10570 buf2 = PyUnicode_DATA(sub);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010571 if (kind2 != kind) {
Antoine Pitrou758153b2012-05-12 15:51:51 +020010572 if (kind2 > kind) {
10573 Py_DECREF(sub);
10574 Py_DECREF(str);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010575 return 0;
Antoine Pitrou758153b2012-05-12 15:51:51 +020010576 }
Victor Stinner7931d9a2011-11-04 00:22:48 +010010577 buf2 = _PyUnicode_AsKind(sub, kind);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010578 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010579 if (!buf2) {
10580 Py_DECREF(sub);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010581 Py_DECREF(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010582 return -1;
10583 }
10584 len1 = PyUnicode_GET_LENGTH(str);
10585 len2 = PyUnicode_GET_LENGTH(sub);
10586
Benjamin Petersonead6b532011-12-20 17:23:42 -060010587 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010588 case PyUnicode_1BYTE_KIND:
10589 result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
10590 break;
10591 case PyUnicode_2BYTE_KIND:
10592 result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
10593 break;
10594 case PyUnicode_4BYTE_KIND:
10595 result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
10596 break;
10597 default:
10598 result = -1;
10599 assert(0);
10600 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000010601
10602 Py_DECREF(str);
10603 Py_DECREF(sub);
10604
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010605 if (kind2 != kind)
10606 PyMem_Free(buf2);
10607
Guido van Rossum403d68b2000-03-13 15:55:09 +000010608 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010609}
10610
Guido van Rossumd57fd912000-03-10 22:53:23 +000010611/* Concat to string or Unicode object giving a new Unicode object. */
10612
Alexander Belopolsky40018472011-02-26 01:02:56 +000010613PyObject *
10614PyUnicode_Concat(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010615{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010616 PyObject *u = NULL, *v = NULL, *w;
Victor Stinner127226b2011-10-13 01:12:34 +020010617 Py_UCS4 maxchar, maxchar2;
Victor Stinner488fa492011-12-12 00:01:39 +010010618 Py_ssize_t u_len, v_len, new_len;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010619
10620 /* Coerce the two arguments */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010621 u = PyUnicode_FromObject(left);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010622 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010623 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010624 v = PyUnicode_FromObject(right);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010625 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010626 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010627
10628 /* Shortcuts */
Victor Stinnera464fc12011-10-02 20:39:30 +020010629 if (v == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010630 Py_DECREF(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010631 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010632 }
Victor Stinnera464fc12011-10-02 20:39:30 +020010633 if (u == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010634 Py_DECREF(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010635 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010636 }
10637
Victor Stinner488fa492011-12-12 00:01:39 +010010638 u_len = PyUnicode_GET_LENGTH(u);
10639 v_len = PyUnicode_GET_LENGTH(v);
10640 if (u_len > PY_SSIZE_T_MAX - v_len) {
10641 PyErr_SetString(PyExc_OverflowError,
10642 "strings are too large to concat");
10643 goto onError;
10644 }
10645 new_len = u_len + v_len;
10646
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010647 maxchar = PyUnicode_MAX_CHAR_VALUE(u);
Victor Stinner127226b2011-10-13 01:12:34 +020010648 maxchar2 = PyUnicode_MAX_CHAR_VALUE(v);
Victor Stinnere6abb482012-05-02 01:15:40 +020010649 maxchar = MAX_MAXCHAR(maxchar, maxchar2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010650
Guido van Rossumd57fd912000-03-10 22:53:23 +000010651 /* Concat the two Unicode strings */
Victor Stinner488fa492011-12-12 00:01:39 +010010652 w = PyUnicode_New(new_len, maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010653 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010654 goto onError;
Victor Stinnerd3f08822012-05-29 12:57:52 +020010655 _PyUnicode_FastCopyCharacters(w, 0, u, 0, u_len);
10656 _PyUnicode_FastCopyCharacters(w, u_len, v, 0, v_len);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010657 Py_DECREF(u);
10658 Py_DECREF(v);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010659 assert(_PyUnicode_CheckConsistency(w, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010660 return w;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010661
Benjamin Peterson29060642009-01-31 22:14:21 +000010662 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000010663 Py_XDECREF(u);
10664 Py_XDECREF(v);
10665 return NULL;
10666}
10667
Walter Dörwald1ab83302007-05-18 17:15:44 +000010668void
Victor Stinner23e56682011-10-03 03:54:37 +020010669PyUnicode_Append(PyObject **p_left, PyObject *right)
Walter Dörwald1ab83302007-05-18 17:15:44 +000010670{
Victor Stinner23e56682011-10-03 03:54:37 +020010671 PyObject *left, *res;
Victor Stinner488fa492011-12-12 00:01:39 +010010672 Py_UCS4 maxchar, maxchar2;
10673 Py_ssize_t left_len, right_len, new_len;
Victor Stinner23e56682011-10-03 03:54:37 +020010674
10675 if (p_left == NULL) {
10676 if (!PyErr_Occurred())
10677 PyErr_BadInternalCall();
Benjamin Peterson14339b62009-01-31 16:36:08 +000010678 return;
10679 }
Victor Stinner23e56682011-10-03 03:54:37 +020010680 left = *p_left;
Serhiy Storchaka6c83e732013-01-04 12:39:34 +020010681 if (right == NULL || left == NULL || !PyUnicode_Check(left)) {
Victor Stinner23e56682011-10-03 03:54:37 +020010682 if (!PyErr_Occurred())
10683 PyErr_BadInternalCall();
10684 goto error;
10685 }
10686
Benjamin Petersonbac79492012-01-14 13:34:47 -050010687 if (PyUnicode_READY(left) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020010688 goto error;
Benjamin Petersonbac79492012-01-14 13:34:47 -050010689 if (PyUnicode_READY(right) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020010690 goto error;
10691
Victor Stinner488fa492011-12-12 00:01:39 +010010692 /* Shortcuts */
10693 if (left == unicode_empty) {
10694 Py_DECREF(left);
10695 Py_INCREF(right);
10696 *p_left = right;
10697 return;
10698 }
10699 if (right == unicode_empty)
10700 return;
10701
10702 left_len = PyUnicode_GET_LENGTH(left);
10703 right_len = PyUnicode_GET_LENGTH(right);
10704 if (left_len > PY_SSIZE_T_MAX - right_len) {
10705 PyErr_SetString(PyExc_OverflowError,
10706 "strings are too large to concat");
10707 goto error;
10708 }
10709 new_len = left_len + right_len;
10710
10711 if (unicode_modifiable(left)
10712 && PyUnicode_CheckExact(right)
10713 && PyUnicode_KIND(right) <= PyUnicode_KIND(left)
Victor Stinnerb0923652011-10-04 01:17:31 +020010714 /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
10715 to change the structure size, but characters are stored just after
Georg Brandl7597add2011-10-05 16:36:47 +020010716 the structure, and so it requires to move all characters which is
Victor Stinnerb0923652011-10-04 01:17:31 +020010717 not so different than duplicating the string. */
Victor Stinner488fa492011-12-12 00:01:39 +010010718 && !(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
10719 {
10720 /* append inplace */
10721 if (unicode_resize(p_left, new_len) != 0) {
10722 /* XXX if _PyUnicode_Resize() fails, 'left' has been
10723 * deallocated so it cannot be put back into
10724 * 'variable'. The MemoryError is raised when there
10725 * is no value in 'variable', which might (very
10726 * remotely) be a cause of incompatibilities.
10727 */
10728 goto error;
Victor Stinner23e56682011-10-03 03:54:37 +020010729 }
Victor Stinner488fa492011-12-12 00:01:39 +010010730 /* copy 'right' into the newly allocated area of 'left' */
Victor Stinnerd3f08822012-05-29 12:57:52 +020010731 _PyUnicode_FastCopyCharacters(*p_left, left_len, right, 0, right_len);
Victor Stinner23e56682011-10-03 03:54:37 +020010732 }
Victor Stinner488fa492011-12-12 00:01:39 +010010733 else {
10734 maxchar = PyUnicode_MAX_CHAR_VALUE(left);
10735 maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
Victor Stinnere6abb482012-05-02 01:15:40 +020010736 maxchar = MAX_MAXCHAR(maxchar, maxchar2);
Victor Stinner23e56682011-10-03 03:54:37 +020010737
Victor Stinner488fa492011-12-12 00:01:39 +010010738 /* Concat the two Unicode strings */
10739 res = PyUnicode_New(new_len, maxchar);
10740 if (res == NULL)
10741 goto error;
Victor Stinnerd3f08822012-05-29 12:57:52 +020010742 _PyUnicode_FastCopyCharacters(res, 0, left, 0, left_len);
10743 _PyUnicode_FastCopyCharacters(res, left_len, right, 0, right_len);
Victor Stinner488fa492011-12-12 00:01:39 +010010744 Py_DECREF(left);
10745 *p_left = res;
10746 }
10747 assert(_PyUnicode_CheckConsistency(*p_left, 1));
Victor Stinner23e56682011-10-03 03:54:37 +020010748 return;
10749
10750error:
Victor Stinner488fa492011-12-12 00:01:39 +010010751 Py_CLEAR(*p_left);
Walter Dörwald1ab83302007-05-18 17:15:44 +000010752}
10753
10754void
10755PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
10756{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010757 PyUnicode_Append(pleft, right);
10758 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +000010759}
10760
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010761PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010762 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010763\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000010764Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010765string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010766interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010767
10768static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010769unicode_count(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010770{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010771 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010772 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010773 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010774 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010775 int kind1, kind2, kind;
10776 void *buf1, *buf2;
10777 Py_ssize_t len1, len2, iresult;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010778
Jesus Ceaac451502011-04-20 17:09:23 +020010779 if (!stringlib_parse_args_finds_unicode("count", args, &substring,
10780 &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000010781 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000010782
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010783 kind1 = PyUnicode_KIND(self);
10784 kind2 = PyUnicode_KIND(substring);
Benjamin Petersonb63f49f2012-05-03 18:31:07 -040010785 if (kind2 > kind1)
10786 return PyLong_FromLong(0);
10787 kind = kind1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010788 buf1 = PyUnicode_DATA(self);
10789 buf2 = PyUnicode_DATA(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010790 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010791 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010792 if (!buf2) {
10793 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010794 return NULL;
10795 }
10796 len1 = PyUnicode_GET_LENGTH(self);
10797 len2 = PyUnicode_GET_LENGTH(substring);
10798
10799 ADJUST_INDICES(start, end, len1);
Benjamin Petersonead6b532011-12-20 17:23:42 -060010800 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010801 case PyUnicode_1BYTE_KIND:
10802 iresult = ucs1lib_count(
10803 ((Py_UCS1*)buf1) + start, end - start,
10804 buf2, len2, PY_SSIZE_T_MAX
10805 );
10806 break;
10807 case PyUnicode_2BYTE_KIND:
10808 iresult = ucs2lib_count(
10809 ((Py_UCS2*)buf1) + start, end - start,
10810 buf2, len2, PY_SSIZE_T_MAX
10811 );
10812 break;
10813 case PyUnicode_4BYTE_KIND:
10814 iresult = ucs4lib_count(
10815 ((Py_UCS4*)buf1) + start, end - start,
10816 buf2, len2, PY_SSIZE_T_MAX
10817 );
10818 break;
10819 default:
10820 assert(0); iresult = 0;
10821 }
10822
10823 result = PyLong_FromSsize_t(iresult);
10824
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010825 if (kind2 != kind)
10826 PyMem_Free(buf2);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010827
10828 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010829
Guido van Rossumd57fd912000-03-10 22:53:23 +000010830 return result;
10831}
10832
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010833PyDoc_STRVAR(encode__doc__,
Victor Stinnerc911bbf2010-11-07 19:04:46 +000010834 "S.encode(encoding='utf-8', errors='strict') -> bytes\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010835\n\
Victor Stinnere14e2122010-11-07 18:41:46 +000010836Encode S using the codec registered for encoding. Default encoding\n\
10837is 'utf-8'. errors may be given to set a different error\n\
Fred Drakee4315f52000-05-09 19:53:39 +000010838handling scheme. Default is 'strict' meaning that encoding errors raise\n\
Walter Dörwald3aeb6322002-09-02 13:14:32 +000010839a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
10840'xmlcharrefreplace' as well as any other name registered with\n\
10841codecs.register_error that can handle UnicodeEncodeErrors.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010842
10843static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010844unicode_encode(PyObject *self, PyObject *args, PyObject *kwargs)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010845{
Benjamin Peterson308d6372009-09-18 21:42:35 +000010846 static char *kwlist[] = {"encoding", "errors", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000010847 char *encoding = NULL;
10848 char *errors = NULL;
Guido van Rossum35d94282007-08-27 18:20:11 +000010849
Benjamin Peterson308d6372009-09-18 21:42:35 +000010850 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:encode",
10851 kwlist, &encoding, &errors))
Guido van Rossumd57fd912000-03-10 22:53:23 +000010852 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010853 return PyUnicode_AsEncodedString(self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +000010854}
10855
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010856PyDoc_STRVAR(expandtabs__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010857 "S.expandtabs([tabsize]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010858\n\
10859Return a copy of S where all tab characters are expanded using spaces.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010860If tabsize is not given, a tab size of 8 characters is assumed.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010861
10862static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010863unicode_expandtabs(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010864{
Antoine Pitroue71d5742011-10-04 15:55:09 +020010865 Py_ssize_t i, j, line_pos, src_len, incr;
10866 Py_UCS4 ch;
10867 PyObject *u;
10868 void *src_data, *dest_data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010869 int tabsize = 8;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010870 int kind;
Antoine Pitroue19aa382011-10-04 16:04:01 +020010871 int found;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010872
10873 if (!PyArg_ParseTuple(args, "|i:expandtabs", &tabsize))
Benjamin Peterson29060642009-01-31 22:14:21 +000010874 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010875
Antoine Pitrou22425222011-10-04 19:10:51 +020010876 if (PyUnicode_READY(self) == -1)
10877 return NULL;
10878
Thomas Wouters7e474022000-07-16 12:04:32 +000010879 /* First pass: determine size of output string */
Antoine Pitroue71d5742011-10-04 15:55:09 +020010880 src_len = PyUnicode_GET_LENGTH(self);
10881 i = j = line_pos = 0;
10882 kind = PyUnicode_KIND(self);
10883 src_data = PyUnicode_DATA(self);
Antoine Pitroue19aa382011-10-04 16:04:01 +020010884 found = 0;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010885 for (; i < src_len; i++) {
10886 ch = PyUnicode_READ(kind, src_data, i);
10887 if (ch == '\t') {
Antoine Pitroue19aa382011-10-04 16:04:01 +020010888 found = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000010889 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020010890 incr = tabsize - (line_pos % tabsize); /* cannot overflow */
Benjamin Peterson29060642009-01-31 22:14:21 +000010891 if (j > PY_SSIZE_T_MAX - incr)
Antoine Pitroue71d5742011-10-04 15:55:09 +020010892 goto overflow;
10893 line_pos += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000010894 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010895 }
Benjamin Peterson29060642009-01-31 22:14:21 +000010896 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010897 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000010898 if (j > PY_SSIZE_T_MAX - 1)
Antoine Pitroue71d5742011-10-04 15:55:09 +020010899 goto overflow;
10900 line_pos++;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010901 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010902 if (ch == '\n' || ch == '\r')
10903 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010904 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020010905 }
Victor Stinnerc4b49542011-12-11 22:44:26 +010010906 if (!found)
10907 return unicode_result_unchanged(self);
Guido van Rossumcd16bf62007-06-13 18:07:49 +000010908
Guido van Rossumd57fd912000-03-10 22:53:23 +000010909 /* Second pass: create output string and fill it */
Antoine Pitroue71d5742011-10-04 15:55:09 +020010910 u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +000010911 if (!u)
10912 return NULL;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010913 dest_data = PyUnicode_DATA(u);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010914
Antoine Pitroue71d5742011-10-04 15:55:09 +020010915 i = j = line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010916
Antoine Pitroue71d5742011-10-04 15:55:09 +020010917 for (; i < src_len; i++) {
10918 ch = PyUnicode_READ(kind, src_data, i);
10919 if (ch == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +000010920 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020010921 incr = tabsize - (line_pos % tabsize);
10922 line_pos += incr;
Victor Stinnerda79e632012-02-22 13:37:04 +010010923 FILL(kind, dest_data, ' ', j, incr);
10924 j += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000010925 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000010926 }
Benjamin Peterson29060642009-01-31 22:14:21 +000010927 else {
Antoine Pitroue71d5742011-10-04 15:55:09 +020010928 line_pos++;
10929 PyUnicode_WRITE(kind, dest_data, j, ch);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010930 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010931 if (ch == '\n' || ch == '\r')
10932 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010933 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020010934 }
10935 assert (j == PyUnicode_GET_LENGTH(u));
Victor Stinnerd3df8ab2011-11-22 01:22:34 +010010936 return unicode_result(u);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010937
Antoine Pitroue71d5742011-10-04 15:55:09 +020010938 overflow:
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010939 PyErr_SetString(PyExc_OverflowError, "new string is too long");
10940 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010941}
10942
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010943PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010944 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010945\n\
10946Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080010947such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010948arguments start and end are interpreted as in slice notation.\n\
10949\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010950Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010951
10952static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010953unicode_find(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010954{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010955 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000010956 Py_ssize_t start;
10957 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010958 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010959
Jesus Ceaac451502011-04-20 17:09:23 +020010960 if (!stringlib_parse_args_finds_unicode("find", args, &substring,
10961 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000010962 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010963
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010964 if (PyUnicode_READY(self) == -1)
10965 return NULL;
10966 if (PyUnicode_READY(substring) == -1)
10967 return NULL;
10968
Victor Stinner7931d9a2011-11-04 00:22:48 +010010969 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010970
10971 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010972
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010973 if (result == -2)
10974 return NULL;
10975
Christian Heimes217cfd12007-12-02 14:31:20 +000010976 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010977}
10978
10979static PyObject *
Victor Stinner2fe5ced2011-10-02 00:25:40 +020010980unicode_getitem(PyObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010981{
Victor Stinnerb6cd0142012-05-03 02:17:04 +020010982 void *data;
10983 enum PyUnicode_Kind kind;
10984 Py_UCS4 ch;
10985 PyObject *res;
10986
10987 if (!PyUnicode_Check(self) || PyUnicode_READY(self) == -1) {
10988 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010989 return NULL;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020010990 }
10991 if (index < 0 || index >= PyUnicode_GET_LENGTH(self)) {
10992 PyErr_SetString(PyExc_IndexError, "string index out of range");
10993 return NULL;
10994 }
10995 kind = PyUnicode_KIND(self);
10996 data = PyUnicode_DATA(self);
10997 ch = PyUnicode_READ(kind, data, index);
10998 if (ch < 256)
10999 return get_latin1_char(ch);
11000
11001 res = PyUnicode_New(1, ch);
11002 if (res == NULL)
11003 return NULL;
11004 kind = PyUnicode_KIND(res);
11005 data = PyUnicode_DATA(res);
11006 PyUnicode_WRITE(kind, data, 0, ch);
11007 assert(_PyUnicode_CheckConsistency(res, 1));
11008 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011009}
11010
Guido van Rossumc2504932007-09-18 19:42:40 +000011011/* Believe it or not, this produces the same value for ASCII strings
Mark Dickinson57e683e2011-09-24 18:18:40 +010011012 as bytes_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +000011013static Py_hash_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011014unicode_hash(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011015{
Guido van Rossumc2504932007-09-18 19:42:40 +000011016 Py_ssize_t len;
Gregory P. Smith27cbcd62012-12-10 18:15:46 -080011017 Py_uhash_t x; /* Unsigned for defined overflow behavior. */
Guido van Rossumc2504932007-09-18 19:42:40 +000011018
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011019#ifdef Py_DEBUG
Benjamin Peterson69e97272012-02-21 11:08:50 -050011020 assert(_Py_HashSecret_Initialized);
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011021#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011022 if (_PyUnicode_HASH(self) != -1)
11023 return _PyUnicode_HASH(self);
11024 if (PyUnicode_READY(self) == -1)
11025 return -1;
11026 len = PyUnicode_GET_LENGTH(self);
Georg Brandl16fa2a12012-02-21 00:50:13 +010011027 /*
11028 We make the hash of the empty string be 0, rather than using
11029 (prefix ^ suffix), since this slightly obfuscates the hash secret
11030 */
11031 if (len == 0) {
11032 _PyUnicode_HASH(self) = 0;
11033 return 0;
11034 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011035
11036 /* The hash function as a macro, gets expanded three times below. */
Georg Brandl2fb477c2012-02-21 00:33:36 +010011037#define HASH(P) \
11038 x ^= (Py_uhash_t) *P << 7; \
11039 while (--len >= 0) \
11040 x = (_PyHASH_MULTIPLIER * x) ^ (Py_uhash_t) *P++; \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011041
Georg Brandl2fb477c2012-02-21 00:33:36 +010011042 x = (Py_uhash_t) _Py_HashSecret.prefix;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011043 switch (PyUnicode_KIND(self)) {
11044 case PyUnicode_1BYTE_KIND: {
11045 const unsigned char *c = PyUnicode_1BYTE_DATA(self);
11046 HASH(c);
11047 break;
11048 }
11049 case PyUnicode_2BYTE_KIND: {
11050 const Py_UCS2 *s = PyUnicode_2BYTE_DATA(self);
11051 HASH(s);
11052 break;
11053 }
11054 default: {
11055 Py_UCS4 *l;
11056 assert(PyUnicode_KIND(self) == PyUnicode_4BYTE_KIND &&
11057 "Impossible switch case in unicode_hash");
11058 l = PyUnicode_4BYTE_DATA(self);
11059 HASH(l);
11060 break;
11061 }
11062 }
Georg Brandl2fb477c2012-02-21 00:33:36 +010011063 x ^= (Py_uhash_t) PyUnicode_GET_LENGTH(self);
11064 x ^= (Py_uhash_t) _Py_HashSecret.suffix;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011065
Guido van Rossumc2504932007-09-18 19:42:40 +000011066 if (x == -1)
11067 x = -2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011068 _PyUnicode_HASH(self) = x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011069 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011070}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011071#undef HASH
Guido van Rossumd57fd912000-03-10 22:53:23 +000011072
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011073PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011074 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011075\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011076Like S.find() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011077
11078static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011079unicode_index(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011080{
Martin v. Löwis18e16552006-02-15 17:27:45 +000011081 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011082 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011083 Py_ssize_t start;
11084 Py_ssize_t end;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011085
Jesus Ceaac451502011-04-20 17:09:23 +020011086 if (!stringlib_parse_args_finds_unicode("index", args, &substring,
11087 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011088 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011089
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011090 if (PyUnicode_READY(self) == -1)
11091 return NULL;
11092 if (PyUnicode_READY(substring) == -1)
11093 return NULL;
11094
Victor Stinner7931d9a2011-11-04 00:22:48 +010011095 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011096
11097 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011098
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011099 if (result == -2)
11100 return NULL;
11101
Guido van Rossumd57fd912000-03-10 22:53:23 +000011102 if (result < 0) {
11103 PyErr_SetString(PyExc_ValueError, "substring not found");
11104 return NULL;
11105 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011106
Christian Heimes217cfd12007-12-02 14:31:20 +000011107 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011108}
11109
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011110PyDoc_STRVAR(islower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011111 "S.islower() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011112\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011113Return True if all cased characters in S are lowercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011114at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011115
11116static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011117unicode_islower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011118{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011119 Py_ssize_t i, length;
11120 int kind;
11121 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011122 int cased;
11123
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011124 if (PyUnicode_READY(self) == -1)
11125 return NULL;
11126 length = PyUnicode_GET_LENGTH(self);
11127 kind = PyUnicode_KIND(self);
11128 data = PyUnicode_DATA(self);
11129
Guido van Rossumd57fd912000-03-10 22:53:23 +000011130 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011131 if (length == 1)
11132 return PyBool_FromLong(
11133 Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011134
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011135 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011136 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011137 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011138
Guido van Rossumd57fd912000-03-10 22:53:23 +000011139 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011140 for (i = 0; i < length; i++) {
11141 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011142
Benjamin Peterson29060642009-01-31 22:14:21 +000011143 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
11144 return PyBool_FromLong(0);
11145 else if (!cased && Py_UNICODE_ISLOWER(ch))
11146 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011147 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011148 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011149}
11150
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011151PyDoc_STRVAR(isupper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011152 "S.isupper() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011153\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011154Return True if all cased characters in S are uppercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011155at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011156
11157static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011158unicode_isupper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011159{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011160 Py_ssize_t i, length;
11161 int kind;
11162 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011163 int cased;
11164
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011165 if (PyUnicode_READY(self) == -1)
11166 return NULL;
11167 length = PyUnicode_GET_LENGTH(self);
11168 kind = PyUnicode_KIND(self);
11169 data = PyUnicode_DATA(self);
11170
Guido van Rossumd57fd912000-03-10 22:53:23 +000011171 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011172 if (length == 1)
11173 return PyBool_FromLong(
11174 Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011175
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011176 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011177 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011178 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011179
Guido van Rossumd57fd912000-03-10 22:53:23 +000011180 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011181 for (i = 0; i < length; i++) {
11182 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011183
Benjamin Peterson29060642009-01-31 22:14:21 +000011184 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
11185 return PyBool_FromLong(0);
11186 else if (!cased && Py_UNICODE_ISUPPER(ch))
11187 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011188 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011189 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011190}
11191
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011192PyDoc_STRVAR(istitle__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011193 "S.istitle() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011194\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011195Return True if S is a titlecased string and there is at least one\n\
11196character in S, i.e. upper- and titlecase characters may only\n\
11197follow uncased characters and lowercase characters only cased ones.\n\
11198Return False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011199
11200static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011201unicode_istitle(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011202{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011203 Py_ssize_t i, length;
11204 int kind;
11205 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011206 int cased, previous_is_cased;
11207
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011208 if (PyUnicode_READY(self) == -1)
11209 return NULL;
11210 length = PyUnicode_GET_LENGTH(self);
11211 kind = PyUnicode_KIND(self);
11212 data = PyUnicode_DATA(self);
11213
Guido van Rossumd57fd912000-03-10 22:53:23 +000011214 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011215 if (length == 1) {
11216 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11217 return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
11218 (Py_UNICODE_ISUPPER(ch) != 0));
11219 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011220
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011221 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011222 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011223 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011224
Guido van Rossumd57fd912000-03-10 22:53:23 +000011225 cased = 0;
11226 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011227 for (i = 0; i < length; i++) {
11228 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011229
Benjamin Peterson29060642009-01-31 22:14:21 +000011230 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
11231 if (previous_is_cased)
11232 return PyBool_FromLong(0);
11233 previous_is_cased = 1;
11234 cased = 1;
11235 }
11236 else if (Py_UNICODE_ISLOWER(ch)) {
11237 if (!previous_is_cased)
11238 return PyBool_FromLong(0);
11239 previous_is_cased = 1;
11240 cased = 1;
11241 }
11242 else
11243 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011244 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011245 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011246}
11247
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011248PyDoc_STRVAR(isspace__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011249 "S.isspace() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011250\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011251Return True if all characters in S are whitespace\n\
11252and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011253
11254static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011255unicode_isspace(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011256{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011257 Py_ssize_t i, length;
11258 int kind;
11259 void *data;
11260
11261 if (PyUnicode_READY(self) == -1)
11262 return NULL;
11263 length = PyUnicode_GET_LENGTH(self);
11264 kind = PyUnicode_KIND(self);
11265 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011266
Guido van Rossumd57fd912000-03-10 22:53:23 +000011267 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011268 if (length == 1)
11269 return PyBool_FromLong(
11270 Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011271
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011272 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011273 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011274 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011275
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011276 for (i = 0; i < length; i++) {
11277 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011278 if (!Py_UNICODE_ISSPACE(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011279 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011280 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011281 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011282}
11283
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011284PyDoc_STRVAR(isalpha__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011285 "S.isalpha() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011286\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011287Return True if all characters in S are alphabetic\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011288and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011289
11290static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011291unicode_isalpha(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011292{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011293 Py_ssize_t i, length;
11294 int kind;
11295 void *data;
11296
11297 if (PyUnicode_READY(self) == -1)
11298 return NULL;
11299 length = PyUnicode_GET_LENGTH(self);
11300 kind = PyUnicode_KIND(self);
11301 data = PyUnicode_DATA(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011302
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011303 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011304 if (length == 1)
11305 return PyBool_FromLong(
11306 Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011307
11308 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011309 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011310 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011311
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011312 for (i = 0; i < length; i++) {
11313 if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011314 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011315 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011316 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011317}
11318
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011319PyDoc_STRVAR(isalnum__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011320 "S.isalnum() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011321\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011322Return True if all characters in S are alphanumeric\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011323and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011324
11325static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011326unicode_isalnum(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011327{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011328 int kind;
11329 void *data;
11330 Py_ssize_t len, i;
11331
11332 if (PyUnicode_READY(self) == -1)
11333 return NULL;
11334
11335 kind = PyUnicode_KIND(self);
11336 data = PyUnicode_DATA(self);
11337 len = PyUnicode_GET_LENGTH(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011338
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011339 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011340 if (len == 1) {
11341 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11342 return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
11343 }
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011344
11345 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011346 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011347 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011348
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011349 for (i = 0; i < len; i++) {
11350 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011351 if (!Py_UNICODE_ISALNUM(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011352 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011353 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011354 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011355}
11356
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011357PyDoc_STRVAR(isdecimal__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011358 "S.isdecimal() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011359\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011360Return True if there are only decimal characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011361False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011362
11363static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011364unicode_isdecimal(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011365{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011366 Py_ssize_t i, length;
11367 int kind;
11368 void *data;
11369
11370 if (PyUnicode_READY(self) == -1)
11371 return NULL;
11372 length = PyUnicode_GET_LENGTH(self);
11373 kind = PyUnicode_KIND(self);
11374 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011375
Guido van Rossumd57fd912000-03-10 22:53:23 +000011376 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011377 if (length == 1)
11378 return PyBool_FromLong(
11379 Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011380
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011381 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011382 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011383 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011384
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011385 for (i = 0; i < length; i++) {
11386 if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011387 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011388 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011389 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011390}
11391
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011392PyDoc_STRVAR(isdigit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011393 "S.isdigit() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011394\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011395Return True if all characters in S are digits\n\
11396and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011397
11398static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011399unicode_isdigit(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011400{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011401 Py_ssize_t i, length;
11402 int kind;
11403 void *data;
11404
11405 if (PyUnicode_READY(self) == -1)
11406 return NULL;
11407 length = PyUnicode_GET_LENGTH(self);
11408 kind = PyUnicode_KIND(self);
11409 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011410
Guido van Rossumd57fd912000-03-10 22:53:23 +000011411 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011412 if (length == 1) {
11413 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11414 return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
11415 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011416
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011417 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011418 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011419 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011420
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011421 for (i = 0; i < length; i++) {
11422 if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011423 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011424 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011425 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011426}
11427
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011428PyDoc_STRVAR(isnumeric__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011429 "S.isnumeric() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011430\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011431Return True if there are only numeric characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011432False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011433
11434static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011435unicode_isnumeric(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011436{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011437 Py_ssize_t i, length;
11438 int kind;
11439 void *data;
11440
11441 if (PyUnicode_READY(self) == -1)
11442 return NULL;
11443 length = PyUnicode_GET_LENGTH(self);
11444 kind = PyUnicode_KIND(self);
11445 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011446
Guido van Rossumd57fd912000-03-10 22:53:23 +000011447 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011448 if (length == 1)
11449 return PyBool_FromLong(
11450 Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011451
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011452 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011453 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011454 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011455
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011456 for (i = 0; i < length; i++) {
11457 if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011458 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011459 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011460 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011461}
11462
Martin v. Löwis47383402007-08-15 07:32:56 +000011463int
11464PyUnicode_IsIdentifier(PyObject *self)
11465{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011466 int kind;
11467 void *data;
11468 Py_ssize_t i;
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011469 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +000011470
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011471 if (PyUnicode_READY(self) == -1) {
11472 Py_FatalError("identifier not ready");
Benjamin Peterson29060642009-01-31 22:14:21 +000011473 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011474 }
11475
11476 /* Special case for empty strings */
11477 if (PyUnicode_GET_LENGTH(self) == 0)
11478 return 0;
11479 kind = PyUnicode_KIND(self);
11480 data = PyUnicode_DATA(self);
Martin v. Löwis47383402007-08-15 07:32:56 +000011481
11482 /* PEP 3131 says that the first character must be in
11483 XID_Start and subsequent characters in XID_Continue,
11484 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +000011485 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +000011486 letters, digits, underscore). However, given the current
11487 definition of XID_Start and XID_Continue, it is sufficient
11488 to check just for these, except that _ must be allowed
11489 as starting an identifier. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011490 first = PyUnicode_READ(kind, data, 0);
Benjamin Petersonf413b802011-08-12 22:17:18 -050011491 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +000011492 return 0;
11493
Benjamin Peterson9c6e6a02011-09-28 08:09:05 -040011494 for (i = 1; i < PyUnicode_GET_LENGTH(self); i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011495 if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011496 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +000011497 return 1;
11498}
11499
11500PyDoc_STRVAR(isidentifier__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011501 "S.isidentifier() -> bool\n\
Martin v. Löwis47383402007-08-15 07:32:56 +000011502\n\
11503Return True if S is a valid identifier according\n\
11504to the language definition.");
11505
11506static PyObject*
11507unicode_isidentifier(PyObject *self)
11508{
11509 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
11510}
11511
Georg Brandl559e5d72008-06-11 18:37:52 +000011512PyDoc_STRVAR(isprintable__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011513 "S.isprintable() -> bool\n\
Georg Brandl559e5d72008-06-11 18:37:52 +000011514\n\
11515Return True if all characters in S are considered\n\
11516printable in repr() or S is empty, False otherwise.");
11517
11518static PyObject*
11519unicode_isprintable(PyObject *self)
11520{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011521 Py_ssize_t i, length;
11522 int kind;
11523 void *data;
11524
11525 if (PyUnicode_READY(self) == -1)
11526 return NULL;
11527 length = PyUnicode_GET_LENGTH(self);
11528 kind = PyUnicode_KIND(self);
11529 data = PyUnicode_DATA(self);
Georg Brandl559e5d72008-06-11 18:37:52 +000011530
11531 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011532 if (length == 1)
11533 return PyBool_FromLong(
11534 Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
Georg Brandl559e5d72008-06-11 18:37:52 +000011535
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011536 for (i = 0; i < length; i++) {
11537 if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
Georg Brandl559e5d72008-06-11 18:37:52 +000011538 Py_RETURN_FALSE;
11539 }
11540 }
11541 Py_RETURN_TRUE;
11542}
11543
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011544PyDoc_STRVAR(join__doc__,
Georg Brandl495f7b52009-10-27 15:28:25 +000011545 "S.join(iterable) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011546\n\
11547Return a string which is the concatenation of the strings in the\n\
Georg Brandl495f7b52009-10-27 15:28:25 +000011548iterable. The separator between elements is S.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011549
11550static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011551unicode_join(PyObject *self, PyObject *data)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011552{
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011553 return PyUnicode_Join(self, data);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011554}
11555
Martin v. Löwis18e16552006-02-15 17:27:45 +000011556static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011557unicode_length(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011558{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011559 if (PyUnicode_READY(self) == -1)
11560 return -1;
11561 return PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011562}
11563
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011564PyDoc_STRVAR(ljust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011565 "S.ljust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011566\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000011567Return S left-justified in a Unicode string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011568done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011569
11570static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020011571unicode_ljust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011572{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011573 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011574 Py_UCS4 fillchar = ' ';
11575
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011576 if (!PyArg_ParseTuple(args, "n|O&:ljust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011577 return NULL;
11578
Benjamin Petersonbac79492012-01-14 13:34:47 -050011579 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010011580 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011581
Victor Stinnerc4b49542011-12-11 22:44:26 +010011582 if (PyUnicode_GET_LENGTH(self) >= width)
11583 return unicode_result_unchanged(self);
11584
11585 return pad(self, 0, width - PyUnicode_GET_LENGTH(self), fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011586}
11587
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011588PyDoc_STRVAR(lower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011589 "S.lower() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011590\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011591Return a copy of the string S converted to lowercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011592
11593static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020011594unicode_lower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011595{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050011596 if (PyUnicode_READY(self) == -1)
11597 return NULL;
11598 if (PyUnicode_IS_ASCII(self))
11599 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010011600 return case_operation(self, do_lower);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011601}
11602
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011603#define LEFTSTRIP 0
11604#define RIGHTSTRIP 1
11605#define BOTHSTRIP 2
11606
11607/* Arrays indexed by above */
11608static const char *stripformat[] = {"|O:lstrip", "|O:rstrip", "|O:strip"};
11609
11610#define STRIPNAME(i) (stripformat[i]+3)
11611
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011612/* externally visible for str.strip(unicode) */
11613PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011614_PyUnicode_XStrip(PyObject *self, int striptype, PyObject *sepobj)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011615{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011616 void *data;
11617 int kind;
11618 Py_ssize_t i, j, len;
11619 BLOOM_MASK sepmask;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011620
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011621 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
11622 return NULL;
11623
11624 kind = PyUnicode_KIND(self);
11625 data = PyUnicode_DATA(self);
11626 len = PyUnicode_GET_LENGTH(self);
11627 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
11628 PyUnicode_DATA(sepobj),
11629 PyUnicode_GET_LENGTH(sepobj));
Thomas Wouters477c8d52006-05-27 19:21:47 +000011630
Benjamin Peterson14339b62009-01-31 16:36:08 +000011631 i = 0;
11632 if (striptype != RIGHTSTRIP) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011633 while (i < len &&
11634 BLOOM_MEMBER(sepmask, PyUnicode_READ(kind, data, i), sepobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011635 i++;
11636 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011637 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011638
Benjamin Peterson14339b62009-01-31 16:36:08 +000011639 j = len;
11640 if (striptype != LEFTSTRIP) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011641 do {
11642 j--;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011643 } while (j >= i &&
11644 BLOOM_MEMBER(sepmask, PyUnicode_READ(kind, data, j), sepobj));
Benjamin Peterson29060642009-01-31 22:14:21 +000011645 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011646 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011647
Victor Stinner7931d9a2011-11-04 00:22:48 +010011648 return PyUnicode_Substring(self, i, j);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011649}
11650
11651PyObject*
11652PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
11653{
11654 unsigned char *data;
11655 int kind;
Victor Stinner12bab6d2011-10-01 01:53:49 +020011656 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011657
Victor Stinnerde636f32011-10-01 03:55:54 +020011658 if (PyUnicode_READY(self) == -1)
11659 return NULL;
11660
Victor Stinner684d5fd2012-05-03 02:32:34 +020011661 length = PyUnicode_GET_LENGTH(self);
11662 end = Py_MIN(end, length);
Victor Stinnerde636f32011-10-01 03:55:54 +020011663
Victor Stinner684d5fd2012-05-03 02:32:34 +020011664 if (start == 0 && end == length)
Victor Stinnerc4b49542011-12-11 22:44:26 +010011665 return unicode_result_unchanged(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011666
Victor Stinnerde636f32011-10-01 03:55:54 +020011667 if (start < 0 || end < 0) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020011668 PyErr_SetString(PyExc_IndexError, "string index out of range");
11669 return NULL;
11670 }
Victor Stinner684d5fd2012-05-03 02:32:34 +020011671 if (start >= length || end < start) {
Victor Stinner3a7f79772012-05-03 03:36:40 +020011672 Py_INCREF(unicode_empty);
11673 return unicode_empty;
Victor Stinner684d5fd2012-05-03 02:32:34 +020011674 }
Victor Stinner12bab6d2011-10-01 01:53:49 +020011675
Victor Stinner684d5fd2012-05-03 02:32:34 +020011676 length = end - start;
Victor Stinnerb9275c12011-10-05 14:01:42 +020011677 if (PyUnicode_IS_ASCII(self)) {
Victor Stinnerb9275c12011-10-05 14:01:42 +020011678 data = PyUnicode_1BYTE_DATA(self);
Victor Stinnerd3f08822012-05-29 12:57:52 +020011679 return _PyUnicode_FromASCII((char*)(data + start), length);
Victor Stinnerb9275c12011-10-05 14:01:42 +020011680 }
11681 else {
11682 kind = PyUnicode_KIND(self);
11683 data = PyUnicode_1BYTE_DATA(self);
11684 return PyUnicode_FromKindAndData(kind,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020011685 data + kind * start,
Victor Stinnerb9275c12011-10-05 14:01:42 +020011686 length);
11687 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011688}
Guido van Rossumd57fd912000-03-10 22:53:23 +000011689
11690static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011691do_strip(PyObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011692{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011693 int kind;
11694 void *data;
11695 Py_ssize_t len, i, j;
11696
11697 if (PyUnicode_READY(self) == -1)
11698 return NULL;
11699
11700 kind = PyUnicode_KIND(self);
11701 data = PyUnicode_DATA(self);
11702 len = PyUnicode_GET_LENGTH(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011703
Benjamin Peterson14339b62009-01-31 16:36:08 +000011704 i = 0;
11705 if (striptype != RIGHTSTRIP) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011706 while (i < len && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, i))) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000011707 i++;
11708 }
11709 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011710
Benjamin Peterson14339b62009-01-31 16:36:08 +000011711 j = len;
11712 if (striptype != LEFTSTRIP) {
11713 do {
11714 j--;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011715 } while (j >= i && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, j)));
Benjamin Peterson14339b62009-01-31 16:36:08 +000011716 j++;
11717 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011718
Victor Stinner7931d9a2011-11-04 00:22:48 +010011719 return PyUnicode_Substring(self, i, j);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011720}
11721
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011722
11723static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011724do_argstrip(PyObject *self, int striptype, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011725{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011726 PyObject *sep = NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011727
Benjamin Peterson14339b62009-01-31 16:36:08 +000011728 if (!PyArg_ParseTuple(args, (char *)stripformat[striptype], &sep))
11729 return NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011730
Benjamin Peterson14339b62009-01-31 16:36:08 +000011731 if (sep != NULL && sep != Py_None) {
11732 if (PyUnicode_Check(sep))
11733 return _PyUnicode_XStrip(self, striptype, sep);
11734 else {
11735 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000011736 "%s arg must be None or str",
11737 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +000011738 return NULL;
11739 }
11740 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011741
Benjamin Peterson14339b62009-01-31 16:36:08 +000011742 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011743}
11744
11745
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011746PyDoc_STRVAR(strip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011747 "S.strip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011748\n\
11749Return a copy of the string S with leading and trailing\n\
11750whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011751If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011752
11753static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011754unicode_strip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011755{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011756 if (PyTuple_GET_SIZE(args) == 0)
11757 return do_strip(self, BOTHSTRIP); /* Common case */
11758 else
11759 return do_argstrip(self, BOTHSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011760}
11761
11762
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011763PyDoc_STRVAR(lstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011764 "S.lstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011765\n\
11766Return a copy of the string S with leading whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011767If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011768
11769static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011770unicode_lstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011771{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011772 if (PyTuple_GET_SIZE(args) == 0)
11773 return do_strip(self, LEFTSTRIP); /* Common case */
11774 else
11775 return do_argstrip(self, LEFTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011776}
11777
11778
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011779PyDoc_STRVAR(rstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011780 "S.rstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011781\n\
11782Return a copy of the string S with trailing whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011783If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011784
11785static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011786unicode_rstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011787{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011788 if (PyTuple_GET_SIZE(args) == 0)
11789 return do_strip(self, RIGHTSTRIP); /* Common case */
11790 else
11791 return do_argstrip(self, RIGHTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011792}
11793
11794
Guido van Rossumd57fd912000-03-10 22:53:23 +000011795static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011796unicode_repeat(PyObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011797{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011798 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011799 Py_ssize_t nchars, n;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011800
Georg Brandl222de0f2009-04-12 12:01:50 +000011801 if (len < 1) {
11802 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +020011803 return unicode_empty;
Georg Brandl222de0f2009-04-12 12:01:50 +000011804 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011805
Victor Stinnerc4b49542011-12-11 22:44:26 +010011806 /* no repeat, return original string */
11807 if (len == 1)
11808 return unicode_result_unchanged(str);
Tim Peters8f422462000-09-09 06:13:41 +000011809
Benjamin Petersonbac79492012-01-14 13:34:47 -050011810 if (PyUnicode_READY(str) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011811 return NULL;
11812
Victor Stinnerc759f3e2011-10-01 03:09:58 +020011813 if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
Victor Stinner67ca64c2011-10-01 02:47:29 +020011814 PyErr_SetString(PyExc_OverflowError,
11815 "repeated string is too long");
11816 return NULL;
11817 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011818 nchars = len * PyUnicode_GET_LENGTH(str);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011819
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011820 u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011821 if (!u)
11822 return NULL;
Victor Stinner67ca64c2011-10-01 02:47:29 +020011823 assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011824
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011825 if (PyUnicode_GET_LENGTH(str) == 1) {
11826 const int kind = PyUnicode_KIND(str);
11827 const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
Victor Stinner73f53b52011-12-18 03:26:31 +010011828 if (kind == PyUnicode_1BYTE_KIND) {
11829 void *to = PyUnicode_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011830 memset(to, (unsigned char)fill_char, len);
Victor Stinner73f53b52011-12-18 03:26:31 +010011831 }
11832 else if (kind == PyUnicode_2BYTE_KIND) {
11833 Py_UCS2 *ucs2 = PyUnicode_2BYTE_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011834 for (n = 0; n < len; ++n)
Victor Stinner73f53b52011-12-18 03:26:31 +010011835 ucs2[n] = fill_char;
11836 } else {
11837 Py_UCS4 *ucs4 = PyUnicode_4BYTE_DATA(u);
11838 assert(kind == PyUnicode_4BYTE_KIND);
11839 for (n = 0; n < len; ++n)
11840 ucs4[n] = fill_char;
Victor Stinner67ca64c2011-10-01 02:47:29 +020011841 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011842 }
11843 else {
11844 /* number of characters copied this far */
11845 Py_ssize_t done = PyUnicode_GET_LENGTH(str);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020011846 const Py_ssize_t char_size = PyUnicode_KIND(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011847 char *to = (char *) PyUnicode_DATA(u);
11848 Py_MEMCPY(to, PyUnicode_DATA(str),
11849 PyUnicode_GET_LENGTH(str) * char_size);
Benjamin Peterson29060642009-01-31 22:14:21 +000011850 while (done < nchars) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011851 n = (done <= nchars-done) ? done : nchars-done;
11852 Py_MEMCPY(to + (done * char_size), to, n * char_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011853 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +000011854 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011855 }
11856
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020011857 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011858 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011859}
11860
Alexander Belopolsky40018472011-02-26 01:02:56 +000011861PyObject *
11862PyUnicode_Replace(PyObject *obj,
11863 PyObject *subobj,
11864 PyObject *replobj,
11865 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011866{
11867 PyObject *self;
11868 PyObject *str1;
11869 PyObject *str2;
11870 PyObject *result;
11871
11872 self = PyUnicode_FromObject(obj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060011873 if (self == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000011874 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011875 str1 = PyUnicode_FromObject(subobj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060011876 if (str1 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011877 Py_DECREF(self);
11878 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011879 }
11880 str2 = PyUnicode_FromObject(replobj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060011881 if (str2 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011882 Py_DECREF(self);
11883 Py_DECREF(str1);
11884 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011885 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060011886 if (PyUnicode_READY(self) == -1 ||
11887 PyUnicode_READY(str1) == -1 ||
11888 PyUnicode_READY(str2) == -1)
11889 result = NULL;
11890 else
11891 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011892 Py_DECREF(self);
11893 Py_DECREF(str1);
11894 Py_DECREF(str2);
11895 return result;
11896}
11897
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011898PyDoc_STRVAR(replace__doc__,
Ezio Melottic1897e72010-06-26 18:50:39 +000011899 "S.replace(old, new[, count]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011900\n\
11901Return a copy of S with all occurrences of substring\n\
Georg Brandlf08a9dd2008-06-10 16:57:31 +000011902old replaced by new. If the optional argument count is\n\
11903given, only the first count occurrences are replaced.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011904
11905static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011906unicode_replace(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011907{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011908 PyObject *str1;
11909 PyObject *str2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011910 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011911 PyObject *result;
11912
Martin v. Löwis18e16552006-02-15 17:27:45 +000011913 if (!PyArg_ParseTuple(args, "OO|n:replace", &str1, &str2, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011914 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060011915 if (PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000011916 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011917 str1 = PyUnicode_FromObject(str1);
Benjamin Peterson22a29702012-01-02 09:00:30 -060011918 if (str1 == NULL)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011919 return NULL;
11920 str2 = PyUnicode_FromObject(str2);
Benjamin Peterson22a29702012-01-02 09:00:30 -060011921 if (str2 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011922 Py_DECREF(str1);
11923 return NULL;
Walter Dörwaldf6b56ae2003-02-09 23:42:56 +000011924 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060011925 if (PyUnicode_READY(str1) == -1 || PyUnicode_READY(str2) == -1)
11926 result = NULL;
11927 else
11928 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011929
11930 Py_DECREF(str1);
11931 Py_DECREF(str2);
11932 return result;
11933}
11934
Alexander Belopolsky40018472011-02-26 01:02:56 +000011935static PyObject *
11936unicode_repr(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011937{
Walter Dörwald79e913e2007-05-12 11:08:06 +000011938 PyObject *repr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011939 Py_ssize_t isize;
11940 Py_ssize_t osize, squote, dquote, i, o;
11941 Py_UCS4 max, quote;
11942 int ikind, okind;
11943 void *idata, *odata;
Walter Dörwald79e913e2007-05-12 11:08:06 +000011944
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011945 if (PyUnicode_READY(unicode) == -1)
Walter Dörwald79e913e2007-05-12 11:08:06 +000011946 return NULL;
11947
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011948 isize = PyUnicode_GET_LENGTH(unicode);
11949 idata = PyUnicode_DATA(unicode);
Walter Dörwald79e913e2007-05-12 11:08:06 +000011950
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011951 /* Compute length of output, quote characters, and
11952 maximum character */
11953 osize = 2; /* quotes */
11954 max = 127;
11955 squote = dquote = 0;
11956 ikind = PyUnicode_KIND(unicode);
11957 for (i = 0; i < isize; i++) {
11958 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
11959 switch (ch) {
11960 case '\'': squote++; osize++; break;
11961 case '"': dquote++; osize++; break;
11962 case '\\': case '\t': case '\r': case '\n':
11963 osize += 2; break;
11964 default:
11965 /* Fast-path ASCII */
11966 if (ch < ' ' || ch == 0x7f)
11967 osize += 4; /* \xHH */
11968 else if (ch < 0x7f)
11969 osize++;
11970 else if (Py_UNICODE_ISPRINTABLE(ch)) {
11971 osize++;
11972 max = ch > max ? ch : max;
11973 }
11974 else if (ch < 0x100)
11975 osize += 4; /* \xHH */
11976 else if (ch < 0x10000)
11977 osize += 6; /* \uHHHH */
11978 else
11979 osize += 10; /* \uHHHHHHHH */
11980 }
11981 }
11982
11983 quote = '\'';
11984 if (squote) {
11985 if (dquote)
11986 /* Both squote and dquote present. Use squote,
11987 and escape them */
11988 osize += squote;
11989 else
11990 quote = '"';
11991 }
11992
11993 repr = PyUnicode_New(osize, max);
11994 if (repr == NULL)
11995 return NULL;
11996 okind = PyUnicode_KIND(repr);
11997 odata = PyUnicode_DATA(repr);
11998
11999 PyUnicode_WRITE(okind, odata, 0, quote);
12000 PyUnicode_WRITE(okind, odata, osize-1, quote);
12001
12002 for (i = 0, o = 1; i < isize; i++) {
12003 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012004
12005 /* Escape quotes and backslashes */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012006 if ((ch == quote) || (ch == '\\')) {
12007 PyUnicode_WRITE(okind, odata, o++, '\\');
12008 PyUnicode_WRITE(okind, odata, o++, ch);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012009 continue;
12010 }
12011
Benjamin Peterson29060642009-01-31 22:14:21 +000012012 /* Map special whitespace to '\t', \n', '\r' */
Georg Brandl559e5d72008-06-11 18:37:52 +000012013 if (ch == '\t') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012014 PyUnicode_WRITE(okind, odata, o++, '\\');
12015 PyUnicode_WRITE(okind, odata, o++, 't');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012016 }
12017 else if (ch == '\n') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012018 PyUnicode_WRITE(okind, odata, o++, '\\');
12019 PyUnicode_WRITE(okind, odata, o++, 'n');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012020 }
12021 else if (ch == '\r') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012022 PyUnicode_WRITE(okind, odata, o++, '\\');
12023 PyUnicode_WRITE(okind, odata, o++, 'r');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012024 }
12025
12026 /* Map non-printable US ASCII to '\xhh' */
Georg Brandl559e5d72008-06-11 18:37:52 +000012027 else if (ch < ' ' || ch == 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012028 PyUnicode_WRITE(okind, odata, o++, '\\');
12029 PyUnicode_WRITE(okind, odata, o++, 'x');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012030 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12031 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012032 }
12033
Georg Brandl559e5d72008-06-11 18:37:52 +000012034 /* Copy ASCII characters as-is */
12035 else if (ch < 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012036 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000012037 }
12038
Benjamin Peterson29060642009-01-31 22:14:21 +000012039 /* Non-ASCII characters */
Georg Brandl559e5d72008-06-11 18:37:52 +000012040 else {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012041 /* Map Unicode whitespace and control characters
Georg Brandl559e5d72008-06-11 18:37:52 +000012042 (categories Z* and C* except ASCII space)
12043 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012044 if (!Py_UNICODE_ISPRINTABLE(ch)) {
Kristján Valur Jónsson55e5dc82012-06-06 21:58:08 +000012045 PyUnicode_WRITE(okind, odata, o++, '\\');
Georg Brandl559e5d72008-06-11 18:37:52 +000012046 /* Map 8-bit characters to '\xhh' */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012047 if (ch <= 0xff) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012048 PyUnicode_WRITE(okind, odata, o++, 'x');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012049 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12050 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012051 }
Kristján Valur Jónsson55e5dc82012-06-06 21:58:08 +000012052 /* Map 16-bit characters to '\uxxxx' */
12053 else if (ch <= 0xffff) {
12054 PyUnicode_WRITE(okind, odata, o++, 'u');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012055 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12056 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12057 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12058 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012059 }
Kristján Valur Jónsson55e5dc82012-06-06 21:58:08 +000012060 /* Map 21-bit characters to '\U00xxxxxx' */
Georg Brandl559e5d72008-06-11 18:37:52 +000012061 else {
Kristján Valur Jónsson55e5dc82012-06-06 21:58:08 +000012062 PyUnicode_WRITE(okind, odata, o++, 'U');
12063 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 28) & 0xF]);
12064 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 24) & 0xF]);
12065 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 20) & 0xF]);
12066 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 16) & 0xF]);
Victor Stinnerf5cff562011-10-14 02:13:11 +020012067 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12068 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12069 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12070 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012071 }
12072 }
12073 /* Copy characters as-is */
12074 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012075 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000012076 }
12077 }
Walter Dörwald79e913e2007-05-12 11:08:06 +000012078 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012079 /* Closing quote already added at the beginning */
Victor Stinner05d11892011-10-06 01:13:58 +020012080 assert(_PyUnicode_CheckConsistency(repr, 1));
Walter Dörwald79e913e2007-05-12 11:08:06 +000012081 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012082}
12083
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012084PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012085 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012086\n\
12087Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080012088such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012089arguments start and end are interpreted as in slice notation.\n\
12090\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012091Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012092
12093static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012094unicode_rfind(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012095{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012096 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012097 Py_ssize_t start;
12098 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012099 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012100
Jesus Ceaac451502011-04-20 17:09:23 +020012101 if (!stringlib_parse_args_finds_unicode("rfind", args, &substring,
12102 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012103 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012104
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012105 if (PyUnicode_READY(self) == -1)
12106 return NULL;
12107 if (PyUnicode_READY(substring) == -1)
12108 return NULL;
12109
Victor Stinner7931d9a2011-11-04 00:22:48 +010012110 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012111
12112 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012113
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012114 if (result == -2)
12115 return NULL;
12116
Christian Heimes217cfd12007-12-02 14:31:20 +000012117 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012118}
12119
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012120PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012121 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012122\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012123Like S.rfind() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012124
12125static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012126unicode_rindex(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012127{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012128 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012129 Py_ssize_t start;
12130 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012131 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012132
Jesus Ceaac451502011-04-20 17:09:23 +020012133 if (!stringlib_parse_args_finds_unicode("rindex", args, &substring,
12134 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012135 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012136
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012137 if (PyUnicode_READY(self) == -1)
12138 return NULL;
12139 if (PyUnicode_READY(substring) == -1)
12140 return NULL;
12141
Victor Stinner7931d9a2011-11-04 00:22:48 +010012142 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012143
12144 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012145
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012146 if (result == -2)
12147 return NULL;
12148
Guido van Rossumd57fd912000-03-10 22:53:23 +000012149 if (result < 0) {
12150 PyErr_SetString(PyExc_ValueError, "substring not found");
12151 return NULL;
12152 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012153
Christian Heimes217cfd12007-12-02 14:31:20 +000012154 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012155}
12156
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012157PyDoc_STRVAR(rjust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012158 "S.rjust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012159\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012160Return S right-justified in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012161done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012162
12163static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012164unicode_rjust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012165{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012166 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012167 Py_UCS4 fillchar = ' ';
12168
Victor Stinnere9a29352011-10-01 02:14:59 +020012169 if (!PyArg_ParseTuple(args, "n|O&:rjust", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012170 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012171
Benjamin Petersonbac79492012-01-14 13:34:47 -050012172 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012173 return NULL;
12174
Victor Stinnerc4b49542011-12-11 22:44:26 +010012175 if (PyUnicode_GET_LENGTH(self) >= width)
12176 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012177
Victor Stinnerc4b49542011-12-11 22:44:26 +010012178 return pad(self, width - PyUnicode_GET_LENGTH(self), 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012179}
12180
Alexander Belopolsky40018472011-02-26 01:02:56 +000012181PyObject *
12182PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012183{
12184 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +000012185
Guido van Rossumd57fd912000-03-10 22:53:23 +000012186 s = PyUnicode_FromObject(s);
12187 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012188 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012189 if (sep != NULL) {
12190 sep = PyUnicode_FromObject(sep);
12191 if (sep == NULL) {
12192 Py_DECREF(s);
12193 return NULL;
12194 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012195 }
12196
Victor Stinner9310abb2011-10-05 00:59:23 +020012197 result = split(s, sep, maxsplit);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012198
12199 Py_DECREF(s);
12200 Py_XDECREF(sep);
12201 return result;
12202}
12203
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012204PyDoc_STRVAR(split__doc__,
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012205 "S.split(sep=None, maxsplit=-1) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012206\n\
12207Return a list of the words in S, using sep as the\n\
12208delimiter string. If maxsplit is given, at most maxsplit\n\
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000012209splits are done. If sep is not specified or is None, any\n\
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +000012210whitespace string is a separator and empty strings are\n\
12211removed from the result.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012212
12213static PyObject*
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012214unicode_split(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012215{
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012216 static char *kwlist[] = {"sep", "maxsplit", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000012217 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012218 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012219
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012220 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:split",
12221 kwlist, &substring, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012222 return NULL;
12223
12224 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012225 return split(self, NULL, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012226 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012227 return split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012228 else
Victor Stinner7931d9a2011-11-04 00:22:48 +010012229 return PyUnicode_Split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012230}
12231
Thomas Wouters477c8d52006-05-27 19:21:47 +000012232PyObject *
12233PyUnicode_Partition(PyObject *str_in, PyObject *sep_in)
12234{
12235 PyObject* str_obj;
12236 PyObject* sep_obj;
12237 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012238 int kind1, kind2, kind;
12239 void *buf1 = NULL, *buf2 = NULL;
12240 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012241
12242 str_obj = PyUnicode_FromObject(str_in);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012243 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012244 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012245 sep_obj = PyUnicode_FromObject(sep_in);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012246 if (!sep_obj) {
12247 Py_DECREF(str_obj);
12248 return NULL;
12249 }
12250 if (PyUnicode_READY(sep_obj) == -1 || PyUnicode_READY(str_obj) == -1) {
12251 Py_DECREF(sep_obj);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012252 Py_DECREF(str_obj);
12253 return NULL;
12254 }
12255
Victor Stinner14f8f022011-10-05 20:58:25 +020012256 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012257 kind2 = PyUnicode_KIND(sep_obj);
Victor Stinner14f8f022011-10-05 20:58:25 +020012258 kind = Py_MAX(kind1, kind2);
12259 buf1 = PyUnicode_DATA(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012260 if (kind1 != kind)
Victor Stinner14f8f022011-10-05 20:58:25 +020012261 buf1 = _PyUnicode_AsKind(str_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012262 if (!buf1)
12263 goto onError;
12264 buf2 = PyUnicode_DATA(sep_obj);
12265 if (kind2 != kind)
12266 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12267 if (!buf2)
12268 goto onError;
12269 len1 = PyUnicode_GET_LENGTH(str_obj);
12270 len2 = PyUnicode_GET_LENGTH(sep_obj);
12271
Benjamin Petersonead6b532011-12-20 17:23:42 -060012272 switch (PyUnicode_KIND(str_obj)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012273 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012274 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12275 out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12276 else
12277 out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012278 break;
12279 case PyUnicode_2BYTE_KIND:
12280 out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12281 break;
12282 case PyUnicode_4BYTE_KIND:
12283 out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12284 break;
12285 default:
12286 assert(0);
12287 out = 0;
12288 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012289
12290 Py_DECREF(sep_obj);
12291 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012292 if (kind1 != kind)
12293 PyMem_Free(buf1);
12294 if (kind2 != kind)
12295 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012296
12297 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012298 onError:
12299 Py_DECREF(sep_obj);
12300 Py_DECREF(str_obj);
12301 if (kind1 != kind && buf1)
12302 PyMem_Free(buf1);
12303 if (kind2 != kind && buf2)
12304 PyMem_Free(buf2);
12305 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012306}
12307
12308
12309PyObject *
12310PyUnicode_RPartition(PyObject *str_in, PyObject *sep_in)
12311{
12312 PyObject* str_obj;
12313 PyObject* sep_obj;
12314 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012315 int kind1, kind2, kind;
12316 void *buf1 = NULL, *buf2 = NULL;
12317 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012318
12319 str_obj = PyUnicode_FromObject(str_in);
12320 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012321 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012322 sep_obj = PyUnicode_FromObject(sep_in);
12323 if (!sep_obj) {
12324 Py_DECREF(str_obj);
12325 return NULL;
12326 }
12327
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012328 kind1 = PyUnicode_KIND(str_in);
12329 kind2 = PyUnicode_KIND(sep_obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +020012330 kind = Py_MAX(kind1, kind2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012331 buf1 = PyUnicode_DATA(str_in);
12332 if (kind1 != kind)
12333 buf1 = _PyUnicode_AsKind(str_in, kind);
12334 if (!buf1)
12335 goto onError;
12336 buf2 = PyUnicode_DATA(sep_obj);
12337 if (kind2 != kind)
12338 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12339 if (!buf2)
12340 goto onError;
12341 len1 = PyUnicode_GET_LENGTH(str_obj);
12342 len2 = PyUnicode_GET_LENGTH(sep_obj);
12343
Benjamin Petersonead6b532011-12-20 17:23:42 -060012344 switch (PyUnicode_KIND(str_in)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012345 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012346 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12347 out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12348 else
12349 out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012350 break;
12351 case PyUnicode_2BYTE_KIND:
12352 out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12353 break;
12354 case PyUnicode_4BYTE_KIND:
12355 out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12356 break;
12357 default:
12358 assert(0);
12359 out = 0;
12360 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012361
12362 Py_DECREF(sep_obj);
12363 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012364 if (kind1 != kind)
12365 PyMem_Free(buf1);
12366 if (kind2 != kind)
12367 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012368
12369 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012370 onError:
12371 Py_DECREF(sep_obj);
12372 Py_DECREF(str_obj);
12373 if (kind1 != kind && buf1)
12374 PyMem_Free(buf1);
12375 if (kind2 != kind && buf2)
12376 PyMem_Free(buf2);
12377 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012378}
12379
12380PyDoc_STRVAR(partition__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012381 "S.partition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012382\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012383Search for the separator sep in S, and return the part before it,\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012384the separator itself, and the part after it. If the separator is not\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012385found, return S and two empty strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012386
12387static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012388unicode_partition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012389{
Victor Stinner9310abb2011-10-05 00:59:23 +020012390 return PyUnicode_Partition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012391}
12392
12393PyDoc_STRVAR(rpartition__doc__,
Ezio Melotti5b2b2422010-01-25 11:58:28 +000012394 "S.rpartition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012395\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012396Search for the separator sep in S, starting at the end of S, and return\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012397the part before it, the separator itself, and the part after it. If the\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012398separator is not found, return two empty strings and S.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012399
12400static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012401unicode_rpartition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012402{
Victor Stinner9310abb2011-10-05 00:59:23 +020012403 return PyUnicode_RPartition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012404}
12405
Alexander Belopolsky40018472011-02-26 01:02:56 +000012406PyObject *
12407PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012408{
12409 PyObject *result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012410
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012411 s = PyUnicode_FromObject(s);
12412 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012413 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012414 if (sep != NULL) {
12415 sep = PyUnicode_FromObject(sep);
12416 if (sep == NULL) {
12417 Py_DECREF(s);
12418 return NULL;
12419 }
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012420 }
12421
Victor Stinner9310abb2011-10-05 00:59:23 +020012422 result = rsplit(s, sep, maxsplit);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012423
12424 Py_DECREF(s);
12425 Py_XDECREF(sep);
12426 return result;
12427}
12428
12429PyDoc_STRVAR(rsplit__doc__,
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012430 "S.rsplit(sep=None, maxsplit=-1) -> list of strings\n\
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012431\n\
12432Return a list of the words in S, using sep as the\n\
12433delimiter string, starting at the end of the string and\n\
12434working to the front. If maxsplit is given, at most maxsplit\n\
12435splits are done. If sep is not specified, any whitespace string\n\
12436is a separator.");
12437
12438static PyObject*
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012439unicode_rsplit(PyObject *self, PyObject *args, PyObject *kwds)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012440{
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012441 static char *kwlist[] = {"sep", "maxsplit", 0};
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012442 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012443 Py_ssize_t maxcount = -1;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012444
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012445 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:rsplit",
12446 kwlist, &substring, &maxcount))
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012447 return NULL;
12448
12449 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012450 return rsplit(self, NULL, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012451 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012452 return rsplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012453 else
Victor Stinner9310abb2011-10-05 00:59:23 +020012454 return PyUnicode_RSplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012455}
12456
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012457PyDoc_STRVAR(splitlines__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012458 "S.splitlines([keepends]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012459\n\
12460Return a list of the lines in S, breaking at line boundaries.\n\
Guido van Rossum86662912000-04-11 15:38:46 +000012461Line breaks are not included in the resulting list unless keepends\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012462is given and true.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012463
12464static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012465unicode_splitlines(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012466{
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012467 static char *kwlist[] = {"keepends", 0};
Guido van Rossum86662912000-04-11 15:38:46 +000012468 int keepends = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012469
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012470 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:splitlines",
12471 kwlist, &keepends))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012472 return NULL;
12473
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012474 return PyUnicode_Splitlines(self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012475}
12476
12477static
Guido van Rossumf15a29f2007-05-04 00:41:39 +000012478PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012479{
Victor Stinnerc4b49542011-12-11 22:44:26 +010012480 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012481}
12482
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012483PyDoc_STRVAR(swapcase__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012484 "S.swapcase() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012485\n\
12486Return a copy of S with uppercase characters converted to lowercase\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012487and vice versa.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012488
12489static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012490unicode_swapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012491{
Benjamin Petersoneea48462012-01-16 14:28:50 -050012492 if (PyUnicode_READY(self) == -1)
12493 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010012494 return case_operation(self, do_swapcase);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012495}
12496
Georg Brandlceee0772007-11-27 23:48:05 +000012497PyDoc_STRVAR(maketrans__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012498 "str.maketrans(x[, y[, z]]) -> dict (static method)\n\
Georg Brandlceee0772007-11-27 23:48:05 +000012499\n\
12500Return a translation table usable for str.translate().\n\
12501If there is only one argument, it must be a dictionary mapping Unicode\n\
12502ordinals (integers) or characters to Unicode ordinals, strings or None.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012503Character keys will be then converted to ordinals.\n\
Georg Brandlceee0772007-11-27 23:48:05 +000012504If there are two arguments, they must be strings of equal length, and\n\
12505in the resulting dictionary, each character in x will be mapped to the\n\
12506character at the same position in y. If there is a third argument, it\n\
12507must be a string, whose characters will be mapped to None in the result.");
12508
12509static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012510unicode_maketrans(PyObject *null, PyObject *args)
Georg Brandlceee0772007-11-27 23:48:05 +000012511{
12512 PyObject *x, *y = NULL, *z = NULL;
12513 PyObject *new = NULL, *key, *value;
12514 Py_ssize_t i = 0;
12515 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012516
Georg Brandlceee0772007-11-27 23:48:05 +000012517 if (!PyArg_ParseTuple(args, "O|UU:maketrans", &x, &y, &z))
12518 return NULL;
12519 new = PyDict_New();
12520 if (!new)
12521 return NULL;
12522 if (y != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012523 int x_kind, y_kind, z_kind;
12524 void *x_data, *y_data, *z_data;
12525
Georg Brandlceee0772007-11-27 23:48:05 +000012526 /* x must be a string too, of equal length */
Georg Brandlceee0772007-11-27 23:48:05 +000012527 if (!PyUnicode_Check(x)) {
12528 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
12529 "be a string if there is a second argument");
12530 goto err;
12531 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012532 if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012533 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
12534 "arguments must have equal length");
12535 goto err;
12536 }
12537 /* create entries for translating chars in x to those in y */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012538 x_kind = PyUnicode_KIND(x);
12539 y_kind = PyUnicode_KIND(y);
12540 x_data = PyUnicode_DATA(x);
12541 y_data = PyUnicode_DATA(y);
12542 for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
12543 key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060012544 if (!key)
Georg Brandlceee0772007-11-27 23:48:05 +000012545 goto err;
Benjamin Peterson822c7902011-12-20 13:32:50 -060012546 value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060012547 if (!value) {
12548 Py_DECREF(key);
12549 goto err;
12550 }
Georg Brandlceee0772007-11-27 23:48:05 +000012551 res = PyDict_SetItem(new, key, value);
12552 Py_DECREF(key);
12553 Py_DECREF(value);
12554 if (res < 0)
12555 goto err;
12556 }
12557 /* create entries for deleting chars in z */
12558 if (z != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012559 z_kind = PyUnicode_KIND(z);
12560 z_data = PyUnicode_DATA(z);
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012561 for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012562 key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000012563 if (!key)
12564 goto err;
12565 res = PyDict_SetItem(new, key, Py_None);
12566 Py_DECREF(key);
12567 if (res < 0)
12568 goto err;
12569 }
12570 }
12571 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012572 int kind;
12573 void *data;
12574
Georg Brandlceee0772007-11-27 23:48:05 +000012575 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +000012576 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012577 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
12578 "to maketrans it must be a dict");
12579 goto err;
12580 }
12581 /* copy entries into the new dict, converting string keys to int keys */
12582 while (PyDict_Next(x, &i, &key, &value)) {
12583 if (PyUnicode_Check(key)) {
12584 /* convert string keys to integer keys */
12585 PyObject *newkey;
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012586 if (PyUnicode_GET_LENGTH(key) != 1) {
Georg Brandlceee0772007-11-27 23:48:05 +000012587 PyErr_SetString(PyExc_ValueError, "string keys in translate "
12588 "table must be of length 1");
12589 goto err;
12590 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012591 kind = PyUnicode_KIND(key);
12592 data = PyUnicode_DATA(key);
12593 newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
Georg Brandlceee0772007-11-27 23:48:05 +000012594 if (!newkey)
12595 goto err;
12596 res = PyDict_SetItem(new, newkey, value);
12597 Py_DECREF(newkey);
12598 if (res < 0)
12599 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +000012600 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012601 /* just keep integer keys */
12602 if (PyDict_SetItem(new, key, value) < 0)
12603 goto err;
12604 } else {
12605 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
12606 "be strings or integers");
12607 goto err;
12608 }
12609 }
12610 }
12611 return new;
12612 err:
12613 Py_DECREF(new);
12614 return NULL;
12615}
12616
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012617PyDoc_STRVAR(translate__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012618 "S.translate(table) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012619\n\
12620Return a copy of the string S, where all characters have been mapped\n\
12621through the given translation table, which must be a mapping of\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012622Unicode ordinals to Unicode ordinals, strings, or None.\n\
Walter Dörwald5c1ee172002-09-04 20:31:32 +000012623Unmapped characters are left untouched. Characters mapped to None\n\
12624are deleted.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012625
12626static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012627unicode_translate(PyObject *self, PyObject *table)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012628{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012629 return _PyUnicode_TranslateCharmap(self, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012630}
12631
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012632PyDoc_STRVAR(upper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012633 "S.upper() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012634\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012635Return a copy of S converted to uppercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012636
12637static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012638unicode_upper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012639{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050012640 if (PyUnicode_READY(self) == -1)
12641 return NULL;
12642 if (PyUnicode_IS_ASCII(self))
12643 return ascii_upper_or_lower(self, 0);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010012644 return case_operation(self, do_upper);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012645}
12646
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012647PyDoc_STRVAR(zfill__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012648 "S.zfill(width) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012649\n\
Benjamin Peterson9aa42992008-09-10 21:57:34 +000012650Pad a numeric string S with zeros on the left, to fill a field\n\
12651of the specified width. The string S is never truncated.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012652
12653static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012654unicode_zfill(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012655{
Martin v. Löwis18e16552006-02-15 17:27:45 +000012656 Py_ssize_t fill;
Victor Stinner9310abb2011-10-05 00:59:23 +020012657 PyObject *u;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012658 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012659 int kind;
12660 void *data;
12661 Py_UCS4 chr;
12662
Martin v. Löwis18e16552006-02-15 17:27:45 +000012663 if (!PyArg_ParseTuple(args, "n:zfill", &width))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012664 return NULL;
12665
Benjamin Petersonbac79492012-01-14 13:34:47 -050012666 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010012667 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012668
Victor Stinnerc4b49542011-12-11 22:44:26 +010012669 if (PyUnicode_GET_LENGTH(self) >= width)
12670 return unicode_result_unchanged(self);
12671
12672 fill = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012673
12674 u = pad(self, fill, 0, '0');
12675
Walter Dörwald068325e2002-04-15 13:36:47 +000012676 if (u == NULL)
12677 return NULL;
12678
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012679 kind = PyUnicode_KIND(u);
12680 data = PyUnicode_DATA(u);
12681 chr = PyUnicode_READ(kind, data, fill);
12682
12683 if (chr == '+' || chr == '-') {
Guido van Rossumd57fd912000-03-10 22:53:23 +000012684 /* move sign to beginning of string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012685 PyUnicode_WRITE(kind, data, 0, chr);
12686 PyUnicode_WRITE(kind, data, fill, '0');
Guido van Rossumd57fd912000-03-10 22:53:23 +000012687 }
12688
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012689 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +010012690 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012691}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012692
12693#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012694static PyObject *
12695unicode__decimal2ascii(PyObject *self)
12696{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012697 return PyUnicode_TransformDecimalAndSpaceToASCII(self);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012698}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012699#endif
12700
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012701PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012702 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012703\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000012704Return True if S starts with the specified prefix, False otherwise.\n\
12705With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012706With optional end, stop comparing S at that position.\n\
12707prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012708
12709static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012710unicode_startswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000012711 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012712{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012713 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012714 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012715 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012716 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012717 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012718
Jesus Ceaac451502011-04-20 17:09:23 +020012719 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000012720 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012721 if (PyTuple_Check(subobj)) {
12722 Py_ssize_t i;
12723 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012724 substring = PyUnicode_FromObject(PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012725 if (substring == NULL)
12726 return NULL;
12727 result = tailmatch(self, substring, start, end, -1);
12728 Py_DECREF(substring);
12729 if (result) {
12730 Py_RETURN_TRUE;
12731 }
12732 }
12733 /* nothing matched */
12734 Py_RETURN_FALSE;
12735 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012736 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030012737 if (substring == NULL) {
12738 if (PyErr_ExceptionMatches(PyExc_TypeError))
12739 PyErr_Format(PyExc_TypeError, "startswith first arg must be str or "
12740 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000012741 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030012742 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012743 result = tailmatch(self, substring, start, end, -1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012744 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012745 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012746}
12747
12748
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012749PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012750 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012751\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000012752Return True if S ends with the specified suffix, False otherwise.\n\
12753With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012754With optional end, stop comparing S at that position.\n\
12755suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012756
12757static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012758unicode_endswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000012759 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012760{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012761 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012762 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012763 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012764 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012765 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012766
Jesus Ceaac451502011-04-20 17:09:23 +020012767 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000012768 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012769 if (PyTuple_Check(subobj)) {
12770 Py_ssize_t i;
12771 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012772 substring = PyUnicode_FromObject(
Benjamin Peterson29060642009-01-31 22:14:21 +000012773 PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012774 if (substring == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000012775 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012776 result = tailmatch(self, substring, start, end, +1);
12777 Py_DECREF(substring);
12778 if (result) {
12779 Py_RETURN_TRUE;
12780 }
12781 }
12782 Py_RETURN_FALSE;
12783 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012784 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030012785 if (substring == NULL) {
12786 if (PyErr_ExceptionMatches(PyExc_TypeError))
12787 PyErr_Format(PyExc_TypeError, "endswith first arg must be str or "
12788 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000012789 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030012790 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012791 result = tailmatch(self, substring, start, end, +1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012792 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012793 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012794}
12795
Victor Stinner202fdca2012-05-07 12:47:02 +020012796Py_LOCAL_INLINE(void)
Victor Stinner3b1a74a2012-05-09 22:25:00 +020012797_PyUnicodeWriter_Update(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020012798{
Victor Stinnerd3f08822012-05-29 12:57:52 +020012799 writer->size = PyUnicode_GET_LENGTH(writer->buffer);
Victor Stinner202fdca2012-05-07 12:47:02 +020012800 writer->maxchar = PyUnicode_MAX_CHAR_VALUE(writer->buffer);
12801 writer->data = PyUnicode_DATA(writer->buffer);
12802 writer->kind = PyUnicode_KIND(writer->buffer);
12803}
12804
Victor Stinnerd3f08822012-05-29 12:57:52 +020012805void
12806_PyUnicodeWriter_Init(_PyUnicodeWriter *writer, Py_ssize_t min_length)
Victor Stinner202fdca2012-05-07 12:47:02 +020012807{
Victor Stinnerd3f08822012-05-29 12:57:52 +020012808 memset(writer, 0, sizeof(*writer));
12809#ifdef Py_DEBUG
12810 writer->kind = 5; /* invalid kind */
12811#endif
12812 writer->min_length = Py_MAX(min_length, 100);
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012813 writer->overallocate = (min_length > 0);
Victor Stinner202fdca2012-05-07 12:47:02 +020012814}
12815
Victor Stinnerd3f08822012-05-29 12:57:52 +020012816int
12817_PyUnicodeWriter_PrepareInternal(_PyUnicodeWriter *writer,
12818 Py_ssize_t length, Py_UCS4 maxchar)
Victor Stinner202fdca2012-05-07 12:47:02 +020012819{
12820 Py_ssize_t newlen;
12821 PyObject *newbuffer;
12822
Victor Stinnerd3f08822012-05-29 12:57:52 +020012823 assert(length > 0);
12824
Victor Stinner202fdca2012-05-07 12:47:02 +020012825 if (length > PY_SSIZE_T_MAX - writer->pos) {
12826 PyErr_NoMemory();
12827 return -1;
12828 }
12829 newlen = writer->pos + length;
12830
Victor Stinnerd3f08822012-05-29 12:57:52 +020012831 if (writer->buffer == NULL) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012832 if (writer->overallocate) {
Victor Stinnerd3f08822012-05-29 12:57:52 +020012833 /* overallocate 25% to limit the number of resize */
12834 if (newlen <= (PY_SSIZE_T_MAX - newlen / 4))
12835 newlen += newlen / 4;
12836 if (newlen < writer->min_length)
12837 newlen = writer->min_length;
12838 }
12839 writer->buffer = PyUnicode_New(newlen, maxchar);
12840 if (writer->buffer == NULL)
12841 return -1;
12842 _PyUnicodeWriter_Update(writer);
12843 return 0;
12844 }
Victor Stinner202fdca2012-05-07 12:47:02 +020012845
Victor Stinnerd3f08822012-05-29 12:57:52 +020012846 if (newlen > writer->size) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012847 if (writer->overallocate) {
Victor Stinnerd3f08822012-05-29 12:57:52 +020012848 /* overallocate 25% to limit the number of resize */
12849 if (newlen <= (PY_SSIZE_T_MAX - newlen / 4))
12850 newlen += newlen / 4;
12851 if (newlen < writer->min_length)
12852 newlen = writer->min_length;
12853 }
12854
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012855 if (maxchar > writer->maxchar || writer->readonly) {
Victor Stinner202fdca2012-05-07 12:47:02 +020012856 /* resize + widen */
12857 newbuffer = PyUnicode_New(newlen, maxchar);
12858 if (newbuffer == NULL)
12859 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020012860 _PyUnicode_FastCopyCharacters(newbuffer, 0,
12861 writer->buffer, 0, writer->pos);
Victor Stinner202fdca2012-05-07 12:47:02 +020012862 Py_DECREF(writer->buffer);
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012863 writer->readonly = 0;
Victor Stinner202fdca2012-05-07 12:47:02 +020012864 }
12865 else {
12866 newbuffer = resize_compact(writer->buffer, newlen);
12867 if (newbuffer == NULL)
12868 return -1;
12869 }
12870 writer->buffer = newbuffer;
Victor Stinner3b1a74a2012-05-09 22:25:00 +020012871 _PyUnicodeWriter_Update(writer);
Victor Stinner202fdca2012-05-07 12:47:02 +020012872 }
12873 else if (maxchar > writer->maxchar) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012874 assert(!writer->readonly);
Victor Stinnerd3f08822012-05-29 12:57:52 +020012875 newbuffer = PyUnicode_New(writer->size, maxchar);
12876 if (newbuffer == NULL)
Victor Stinner202fdca2012-05-07 12:47:02 +020012877 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020012878 _PyUnicode_FastCopyCharacters(newbuffer, 0,
12879 writer->buffer, 0, writer->pos);
12880 Py_DECREF(writer->buffer);
12881 writer->buffer = newbuffer;
Victor Stinner3b1a74a2012-05-09 22:25:00 +020012882 _PyUnicodeWriter_Update(writer);
Victor Stinner202fdca2012-05-07 12:47:02 +020012883 }
12884 return 0;
12885}
12886
Victor Stinnerd3f08822012-05-29 12:57:52 +020012887int
12888_PyUnicodeWriter_WriteStr(_PyUnicodeWriter *writer, PyObject *str)
12889{
12890 Py_UCS4 maxchar;
12891 Py_ssize_t len;
12892
12893 if (PyUnicode_READY(str) == -1)
12894 return -1;
12895 len = PyUnicode_GET_LENGTH(str);
12896 if (len == 0)
12897 return 0;
12898 maxchar = PyUnicode_MAX_CHAR_VALUE(str);
12899 if (maxchar > writer->maxchar || len > writer->size - writer->pos) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012900 if (writer->buffer == NULL && !writer->overallocate) {
Victor Stinnerd3f08822012-05-29 12:57:52 +020012901 Py_INCREF(str);
12902 writer->buffer = str;
12903 _PyUnicodeWriter_Update(writer);
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012904 writer->readonly = 1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020012905 writer->size = 0;
12906 writer->pos += len;
12907 return 0;
12908 }
12909 if (_PyUnicodeWriter_PrepareInternal(writer, len, maxchar) == -1)
12910 return -1;
12911 }
12912 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
12913 str, 0, len);
12914 writer->pos += len;
12915 return 0;
12916}
12917
12918PyObject *
Victor Stinner3b1a74a2012-05-09 22:25:00 +020012919_PyUnicodeWriter_Finish(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020012920{
Victor Stinnerd3f08822012-05-29 12:57:52 +020012921 if (writer->pos == 0) {
12922 Py_XDECREF(writer->buffer);
12923 Py_INCREF(unicode_empty);
12924 return unicode_empty;
12925 }
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012926 if (writer->readonly) {
Victor Stinnerd3f08822012-05-29 12:57:52 +020012927 assert(PyUnicode_GET_LENGTH(writer->buffer) == writer->pos);
12928 return writer->buffer;
12929 }
12930 if (PyUnicode_GET_LENGTH(writer->buffer) != writer->pos) {
12931 PyObject *newbuffer;
12932 newbuffer = resize_compact(writer->buffer, writer->pos);
12933 if (newbuffer == NULL) {
12934 Py_DECREF(writer->buffer);
12935 return NULL;
12936 }
12937 writer->buffer = newbuffer;
Victor Stinner202fdca2012-05-07 12:47:02 +020012938 }
Victor Stinnerf59c28c2012-05-09 03:24:14 +020012939 assert(_PyUnicode_CheckConsistency(writer->buffer, 1));
Victor Stinner202fdca2012-05-07 12:47:02 +020012940 return writer->buffer;
12941}
12942
Victor Stinnerd3f08822012-05-29 12:57:52 +020012943void
Victor Stinner3b1a74a2012-05-09 22:25:00 +020012944_PyUnicodeWriter_Dealloc(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020012945{
12946 Py_CLEAR(writer->buffer);
12947}
12948
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012949#include "stringlib/unicode_format.h"
Eric Smith8c663262007-08-25 02:26:07 +000012950
12951PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012952 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000012953\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012954Return a formatted version of S, using substitutions from args and kwargs.\n\
12955The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +000012956
Eric Smith27bbca62010-11-04 17:06:58 +000012957PyDoc_STRVAR(format_map__doc__,
12958 "S.format_map(mapping) -> str\n\
12959\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012960Return a formatted version of S, using substitutions from mapping.\n\
12961The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +000012962
Eric Smith4a7d76d2008-05-30 18:10:19 +000012963static PyObject *
12964unicode__format__(PyObject* self, PyObject* args)
12965{
Victor Stinnerd3f08822012-05-29 12:57:52 +020012966 PyObject *format_spec;
12967 _PyUnicodeWriter writer;
12968 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +000012969
12970 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
12971 return NULL;
12972
Victor Stinnerd3f08822012-05-29 12:57:52 +020012973 if (PyUnicode_READY(self) == -1)
12974 return NULL;
12975 _PyUnicodeWriter_Init(&writer, 0);
12976 ret = _PyUnicode_FormatAdvancedWriter(&writer,
12977 self, format_spec, 0,
12978 PyUnicode_GET_LENGTH(format_spec));
12979 if (ret == -1) {
12980 _PyUnicodeWriter_Dealloc(&writer);
12981 return NULL;
12982 }
12983 return _PyUnicodeWriter_Finish(&writer);
Eric Smith4a7d76d2008-05-30 18:10:19 +000012984}
12985
Eric Smith8c663262007-08-25 02:26:07 +000012986PyDoc_STRVAR(p_format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012987 "S.__format__(format_spec) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000012988\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012989Return a formatted version of S as described by format_spec.");
Eric Smith8c663262007-08-25 02:26:07 +000012990
12991static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012992unicode__sizeof__(PyObject *v)
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012993{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012994 Py_ssize_t size;
12995
12996 /* If it's a compact object, account for base structure +
12997 character data. */
12998 if (PyUnicode_IS_COMPACT_ASCII(v))
12999 size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(v) + 1;
13000 else if (PyUnicode_IS_COMPACT(v))
13001 size = sizeof(PyCompactUnicodeObject) +
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013002 (PyUnicode_GET_LENGTH(v) + 1) * PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013003 else {
13004 /* If it is a two-block object, account for base object, and
13005 for character block if present. */
13006 size = sizeof(PyUnicodeObject);
Victor Stinnerc3c74152011-10-02 20:39:55 +020013007 if (_PyUnicode_DATA_ANY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013008 size += (PyUnicode_GET_LENGTH(v) + 1) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013009 PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013010 }
13011 /* If the wstr pointer is present, account for it unless it is shared
Victor Stinnera3be6132011-10-03 02:16:37 +020013012 with the data pointer. Check if the data is not shared. */
Victor Stinner03490912011-10-03 23:45:12 +020013013 if (_PyUnicode_HAS_WSTR_MEMORY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013014 size += (PyUnicode_WSTR_LENGTH(v) + 1) * sizeof(wchar_t);
Victor Stinner829c0ad2011-10-03 01:08:02 +020013015 if (_PyUnicode_HAS_UTF8_MEMORY(v))
Victor Stinnere90fe6a2011-10-01 16:48:13 +020013016 size += PyUnicode_UTF8_LENGTH(v) + 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013017
13018 return PyLong_FromSsize_t(size);
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013019}
13020
13021PyDoc_STRVAR(sizeof__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013022 "S.__sizeof__() -> size of S in memory, in bytes");
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013023
13024static PyObject *
Victor Stinner034f6cf2011-09-30 02:26:44 +020013025unicode_getnewargs(PyObject *v)
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013026{
Victor Stinnerbf6e5602011-12-12 01:53:47 +010013027 PyObject *copy = _PyUnicode_Copy(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013028 if (!copy)
13029 return NULL;
13030 return Py_BuildValue("(N)", copy);
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013031}
13032
Guido van Rossumd57fd912000-03-10 22:53:23 +000013033static PyMethodDef unicode_methods[] = {
Benjamin Peterson28a4dce2010-12-12 01:33:04 +000013034 {"encode", (PyCFunction) unicode_encode, METH_VARARGS | METH_KEYWORDS, encode__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013035 {"replace", (PyCFunction) unicode_replace, METH_VARARGS, replace__doc__},
Ezio Melotticda6b6d2012-02-26 09:39:55 +020013036 {"split", (PyCFunction) unicode_split, METH_VARARGS | METH_KEYWORDS, split__doc__},
13037 {"rsplit", (PyCFunction) unicode_rsplit, METH_VARARGS | METH_KEYWORDS, rsplit__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013038 {"join", (PyCFunction) unicode_join, METH_O, join__doc__},
13039 {"capitalize", (PyCFunction) unicode_capitalize, METH_NOARGS, capitalize__doc__},
Benjamin Petersond5890c82012-01-14 13:23:30 -050013040 {"casefold", (PyCFunction) unicode_casefold, METH_NOARGS, casefold__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013041 {"title", (PyCFunction) unicode_title, METH_NOARGS, title__doc__},
13042 {"center", (PyCFunction) unicode_center, METH_VARARGS, center__doc__},
13043 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
13044 {"expandtabs", (PyCFunction) unicode_expandtabs, METH_VARARGS, expandtabs__doc__},
13045 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013046 {"partition", (PyCFunction) unicode_partition, METH_O, partition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013047 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
13048 {"ljust", (PyCFunction) unicode_ljust, METH_VARARGS, ljust__doc__},
13049 {"lower", (PyCFunction) unicode_lower, METH_NOARGS, lower__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013050 {"lstrip", (PyCFunction) unicode_lstrip, METH_VARARGS, lstrip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013051 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
13052 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
13053 {"rjust", (PyCFunction) unicode_rjust, METH_VARARGS, rjust__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013054 {"rstrip", (PyCFunction) unicode_rstrip, METH_VARARGS, rstrip__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013055 {"rpartition", (PyCFunction) unicode_rpartition, METH_O, rpartition__doc__},
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010013056 {"splitlines", (PyCFunction) unicode_splitlines, METH_VARARGS | METH_KEYWORDS, splitlines__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013057 {"strip", (PyCFunction) unicode_strip, METH_VARARGS, strip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013058 {"swapcase", (PyCFunction) unicode_swapcase, METH_NOARGS, swapcase__doc__},
13059 {"translate", (PyCFunction) unicode_translate, METH_O, translate__doc__},
13060 {"upper", (PyCFunction) unicode_upper, METH_NOARGS, upper__doc__},
13061 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
13062 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
13063 {"islower", (PyCFunction) unicode_islower, METH_NOARGS, islower__doc__},
13064 {"isupper", (PyCFunction) unicode_isupper, METH_NOARGS, isupper__doc__},
13065 {"istitle", (PyCFunction) unicode_istitle, METH_NOARGS, istitle__doc__},
13066 {"isspace", (PyCFunction) unicode_isspace, METH_NOARGS, isspace__doc__},
13067 {"isdecimal", (PyCFunction) unicode_isdecimal, METH_NOARGS, isdecimal__doc__},
13068 {"isdigit", (PyCFunction) unicode_isdigit, METH_NOARGS, isdigit__doc__},
13069 {"isnumeric", (PyCFunction) unicode_isnumeric, METH_NOARGS, isnumeric__doc__},
13070 {"isalpha", (PyCFunction) unicode_isalpha, METH_NOARGS, isalpha__doc__},
13071 {"isalnum", (PyCFunction) unicode_isalnum, METH_NOARGS, isalnum__doc__},
Martin v. Löwis47383402007-08-15 07:32:56 +000013072 {"isidentifier", (PyCFunction) unicode_isidentifier, METH_NOARGS, isidentifier__doc__},
Georg Brandl559e5d72008-06-11 18:37:52 +000013073 {"isprintable", (PyCFunction) unicode_isprintable, METH_NOARGS, isprintable__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013074 {"zfill", (PyCFunction) unicode_zfill, METH_VARARGS, zfill__doc__},
Eric Smith9cd1e092007-08-31 18:39:38 +000013075 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +000013076 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
Eric Smith4a7d76d2008-05-30 18:10:19 +000013077 {"__format__", (PyCFunction) unicode__format__, METH_VARARGS, p_format__doc__},
Georg Brandlceee0772007-11-27 23:48:05 +000013078 {"maketrans", (PyCFunction) unicode_maketrans,
13079 METH_VARARGS | METH_STATIC, maketrans__doc__},
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013080 {"__sizeof__", (PyCFunction) unicode__sizeof__, METH_NOARGS, sizeof__doc__},
Walter Dörwald068325e2002-04-15 13:36:47 +000013081#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013082 /* These methods are just used for debugging the implementation. */
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013083 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013084#endif
13085
Benjamin Peterson14339b62009-01-31 16:36:08 +000013086 {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013087 {NULL, NULL}
13088};
13089
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013090static PyObject *
13091unicode_mod(PyObject *v, PyObject *w)
13092{
Brian Curtindfc80e32011-08-10 20:28:54 -050013093 if (!PyUnicode_Check(v))
13094 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson29060642009-01-31 22:14:21 +000013095 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013096}
13097
13098static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013099 0, /*nb_add*/
13100 0, /*nb_subtract*/
13101 0, /*nb_multiply*/
13102 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013103};
13104
Guido van Rossumd57fd912000-03-10 22:53:23 +000013105static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013106 (lenfunc) unicode_length, /* sq_length */
13107 PyUnicode_Concat, /* sq_concat */
13108 (ssizeargfunc) unicode_repeat, /* sq_repeat */
13109 (ssizeargfunc) unicode_getitem, /* sq_item */
13110 0, /* sq_slice */
13111 0, /* sq_ass_item */
13112 0, /* sq_ass_slice */
13113 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013114};
13115
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013116static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013117unicode_subscript(PyObject* self, PyObject* item)
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013118{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013119 if (PyUnicode_READY(self) == -1)
13120 return NULL;
13121
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000013122 if (PyIndex_Check(item)) {
13123 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013124 if (i == -1 && PyErr_Occurred())
13125 return NULL;
13126 if (i < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013127 i += PyUnicode_GET_LENGTH(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013128 return unicode_getitem(self, i);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013129 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000013130 Py_ssize_t start, stop, step, slicelength, cur, i;
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013131 PyObject *result;
13132 void *src_data, *dest_data;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013133 int src_kind, dest_kind;
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013134 Py_UCS4 ch, max_char, kind_limit;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013135
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013136 if (PySlice_GetIndicesEx(item, PyUnicode_GET_LENGTH(self),
Benjamin Peterson29060642009-01-31 22:14:21 +000013137 &start, &stop, &step, &slicelength) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013138 return NULL;
13139 }
13140
13141 if (slicelength <= 0) {
Victor Stinner382955f2011-12-11 21:44:00 +010013142 Py_INCREF(unicode_empty);
13143 return unicode_empty;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013144 } else if (start == 0 && step == 1 &&
Victor Stinnerc4b49542011-12-11 22:44:26 +010013145 slicelength == PyUnicode_GET_LENGTH(self)) {
13146 return unicode_result_unchanged(self);
Thomas Woutersed03b412007-08-28 21:37:11 +000013147 } else if (step == 1) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013148 return PyUnicode_Substring(self,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013149 start, start + slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013150 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013151 /* General case */
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013152 src_kind = PyUnicode_KIND(self);
13153 src_data = PyUnicode_DATA(self);
Victor Stinner55c99112011-10-13 01:17:06 +020013154 if (!PyUnicode_IS_ASCII(self)) {
13155 kind_limit = kind_maxchar_limit(src_kind);
13156 max_char = 0;
13157 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
13158 ch = PyUnicode_READ(src_kind, src_data, cur);
13159 if (ch > max_char) {
13160 max_char = ch;
13161 if (max_char >= kind_limit)
13162 break;
13163 }
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013164 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013165 }
Victor Stinner55c99112011-10-13 01:17:06 +020013166 else
13167 max_char = 127;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013168 result = PyUnicode_New(slicelength, max_char);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013169 if (result == NULL)
13170 return NULL;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013171 dest_kind = PyUnicode_KIND(result);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013172 dest_data = PyUnicode_DATA(result);
13173
13174 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013175 Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
13176 PyUnicode_WRITE(dest_kind, dest_data, i, ch);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013177 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013178 assert(_PyUnicode_CheckConsistency(result, 1));
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013179 return result;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013180 } else {
13181 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
13182 return NULL;
13183 }
13184}
13185
13186static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013187 (lenfunc)unicode_length, /* mp_length */
13188 (binaryfunc)unicode_subscript, /* mp_subscript */
13189 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013190};
13191
Guido van Rossumd57fd912000-03-10 22:53:23 +000013192
Guido van Rossumd57fd912000-03-10 22:53:23 +000013193/* Helpers for PyUnicode_Format() */
13194
13195static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +000013196getnextarg(PyObject *args, Py_ssize_t arglen, Py_ssize_t *p_argidx)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013197{
Martin v. Löwis18e16552006-02-15 17:27:45 +000013198 Py_ssize_t argidx = *p_argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013199 if (argidx < arglen) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013200 (*p_argidx)++;
13201 if (arglen < 0)
13202 return args;
13203 else
13204 return PyTuple_GetItem(args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013205 }
13206 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013207 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013208 return NULL;
13209}
13210
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013211/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013212
Victor Stinnerd3f08822012-05-29 12:57:52 +020013213static int
13214formatfloat(PyObject *v, int flags, int prec, int type,
13215 PyObject **p_output, _PyUnicodeWriter *writer)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013216{
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013217 char *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013218 double x;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013219 Py_ssize_t len;
Tim Petersced69f82003-09-16 20:30:58 +000013220
Guido van Rossumd57fd912000-03-10 22:53:23 +000013221 x = PyFloat_AsDouble(v);
13222 if (x == -1.0 && PyErr_Occurred())
Victor Stinnerd3f08822012-05-29 12:57:52 +020013223 return -1;
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013224
Guido van Rossumd57fd912000-03-10 22:53:23 +000013225 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000013226 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +000013227
Eric Smith0923d1d2009-04-16 20:16:10 +000013228 p = PyOS_double_to_string(x, type, prec,
13229 (flags & F_ALT) ? Py_DTSF_ALT : 0, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013230 if (p == NULL)
Victor Stinnerd3f08822012-05-29 12:57:52 +020013231 return -1;
13232 len = strlen(p);
13233 if (writer) {
Christian Heimesf4f99392012-09-10 11:48:41 +020013234 if (_PyUnicodeWriter_Prepare(writer, len, 127) == -1) {
13235 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013236 return -1;
Christian Heimesf4f99392012-09-10 11:48:41 +020013237 }
Victor Stinner184252a2012-06-16 02:57:41 +020013238 unicode_write_cstr(writer->buffer, writer->pos, p, len);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013239 writer->pos += len;
13240 }
13241 else
13242 *p_output = _PyUnicode_FromASCII(p, len);
Eric Smith0923d1d2009-04-16 20:16:10 +000013243 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013244 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013245}
13246
Victor Stinnerd0880d52012-04-27 23:40:13 +020013247/* formatlong() emulates the format codes d, u, o, x and X, and
13248 * the F_ALT flag, for Python's long (unbounded) ints. It's not used for
13249 * Python's regular ints.
13250 * Return value: a new PyUnicodeObject*, or NULL if error.
13251 * The output string is of the form
13252 * "-"? ("0x" | "0X")? digit+
13253 * "0x"/"0X" are present only for x and X conversions, with F_ALT
13254 * set in flags. The case of hex digits will be correct,
13255 * There will be at least prec digits, zero-filled on the left if
13256 * necessary to get that many.
13257 * val object to be converted
13258 * flags bitmask of format flags; only F_ALT is looked at
13259 * prec minimum number of digits; 0-fill on left if needed
13260 * type a character in [duoxX]; u acts the same as d
13261 *
13262 * CAUTION: o, x and X conversions on regular ints can never
13263 * produce a '-' sign, but can for Python's unbounded ints.
13264 */
Tim Peters38fd5b62000-09-21 05:43:11 +000013265static PyObject*
13266formatlong(PyObject *val, int flags, int prec, int type)
13267{
Victor Stinnerd0880d52012-04-27 23:40:13 +020013268 PyObject *result = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013269 char *buf;
Victor Stinnerd0880d52012-04-27 23:40:13 +020013270 Py_ssize_t i;
13271 int sign; /* 1 if '-', else 0 */
13272 int len; /* number of characters */
13273 Py_ssize_t llen;
13274 int numdigits; /* len == numnondigits + numdigits */
13275 int numnondigits = 0;
Tim Peters38fd5b62000-09-21 05:43:11 +000013276
Victor Stinnerd0880d52012-04-27 23:40:13 +020013277 /* Avoid exceeding SSIZE_T_MAX */
13278 if (prec > INT_MAX-3) {
13279 PyErr_SetString(PyExc_OverflowError,
13280 "precision too large");
Benjamin Peterson14339b62009-01-31 16:36:08 +000013281 return NULL;
Victor Stinnerd0880d52012-04-27 23:40:13 +020013282 }
13283
13284 assert(PyLong_Check(val));
13285
13286 switch (type) {
13287 case 'd':
13288 case 'u':
13289 /* Special-case boolean: we want 0/1 */
Victor Stinnerb11d91d2012-04-28 00:25:34 +020013290 if (PyBool_Check(val))
13291 result = PyNumber_ToBase(val, 10);
13292 else
13293 result = Py_TYPE(val)->tp_str(val);
Victor Stinnerd0880d52012-04-27 23:40:13 +020013294 break;
13295 case 'o':
13296 numnondigits = 2;
13297 result = PyNumber_ToBase(val, 8);
13298 break;
13299 case 'x':
13300 case 'X':
13301 numnondigits = 2;
13302 result = PyNumber_ToBase(val, 16);
13303 break;
13304 default:
13305 assert(!"'type' not in [duoxX]");
13306 }
13307 if (!result)
13308 return NULL;
13309
13310 assert(unicode_modifiable(result));
13311 assert(PyUnicode_IS_READY(result));
13312 assert(PyUnicode_IS_ASCII(result));
13313
13314 /* To modify the string in-place, there can only be one reference. */
13315 if (Py_REFCNT(result) != 1) {
13316 PyErr_BadInternalCall();
13317 return NULL;
13318 }
13319 buf = PyUnicode_DATA(result);
13320 llen = PyUnicode_GET_LENGTH(result);
13321 if (llen > INT_MAX) {
13322 PyErr_SetString(PyExc_ValueError,
13323 "string too large in _PyBytes_FormatLong");
13324 return NULL;
13325 }
13326 len = (int)llen;
13327 sign = buf[0] == '-';
13328 numnondigits += sign;
13329 numdigits = len - numnondigits;
13330 assert(numdigits > 0);
13331
13332 /* Get rid of base marker unless F_ALT */
13333 if (((flags & F_ALT) == 0 &&
13334 (type == 'o' || type == 'x' || type == 'X'))) {
13335 assert(buf[sign] == '0');
13336 assert(buf[sign+1] == 'x' || buf[sign+1] == 'X' ||
13337 buf[sign+1] == 'o');
13338 numnondigits -= 2;
13339 buf += 2;
13340 len -= 2;
13341 if (sign)
13342 buf[0] = '-';
13343 assert(len == numnondigits + numdigits);
13344 assert(numdigits > 0);
13345 }
13346
13347 /* Fill with leading zeroes to meet minimum width. */
13348 if (prec > numdigits) {
13349 PyObject *r1 = PyBytes_FromStringAndSize(NULL,
13350 numnondigits + prec);
13351 char *b1;
13352 if (!r1) {
13353 Py_DECREF(result);
13354 return NULL;
13355 }
13356 b1 = PyBytes_AS_STRING(r1);
13357 for (i = 0; i < numnondigits; ++i)
13358 *b1++ = *buf++;
13359 for (i = 0; i < prec - numdigits; i++)
13360 *b1++ = '0';
13361 for (i = 0; i < numdigits; i++)
13362 *b1++ = *buf++;
13363 *b1 = '\0';
13364 Py_DECREF(result);
13365 result = r1;
13366 buf = PyBytes_AS_STRING(result);
13367 len = numnondigits + prec;
13368 }
13369
13370 /* Fix up case for hex conversions. */
13371 if (type == 'X') {
13372 /* Need to convert all lower case letters to upper case.
13373 and need to convert 0x to 0X (and -0x to -0X). */
13374 for (i = 0; i < len; i++)
13375 if (buf[i] >= 'a' && buf[i] <= 'x')
13376 buf[i] -= 'a'-'A';
13377 }
13378 if (!PyUnicode_Check(result) || len != PyUnicode_GET_LENGTH(result)) {
13379 PyObject *unicode;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013380 unicode = _PyUnicode_FromASCII(buf, len);
Victor Stinnerd0880d52012-04-27 23:40:13 +020013381 Py_DECREF(result);
13382 result = unicode;
13383 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000013384 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +000013385}
13386
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013387static Py_UCS4
13388formatchar(PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013389{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000013390 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000013391 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013392 if (PyUnicode_GET_LENGTH(v) == 1) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013393 return PyUnicode_READ_CHAR(v, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +000013394 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013395 goto onError;
13396 }
13397 else {
13398 /* Integer input truncated to a character */
13399 long x;
13400 x = PyLong_AsLong(v);
13401 if (x == -1 && PyErr_Occurred())
13402 goto onError;
13403
Victor Stinner8faf8212011-12-08 22:14:11 +010013404 if (x < 0 || x > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013405 PyErr_SetString(PyExc_OverflowError,
13406 "%c arg not in range(0x110000)");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013407 return (Py_UCS4) -1;
Benjamin Peterson29060642009-01-31 22:14:21 +000013408 }
13409
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013410 return (Py_UCS4) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013411 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000013412
Benjamin Peterson29060642009-01-31 22:14:21 +000013413 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000013414 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013415 "%c requires int or char");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013416 return (Py_UCS4) -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013417}
13418
Alexander Belopolsky40018472011-02-26 01:02:56 +000013419PyObject *
13420PyUnicode_Format(PyObject *format, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013421{
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013422 Py_ssize_t fmtcnt, fmtpos, arglen, argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013423 int args_owned = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013424 PyObject *dict = NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013425 PyObject *temp = NULL;
13426 PyObject *second = NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013427 PyObject *uformat;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013428 void *fmt;
13429 enum PyUnicode_Kind kind, fmtkind;
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013430 _PyUnicodeWriter writer;
Victor Stinneree4544c2012-05-09 22:24:08 +020013431 Py_ssize_t sublen;
13432 Py_UCS4 maxchar;
Tim Petersced69f82003-09-16 20:30:58 +000013433
Guido van Rossumd57fd912000-03-10 22:53:23 +000013434 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013435 PyErr_BadInternalCall();
13436 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013437 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013438 uformat = PyUnicode_FromObject(format);
Benjamin Peterson22a29702012-01-02 09:00:30 -060013439 if (uformat == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000013440 return NULL;
Victor Stinner19294072012-10-05 00:09:33 +020013441 if (PyUnicode_READY(uformat) == -1) {
Benjamin Peterson22a29702012-01-02 09:00:30 -060013442 Py_DECREF(uformat);
Victor Stinner19294072012-10-05 00:09:33 +020013443 return NULL;
13444 }
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013445
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013446 fmt = PyUnicode_DATA(uformat);
13447 fmtkind = PyUnicode_KIND(uformat);
13448 fmtcnt = PyUnicode_GET_LENGTH(uformat);
13449 fmtpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013450
Victor Stinnerd3f08822012-05-29 12:57:52 +020013451 _PyUnicodeWriter_Init(&writer, fmtcnt + 100);
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013452
Guido van Rossumd57fd912000-03-10 22:53:23 +000013453 if (PyTuple_Check(args)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013454 arglen = PyTuple_Size(args);
13455 argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013456 }
13457 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013458 arglen = -1;
13459 argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013460 }
Benjamin Peterson28a6cfa2012-08-28 17:55:35 -040013461 if (PyMapping_Check(args) && !PyTuple_Check(args) && !PyUnicode_Check(args))
Benjamin Peterson29060642009-01-31 22:14:21 +000013462 dict = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013463
13464 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013465 if (PyUnicode_READ(fmtkind, fmt, fmtpos) != '%') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013466 Py_ssize_t nonfmtpos;
13467 nonfmtpos = fmtpos++;
13468 while (fmtcnt >= 0 &&
13469 PyUnicode_READ(fmtkind, fmt, fmtpos) != '%') {
13470 fmtpos++;
13471 fmtcnt--;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013472 }
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013473 if (fmtcnt < 0)
13474 fmtpos--;
Victor Stinneree4544c2012-05-09 22:24:08 +020013475 sublen = fmtpos - nonfmtpos;
13476 maxchar = _PyUnicode_FindMaxChar(uformat,
13477 nonfmtpos, nonfmtpos + sublen);
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013478 if (_PyUnicodeWriter_Prepare(&writer, sublen, maxchar) == -1)
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013479 goto onError;
Victor Stinneree4544c2012-05-09 22:24:08 +020013480
Victor Stinnerd3f08822012-05-29 12:57:52 +020013481 _PyUnicode_FastCopyCharacters(writer.buffer, writer.pos,
13482 uformat, nonfmtpos, sublen);
Victor Stinneree4544c2012-05-09 22:24:08 +020013483 writer.pos += sublen;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013484 }
13485 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013486 /* Got a format specifier */
13487 int flags = 0;
13488 Py_ssize_t width = -1;
13489 int prec = -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013490 Py_UCS4 c = '\0';
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013491 Py_UCS4 fill;
13492 int sign;
13493 Py_UCS4 signchar;
Benjamin Peterson29060642009-01-31 22:14:21 +000013494 int isnumok;
13495 PyObject *v = NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013496 void *pbuf = NULL;
13497 Py_ssize_t pindex, len;
Victor Stinneree4544c2012-05-09 22:24:08 +020013498 Py_UCS4 bufmaxchar;
13499 Py_ssize_t buflen;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013500
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013501 fmtpos++;
Victor Stinner438106b2012-05-02 00:41:57 +020013502 c = PyUnicode_READ(fmtkind, fmt, fmtpos);
13503 if (c == '(') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013504 Py_ssize_t keystart;
Benjamin Peterson29060642009-01-31 22:14:21 +000013505 Py_ssize_t keylen;
13506 PyObject *key;
13507 int pcount = 1;
Christian Heimesa612dc02008-02-24 13:08:18 +000013508
Benjamin Peterson29060642009-01-31 22:14:21 +000013509 if (dict == NULL) {
13510 PyErr_SetString(PyExc_TypeError,
13511 "format requires a mapping");
13512 goto onError;
13513 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013514 ++fmtpos;
Benjamin Peterson29060642009-01-31 22:14:21 +000013515 --fmtcnt;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013516 keystart = fmtpos;
Benjamin Peterson29060642009-01-31 22:14:21 +000013517 /* Skip over balanced parentheses */
13518 while (pcount > 0 && --fmtcnt >= 0) {
Victor Stinnerbff7c962012-05-03 01:44:59 +020013519 c = PyUnicode_READ(fmtkind, fmt, fmtpos);
13520 if (c == ')')
Benjamin Peterson29060642009-01-31 22:14:21 +000013521 --pcount;
Victor Stinnerbff7c962012-05-03 01:44:59 +020013522 else if (c == '(')
Benjamin Peterson29060642009-01-31 22:14:21 +000013523 ++pcount;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013524 fmtpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +000013525 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013526 keylen = fmtpos - keystart - 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000013527 if (fmtcnt < 0 || pcount > 0) {
13528 PyErr_SetString(PyExc_ValueError,
13529 "incomplete format key");
13530 goto onError;
13531 }
Victor Stinner7931d9a2011-11-04 00:22:48 +010013532 key = PyUnicode_Substring(uformat,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013533 keystart, keystart + keylen);
Benjamin Peterson29060642009-01-31 22:14:21 +000013534 if (key == NULL)
13535 goto onError;
13536 if (args_owned) {
13537 Py_DECREF(args);
13538 args_owned = 0;
13539 }
13540 args = PyObject_GetItem(dict, key);
13541 Py_DECREF(key);
13542 if (args == NULL) {
13543 goto onError;
13544 }
13545 args_owned = 1;
13546 arglen = -1;
13547 argidx = -2;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013548 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013549 while (--fmtcnt >= 0) {
Victor Stinner438106b2012-05-02 00:41:57 +020013550 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
13551 switch (c) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013552 case '-': flags |= F_LJUST; continue;
13553 case '+': flags |= F_SIGN; continue;
13554 case ' ': flags |= F_BLANK; continue;
13555 case '#': flags |= F_ALT; continue;
13556 case '0': flags |= F_ZERO; continue;
13557 }
13558 break;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013559 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013560 if (c == '*') {
13561 v = getnextarg(args, arglen, &argidx);
13562 if (v == NULL)
13563 goto onError;
13564 if (!PyLong_Check(v)) {
13565 PyErr_SetString(PyExc_TypeError,
13566 "* wants int");
13567 goto onError;
13568 }
13569 width = PyLong_AsLong(v);
13570 if (width == -1 && PyErr_Occurred())
13571 goto onError;
13572 if (width < 0) {
13573 flags |= F_LJUST;
13574 width = -width;
13575 }
13576 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013577 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013578 }
13579 else if (c >= '0' && c <= '9') {
13580 width = c - '0';
13581 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013582 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013583 if (c < '0' || c > '9')
13584 break;
Martin v. Löwisb05c0732012-05-15 13:45:49 +020013585 /* Since c is unsigned, the RHS would end up as unsigned,
13586 mixing signed and unsigned comparison. Since c is between
13587 '0' and '9', casting to int is safe. */
13588 if (width > (PY_SSIZE_T_MAX - ((int)c - '0')) / 10) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013589 PyErr_SetString(PyExc_ValueError,
13590 "width too big");
Benjamin Peterson14339b62009-01-31 16:36:08 +000013591 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +000013592 }
13593 width = width*10 + (c - '0');
13594 }
13595 }
13596 if (c == '.') {
13597 prec = 0;
13598 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013599 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013600 if (c == '*') {
13601 v = getnextarg(args, arglen, &argidx);
13602 if (v == NULL)
13603 goto onError;
13604 if (!PyLong_Check(v)) {
13605 PyErr_SetString(PyExc_TypeError,
13606 "* wants int");
13607 goto onError;
13608 }
13609 prec = PyLong_AsLong(v);
13610 if (prec == -1 && PyErr_Occurred())
13611 goto onError;
13612 if (prec < 0)
13613 prec = 0;
13614 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013615 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013616 }
13617 else if (c >= '0' && c <= '9') {
13618 prec = c - '0';
13619 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013620 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013621 if (c < '0' || c > '9')
13622 break;
Martin v. Löwisb05c0732012-05-15 13:45:49 +020013623 if (prec > (INT_MAX - ((int)c - '0')) / 10) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013624 PyErr_SetString(PyExc_ValueError,
13625 "prec too big");
13626 goto onError;
13627 }
13628 prec = prec*10 + (c - '0');
13629 }
13630 }
13631 } /* prec */
13632 if (fmtcnt >= 0) {
13633 if (c == 'h' || c == 'l' || c == 'L') {
13634 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013635 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013636 }
13637 }
13638 if (fmtcnt < 0) {
13639 PyErr_SetString(PyExc_ValueError,
13640 "incomplete format");
13641 goto onError;
13642 }
Victor Stinnerd3f08822012-05-29 12:57:52 +020013643 if (fmtcnt == 0)
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013644 writer.overallocate = 0;
Victor Stinneraff3cc62012-04-30 05:19:21 +020013645
13646 if (c == '%') {
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013647 if (_PyUnicodeWriter_Prepare(&writer, 1, '%') == -1)
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013648 goto onError;
Victor Stinneree4544c2012-05-09 22:24:08 +020013649 PyUnicode_WRITE(writer.kind, writer.data, writer.pos, '%');
13650 writer.pos += 1;
Victor Stinneraff3cc62012-04-30 05:19:21 +020013651 continue;
Benjamin Peterson29060642009-01-31 22:14:21 +000013652 }
Victor Stinneraff3cc62012-04-30 05:19:21 +020013653
Victor Stinneraff3cc62012-04-30 05:19:21 +020013654 v = getnextarg(args, arglen, &argidx);
13655 if (v == NULL)
13656 goto onError;
13657
Benjamin Peterson29060642009-01-31 22:14:21 +000013658 sign = 0;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013659 signchar = '\0';
Benjamin Peterson29060642009-01-31 22:14:21 +000013660 fill = ' ';
13661 switch (c) {
13662
Benjamin Peterson29060642009-01-31 22:14:21 +000013663 case 's':
13664 case 'r':
13665 case 'a':
Victor Stinnerd3f08822012-05-29 12:57:52 +020013666 if (PyLong_CheckExact(v) && width == -1 && prec == -1) {
13667 /* Fast path */
13668 if (_PyLong_FormatWriter(&writer, v, 10, flags & F_ALT) == -1)
13669 goto onError;
13670 goto nextarg;
13671 }
13672
Victor Stinner808fc0a2010-03-22 12:50:40 +000013673 if (PyUnicode_CheckExact(v) && c == 's') {
Benjamin Peterson29060642009-01-31 22:14:21 +000013674 temp = v;
13675 Py_INCREF(temp);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013676 }
13677 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013678 if (c == 's')
13679 temp = PyObject_Str(v);
13680 else if (c == 'r')
13681 temp = PyObject_Repr(v);
13682 else
13683 temp = PyObject_ASCII(v);
Benjamin Peterson29060642009-01-31 22:14:21 +000013684 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013685 break;
13686
13687 case 'i':
13688 case 'd':
13689 case 'u':
13690 case 'o':
13691 case 'x':
13692 case 'X':
Victor Stinnerd3f08822012-05-29 12:57:52 +020013693 if (PyLong_CheckExact(v)
13694 && width == -1 && prec == -1
13695 && !(flags & (F_SIGN | F_BLANK)))
13696 {
13697 /* Fast path */
13698 switch(c)
13699 {
13700 case 'd':
13701 case 'i':
13702 case 'u':
13703 if (_PyLong_FormatWriter(&writer, v, 10, flags & F_ALT) == -1)
13704 goto onError;
13705 goto nextarg;
13706 case 'x':
13707 if (_PyLong_FormatWriter(&writer, v, 16, flags & F_ALT) == -1)
13708 goto onError;
13709 goto nextarg;
13710 case 'o':
13711 if (_PyLong_FormatWriter(&writer, v, 8, flags & F_ALT) == -1)
13712 goto onError;
13713 goto nextarg;
13714 default:
13715 break;
13716 }
13717 }
13718
Benjamin Peterson29060642009-01-31 22:14:21 +000013719 isnumok = 0;
13720 if (PyNumber_Check(v)) {
13721 PyObject *iobj=NULL;
13722
13723 if (PyLong_Check(v)) {
13724 iobj = v;
13725 Py_INCREF(iobj);
13726 }
13727 else {
13728 iobj = PyNumber_Long(v);
13729 }
13730 if (iobj!=NULL) {
13731 if (PyLong_Check(iobj)) {
13732 isnumok = 1;
Victor Stinneraff3cc62012-04-30 05:19:21 +020013733 sign = 1;
Senthil Kumaran9ebe08d2011-07-03 21:03:16 -070013734 temp = formatlong(iobj, flags, prec, (c == 'i'? 'd': c));
Benjamin Peterson29060642009-01-31 22:14:21 +000013735 Py_DECREF(iobj);
Benjamin Peterson29060642009-01-31 22:14:21 +000013736 }
13737 else {
13738 Py_DECREF(iobj);
13739 }
13740 }
13741 }
13742 if (!isnumok) {
13743 PyErr_Format(PyExc_TypeError,
13744 "%%%c format: a number is required, "
13745 "not %.200s", (char)c, Py_TYPE(v)->tp_name);
13746 goto onError;
13747 }
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013748 if (flags & F_ZERO)
Benjamin Peterson29060642009-01-31 22:14:21 +000013749 fill = '0';
13750 break;
13751
13752 case 'e':
13753 case 'E':
13754 case 'f':
13755 case 'F':
13756 case 'g':
13757 case 'G':
Victor Stinnerd3f08822012-05-29 12:57:52 +020013758 if (width == -1 && prec == -1
13759 && !(flags & (F_SIGN | F_BLANK)))
13760 {
13761 /* Fast path */
13762 if (formatfloat(v, flags, prec, c, NULL, &writer) == -1)
13763 goto onError;
13764 goto nextarg;
13765 }
13766
Benjamin Peterson29060642009-01-31 22:14:21 +000013767 sign = 1;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013768 if (flags & F_ZERO)
Benjamin Peterson29060642009-01-31 22:14:21 +000013769 fill = '0';
Victor Stinnerd3f08822012-05-29 12:57:52 +020013770 if (formatfloat(v, flags, prec, c, &temp, NULL) == -1)
13771 temp = NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000013772 break;
13773
13774 case 'c':
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013775 {
13776 Py_UCS4 ch = formatchar(v);
13777 if (ch == (Py_UCS4) -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000013778 goto onError;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013779 if (width == -1 && prec == -1) {
13780 /* Fast path */
13781 if (_PyUnicodeWriter_Prepare(&writer, 1, ch) == -1)
13782 goto onError;
13783 PyUnicode_WRITE(writer.kind, writer.data, writer.pos, ch);
13784 writer.pos += 1;
13785 goto nextarg;
13786 }
Victor Stinnerb5c3ea32012-05-02 00:29:36 +020013787 temp = PyUnicode_FromOrdinal(ch);
Benjamin Peterson29060642009-01-31 22:14:21 +000013788 break;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013789 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013790
13791 default:
13792 PyErr_Format(PyExc_ValueError,
13793 "unsupported format character '%c' (0x%x) "
13794 "at index %zd",
13795 (31<=c && c<=126) ? (char)c : '?',
13796 (int)c,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013797 fmtpos - 1);
Benjamin Peterson29060642009-01-31 22:14:21 +000013798 goto onError;
13799 }
Victor Stinneraff3cc62012-04-30 05:19:21 +020013800 if (temp == NULL)
13801 goto onError;
13802 assert (PyUnicode_Check(temp));
Victor Stinnerd3f08822012-05-29 12:57:52 +020013803
13804 if (width == -1 && prec == -1
13805 && !(flags & (F_SIGN | F_BLANK)))
13806 {
13807 /* Fast path */
13808 if (_PyUnicodeWriter_WriteStr(&writer, temp) == -1)
13809 goto onError;
13810 goto nextarg;
13811 }
13812
Victor Stinneraff3cc62012-04-30 05:19:21 +020013813 if (PyUnicode_READY(temp) == -1) {
13814 Py_CLEAR(temp);
13815 goto onError;
13816 }
13817 kind = PyUnicode_KIND(temp);
13818 pbuf = PyUnicode_DATA(temp);
13819 len = PyUnicode_GET_LENGTH(temp);
13820
13821 if (c == 's' || c == 'r' || c == 'a') {
13822 if (prec >= 0 && len > prec)
13823 len = prec;
13824 }
13825
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013826 /* pbuf is initialized here. */
13827 pindex = 0;
Benjamin Peterson29060642009-01-31 22:14:21 +000013828 if (sign) {
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013829 Py_UCS4 ch = PyUnicode_READ(kind, pbuf, pindex);
13830 if (ch == '-' || ch == '+') {
13831 signchar = ch;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013832 len--;
13833 pindex++;
Benjamin Peterson29060642009-01-31 22:14:21 +000013834 }
13835 else if (flags & F_SIGN)
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013836 signchar = '+';
Benjamin Peterson29060642009-01-31 22:14:21 +000013837 else if (flags & F_BLANK)
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013838 signchar = ' ';
Benjamin Peterson29060642009-01-31 22:14:21 +000013839 else
13840 sign = 0;
13841 }
13842 if (width < len)
13843 width = len;
Victor Stinneree4544c2012-05-09 22:24:08 +020013844
13845 /* Compute the length and maximum character of the
13846 written characters */
13847 bufmaxchar = 127;
13848 if (!(flags & F_LJUST)) {
13849 if (sign) {
13850 if ((width-1) > len)
Victor Stinnerd3f08822012-05-29 12:57:52 +020013851 bufmaxchar = MAX_MAXCHAR(bufmaxchar, fill);
Victor Stinneree4544c2012-05-09 22:24:08 +020013852 }
13853 else {
13854 if (width > len)
Victor Stinnerd3f08822012-05-29 12:57:52 +020013855 bufmaxchar = MAX_MAXCHAR(bufmaxchar, fill);
Victor Stinneree4544c2012-05-09 22:24:08 +020013856 }
13857 }
13858 maxchar = _PyUnicode_FindMaxChar(temp, 0, pindex+len);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013859 bufmaxchar = MAX_MAXCHAR(bufmaxchar, maxchar);
Victor Stinneree4544c2012-05-09 22:24:08 +020013860
13861 buflen = width;
13862 if (sign && len == width)
13863 buflen++;
13864
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013865 if (_PyUnicodeWriter_Prepare(&writer, buflen, bufmaxchar) == -1)
Victor Stinneree4544c2012-05-09 22:24:08 +020013866 goto onError;
13867
13868 /* Write characters */
Benjamin Peterson29060642009-01-31 22:14:21 +000013869 if (sign) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013870 if (fill != ' ') {
Victor Stinneree4544c2012-05-09 22:24:08 +020013871 PyUnicode_WRITE(writer.kind, writer.data, writer.pos, signchar);
13872 writer.pos += 1;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013873 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013874 if (width > len)
13875 width--;
13876 }
13877 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013878 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013879 assert(PyUnicode_READ(kind, pbuf, pindex + 1) == c);
Benjamin Peterson29060642009-01-31 22:14:21 +000013880 if (fill != ' ') {
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013881 PyUnicode_WRITE(writer.kind, writer.data, writer.pos, '0');
13882 PyUnicode_WRITE(writer.kind, writer.data, writer.pos+1, c);
13883 writer.pos += 2;
13884 pindex += 2;
Benjamin Peterson29060642009-01-31 22:14:21 +000013885 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013886 width -= 2;
13887 if (width < 0)
13888 width = 0;
13889 len -= 2;
13890 }
13891 if (width > len && !(flags & F_LJUST)) {
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013892 sublen = width - len;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013893 FILL(writer.kind, writer.data, fill, writer.pos, sublen);
13894 writer.pos += sublen;
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013895 width = len;
Benjamin Peterson29060642009-01-31 22:14:21 +000013896 }
13897 if (fill == ' ') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013898 if (sign) {
Victor Stinneree4544c2012-05-09 22:24:08 +020013899 PyUnicode_WRITE(writer.kind, writer.data, writer.pos, signchar);
13900 writer.pos += 1;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013901 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013902 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013903 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
13904 assert(PyUnicode_READ(kind, pbuf, pindex+1) == c);
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013905 PyUnicode_WRITE(writer.kind, writer.data, writer.pos, '0');
13906 PyUnicode_WRITE(writer.kind, writer.data, writer.pos+1, c);
13907 writer.pos += 2;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013908 pindex += 2;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013909 }
13910 }
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013911
Victor Stinnerc9d369f2012-06-16 02:22:37 +020013912 if (len) {
13913 _PyUnicode_FastCopyCharacters(writer.buffer, writer.pos,
13914 temp, pindex, len);
13915 writer.pos += len;
13916 }
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013917 if (width > len) {
Victor Stinneree4544c2012-05-09 22:24:08 +020013918 sublen = width - len;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013919 FILL(writer.kind, writer.data, ' ', writer.pos, sublen);
13920 writer.pos += sublen;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013921 }
Victor Stinneree4544c2012-05-09 22:24:08 +020013922
Victor Stinnerd3f08822012-05-29 12:57:52 +020013923nextarg:
Benjamin Peterson29060642009-01-31 22:14:21 +000013924 if (dict && (argidx < arglen) && c != '%') {
13925 PyErr_SetString(PyExc_TypeError,
13926 "not all arguments converted during string formatting");
Benjamin Peterson29060642009-01-31 22:14:21 +000013927 goto onError;
13928 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013929 Py_CLEAR(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013930 } /* '%' */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013931 } /* until end */
13932 if (argidx < arglen && !dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013933 PyErr_SetString(PyExc_TypeError,
13934 "not all arguments converted during string formatting");
13935 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013936 }
13937
13938 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013939 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013940 }
13941 Py_DECREF(uformat);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013942 Py_XDECREF(temp);
13943 Py_XDECREF(second);
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013944 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013945
Benjamin Peterson29060642009-01-31 22:14:21 +000013946 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000013947 Py_DECREF(uformat);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013948 Py_XDECREF(temp);
13949 Py_XDECREF(second);
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013950 _PyUnicodeWriter_Dealloc(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013951 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013952 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013953 }
13954 return NULL;
13955}
13956
Jeremy Hylton938ace62002-07-17 16:30:39 +000013957static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +000013958unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
13959
Tim Peters6d6c1a32001-08-02 04:15:00 +000013960static PyObject *
13961unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
13962{
Benjamin Peterson29060642009-01-31 22:14:21 +000013963 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013964 static char *kwlist[] = {"object", "encoding", "errors", 0};
13965 char *encoding = NULL;
13966 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000013967
Benjamin Peterson14339b62009-01-31 16:36:08 +000013968 if (type != &PyUnicode_Type)
13969 return unicode_subtype_new(type, args, kwds);
13970 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +000013971 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +000013972 return NULL;
Victor Stinner382955f2011-12-11 21:44:00 +010013973 if (x == NULL) {
13974 Py_INCREF(unicode_empty);
13975 return unicode_empty;
13976 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000013977 if (encoding == NULL && errors == NULL)
13978 return PyObject_Str(x);
13979 else
Benjamin Peterson29060642009-01-31 22:14:21 +000013980 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +000013981}
13982
Guido van Rossume023fe02001-08-30 03:12:59 +000013983static PyObject *
13984unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
13985{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013986 PyObject *unicode, *self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013987 Py_ssize_t length, char_size;
13988 int share_wstr, share_utf8;
13989 unsigned int kind;
13990 void *data;
Guido van Rossume023fe02001-08-30 03:12:59 +000013991
Benjamin Peterson14339b62009-01-31 16:36:08 +000013992 assert(PyType_IsSubtype(type, &PyUnicode_Type));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013993
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013994 unicode = unicode_new(&PyUnicode_Type, args, kwds);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013995 if (unicode == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000013996 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020013997 assert(_PyUnicode_CHECK(unicode));
Benjamin Petersonbac79492012-01-14 13:34:47 -050013998 if (PyUnicode_READY(unicode) == -1) {
Benjamin Peterson22a29702012-01-02 09:00:30 -060013999 Py_DECREF(unicode);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014000 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060014001 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014002
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014003 self = type->tp_alloc(type, 0);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014004 if (self == NULL) {
14005 Py_DECREF(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014006 return NULL;
14007 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014008 kind = PyUnicode_KIND(unicode);
14009 length = PyUnicode_GET_LENGTH(unicode);
14010
14011 _PyUnicode_LENGTH(self) = length;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014012#ifdef Py_DEBUG
14013 _PyUnicode_HASH(self) = -1;
14014#else
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014015 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014016#endif
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014017 _PyUnicode_STATE(self).interned = 0;
14018 _PyUnicode_STATE(self).kind = kind;
14019 _PyUnicode_STATE(self).compact = 0;
Victor Stinner3cf46372011-10-03 14:42:15 +020014020 _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014021 _PyUnicode_STATE(self).ready = 1;
14022 _PyUnicode_WSTR(self) = NULL;
14023 _PyUnicode_UTF8_LENGTH(self) = 0;
14024 _PyUnicode_UTF8(self) = NULL;
14025 _PyUnicode_WSTR_LENGTH(self) = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +020014026 _PyUnicode_DATA_ANY(self) = NULL;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014027
14028 share_utf8 = 0;
14029 share_wstr = 0;
14030 if (kind == PyUnicode_1BYTE_KIND) {
14031 char_size = 1;
14032 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
14033 share_utf8 = 1;
14034 }
14035 else if (kind == PyUnicode_2BYTE_KIND) {
14036 char_size = 2;
14037 if (sizeof(wchar_t) == 2)
14038 share_wstr = 1;
14039 }
14040 else {
14041 assert(kind == PyUnicode_4BYTE_KIND);
14042 char_size = 4;
14043 if (sizeof(wchar_t) == 4)
14044 share_wstr = 1;
14045 }
14046
14047 /* Ensure we won't overflow the length. */
14048 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
14049 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014050 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014051 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014052 data = PyObject_MALLOC((length + 1) * char_size);
14053 if (data == NULL) {
14054 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014055 goto onError;
14056 }
14057
Victor Stinnerc3c74152011-10-02 20:39:55 +020014058 _PyUnicode_DATA_ANY(self) = data;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014059 if (share_utf8) {
14060 _PyUnicode_UTF8_LENGTH(self) = length;
14061 _PyUnicode_UTF8(self) = data;
14062 }
14063 if (share_wstr) {
14064 _PyUnicode_WSTR_LENGTH(self) = length;
14065 _PyUnicode_WSTR(self) = (wchar_t *)data;
14066 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014067
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014068 Py_MEMCPY(data, PyUnicode_DATA(unicode),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020014069 kind * (length + 1));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020014070 assert(_PyUnicode_CheckConsistency(self, 1));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014071#ifdef Py_DEBUG
14072 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
14073#endif
Victor Stinnerdd18d3a2011-10-22 11:08:10 +020014074 Py_DECREF(unicode);
Victor Stinner7931d9a2011-11-04 00:22:48 +010014075 return self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014076
14077onError:
14078 Py_DECREF(unicode);
14079 Py_DECREF(self);
14080 return NULL;
Guido van Rossume023fe02001-08-30 03:12:59 +000014081}
14082
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000014083PyDoc_STRVAR(unicode_doc,
Chris Jerdonek83fe2e12012-10-07 14:48:36 -070014084"str(object='') -> str\n\
14085str(bytes_or_buffer[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +000014086\n\
Nick Coghlan573b1fd2012-08-16 14:13:07 +100014087Create a new string object from the given object. If encoding or\n\
14088errors is specified, then the object must expose a data buffer\n\
14089that will be decoded using the given encoding and error handler.\n\
14090Otherwise, returns the result of object.__str__() (if defined)\n\
14091or repr(object).\n\
14092encoding defaults to sys.getdefaultencoding().\n\
14093errors defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +000014094
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014095static PyObject *unicode_iter(PyObject *seq);
14096
Guido van Rossumd57fd912000-03-10 22:53:23 +000014097PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000014098 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Benjamin Peterson14339b62009-01-31 16:36:08 +000014099 "str", /* tp_name */
14100 sizeof(PyUnicodeObject), /* tp_size */
14101 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014102 /* Slots */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014103 (destructor)unicode_dealloc, /* tp_dealloc */
14104 0, /* tp_print */
14105 0, /* tp_getattr */
14106 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000014107 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014108 unicode_repr, /* tp_repr */
14109 &unicode_as_number, /* tp_as_number */
14110 &unicode_as_sequence, /* tp_as_sequence */
14111 &unicode_as_mapping, /* tp_as_mapping */
14112 (hashfunc) unicode_hash, /* tp_hash*/
14113 0, /* tp_call*/
14114 (reprfunc) unicode_str, /* tp_str */
14115 PyObject_GenericGetAttr, /* tp_getattro */
14116 0, /* tp_setattro */
14117 0, /* tp_as_buffer */
14118 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Benjamin Peterson29060642009-01-31 22:14:21 +000014119 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014120 unicode_doc, /* tp_doc */
14121 0, /* tp_traverse */
14122 0, /* tp_clear */
14123 PyUnicode_RichCompare, /* tp_richcompare */
14124 0, /* tp_weaklistoffset */
14125 unicode_iter, /* tp_iter */
14126 0, /* tp_iternext */
14127 unicode_methods, /* tp_methods */
14128 0, /* tp_members */
14129 0, /* tp_getset */
14130 &PyBaseObject_Type, /* tp_base */
14131 0, /* tp_dict */
14132 0, /* tp_descr_get */
14133 0, /* tp_descr_set */
14134 0, /* tp_dictoffset */
14135 0, /* tp_init */
14136 0, /* tp_alloc */
14137 unicode_new, /* tp_new */
14138 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014139};
14140
14141/* Initialize the Unicode implementation */
14142
Victor Stinner3a50e702011-10-18 21:21:00 +020014143int _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014144{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014145 int i;
14146
Thomas Wouters477c8d52006-05-27 19:21:47 +000014147 /* XXX - move this array to unicodectype.c ? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014148 Py_UCS2 linebreak[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +000014149 0x000A, /* LINE FEED */
14150 0x000D, /* CARRIAGE RETURN */
14151 0x001C, /* FILE SEPARATOR */
14152 0x001D, /* GROUP SEPARATOR */
14153 0x001E, /* RECORD SEPARATOR */
14154 0x0085, /* NEXT LINE */
14155 0x2028, /* LINE SEPARATOR */
14156 0x2029, /* PARAGRAPH SEPARATOR */
14157 };
14158
Fred Drakee4315f52000-05-09 19:53:39 +000014159 /* Init the implementation */
Victor Stinnera464fc12011-10-02 20:39:30 +020014160 unicode_empty = PyUnicode_New(0, 0);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014161 if (!unicode_empty)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014162 Py_FatalError("Can't create empty string");
Victor Stinnerd3df8ab2011-11-22 01:22:34 +010014163 assert(_PyUnicode_CheckConsistency(unicode_empty, 1));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014164
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014165 for (i = 0; i < 256; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +000014166 unicode_latin1[i] = NULL;
Guido van Rossumcacfc072002-05-24 19:01:59 +000014167 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000014168 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +000014169
14170 /* initialize the linebreak bloom filter */
14171 bloom_linebreak = make_bloom_mask(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014172 PyUnicode_2BYTE_KIND, linebreak,
Victor Stinner63941882011-09-29 00:42:28 +020014173 Py_ARRAY_LENGTH(linebreak));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014174
14175 PyType_Ready(&EncodingMapType);
Victor Stinner3a50e702011-10-18 21:21:00 +020014176
Benjamin Petersonc4311282012-10-30 23:21:10 -040014177 if (PyType_Ready(&PyFieldNameIter_Type) < 0)
14178 Py_FatalError("Can't initialize field name iterator type");
14179
14180 if (PyType_Ready(&PyFormatterIter_Type) < 0)
14181 Py_FatalError("Can't initialize formatter iter type");
Benjamin Petersone8ea97f2012-10-30 23:27:52 -040014182
Victor Stinner3a50e702011-10-18 21:21:00 +020014183#ifdef HAVE_MBCS
14184 winver.dwOSVersionInfoSize = sizeof(winver);
14185 if (!GetVersionEx((OSVERSIONINFO*)&winver)) {
14186 PyErr_SetFromWindowsErr(0);
14187 return -1;
14188 }
14189#endif
14190 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014191}
14192
14193/* Finalize the Unicode implementation */
14194
Christian Heimesa156e092008-02-16 07:38:31 +000014195int
14196PyUnicode_ClearFreeList(void)
14197{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014198 return 0;
Christian Heimesa156e092008-02-16 07:38:31 +000014199}
14200
Guido van Rossumd57fd912000-03-10 22:53:23 +000014201void
Thomas Wouters78890102000-07-22 19:25:51 +000014202_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014203{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014204 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014205
Guido van Rossum4ae8ef82000-10-03 18:09:04 +000014206 Py_XDECREF(unicode_empty);
14207 unicode_empty = NULL;
Barry Warsaw5b4c2282000-10-03 20:45:26 +000014208
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014209 for (i = 0; i < 256; i++) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014210 if (unicode_latin1[i]) {
14211 Py_DECREF(unicode_latin1[i]);
14212 unicode_latin1[i] = NULL;
14213 }
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014214 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020014215 _PyUnicode_ClearStaticStrings();
Christian Heimesa156e092008-02-16 07:38:31 +000014216 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +000014217}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000014218
Walter Dörwald16807132007-05-25 13:52:07 +000014219void
14220PyUnicode_InternInPlace(PyObject **p)
14221{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014222 register PyObject *s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014223 PyObject *t;
Victor Stinner4fae54c2011-10-03 02:01:52 +020014224#ifdef Py_DEBUG
14225 assert(s != NULL);
14226 assert(_PyUnicode_CHECK(s));
14227#else
Benjamin Peterson14339b62009-01-31 16:36:08 +000014228 if (s == NULL || !PyUnicode_Check(s))
Victor Stinner4fae54c2011-10-03 02:01:52 +020014229 return;
14230#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000014231 /* If it's a subclass, we don't really know what putting
14232 it in the interned dict might do. */
14233 if (!PyUnicode_CheckExact(s))
14234 return;
14235 if (PyUnicode_CHECK_INTERNED(s))
14236 return;
14237 if (interned == NULL) {
14238 interned = PyDict_New();
14239 if (interned == NULL) {
14240 PyErr_Clear(); /* Don't leave an exception */
14241 return;
14242 }
14243 }
14244 /* It might be that the GetItem call fails even
14245 though the key is present in the dictionary,
14246 namely when this happens during a stack overflow. */
14247 Py_ALLOW_RECURSION
Victor Stinner7931d9a2011-11-04 00:22:48 +010014248 t = PyDict_GetItem(interned, s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014249 Py_END_ALLOW_RECURSION
Martin v. Löwis5b222132007-06-10 09:51:05 +000014250
Benjamin Peterson29060642009-01-31 22:14:21 +000014251 if (t) {
14252 Py_INCREF(t);
14253 Py_DECREF(*p);
14254 *p = t;
14255 return;
14256 }
Walter Dörwald16807132007-05-25 13:52:07 +000014257
Benjamin Peterson14339b62009-01-31 16:36:08 +000014258 PyThreadState_GET()->recursion_critical = 1;
Victor Stinner7931d9a2011-11-04 00:22:48 +010014259 if (PyDict_SetItem(interned, s, s) < 0) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014260 PyErr_Clear();
14261 PyThreadState_GET()->recursion_critical = 0;
14262 return;
14263 }
14264 PyThreadState_GET()->recursion_critical = 0;
14265 /* The two references in interned are not counted by refcnt.
14266 The deallocator will take care of this */
14267 Py_REFCNT(s) -= 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014268 _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000014269}
14270
14271void
14272PyUnicode_InternImmortal(PyObject **p)
14273{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014274 PyUnicode_InternInPlace(p);
14275 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
Victor Stinneraf9e4b82011-10-23 20:07:00 +020014276 _PyUnicode_STATE(*p).interned = SSTATE_INTERNED_IMMORTAL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014277 Py_INCREF(*p);
14278 }
Walter Dörwald16807132007-05-25 13:52:07 +000014279}
14280
14281PyObject *
14282PyUnicode_InternFromString(const char *cp)
14283{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014284 PyObject *s = PyUnicode_FromString(cp);
14285 if (s == NULL)
14286 return NULL;
14287 PyUnicode_InternInPlace(&s);
14288 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000014289}
14290
Alexander Belopolsky40018472011-02-26 01:02:56 +000014291void
14292_Py_ReleaseInternedUnicodeStrings(void)
Walter Dörwald16807132007-05-25 13:52:07 +000014293{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014294 PyObject *keys;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014295 PyObject *s;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014296 Py_ssize_t i, n;
14297 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000014298
Benjamin Peterson14339b62009-01-31 16:36:08 +000014299 if (interned == NULL || !PyDict_Check(interned))
14300 return;
14301 keys = PyDict_Keys(interned);
14302 if (keys == NULL || !PyList_Check(keys)) {
14303 PyErr_Clear();
14304 return;
14305 }
Walter Dörwald16807132007-05-25 13:52:07 +000014306
Benjamin Peterson14339b62009-01-31 16:36:08 +000014307 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
14308 detector, interned unicode strings are not forcibly deallocated;
14309 rather, we give them their stolen references back, and then clear
14310 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000014311
Benjamin Peterson14339b62009-01-31 16:36:08 +000014312 n = PyList_GET_SIZE(keys);
14313 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000014314 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014315 for (i = 0; i < n; i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014316 s = PyList_GET_ITEM(keys, i);
Victor Stinner6b56a7f2011-10-04 20:04:52 +020014317 if (PyUnicode_READY(s) == -1) {
14318 assert(0 && "could not ready string");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014319 fprintf(stderr, "could not ready string\n");
Victor Stinner6b56a7f2011-10-04 20:04:52 +020014320 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014321 switch (PyUnicode_CHECK_INTERNED(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014322 case SSTATE_NOT_INTERNED:
14323 /* XXX Shouldn't happen */
14324 break;
14325 case SSTATE_INTERNED_IMMORTAL:
14326 Py_REFCNT(s) += 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014327 immortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014328 break;
14329 case SSTATE_INTERNED_MORTAL:
14330 Py_REFCNT(s) += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014331 mortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014332 break;
14333 default:
14334 Py_FatalError("Inconsistent interned string state.");
14335 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014336 _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014337 }
14338 fprintf(stderr, "total size of all interned strings: "
14339 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
14340 "mortal/immortal\n", mortal_size, immortal_size);
14341 Py_DECREF(keys);
14342 PyDict_Clear(interned);
14343 Py_DECREF(interned);
14344 interned = NULL;
Walter Dörwald16807132007-05-25 13:52:07 +000014345}
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014346
14347
14348/********************* Unicode Iterator **************************/
14349
14350typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014351 PyObject_HEAD
14352 Py_ssize_t it_index;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014353 PyObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014354} unicodeiterobject;
14355
14356static void
14357unicodeiter_dealloc(unicodeiterobject *it)
14358{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014359 _PyObject_GC_UNTRACK(it);
14360 Py_XDECREF(it->it_seq);
14361 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014362}
14363
14364static int
14365unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
14366{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014367 Py_VISIT(it->it_seq);
14368 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014369}
14370
14371static PyObject *
14372unicodeiter_next(unicodeiterobject *it)
14373{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014374 PyObject *seq, *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014375
Benjamin Peterson14339b62009-01-31 16:36:08 +000014376 assert(it != NULL);
14377 seq = it->it_seq;
14378 if (seq == NULL)
14379 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020014380 assert(_PyUnicode_CHECK(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014381
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014382 if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
14383 int kind = PyUnicode_KIND(seq);
14384 void *data = PyUnicode_DATA(seq);
14385 Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
14386 item = PyUnicode_FromOrdinal(chr);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014387 if (item != NULL)
14388 ++it->it_index;
14389 return item;
14390 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014391
Benjamin Peterson14339b62009-01-31 16:36:08 +000014392 Py_DECREF(seq);
14393 it->it_seq = NULL;
14394 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014395}
14396
14397static PyObject *
14398unicodeiter_len(unicodeiterobject *it)
14399{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014400 Py_ssize_t len = 0;
14401 if (it->it_seq)
Victor Stinnerc4f281e2011-10-11 22:11:42 +020014402 len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014403 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014404}
14405
14406PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
14407
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000014408static PyObject *
14409unicodeiter_reduce(unicodeiterobject *it)
14410{
14411 if (it->it_seq != NULL) {
Antoine Pitroua7013882012-04-05 00:04:20 +020014412 return Py_BuildValue("N(O)n", _PyObject_GetBuiltin("iter"),
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000014413 it->it_seq, it->it_index);
14414 } else {
14415 PyObject *u = PyUnicode_FromUnicode(NULL, 0);
14416 if (u == NULL)
14417 return NULL;
Antoine Pitroua7013882012-04-05 00:04:20 +020014418 return Py_BuildValue("N(N)", _PyObject_GetBuiltin("iter"), u);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000014419 }
14420}
14421
14422PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
14423
14424static PyObject *
14425unicodeiter_setstate(unicodeiterobject *it, PyObject *state)
14426{
14427 Py_ssize_t index = PyLong_AsSsize_t(state);
14428 if (index == -1 && PyErr_Occurred())
14429 return NULL;
14430 if (index < 0)
14431 index = 0;
14432 it->it_index = index;
14433 Py_RETURN_NONE;
14434}
14435
14436PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
14437
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014438static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014439 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000014440 length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000014441 {"__reduce__", (PyCFunction)unicodeiter_reduce, METH_NOARGS,
14442 reduce_doc},
14443 {"__setstate__", (PyCFunction)unicodeiter_setstate, METH_O,
14444 setstate_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000014445 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014446};
14447
14448PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014449 PyVarObject_HEAD_INIT(&PyType_Type, 0)
14450 "str_iterator", /* tp_name */
14451 sizeof(unicodeiterobject), /* tp_basicsize */
14452 0, /* tp_itemsize */
14453 /* methods */
14454 (destructor)unicodeiter_dealloc, /* tp_dealloc */
14455 0, /* tp_print */
14456 0, /* tp_getattr */
14457 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000014458 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014459 0, /* tp_repr */
14460 0, /* tp_as_number */
14461 0, /* tp_as_sequence */
14462 0, /* tp_as_mapping */
14463 0, /* tp_hash */
14464 0, /* tp_call */
14465 0, /* tp_str */
14466 PyObject_GenericGetAttr, /* tp_getattro */
14467 0, /* tp_setattro */
14468 0, /* tp_as_buffer */
14469 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
14470 0, /* tp_doc */
14471 (traverseproc)unicodeiter_traverse, /* tp_traverse */
14472 0, /* tp_clear */
14473 0, /* tp_richcompare */
14474 0, /* tp_weaklistoffset */
14475 PyObject_SelfIter, /* tp_iter */
14476 (iternextfunc)unicodeiter_next, /* tp_iternext */
14477 unicodeiter_methods, /* tp_methods */
14478 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014479};
14480
14481static PyObject *
14482unicode_iter(PyObject *seq)
14483{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014484 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014485
Benjamin Peterson14339b62009-01-31 16:36:08 +000014486 if (!PyUnicode_Check(seq)) {
14487 PyErr_BadInternalCall();
14488 return NULL;
14489 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014490 if (PyUnicode_READY(seq) == -1)
14491 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014492 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
14493 if (it == NULL)
14494 return NULL;
14495 it->it_index = 0;
14496 Py_INCREF(seq);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014497 it->it_seq = seq;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014498 _PyObject_GC_TRACK(it);
14499 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014500}
14501
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010014502
14503size_t
14504Py_UNICODE_strlen(const Py_UNICODE *u)
14505{
14506 int res = 0;
14507 while(*u++)
14508 res++;
14509 return res;
14510}
14511
14512Py_UNICODE*
14513Py_UNICODE_strcpy(Py_UNICODE *s1, const Py_UNICODE *s2)
14514{
14515 Py_UNICODE *u = s1;
14516 while ((*u++ = *s2++));
14517 return s1;
14518}
14519
14520Py_UNICODE*
14521Py_UNICODE_strncpy(Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
14522{
14523 Py_UNICODE *u = s1;
14524 while ((*u++ = *s2++))
14525 if (n-- == 0)
14526 break;
14527 return s1;
14528}
14529
14530Py_UNICODE*
14531Py_UNICODE_strcat(Py_UNICODE *s1, const Py_UNICODE *s2)
14532{
14533 Py_UNICODE *u1 = s1;
14534 u1 += Py_UNICODE_strlen(u1);
14535 Py_UNICODE_strcpy(u1, s2);
14536 return s1;
14537}
14538
14539int
14540Py_UNICODE_strcmp(const Py_UNICODE *s1, const Py_UNICODE *s2)
14541{
14542 while (*s1 && *s2 && *s1 == *s2)
14543 s1++, s2++;
14544 if (*s1 && *s2)
14545 return (*s1 < *s2) ? -1 : +1;
14546 if (*s1)
14547 return 1;
14548 if (*s2)
14549 return -1;
14550 return 0;
14551}
14552
14553int
14554Py_UNICODE_strncmp(const Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
14555{
14556 register Py_UNICODE u1, u2;
14557 for (; n != 0; n--) {
14558 u1 = *s1;
14559 u2 = *s2;
14560 if (u1 != u2)
14561 return (u1 < u2) ? -1 : +1;
14562 if (u1 == '\0')
14563 return 0;
14564 s1++;
14565 s2++;
14566 }
14567 return 0;
14568}
14569
14570Py_UNICODE*
14571Py_UNICODE_strchr(const Py_UNICODE *s, Py_UNICODE c)
14572{
14573 const Py_UNICODE *p;
14574 for (p = s; *p; p++)
14575 if (*p == c)
14576 return (Py_UNICODE*)p;
14577 return NULL;
14578}
14579
14580Py_UNICODE*
14581Py_UNICODE_strrchr(const Py_UNICODE *s, Py_UNICODE c)
14582{
14583 const Py_UNICODE *p;
14584 p = s + Py_UNICODE_strlen(s);
14585 while (p != s) {
14586 p--;
14587 if (*p == c)
14588 return (Py_UNICODE*)p;
14589 }
14590 return NULL;
14591}
Victor Stinner331ea922010-08-10 16:37:20 +000014592
Victor Stinner71133ff2010-09-01 23:43:53 +000014593Py_UNICODE*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014594PyUnicode_AsUnicodeCopy(PyObject *unicode)
Victor Stinner71133ff2010-09-01 23:43:53 +000014595{
Victor Stinner577db2c2011-10-11 22:12:48 +020014596 Py_UNICODE *u, *copy;
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014597 Py_ssize_t len, size;
Victor Stinner71133ff2010-09-01 23:43:53 +000014598
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014599 if (!PyUnicode_Check(unicode)) {
14600 PyErr_BadArgument();
14601 return NULL;
14602 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014603 u = PyUnicode_AsUnicodeAndSize(unicode, &len);
Victor Stinner577db2c2011-10-11 22:12:48 +020014604 if (u == NULL)
14605 return NULL;
Victor Stinner71133ff2010-09-01 23:43:53 +000014606 /* Ensure we won't overflow the size. */
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014607 if (len > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
Victor Stinner71133ff2010-09-01 23:43:53 +000014608 PyErr_NoMemory();
14609 return NULL;
14610 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014611 size = len + 1; /* copy the null character */
Victor Stinner71133ff2010-09-01 23:43:53 +000014612 size *= sizeof(Py_UNICODE);
14613 copy = PyMem_Malloc(size);
14614 if (copy == NULL) {
14615 PyErr_NoMemory();
14616 return NULL;
14617 }
Victor Stinner577db2c2011-10-11 22:12:48 +020014618 memcpy(copy, u, size);
Victor Stinner71133ff2010-09-01 23:43:53 +000014619 return copy;
14620}
Martin v. Löwis5b222132007-06-10 09:51:05 +000014621
Georg Brandl66c221e2010-10-14 07:04:07 +000014622/* A _string module, to export formatter_parser and formatter_field_name_split
14623 to the string.Formatter class implemented in Python. */
14624
14625static PyMethodDef _string_methods[] = {
14626 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
14627 METH_O, PyDoc_STR("split the argument as a field name")},
14628 {"formatter_parser", (PyCFunction) formatter_parser,
14629 METH_O, PyDoc_STR("parse the argument as a format string")},
14630 {NULL, NULL}
14631};
14632
14633static struct PyModuleDef _string_module = {
14634 PyModuleDef_HEAD_INIT,
14635 "_string",
14636 PyDoc_STR("string helper module"),
14637 0,
14638 _string_methods,
14639 NULL,
14640 NULL,
14641 NULL,
14642 NULL
14643};
14644
14645PyMODINIT_FUNC
14646PyInit__string(void)
14647{
14648 return PyModule_Create(&_string_module);
14649}
14650
14651
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000014652#ifdef __cplusplus
14653}
14654#endif