blob: 665f03d8849d7102f597d035a42e24a1055d9cba [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{
1829 _Py_Identifier *i;
1830 for (i = static_strings; i; i = i->next) {
1831 Py_DECREF(i->object);
1832 i->object = NULL;
1833 i->next = NULL;
1834 }
1835}
1836
Benjamin Peterson0df54292012-03-26 14:50:32 -04001837/* Internal function, doesn't check maximum character */
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001838
Victor Stinnerd3f08822012-05-29 12:57:52 +02001839PyObject*
1840_PyUnicode_FromASCII(const char *buffer, Py_ssize_t size)
Victor Stinner702c7342011-10-05 13:50:52 +02001841{
Victor Stinnerd3f08822012-05-29 12:57:52 +02001842 const unsigned char *s = (const unsigned char *)buffer;
Victor Stinner785938e2011-12-11 20:09:03 +01001843 PyObject *unicode;
Victor Stinnere6b2d442011-12-11 21:54:30 +01001844 if (size == 1) {
Victor Stinner0617b6e2011-10-05 23:26:01 +02001845#ifdef Py_DEBUG
Victor Stinnere6b2d442011-12-11 21:54:30 +01001846 assert(s[0] < 128);
Victor Stinner0617b6e2011-10-05 23:26:01 +02001847#endif
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001848 return get_latin1_char(s[0]);
Victor Stinnere6b2d442011-12-11 21:54:30 +01001849 }
Victor Stinner785938e2011-12-11 20:09:03 +01001850 unicode = PyUnicode_New(size, 127);
1851 if (!unicode)
Victor Stinner702c7342011-10-05 13:50:52 +02001852 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01001853 memcpy(PyUnicode_1BYTE_DATA(unicode), s, size);
1854 assert(_PyUnicode_CheckConsistency(unicode, 1));
1855 return unicode;
Victor Stinner702c7342011-10-05 13:50:52 +02001856}
1857
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001858static Py_UCS4
1859kind_maxchar_limit(unsigned int kind)
1860{
Benjamin Petersonead6b532011-12-20 17:23:42 -06001861 switch (kind) {
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001862 case PyUnicode_1BYTE_KIND:
1863 return 0x80;
1864 case PyUnicode_2BYTE_KIND:
1865 return 0x100;
1866 case PyUnicode_4BYTE_KIND:
1867 return 0x10000;
1868 default:
1869 assert(0 && "invalid kind");
Victor Stinner8faf8212011-12-08 22:14:11 +01001870 return MAX_UNICODE;
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001871 }
1872}
1873
Victor Stinnere6abb482012-05-02 01:15:40 +02001874Py_LOCAL_INLINE(Py_UCS4)
1875align_maxchar(Py_UCS4 maxchar)
1876{
1877 if (maxchar <= 127)
1878 return 127;
1879 else if (maxchar <= 255)
1880 return 255;
1881 else if (maxchar <= 65535)
1882 return 65535;
1883 else
1884 return MAX_UNICODE;
1885}
1886
Victor Stinner702c7342011-10-05 13:50:52 +02001887static PyObject*
Victor Stinnere57b1c02011-09-28 22:20:48 +02001888_PyUnicode_FromUCS1(const unsigned char* u, Py_ssize_t size)
Mark Dickinson081dfee2009-03-18 14:47:41 +00001889{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001890 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001891 unsigned char max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001892
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001893 if (size == 0) {
1894 Py_INCREF(unicode_empty);
1895 return unicode_empty;
1896 }
1897 assert(size > 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001898 if (size == 1)
1899 return get_latin1_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001900
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001901 max_char = ucs1lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001902 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001903 if (!res)
1904 return NULL;
1905 memcpy(PyUnicode_1BYTE_DATA(res), u, size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001906 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001907 return res;
Mark Dickinson081dfee2009-03-18 14:47:41 +00001908}
1909
Victor Stinnere57b1c02011-09-28 22:20:48 +02001910static PyObject*
1911_PyUnicode_FromUCS2(const Py_UCS2 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001912{
1913 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001914 Py_UCS2 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001915
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001916 if (size == 0) {
1917 Py_INCREF(unicode_empty);
1918 return unicode_empty;
1919 }
1920 assert(size > 0);
Victor Stinnerb6cd0142012-05-03 02:17:04 +02001921 if (size == 1) {
1922 Py_UCS4 ch = u[0];
1923 if (ch < 256)
1924 return get_latin1_char((unsigned char)ch);
1925
1926 res = PyUnicode_New(1, ch);
1927 if (res == NULL)
1928 return NULL;
1929 PyUnicode_WRITE(PyUnicode_KIND(res), PyUnicode_DATA(res), 0, ch);
1930 assert(_PyUnicode_CheckConsistency(res, 1));
1931 return res;
1932 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001933
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001934 max_char = ucs2lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001935 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001936 if (!res)
1937 return NULL;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001938 if (max_char >= 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001939 memcpy(PyUnicode_2BYTE_DATA(res), u, sizeof(Py_UCS2)*size);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001940 else {
1941 _PyUnicode_CONVERT_BYTES(
1942 Py_UCS2, Py_UCS1, u, u + size, PyUnicode_1BYTE_DATA(res));
1943 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001944 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001945 return res;
1946}
1947
Victor Stinnere57b1c02011-09-28 22:20:48 +02001948static PyObject*
1949_PyUnicode_FromUCS4(const Py_UCS4 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001950{
1951 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001952 Py_UCS4 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001953
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001954 if (size == 0) {
1955 Py_INCREF(unicode_empty);
1956 return unicode_empty;
1957 }
1958 assert(size > 0);
Victor Stinnerb6cd0142012-05-03 02:17:04 +02001959 if (size == 1) {
1960 Py_UCS4 ch = u[0];
1961 if (ch < 256)
1962 return get_latin1_char((unsigned char)ch);
1963
1964 res = PyUnicode_New(1, ch);
1965 if (res == NULL)
1966 return NULL;
1967 PyUnicode_WRITE(PyUnicode_KIND(res), PyUnicode_DATA(res), 0, ch);
1968 assert(_PyUnicode_CheckConsistency(res, 1));
1969 return res;
1970 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001971
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001972 max_char = ucs4lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001973 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001974 if (!res)
1975 return NULL;
Antoine Pitrou950468e2011-10-11 22:45:48 +02001976 if (max_char < 256)
1977 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, u, u + size,
1978 PyUnicode_1BYTE_DATA(res));
1979 else if (max_char < 0x10000)
1980 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, u, u + size,
1981 PyUnicode_2BYTE_DATA(res));
1982 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001983 memcpy(PyUnicode_4BYTE_DATA(res), u, sizeof(Py_UCS4)*size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001984 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001985 return res;
1986}
1987
1988PyObject*
1989PyUnicode_FromKindAndData(int kind, const void *buffer, Py_ssize_t size)
1990{
Victor Stinnercfed46e2011-11-22 01:29:14 +01001991 if (size < 0) {
1992 PyErr_SetString(PyExc_ValueError, "size must be positive");
1993 return NULL;
1994 }
Benjamin Petersonead6b532011-12-20 17:23:42 -06001995 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001996 case PyUnicode_1BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02001997 return _PyUnicode_FromUCS1(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001998 case PyUnicode_2BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02001999 return _PyUnicode_FromUCS2(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002000 case PyUnicode_4BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002001 return _PyUnicode_FromUCS4(buffer, size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002002 default:
Victor Stinnerb9275c12011-10-05 14:01:42 +02002003 PyErr_SetString(PyExc_SystemError, "invalid kind");
2004 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002005 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002006}
2007
Victor Stinnerece58de2012-04-23 23:36:38 +02002008Py_UCS4
2009_PyUnicode_FindMaxChar(PyObject *unicode, Py_ssize_t start, Py_ssize_t end)
2010{
2011 enum PyUnicode_Kind kind;
2012 void *startptr, *endptr;
2013
2014 assert(PyUnicode_IS_READY(unicode));
2015 assert(0 <= start);
2016 assert(end <= PyUnicode_GET_LENGTH(unicode));
2017 assert(start <= end);
2018
2019 if (start == 0 && end == PyUnicode_GET_LENGTH(unicode))
2020 return PyUnicode_MAX_CHAR_VALUE(unicode);
2021
2022 if (start == end)
2023 return 127;
2024
Victor Stinner94d558b2012-04-27 22:26:58 +02002025 if (PyUnicode_IS_ASCII(unicode))
2026 return 127;
2027
Victor Stinnerece58de2012-04-23 23:36:38 +02002028 kind = PyUnicode_KIND(unicode);
Benjamin Petersonf3b7d862012-04-23 18:07:01 -04002029 startptr = PyUnicode_DATA(unicode);
Benjamin Petersonb9f4c9d2012-04-23 21:45:40 -04002030 endptr = (char *)startptr + end * kind;
2031 startptr = (char *)startptr + start * kind;
Benjamin Peterson2844a7a2012-04-23 18:00:25 -04002032 switch(kind) {
2033 case PyUnicode_1BYTE_KIND:
2034 return ucs1lib_find_max_char(startptr, endptr);
2035 case PyUnicode_2BYTE_KIND:
2036 return ucs2lib_find_max_char(startptr, endptr);
2037 case PyUnicode_4BYTE_KIND:
2038 return ucs4lib_find_max_char(startptr, endptr);
Victor Stinnerece58de2012-04-23 23:36:38 +02002039 default:
Benjamin Peterson2844a7a2012-04-23 18:00:25 -04002040 assert(0);
2041 return 0;
Victor Stinnerece58de2012-04-23 23:36:38 +02002042 }
2043}
2044
Victor Stinner25a4b292011-10-06 12:31:55 +02002045/* Ensure that a string uses the most efficient storage, if it is not the
2046 case: create a new string with of the right kind. Write NULL into *p_unicode
2047 on error. */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02002048static void
Victor Stinner25a4b292011-10-06 12:31:55 +02002049unicode_adjust_maxchar(PyObject **p_unicode)
2050{
2051 PyObject *unicode, *copy;
2052 Py_UCS4 max_char;
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002053 Py_ssize_t len;
Victor Stinner25a4b292011-10-06 12:31:55 +02002054 unsigned int kind;
2055
2056 assert(p_unicode != NULL);
2057 unicode = *p_unicode;
2058 assert(PyUnicode_IS_READY(unicode));
2059 if (PyUnicode_IS_ASCII(unicode))
2060 return;
2061
2062 len = PyUnicode_GET_LENGTH(unicode);
2063 kind = PyUnicode_KIND(unicode);
2064 if (kind == PyUnicode_1BYTE_KIND) {
2065 const Py_UCS1 *u = PyUnicode_1BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002066 max_char = ucs1lib_find_max_char(u, u + len);
2067 if (max_char >= 128)
2068 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002069 }
2070 else if (kind == PyUnicode_2BYTE_KIND) {
2071 const Py_UCS2 *u = PyUnicode_2BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002072 max_char = ucs2lib_find_max_char(u, u + len);
2073 if (max_char >= 256)
2074 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002075 }
2076 else {
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002077 const Py_UCS4 *u = PyUnicode_4BYTE_DATA(unicode);
Victor Stinner25a4b292011-10-06 12:31:55 +02002078 assert(kind == PyUnicode_4BYTE_KIND);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002079 max_char = ucs4lib_find_max_char(u, u + len);
2080 if (max_char >= 0x10000)
2081 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002082 }
Victor Stinner25a4b292011-10-06 12:31:55 +02002083 copy = PyUnicode_New(len, max_char);
Victor Stinnerca439ee2012-06-16 03:17:34 +02002084 if (copy != NULL)
2085 _PyUnicode_FastCopyCharacters(copy, 0, unicode, 0, len);
Victor Stinner25a4b292011-10-06 12:31:55 +02002086 Py_DECREF(unicode);
2087 *p_unicode = copy;
2088}
2089
Victor Stinner034f6cf2011-09-30 02:26:44 +02002090PyObject*
Victor Stinnerbf6e5602011-12-12 01:53:47 +01002091_PyUnicode_Copy(PyObject *unicode)
Victor Stinner034f6cf2011-09-30 02:26:44 +02002092{
Victor Stinner87af4f22011-11-21 23:03:47 +01002093 Py_ssize_t length;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002094 PyObject *copy;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002095
Victor Stinner034f6cf2011-09-30 02:26:44 +02002096 if (!PyUnicode_Check(unicode)) {
2097 PyErr_BadInternalCall();
2098 return NULL;
2099 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05002100 if (PyUnicode_READY(unicode) == -1)
Victor Stinner034f6cf2011-09-30 02:26:44 +02002101 return NULL;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002102
Victor Stinner87af4f22011-11-21 23:03:47 +01002103 length = PyUnicode_GET_LENGTH(unicode);
2104 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002105 if (!copy)
2106 return NULL;
2107 assert(PyUnicode_KIND(copy) == PyUnicode_KIND(unicode));
2108
Victor Stinner87af4f22011-11-21 23:03:47 +01002109 Py_MEMCPY(PyUnicode_DATA(copy), PyUnicode_DATA(unicode),
2110 length * PyUnicode_KIND(unicode));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002111 assert(_PyUnicode_CheckConsistency(copy, 1));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002112 return copy;
Victor Stinner034f6cf2011-09-30 02:26:44 +02002113}
2114
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002115
Victor Stinnerbc603d12011-10-02 01:00:40 +02002116/* Widen Unicode objects to larger buffers. Don't write terminating null
2117 character. Return NULL on error. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002118
2119void*
2120_PyUnicode_AsKind(PyObject *s, unsigned int kind)
2121{
Victor Stinnerbc603d12011-10-02 01:00:40 +02002122 Py_ssize_t len;
2123 void *result;
2124 unsigned int skind;
2125
Benjamin Petersonbac79492012-01-14 13:34:47 -05002126 if (PyUnicode_READY(s) == -1)
Victor Stinnerbc603d12011-10-02 01:00:40 +02002127 return NULL;
2128
2129 len = PyUnicode_GET_LENGTH(s);
2130 skind = PyUnicode_KIND(s);
2131 if (skind >= kind) {
Victor Stinner01698042011-10-04 00:04:26 +02002132 PyErr_SetString(PyExc_SystemError, "invalid widening attempt");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002133 return NULL;
2134 }
Benjamin Petersonead6b532011-12-20 17:23:42 -06002135 switch (kind) {
Victor Stinnerbc603d12011-10-02 01:00:40 +02002136 case PyUnicode_2BYTE_KIND:
2137 result = PyMem_Malloc(len * sizeof(Py_UCS2));
2138 if (!result)
2139 return PyErr_NoMemory();
2140 assert(skind == PyUnicode_1BYTE_KIND);
2141 _PyUnicode_CONVERT_BYTES(
2142 Py_UCS1, Py_UCS2,
2143 PyUnicode_1BYTE_DATA(s),
2144 PyUnicode_1BYTE_DATA(s) + len,
2145 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002146 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002147 case PyUnicode_4BYTE_KIND:
2148 result = PyMem_Malloc(len * sizeof(Py_UCS4));
2149 if (!result)
2150 return PyErr_NoMemory();
2151 if (skind == PyUnicode_2BYTE_KIND) {
2152 _PyUnicode_CONVERT_BYTES(
2153 Py_UCS2, Py_UCS4,
2154 PyUnicode_2BYTE_DATA(s),
2155 PyUnicode_2BYTE_DATA(s) + len,
2156 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002157 }
Victor Stinnerbc603d12011-10-02 01:00:40 +02002158 else {
2159 assert(skind == PyUnicode_1BYTE_KIND);
2160 _PyUnicode_CONVERT_BYTES(
2161 Py_UCS1, Py_UCS4,
2162 PyUnicode_1BYTE_DATA(s),
2163 PyUnicode_1BYTE_DATA(s) + len,
2164 result);
2165 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002166 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002167 default:
2168 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002169 }
Victor Stinner01698042011-10-04 00:04:26 +02002170 PyErr_SetString(PyExc_SystemError, "invalid kind");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002171 return NULL;
2172}
2173
2174static Py_UCS4*
2175as_ucs4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2176 int copy_null)
2177{
2178 int kind;
2179 void *data;
2180 Py_ssize_t len, targetlen;
2181 if (PyUnicode_READY(string) == -1)
2182 return NULL;
2183 kind = PyUnicode_KIND(string);
2184 data = PyUnicode_DATA(string);
2185 len = PyUnicode_GET_LENGTH(string);
2186 targetlen = len;
2187 if (copy_null)
2188 targetlen++;
2189 if (!target) {
2190 if (PY_SSIZE_T_MAX / sizeof(Py_UCS4) < targetlen) {
2191 PyErr_NoMemory();
2192 return NULL;
2193 }
2194 target = PyMem_Malloc(targetlen * sizeof(Py_UCS4));
2195 if (!target) {
2196 PyErr_NoMemory();
2197 return NULL;
2198 }
2199 }
2200 else {
2201 if (targetsize < targetlen) {
2202 PyErr_Format(PyExc_SystemError,
2203 "string is longer than the buffer");
2204 if (copy_null && 0 < targetsize)
2205 target[0] = 0;
2206 return NULL;
2207 }
2208 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002209 if (kind == PyUnicode_1BYTE_KIND) {
2210 Py_UCS1 *start = (Py_UCS1 *) data;
2211 _PyUnicode_CONVERT_BYTES(Py_UCS1, Py_UCS4, start, start + len, target);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002212 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002213 else if (kind == PyUnicode_2BYTE_KIND) {
2214 Py_UCS2 *start = (Py_UCS2 *) data;
2215 _PyUnicode_CONVERT_BYTES(Py_UCS2, Py_UCS4, start, start + len, target);
2216 }
2217 else {
2218 assert(kind == PyUnicode_4BYTE_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002219 Py_MEMCPY(target, data, len * sizeof(Py_UCS4));
Antoine Pitrou950468e2011-10-11 22:45:48 +02002220 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002221 if (copy_null)
2222 target[len] = 0;
2223 return target;
2224}
2225
2226Py_UCS4*
2227PyUnicode_AsUCS4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2228 int copy_null)
2229{
Antoine Pitroude20b0b2011-11-10 21:47:38 +01002230 if (target == NULL || targetsize < 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002231 PyErr_BadInternalCall();
2232 return NULL;
2233 }
2234 return as_ucs4(string, target, targetsize, copy_null);
2235}
2236
2237Py_UCS4*
2238PyUnicode_AsUCS4Copy(PyObject *string)
2239{
2240 return as_ucs4(string, NULL, 0, 1);
2241}
2242
2243#ifdef HAVE_WCHAR_H
Mark Dickinson081dfee2009-03-18 14:47:41 +00002244
Alexander Belopolsky40018472011-02-26 01:02:56 +00002245PyObject *
2246PyUnicode_FromWideChar(register const wchar_t *w, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002247{
Guido van Rossumd57fd912000-03-10 22:53:23 +00002248 if (w == NULL) {
Victor Stinner382955f2011-12-11 21:44:00 +01002249 if (size == 0) {
2250 Py_INCREF(unicode_empty);
2251 return unicode_empty;
2252 }
Benjamin Peterson29060642009-01-31 22:14:21 +00002253 PyErr_BadInternalCall();
2254 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002255 }
2256
Martin v. Löwis790465f2008-04-05 20:41:37 +00002257 if (size == -1) {
2258 size = wcslen(w);
2259 }
2260
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002261 return PyUnicode_FromUnicode(w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002262}
2263
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002264#endif /* HAVE_WCHAR_H */
Mark Dickinson081dfee2009-03-18 14:47:41 +00002265
Walter Dörwald346737f2007-05-31 10:44:43 +00002266static void
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002267makefmt(char *fmt, int longflag, int longlongflag, int size_tflag,
2268 int zeropad, int width, int precision, char c)
Walter Dörwald346737f2007-05-31 10:44:43 +00002269{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002270 *fmt++ = '%';
2271 if (width) {
2272 if (zeropad)
2273 *fmt++ = '0';
2274 fmt += sprintf(fmt, "%d", width);
2275 }
2276 if (precision)
2277 fmt += sprintf(fmt, ".%d", precision);
2278 if (longflag)
2279 *fmt++ = 'l';
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002280 else if (longlongflag) {
2281 /* longlongflag should only ever be nonzero on machines with
2282 HAVE_LONG_LONG defined */
2283#ifdef HAVE_LONG_LONG
2284 char *f = PY_FORMAT_LONG_LONG;
2285 while (*f)
2286 *fmt++ = *f++;
2287#else
2288 /* we shouldn't ever get here */
2289 assert(0);
2290 *fmt++ = 'l';
2291#endif
2292 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002293 else if (size_tflag) {
2294 char *f = PY_FORMAT_SIZE_T;
2295 while (*f)
2296 *fmt++ = *f++;
2297 }
2298 *fmt++ = c;
2299 *fmt = '\0';
Walter Dörwald346737f2007-05-31 10:44:43 +00002300}
2301
Victor Stinner96865452011-03-01 23:44:09 +00002302/* helper for PyUnicode_FromFormatV() */
2303
2304static const char*
2305parse_format_flags(const char *f,
2306 int *p_width, int *p_precision,
2307 int *p_longflag, int *p_longlongflag, int *p_size_tflag)
2308{
2309 int width, precision, longflag, longlongflag, size_tflag;
2310
2311 /* parse the width.precision part, e.g. "%2.5s" => width=2, precision=5 */
2312 f++;
2313 width = 0;
2314 while (Py_ISDIGIT((unsigned)*f))
2315 width = (width*10) + *f++ - '0';
2316 precision = 0;
2317 if (*f == '.') {
2318 f++;
2319 while (Py_ISDIGIT((unsigned)*f))
2320 precision = (precision*10) + *f++ - '0';
2321 if (*f == '%') {
2322 /* "%.3%s" => f points to "3" */
2323 f--;
2324 }
2325 }
2326 if (*f == '\0') {
2327 /* bogus format "%.1" => go backward, f points to "1" */
2328 f--;
2329 }
2330 if (p_width != NULL)
2331 *p_width = width;
2332 if (p_precision != NULL)
2333 *p_precision = precision;
2334
2335 /* Handle %ld, %lu, %lld and %llu. */
2336 longflag = 0;
2337 longlongflag = 0;
Victor Stinnere7faec12011-03-02 00:01:53 +00002338 size_tflag = 0;
Victor Stinner96865452011-03-01 23:44:09 +00002339
2340 if (*f == 'l') {
Victor Stinner6d970f42011-03-02 00:04:25 +00002341 if (f[1] == 'd' || f[1] == 'u' || f[1] == 'i') {
Victor Stinner96865452011-03-01 23:44:09 +00002342 longflag = 1;
2343 ++f;
2344 }
2345#ifdef HAVE_LONG_LONG
2346 else if (f[1] == 'l' &&
Victor Stinner6d970f42011-03-02 00:04:25 +00002347 (f[2] == 'd' || f[2] == 'u' || f[2] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002348 longlongflag = 1;
2349 f += 2;
2350 }
2351#endif
2352 }
2353 /* handle the size_t flag. */
Victor Stinner6d970f42011-03-02 00:04:25 +00002354 else if (*f == 'z' && (f[1] == 'd' || f[1] == 'u' || f[1] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002355 size_tflag = 1;
2356 ++f;
2357 }
2358 if (p_longflag != NULL)
2359 *p_longflag = longflag;
2360 if (p_longlongflag != NULL)
2361 *p_longlongflag = longlongflag;
2362 if (p_size_tflag != NULL)
2363 *p_size_tflag = size_tflag;
2364 return f;
2365}
2366
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002367/* maximum number of characters required for output of %ld. 21 characters
2368 allows for 64-bit integers (in decimal) and an optional sign. */
2369#define MAX_LONG_CHARS 21
2370/* maximum number of characters required for output of %lld.
2371 We need at most ceil(log10(256)*SIZEOF_LONG_LONG) digits,
2372 plus 1 for the sign. 53/22 is an upper bound for log10(256). */
2373#define MAX_LONG_LONG_CHARS (2 + (SIZEOF_LONG_LONG*53-1) / 22)
2374
Walter Dörwaldd2034312007-05-18 16:29:38 +00002375PyObject *
2376PyUnicode_FromFormatV(const char *format, va_list vargs)
2377{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002378 va_list count;
2379 Py_ssize_t callcount = 0;
2380 PyObject **callresults = NULL;
2381 PyObject **callresult = NULL;
2382 Py_ssize_t n = 0;
2383 int width = 0;
2384 int precision = 0;
2385 int zeropad;
2386 const char* f;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002387 PyObject *string;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002388 /* used by sprintf */
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002389 char fmt[61]; /* should be enough for %0width.precisionlld */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002390 Py_UCS4 maxchar = 127; /* result is ASCII by default */
2391 Py_UCS4 argmaxchar;
2392 Py_ssize_t numbersize = 0;
2393 char *numberresults = NULL;
2394 char *numberresult = NULL;
2395 Py_ssize_t i;
2396 int kind;
2397 void *data;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002398
Victor Stinner4a2b7a12010-08-13 14:03:48 +00002399 Py_VA_COPY(count, vargs);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002400 /* step 1: count the number of %S/%R/%A/%s format specifications
2401 * (we call PyObject_Str()/PyObject_Repr()/PyObject_ASCII()/
2402 * PyUnicode_DecodeUTF8() for these objects once during step 3 and put the
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002403 * result in an array)
Georg Brandl7597add2011-10-05 16:36:47 +02002404 * also estimate a upper bound for all the number formats in the string,
2405 * numbers will be formatted in step 3 and be kept in a '\0'-separated
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002406 * buffer before putting everything together. */
Benjamin Peterson14339b62009-01-31 16:36:08 +00002407 for (f = format; *f; f++) {
2408 if (*f == '%') {
Victor Stinner96865452011-03-01 23:44:09 +00002409 int longlongflag;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002410 /* skip width or width.precision (eg. "1.2" of "%1.2f") */
2411 f = parse_format_flags(f, &width, NULL, NULL, &longlongflag, NULL);
2412 if (*f == 's' || *f=='S' || *f=='R' || *f=='A' || *f=='V')
2413 ++callcount;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002414
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002415 else if (*f == 'd' || *f=='u' || *f=='i' || *f=='x' || *f=='p') {
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002416#ifdef HAVE_LONG_LONG
2417 if (longlongflag) {
2418 if (width < MAX_LONG_LONG_CHARS)
2419 width = MAX_LONG_LONG_CHARS;
2420 }
2421 else
2422#endif
2423 /* MAX_LONG_CHARS is enough to hold a 64-bit integer,
2424 including sign. Decimal takes the most space. This
2425 isn't enough for octal. If a width is specified we
2426 need more (which we allocate later). */
2427 if (width < MAX_LONG_CHARS)
2428 width = MAX_LONG_CHARS;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002429
2430 /* account for the size + '\0' to separate numbers
2431 inside of the numberresults buffer */
2432 numbersize += (width + 1);
2433 }
2434 }
2435 else if ((unsigned char)*f > 127) {
2436 PyErr_Format(PyExc_ValueError,
2437 "PyUnicode_FromFormatV() expects an ASCII-encoded format "
2438 "string, got a non-ASCII byte: 0x%02x",
2439 (unsigned char)*f);
2440 return NULL;
2441 }
2442 }
2443 /* step 2: allocate memory for the results of
2444 * PyObject_Str()/PyObject_Repr()/PyUnicode_DecodeUTF8() calls */
2445 if (callcount) {
2446 callresults = PyObject_Malloc(sizeof(PyObject *) * callcount);
2447 if (!callresults) {
2448 PyErr_NoMemory();
2449 return NULL;
2450 }
2451 callresult = callresults;
2452 }
2453 /* step 2.5: allocate memory for the results of formating numbers */
2454 if (numbersize) {
2455 numberresults = PyObject_Malloc(numbersize);
2456 if (!numberresults) {
2457 PyErr_NoMemory();
2458 goto fail;
2459 }
2460 numberresult = numberresults;
2461 }
2462
2463 /* step 3: format numbers and figure out how large a buffer we need */
2464 for (f = format; *f; f++) {
2465 if (*f == '%') {
2466 const char* p;
2467 int longflag;
2468 int longlongflag;
2469 int size_tflag;
2470 int numprinted;
2471
2472 p = f;
2473 zeropad = (f[1] == '0');
2474 f = parse_format_flags(f, &width, &precision,
2475 &longflag, &longlongflag, &size_tflag);
2476 switch (*f) {
2477 case 'c':
2478 {
2479 Py_UCS4 ordinal = va_arg(count, int);
Victor Stinnere6abb482012-05-02 01:15:40 +02002480 maxchar = MAX_MAXCHAR(maxchar, ordinal);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002481 n++;
2482 break;
2483 }
2484 case '%':
2485 n++;
2486 break;
2487 case 'i':
2488 case 'd':
2489 makefmt(fmt, longflag, longlongflag, size_tflag, zeropad,
2490 width, precision, *f);
2491 if (longflag)
2492 numprinted = sprintf(numberresult, fmt,
2493 va_arg(count, long));
2494#ifdef HAVE_LONG_LONG
2495 else if (longlongflag)
2496 numprinted = sprintf(numberresult, fmt,
2497 va_arg(count, PY_LONG_LONG));
2498#endif
2499 else if (size_tflag)
2500 numprinted = sprintf(numberresult, fmt,
2501 va_arg(count, Py_ssize_t));
2502 else
2503 numprinted = sprintf(numberresult, fmt,
2504 va_arg(count, int));
2505 n += numprinted;
2506 /* advance by +1 to skip over the '\0' */
2507 numberresult += (numprinted + 1);
2508 assert(*(numberresult - 1) == '\0');
2509 assert(*(numberresult - 2) != '\0');
2510 assert(numprinted >= 0);
2511 assert(numberresult <= numberresults + numbersize);
2512 break;
2513 case 'u':
2514 makefmt(fmt, longflag, longlongflag, size_tflag, zeropad,
2515 width, precision, 'u');
2516 if (longflag)
2517 numprinted = sprintf(numberresult, fmt,
2518 va_arg(count, unsigned long));
2519#ifdef HAVE_LONG_LONG
2520 else if (longlongflag)
2521 numprinted = sprintf(numberresult, fmt,
2522 va_arg(count, unsigned PY_LONG_LONG));
2523#endif
2524 else if (size_tflag)
2525 numprinted = sprintf(numberresult, fmt,
2526 va_arg(count, size_t));
2527 else
2528 numprinted = sprintf(numberresult, fmt,
2529 va_arg(count, unsigned int));
2530 n += numprinted;
2531 numberresult += (numprinted + 1);
2532 assert(*(numberresult - 1) == '\0');
2533 assert(*(numberresult - 2) != '\0');
2534 assert(numprinted >= 0);
2535 assert(numberresult <= numberresults + numbersize);
2536 break;
2537 case 'x':
2538 makefmt(fmt, 0, 0, 0, zeropad, width, precision, 'x');
2539 numprinted = sprintf(numberresult, fmt, va_arg(count, int));
2540 n += numprinted;
2541 numberresult += (numprinted + 1);
2542 assert(*(numberresult - 1) == '\0');
2543 assert(*(numberresult - 2) != '\0');
2544 assert(numprinted >= 0);
2545 assert(numberresult <= numberresults + numbersize);
2546 break;
2547 case 'p':
2548 numprinted = sprintf(numberresult, "%p", va_arg(count, void*));
2549 /* %p is ill-defined: ensure leading 0x. */
2550 if (numberresult[1] == 'X')
2551 numberresult[1] = 'x';
2552 else if (numberresult[1] != 'x') {
2553 memmove(numberresult + 2, numberresult,
2554 strlen(numberresult) + 1);
2555 numberresult[0] = '0';
2556 numberresult[1] = 'x';
2557 numprinted += 2;
2558 }
2559 n += numprinted;
2560 numberresult += (numprinted + 1);
2561 assert(*(numberresult - 1) == '\0');
2562 assert(*(numberresult - 2) != '\0');
2563 assert(numprinted >= 0);
2564 assert(numberresult <= numberresults + numbersize);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002565 break;
2566 case 's':
2567 {
2568 /* UTF-8 */
Georg Brandl780b2a62009-05-05 09:19:59 +00002569 const char *s = va_arg(count, const char*);
Victor Stinnera1d12bb2011-12-11 21:53:09 +01002570 PyObject *str = PyUnicode_DecodeUTF8Stateful(s, strlen(s), "replace", NULL);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002571 if (!str)
2572 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002573 /* since PyUnicode_DecodeUTF8 returns already flexible
2574 unicode objects, there is no need to call ready on them */
2575 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str);
Victor Stinnere6abb482012-05-02 01:15:40 +02002576 maxchar = MAX_MAXCHAR(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002577 n += PyUnicode_GET_LENGTH(str);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002578 /* Remember the str and switch to the next slot */
2579 *callresult++ = str;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002580 break;
2581 }
2582 case 'U':
2583 {
2584 PyObject *obj = va_arg(count, PyObject *);
Victor Stinner910337b2011-10-03 03:20:16 +02002585 assert(obj && _PyUnicode_CHECK(obj));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002586 if (PyUnicode_READY(obj) == -1)
2587 goto fail;
2588 argmaxchar = PyUnicode_MAX_CHAR_VALUE(obj);
Victor Stinnere6abb482012-05-02 01:15:40 +02002589 maxchar = MAX_MAXCHAR(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002590 n += PyUnicode_GET_LENGTH(obj);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002591 break;
2592 }
2593 case 'V':
2594 {
2595 PyObject *obj = va_arg(count, PyObject *);
2596 const char *str = va_arg(count, const char *);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002597 PyObject *str_obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002598 assert(obj || str);
Victor Stinner910337b2011-10-03 03:20:16 +02002599 assert(!obj || _PyUnicode_CHECK(obj));
Victor Stinner2512a8b2011-03-01 22:46:52 +00002600 if (obj) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002601 if (PyUnicode_READY(obj) == -1)
2602 goto fail;
2603 argmaxchar = PyUnicode_MAX_CHAR_VALUE(obj);
Victor Stinnere6abb482012-05-02 01:15:40 +02002604 maxchar = MAX_MAXCHAR(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002605 n += PyUnicode_GET_LENGTH(obj);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002606 *callresult++ = NULL;
2607 }
2608 else {
Victor Stinnera1d12bb2011-12-11 21:53:09 +01002609 str_obj = PyUnicode_DecodeUTF8Stateful(str, strlen(str), "replace", NULL);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002610 if (!str_obj)
2611 goto fail;
Benjamin Petersonbac79492012-01-14 13:34:47 -05002612 if (PyUnicode_READY(str_obj) == -1) {
Victor Stinnere1335c72011-10-04 20:53:03 +02002613 Py_DECREF(str_obj);
2614 goto fail;
2615 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002616 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str_obj);
Victor Stinnere6abb482012-05-02 01:15:40 +02002617 maxchar = MAX_MAXCHAR(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002618 n += PyUnicode_GET_LENGTH(str_obj);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002619 *callresult++ = str_obj;
2620 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002621 break;
2622 }
2623 case 'S':
2624 {
2625 PyObject *obj = va_arg(count, PyObject *);
2626 PyObject *str;
2627 assert(obj);
2628 str = PyObject_Str(obj);
Benjamin Petersonc8d8b882012-01-14 13:37:31 -05002629 if (!str)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002630 goto fail;
Benjamin Petersonc8d8b882012-01-14 13:37:31 -05002631 if (PyUnicode_READY(str) == -1) {
2632 Py_DECREF(str);
2633 goto fail;
2634 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002635 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str);
Victor Stinnere6abb482012-05-02 01:15:40 +02002636 maxchar = MAX_MAXCHAR(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002637 n += PyUnicode_GET_LENGTH(str);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002638 /* Remember the str and switch to the next slot */
2639 *callresult++ = str;
2640 break;
2641 }
2642 case 'R':
2643 {
2644 PyObject *obj = va_arg(count, PyObject *);
2645 PyObject *repr;
2646 assert(obj);
2647 repr = PyObject_Repr(obj);
Benjamin Petersonc8d8b882012-01-14 13:37:31 -05002648 if (!repr)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002649 goto fail;
Benjamin Petersonc8d8b882012-01-14 13:37:31 -05002650 if (PyUnicode_READY(repr) == -1) {
2651 Py_DECREF(repr);
2652 goto fail;
2653 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002654 argmaxchar = PyUnicode_MAX_CHAR_VALUE(repr);
Victor Stinnere6abb482012-05-02 01:15:40 +02002655 maxchar = MAX_MAXCHAR(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002656 n += PyUnicode_GET_LENGTH(repr);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002657 /* Remember the repr and switch to the next slot */
2658 *callresult++ = repr;
2659 break;
2660 }
2661 case 'A':
2662 {
2663 PyObject *obj = va_arg(count, PyObject *);
2664 PyObject *ascii;
2665 assert(obj);
2666 ascii = PyObject_ASCII(obj);
Benjamin Petersonc8d8b882012-01-14 13:37:31 -05002667 if (!ascii)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002668 goto fail;
Benjamin Petersonc8d8b882012-01-14 13:37:31 -05002669 if (PyUnicode_READY(ascii) == -1) {
2670 Py_DECREF(ascii);
2671 goto fail;
2672 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002673 argmaxchar = PyUnicode_MAX_CHAR_VALUE(ascii);
Victor Stinnere6abb482012-05-02 01:15:40 +02002674 maxchar = MAX_MAXCHAR(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002675 n += PyUnicode_GET_LENGTH(ascii);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002676 /* Remember the repr and switch to the next slot */
2677 *callresult++ = ascii;
2678 break;
2679 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002680 default:
2681 /* if we stumble upon an unknown
2682 formatting code, copy the rest of
2683 the format string to the output
2684 string. (we cannot just skip the
2685 code, since there's no way to know
2686 what's in the argument list) */
2687 n += strlen(p);
2688 goto expand;
2689 }
2690 } else
2691 n++;
2692 }
Benjamin Peterson29060642009-01-31 22:14:21 +00002693 expand:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002694 /* step 4: fill the buffer */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002695 /* Since we've analyzed how much space we need,
Benjamin Peterson14339b62009-01-31 16:36:08 +00002696 we don't have to resize the string.
2697 There can be no errors beyond this point. */
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002698 string = PyUnicode_New(n, maxchar);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002699 if (!string)
2700 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002701 kind = PyUnicode_KIND(string);
2702 data = PyUnicode_DATA(string);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002703 callresult = callresults;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002704 numberresult = numberresults;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002705
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002706 for (i = 0, f = format; *f; f++) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00002707 if (*f == '%') {
Victor Stinner96865452011-03-01 23:44:09 +00002708 const char* p;
Victor Stinner96865452011-03-01 23:44:09 +00002709
2710 p = f;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002711 f = parse_format_flags(f, NULL, NULL, NULL, NULL, NULL);
2712 /* checking for == because the last argument could be a empty
2713 string, which causes i to point to end, the assert at the end of
2714 the loop */
2715 assert(i <= PyUnicode_GET_LENGTH(string));
Walter Dörwaldd2034312007-05-18 16:29:38 +00002716
Benjamin Peterson14339b62009-01-31 16:36:08 +00002717 switch (*f) {
2718 case 'c':
Victor Stinner5ed8b2c2011-02-21 21:13:44 +00002719 {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002720 const int ordinal = va_arg(vargs, int);
2721 PyUnicode_WRITE(kind, data, i++, ordinal);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002722 break;
Victor Stinner5ed8b2c2011-02-21 21:13:44 +00002723 }
Victor Stinner6d970f42011-03-02 00:04:25 +00002724 case 'i':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002725 case 'd':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002726 case 'u':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002727 case 'x':
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002728 case 'p':
Victor Stinnerc5166102012-02-22 13:55:02 +01002729 {
Victor Stinner184252a2012-06-16 02:57:41 +02002730 Py_ssize_t len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002731 /* unused, since we already have the result */
2732 if (*f == 'p')
2733 (void) va_arg(vargs, void *);
2734 else
2735 (void) va_arg(vargs, int);
2736 /* extract the result from numberresults and append. */
Victor Stinner184252a2012-06-16 02:57:41 +02002737 len = strlen(numberresult);
2738 unicode_write_cstr(string, i, numberresult, len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002739 /* skip over the separating '\0' */
Victor Stinner184252a2012-06-16 02:57:41 +02002740 i += len;
2741 numberresult += len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002742 assert(*numberresult == '\0');
2743 numberresult++;
2744 assert(numberresult <= numberresults + numbersize);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002745 break;
Victor Stinnerc5166102012-02-22 13:55:02 +01002746 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002747 case 's':
2748 {
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002749 /* unused, since we already have the result */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002750 Py_ssize_t size;
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002751 (void) va_arg(vargs, char *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002752 size = PyUnicode_GET_LENGTH(*callresult);
2753 assert(PyUnicode_KIND(*callresult) <= PyUnicode_KIND(string));
Victor Stinnerd3f08822012-05-29 12:57:52 +02002754 _PyUnicode_FastCopyCharacters(string, i, *callresult, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002755 i += size;
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002756 /* We're done with the unicode()/repr() => forget it */
2757 Py_DECREF(*callresult);
2758 /* switch to next unicode()/repr() result */
2759 ++callresult;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002760 break;
2761 }
2762 case 'U':
2763 {
2764 PyObject *obj = va_arg(vargs, PyObject *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002765 Py_ssize_t size;
2766 assert(PyUnicode_KIND(obj) <= PyUnicode_KIND(string));
2767 size = PyUnicode_GET_LENGTH(obj);
Victor Stinnerd3f08822012-05-29 12:57:52 +02002768 _PyUnicode_FastCopyCharacters(string, i, obj, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002769 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002770 break;
2771 }
2772 case 'V':
2773 {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002774 Py_ssize_t size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002775 PyObject *obj = va_arg(vargs, PyObject *);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002776 va_arg(vargs, const char *);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002777 if (obj) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002778 size = PyUnicode_GET_LENGTH(obj);
2779 assert(PyUnicode_KIND(obj) <= PyUnicode_KIND(string));
Victor Stinnerd3f08822012-05-29 12:57:52 +02002780 _PyUnicode_FastCopyCharacters(string, i, obj, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002781 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002782 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002783 size = PyUnicode_GET_LENGTH(*callresult);
2784 assert(PyUnicode_KIND(*callresult) <=
2785 PyUnicode_KIND(string));
Victor Stinnerd3f08822012-05-29 12:57:52 +02002786 _PyUnicode_FastCopyCharacters(string, i, *callresult, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002787 i += size;
Victor Stinner2512a8b2011-03-01 22:46:52 +00002788 Py_DECREF(*callresult);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002789 }
Victor Stinner2512a8b2011-03-01 22:46:52 +00002790 ++callresult;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002791 break;
2792 }
2793 case 'S':
2794 case 'R':
Victor Stinner9a909002010-10-18 20:59:24 +00002795 case 'A':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002796 {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002797 Py_ssize_t size = PyUnicode_GET_LENGTH(*callresult);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002798 /* unused, since we already have the result */
2799 (void) va_arg(vargs, PyObject *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002800 assert(PyUnicode_KIND(*callresult) <= PyUnicode_KIND(string));
Victor Stinnerd3f08822012-05-29 12:57:52 +02002801 _PyUnicode_FastCopyCharacters(string, i, *callresult, 0, size);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002802 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002803 /* We're done with the unicode()/repr() => forget it */
2804 Py_DECREF(*callresult);
2805 /* switch to next unicode()/repr() result */
2806 ++callresult;
2807 break;
2808 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002809 case '%':
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002810 PyUnicode_WRITE(kind, data, i++, '%');
Benjamin Peterson14339b62009-01-31 16:36:08 +00002811 break;
2812 default:
Victor Stinner184252a2012-06-16 02:57:41 +02002813 {
2814 Py_ssize_t len = strlen(p);
2815 unicode_write_cstr(string, i, p, len);
2816 i += len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002817 assert(i == PyUnicode_GET_LENGTH(string));
Benjamin Peterson14339b62009-01-31 16:36:08 +00002818 goto end;
2819 }
Victor Stinner184252a2012-06-16 02:57:41 +02002820 }
Victor Stinner1205f272010-09-11 00:54:47 +00002821 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002822 else {
2823 assert(i < PyUnicode_GET_LENGTH(string));
2824 PyUnicode_WRITE(kind, data, i++, *f);
2825 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002826 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002827 assert(i == PyUnicode_GET_LENGTH(string));
Walter Dörwaldd2034312007-05-18 16:29:38 +00002828
Benjamin Peterson29060642009-01-31 22:14:21 +00002829 end:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002830 if (callresults)
2831 PyObject_Free(callresults);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002832 if (numberresults)
2833 PyObject_Free(numberresults);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002834 return unicode_result(string);
Benjamin Peterson29060642009-01-31 22:14:21 +00002835 fail:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002836 if (callresults) {
2837 PyObject **callresult2 = callresults;
2838 while (callresult2 < callresult) {
Victor Stinner2512a8b2011-03-01 22:46:52 +00002839 Py_XDECREF(*callresult2);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002840 ++callresult2;
2841 }
2842 PyObject_Free(callresults);
2843 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002844 if (numberresults)
2845 PyObject_Free(numberresults);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002846 return NULL;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002847}
2848
Walter Dörwaldd2034312007-05-18 16:29:38 +00002849PyObject *
2850PyUnicode_FromFormat(const char *format, ...)
2851{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002852 PyObject* ret;
2853 va_list vargs;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002854
2855#ifdef HAVE_STDARG_PROTOTYPES
Benjamin Peterson14339b62009-01-31 16:36:08 +00002856 va_start(vargs, format);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002857#else
Benjamin Peterson14339b62009-01-31 16:36:08 +00002858 va_start(vargs);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002859#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00002860 ret = PyUnicode_FromFormatV(format, vargs);
2861 va_end(vargs);
2862 return ret;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002863}
2864
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002865#ifdef HAVE_WCHAR_H
2866
Victor Stinner5593d8a2010-10-02 11:11:27 +00002867/* Helper function for PyUnicode_AsWideChar() and PyUnicode_AsWideCharString():
2868 convert a Unicode object to a wide character string.
2869
Victor Stinnerd88d9832011-09-06 02:00:05 +02002870 - If w is NULL: return the number of wide characters (including the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002871 character) required to convert the unicode object. Ignore size argument.
2872
Victor Stinnerd88d9832011-09-06 02:00:05 +02002873 - Otherwise: return the number of wide characters (excluding the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002874 character) written into w. Write at most size wide characters (including
Victor Stinnerd88d9832011-09-06 02:00:05 +02002875 the null character). */
Victor Stinner5593d8a2010-10-02 11:11:27 +00002876static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002877unicode_aswidechar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002878 wchar_t *w,
2879 Py_ssize_t size)
2880{
Victor Stinner5593d8a2010-10-02 11:11:27 +00002881 Py_ssize_t res;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002882 const wchar_t *wstr;
2883
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002884 wstr = PyUnicode_AsUnicodeAndSize(unicode, &res);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002885 if (wstr == NULL)
2886 return -1;
2887
Victor Stinner5593d8a2010-10-02 11:11:27 +00002888 if (w != NULL) {
Victor Stinner5593d8a2010-10-02 11:11:27 +00002889 if (size > res)
2890 size = res + 1;
2891 else
2892 res = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002893 Py_MEMCPY(w, wstr, size * sizeof(wchar_t));
Victor Stinner5593d8a2010-10-02 11:11:27 +00002894 return res;
2895 }
2896 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002897 return res + 1;
Victor Stinner137c34c2010-09-29 10:25:54 +00002898}
2899
2900Py_ssize_t
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002901PyUnicode_AsWideChar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002902 wchar_t *w,
2903 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002904{
2905 if (unicode == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002906 PyErr_BadInternalCall();
2907 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002908 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002909 return unicode_aswidechar(unicode, w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002910}
2911
Victor Stinner137c34c2010-09-29 10:25:54 +00002912wchar_t*
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00002913PyUnicode_AsWideCharString(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002914 Py_ssize_t *size)
2915{
2916 wchar_t* buffer;
2917 Py_ssize_t buflen;
2918
2919 if (unicode == NULL) {
2920 PyErr_BadInternalCall();
2921 return NULL;
2922 }
2923
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002924 buflen = unicode_aswidechar(unicode, NULL, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002925 if (buflen == -1)
2926 return NULL;
Victor Stinner5593d8a2010-10-02 11:11:27 +00002927 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < buflen) {
Victor Stinner137c34c2010-09-29 10:25:54 +00002928 PyErr_NoMemory();
2929 return NULL;
2930 }
2931
Victor Stinner137c34c2010-09-29 10:25:54 +00002932 buffer = PyMem_MALLOC(buflen * sizeof(wchar_t));
2933 if (buffer == NULL) {
2934 PyErr_NoMemory();
2935 return NULL;
2936 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002937 buflen = unicode_aswidechar(unicode, buffer, buflen);
Stefan Krah8528c312012-08-19 21:52:43 +02002938 if (buflen == -1) {
2939 PyMem_FREE(buffer);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002940 return NULL;
Stefan Krah8528c312012-08-19 21:52:43 +02002941 }
Victor Stinner5593d8a2010-10-02 11:11:27 +00002942 if (size != NULL)
2943 *size = buflen;
Victor Stinner137c34c2010-09-29 10:25:54 +00002944 return buffer;
2945}
2946
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002947#endif /* HAVE_WCHAR_H */
Guido van Rossumd57fd912000-03-10 22:53:23 +00002948
Alexander Belopolsky40018472011-02-26 01:02:56 +00002949PyObject *
2950PyUnicode_FromOrdinal(int ordinal)
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002951{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002952 PyObject *v;
Victor Stinner8faf8212011-12-08 22:14:11 +01002953 if (ordinal < 0 || ordinal > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002954 PyErr_SetString(PyExc_ValueError,
2955 "chr() arg not in range(0x110000)");
2956 return NULL;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002957 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00002958
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002959 if (ordinal < 256)
2960 return get_latin1_char(ordinal);
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002961
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002962 v = PyUnicode_New(1, ordinal);
2963 if (v == NULL)
2964 return NULL;
2965 PyUnicode_WRITE(PyUnicode_KIND(v), PyUnicode_DATA(v), 0, ordinal);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002966 assert(_PyUnicode_CheckConsistency(v, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002967 return v;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002968}
2969
Alexander Belopolsky40018472011-02-26 01:02:56 +00002970PyObject *
2971PyUnicode_FromObject(register PyObject *obj)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002972{
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002973 /* XXX Perhaps we should make this API an alias of
Benjamin Peterson29060642009-01-31 22:14:21 +00002974 PyObject_Str() instead ?! */
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002975 if (PyUnicode_CheckExact(obj)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -05002976 if (PyUnicode_READY(obj) == -1)
Victor Stinnerd3a83d52011-10-01 03:09:33 +02002977 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +00002978 Py_INCREF(obj);
2979 return obj;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002980 }
2981 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002982 /* For a Unicode subtype that's not a Unicode object,
2983 return a true Unicode object with the same data. */
Victor Stinnerbf6e5602011-12-12 01:53:47 +01002984 return _PyUnicode_Copy(obj);
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002985 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00002986 PyErr_Format(PyExc_TypeError,
2987 "Can't convert '%.100s' object to str implicitly",
Christian Heimes90aa7642007-12-19 02:45:37 +00002988 Py_TYPE(obj)->tp_name);
Guido van Rossum98297ee2007-11-06 21:34:58 +00002989 return NULL;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002990}
2991
Alexander Belopolsky40018472011-02-26 01:02:56 +00002992PyObject *
2993PyUnicode_FromEncodedObject(register PyObject *obj,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002994 const char *encoding,
2995 const char *errors)
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002996{
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002997 Py_buffer buffer;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002998 PyObject *v;
Tim Petersced69f82003-09-16 20:30:58 +00002999
Guido van Rossumd57fd912000-03-10 22:53:23 +00003000 if (obj == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003001 PyErr_BadInternalCall();
3002 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003003 }
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003004
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003005 /* Decoding bytes objects is the most common case and should be fast */
3006 if (PyBytes_Check(obj)) {
3007 if (PyBytes_GET_SIZE(obj) == 0) {
3008 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02003009 v = unicode_empty;
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003010 }
3011 else {
3012 v = PyUnicode_Decode(
3013 PyBytes_AS_STRING(obj), PyBytes_GET_SIZE(obj),
3014 encoding, errors);
3015 }
3016 return v;
3017 }
3018
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003019 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003020 PyErr_SetString(PyExc_TypeError,
3021 "decoding str is not supported");
3022 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +00003023 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003024
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003025 /* Retrieve a bytes buffer view through the PEP 3118 buffer interface */
3026 if (PyObject_GetBuffer(obj, &buffer, PyBUF_SIMPLE) < 0) {
3027 PyErr_Format(PyExc_TypeError,
3028 "coercing to str: need bytes, bytearray "
3029 "or buffer-like object, %.80s found",
3030 Py_TYPE(obj)->tp_name);
3031 return NULL;
Marc-André Lemburg6871f6a2001-09-20 12:53:16 +00003032 }
Tim Petersced69f82003-09-16 20:30:58 +00003033
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003034 if (buffer.len == 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003035 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02003036 v = unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003037 }
Tim Petersced69f82003-09-16 20:30:58 +00003038 else
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003039 v = PyUnicode_Decode((char*) buffer.buf, buffer.len, encoding, errors);
Marc-André Lemburgad7c98e2001-01-17 17:09:53 +00003040
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003041 PyBuffer_Release(&buffer);
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003042 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003043}
3044
Victor Stinner600d3be2010-06-10 12:00:55 +00003045/* Convert encoding to lower case and replace '_' with '-' in order to
Victor Stinner37296e82010-06-10 13:36:23 +00003046 catch e.g. UTF_8. Return 0 on error (encoding is longer than lower_len-1),
3047 1 on success. */
3048static int
3049normalize_encoding(const char *encoding,
3050 char *lower,
3051 size_t lower_len)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003052{
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003053 const char *e;
Victor Stinner600d3be2010-06-10 12:00:55 +00003054 char *l;
3055 char *l_end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003056
Benjamin Peterson7a6debe2011-10-15 09:25:28 -04003057 if (encoding == NULL) {
3058 strcpy(lower, "utf-8");
3059 return 1;
3060 }
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003061 e = encoding;
3062 l = lower;
Victor Stinner600d3be2010-06-10 12:00:55 +00003063 l_end = &lower[lower_len - 1];
Victor Stinner37296e82010-06-10 13:36:23 +00003064 while (*e) {
3065 if (l == l_end)
3066 return 0;
David Malcolm96960882010-11-05 17:23:41 +00003067 if (Py_ISUPPER(*e)) {
3068 *l++ = Py_TOLOWER(*e++);
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003069 }
3070 else if (*e == '_') {
3071 *l++ = '-';
3072 e++;
3073 }
3074 else {
3075 *l++ = *e++;
3076 }
3077 }
3078 *l = '\0';
Victor Stinner37296e82010-06-10 13:36:23 +00003079 return 1;
Victor Stinner600d3be2010-06-10 12:00:55 +00003080}
3081
Alexander Belopolsky40018472011-02-26 01:02:56 +00003082PyObject *
3083PyUnicode_Decode(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003084 Py_ssize_t size,
3085 const char *encoding,
3086 const char *errors)
Victor Stinner600d3be2010-06-10 12:00:55 +00003087{
3088 PyObject *buffer = NULL, *unicode;
3089 Py_buffer info;
3090 char lower[11]; /* Enough for any encoding shortcut */
3091
Fred Drakee4315f52000-05-09 19:53:39 +00003092 /* Shortcuts for common default encodings */
Victor Stinner37296e82010-06-10 13:36:23 +00003093 if (normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003094 if ((strcmp(lower, "utf-8") == 0) ||
3095 (strcmp(lower, "utf8") == 0))
Victor Stinnera1d12bb2011-12-11 21:53:09 +01003096 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
Victor Stinner37296e82010-06-10 13:36:23 +00003097 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003098 (strcmp(lower, "latin1") == 0) ||
Victor Stinner37296e82010-06-10 13:36:23 +00003099 (strcmp(lower, "iso-8859-1") == 0))
3100 return PyUnicode_DecodeLatin1(s, size, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02003101#ifdef HAVE_MBCS
Victor Stinner37296e82010-06-10 13:36:23 +00003102 else if (strcmp(lower, "mbcs") == 0)
3103 return PyUnicode_DecodeMBCS(s, size, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003104#endif
Victor Stinner37296e82010-06-10 13:36:23 +00003105 else if (strcmp(lower, "ascii") == 0)
3106 return PyUnicode_DecodeASCII(s, size, errors);
3107 else if (strcmp(lower, "utf-16") == 0)
3108 return PyUnicode_DecodeUTF16(s, size, errors, 0);
3109 else if (strcmp(lower, "utf-32") == 0)
3110 return PyUnicode_DecodeUTF32(s, size, errors, 0);
3111 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003112
3113 /* Decode via the codec registry */
Guido van Rossumbe801ac2007-10-08 03:32:34 +00003114 buffer = NULL;
Antoine Pitrouc3b39242009-01-03 16:59:18 +00003115 if (PyBuffer_FillInfo(&info, NULL, (void *)s, size, 1, PyBUF_FULL_RO) < 0)
Guido van Rossumbe801ac2007-10-08 03:32:34 +00003116 goto onError;
Antoine Pitrouee58fa42008-08-19 18:22:14 +00003117 buffer = PyMemoryView_FromBuffer(&info);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003118 if (buffer == NULL)
3119 goto onError;
3120 unicode = PyCodec_Decode(buffer, encoding, errors);
3121 if (unicode == NULL)
3122 goto onError;
3123 if (!PyUnicode_Check(unicode)) {
3124 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00003125 "decoder did not return a str object (type=%.400s)",
Christian Heimes90aa7642007-12-19 02:45:37 +00003126 Py_TYPE(unicode)->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003127 Py_DECREF(unicode);
3128 goto onError;
3129 }
3130 Py_DECREF(buffer);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003131 return unicode_result(unicode);
Tim Petersced69f82003-09-16 20:30:58 +00003132
Benjamin Peterson29060642009-01-31 22:14:21 +00003133 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003134 Py_XDECREF(buffer);
3135 return NULL;
3136}
3137
Alexander Belopolsky40018472011-02-26 01:02:56 +00003138PyObject *
3139PyUnicode_AsDecodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003140 const char *encoding,
3141 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003142{
3143 PyObject *v;
3144
3145 if (!PyUnicode_Check(unicode)) {
3146 PyErr_BadArgument();
3147 goto onError;
3148 }
3149
3150 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003151 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003152
3153 /* Decode via the codec registry */
3154 v = PyCodec_Decode(unicode, encoding, errors);
3155 if (v == NULL)
3156 goto onError;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003157 return unicode_result(v);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003158
Benjamin Peterson29060642009-01-31 22:14:21 +00003159 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003160 return NULL;
3161}
3162
Alexander Belopolsky40018472011-02-26 01:02:56 +00003163PyObject *
3164PyUnicode_AsDecodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003165 const char *encoding,
3166 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003167{
3168 PyObject *v;
3169
3170 if (!PyUnicode_Check(unicode)) {
3171 PyErr_BadArgument();
3172 goto onError;
3173 }
3174
3175 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003176 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003177
3178 /* Decode via the codec registry */
3179 v = PyCodec_Decode(unicode, encoding, errors);
3180 if (v == NULL)
3181 goto onError;
3182 if (!PyUnicode_Check(v)) {
3183 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00003184 "decoder did not return a str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003185 Py_TYPE(v)->tp_name);
3186 Py_DECREF(v);
3187 goto onError;
3188 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003189 return unicode_result(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003190
Benjamin Peterson29060642009-01-31 22:14:21 +00003191 onError:
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003192 return NULL;
3193}
3194
Alexander Belopolsky40018472011-02-26 01:02:56 +00003195PyObject *
3196PyUnicode_Encode(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003197 Py_ssize_t size,
3198 const char *encoding,
3199 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003200{
3201 PyObject *v, *unicode;
Tim Petersced69f82003-09-16 20:30:58 +00003202
Guido van Rossumd57fd912000-03-10 22:53:23 +00003203 unicode = PyUnicode_FromUnicode(s, size);
3204 if (unicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003205 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003206 v = PyUnicode_AsEncodedString(unicode, encoding, errors);
3207 Py_DECREF(unicode);
3208 return v;
3209}
3210
Alexander Belopolsky40018472011-02-26 01:02:56 +00003211PyObject *
3212PyUnicode_AsEncodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003213 const char *encoding,
3214 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003215{
3216 PyObject *v;
3217
3218 if (!PyUnicode_Check(unicode)) {
3219 PyErr_BadArgument();
3220 goto onError;
3221 }
3222
3223 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003224 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003225
3226 /* Encode via the codec registry */
3227 v = PyCodec_Encode(unicode, encoding, errors);
3228 if (v == NULL)
3229 goto onError;
3230 return v;
3231
Benjamin Peterson29060642009-01-31 22:14:21 +00003232 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003233 return NULL;
3234}
3235
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003236static size_t
3237wcstombs_errorpos(const wchar_t *wstr)
3238{
3239 size_t len;
3240#if SIZEOF_WCHAR_T == 2
3241 wchar_t buf[3];
3242#else
3243 wchar_t buf[2];
3244#endif
3245 char outbuf[MB_LEN_MAX];
3246 const wchar_t *start, *previous;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003247
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003248#if SIZEOF_WCHAR_T == 2
3249 buf[2] = 0;
3250#else
3251 buf[1] = 0;
3252#endif
3253 start = wstr;
3254 while (*wstr != L'\0')
3255 {
3256 previous = wstr;
3257#if SIZEOF_WCHAR_T == 2
3258 if (Py_UNICODE_IS_HIGH_SURROGATE(wstr[0])
3259 && Py_UNICODE_IS_LOW_SURROGATE(wstr[1]))
3260 {
3261 buf[0] = wstr[0];
3262 buf[1] = wstr[1];
3263 wstr += 2;
3264 }
3265 else {
3266 buf[0] = *wstr;
3267 buf[1] = 0;
3268 wstr++;
3269 }
3270#else
3271 buf[0] = *wstr;
3272 wstr++;
3273#endif
3274 len = wcstombs(outbuf, buf, sizeof(outbuf));
Victor Stinner2f197072011-12-17 07:08:30 +01003275 if (len == (size_t)-1)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003276 return previous - start;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003277 }
3278
3279 /* failed to find the unencodable character */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003280 return 0;
3281}
3282
Victor Stinner1b579672011-12-17 05:47:23 +01003283static int
3284locale_error_handler(const char *errors, int *surrogateescape)
3285{
3286 if (errors == NULL) {
3287 *surrogateescape = 0;
3288 return 0;
3289 }
3290
3291 if (strcmp(errors, "strict") == 0) {
3292 *surrogateescape = 0;
3293 return 0;
3294 }
3295 if (strcmp(errors, "surrogateescape") == 0) {
3296 *surrogateescape = 1;
3297 return 0;
3298 }
3299 PyErr_Format(PyExc_ValueError,
3300 "only 'strict' and 'surrogateescape' error handlers "
3301 "are supported, not '%s'",
3302 errors);
3303 return -1;
3304}
3305
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003306PyObject *
Victor Stinner1b579672011-12-17 05:47:23 +01003307PyUnicode_EncodeLocale(PyObject *unicode, const char *errors)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003308{
3309 Py_ssize_t wlen, wlen2;
3310 wchar_t *wstr;
3311 PyObject *bytes = NULL;
3312 char *errmsg;
Victor Stinner1f33f2b2011-12-17 04:45:09 +01003313 PyObject *reason;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003314 PyObject *exc;
3315 size_t error_pos;
Victor Stinner1b579672011-12-17 05:47:23 +01003316 int surrogateescape;
3317
3318 if (locale_error_handler(errors, &surrogateescape) < 0)
3319 return NULL;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003320
3321 wstr = PyUnicode_AsWideCharString(unicode, &wlen);
3322 if (wstr == NULL)
3323 return NULL;
3324
3325 wlen2 = wcslen(wstr);
3326 if (wlen2 != wlen) {
3327 PyMem_Free(wstr);
3328 PyErr_SetString(PyExc_TypeError, "embedded null character");
3329 return NULL;
3330 }
3331
3332 if (surrogateescape) {
3333 /* locale encoding with surrogateescape */
3334 char *str;
3335
3336 str = _Py_wchar2char(wstr, &error_pos);
3337 if (str == NULL) {
3338 if (error_pos == (size_t)-1) {
3339 PyErr_NoMemory();
3340 PyMem_Free(wstr);
3341 return NULL;
3342 }
3343 else {
3344 goto encode_error;
3345 }
3346 }
3347 PyMem_Free(wstr);
3348
3349 bytes = PyBytes_FromString(str);
3350 PyMem_Free(str);
3351 }
3352 else {
3353 size_t len, len2;
3354
3355 len = wcstombs(NULL, wstr, 0);
3356 if (len == (size_t)-1) {
Victor Stinner2f197072011-12-17 07:08:30 +01003357 error_pos = (size_t)-1;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003358 goto encode_error;
3359 }
3360
3361 bytes = PyBytes_FromStringAndSize(NULL, len);
3362 if (bytes == NULL) {
3363 PyMem_Free(wstr);
3364 return NULL;
3365 }
3366
3367 len2 = wcstombs(PyBytes_AS_STRING(bytes), wstr, len+1);
3368 if (len2 == (size_t)-1 || len2 > len) {
Victor Stinner2f197072011-12-17 07:08:30 +01003369 error_pos = (size_t)-1;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003370 goto encode_error;
3371 }
3372 PyMem_Free(wstr);
3373 }
3374 return bytes;
3375
3376encode_error:
3377 errmsg = strerror(errno);
3378 assert(errmsg != NULL);
Victor Stinner2f197072011-12-17 07:08:30 +01003379
3380 if (error_pos == (size_t)-1)
3381 error_pos = wcstombs_errorpos(wstr);
3382
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003383 PyMem_Free(wstr);
3384 Py_XDECREF(bytes);
3385
Victor Stinner2f197072011-12-17 07:08:30 +01003386 if (errmsg != NULL) {
3387 size_t errlen;
3388 wstr = _Py_char2wchar(errmsg, &errlen);
3389 if (wstr != NULL) {
3390 reason = PyUnicode_FromWideChar(wstr, errlen);
3391 PyMem_Free(wstr);
3392 } else
3393 errmsg = NULL;
3394 }
3395 if (errmsg == NULL)
Victor Stinner1f33f2b2011-12-17 04:45:09 +01003396 reason = PyUnicode_FromString(
3397 "wcstombs() encountered an unencodable "
3398 "wide character");
3399 if (reason == NULL)
3400 return NULL;
3401
3402 exc = PyObject_CallFunction(PyExc_UnicodeEncodeError, "sOnnO",
3403 "locale", unicode,
3404 (Py_ssize_t)error_pos,
3405 (Py_ssize_t)(error_pos+1),
3406 reason);
3407 Py_DECREF(reason);
3408 if (exc != NULL) {
3409 PyCodec_StrictErrors(exc);
3410 Py_XDECREF(exc);
3411 }
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003412 return NULL;
3413}
3414
Victor Stinnerad158722010-10-27 00:25:46 +00003415PyObject *
3416PyUnicode_EncodeFSDefault(PyObject *unicode)
Victor Stinnerae6265f2010-05-15 16:27:27 +00003417{
Victor Stinner99b95382011-07-04 14:23:54 +02003418#ifdef HAVE_MBCS
Victor Stinnerac931b12011-11-20 18:27:03 +01003419 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003420#elif defined(__APPLE__)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003421 return _PyUnicode_AsUTF8String(unicode, "surrogateescape");
Victor Stinnerad158722010-10-27 00:25:46 +00003422#else
Victor Stinner793b5312011-04-27 00:24:21 +02003423 PyInterpreterState *interp = PyThreadState_GET()->interp;
3424 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3425 cannot use it to encode and decode filenames before it is loaded. Load
3426 the Python codec requires to encode at least its own filename. Use the C
3427 version of the locale codec until the codec registry is initialized and
3428 the Python codec is loaded.
3429
3430 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3431 cannot only rely on it: check also interp->fscodec_initialized for
3432 subinterpreters. */
3433 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Victor Stinnerae6265f2010-05-15 16:27:27 +00003434 return PyUnicode_AsEncodedString(unicode,
3435 Py_FileSystemDefaultEncoding,
3436 "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00003437 }
3438 else {
Victor Stinner1b579672011-12-17 05:47:23 +01003439 return PyUnicode_EncodeLocale(unicode, "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00003440 }
Victor Stinnerad158722010-10-27 00:25:46 +00003441#endif
Victor Stinnerae6265f2010-05-15 16:27:27 +00003442}
3443
Alexander Belopolsky40018472011-02-26 01:02:56 +00003444PyObject *
3445PyUnicode_AsEncodedString(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003446 const char *encoding,
3447 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003448{
3449 PyObject *v;
Victor Stinner600d3be2010-06-10 12:00:55 +00003450 char lower[11]; /* Enough for any encoding shortcut */
Tim Petersced69f82003-09-16 20:30:58 +00003451
Guido van Rossumd57fd912000-03-10 22:53:23 +00003452 if (!PyUnicode_Check(unicode)) {
3453 PyErr_BadArgument();
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003454 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003455 }
Fred Drakee4315f52000-05-09 19:53:39 +00003456
Fred Drakee4315f52000-05-09 19:53:39 +00003457 /* Shortcuts for common default encodings */
Victor Stinner37296e82010-06-10 13:36:23 +00003458 if (normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003459 if ((strcmp(lower, "utf-8") == 0) ||
3460 (strcmp(lower, "utf8") == 0))
Victor Stinnera5c68c32011-03-02 01:03:14 +00003461 {
Victor Stinner2f283c22011-03-02 01:21:46 +00003462 if (errors == NULL || strcmp(errors, "strict") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003463 return _PyUnicode_AsUTF8String(unicode, NULL);
Victor Stinner2f283c22011-03-02 01:21:46 +00003464 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003465 return _PyUnicode_AsUTF8String(unicode, errors);
Victor Stinnera5c68c32011-03-02 01:03:14 +00003466 }
Victor Stinner37296e82010-06-10 13:36:23 +00003467 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003468 (strcmp(lower, "latin1") == 0) ||
Victor Stinner37296e82010-06-10 13:36:23 +00003469 (strcmp(lower, "iso-8859-1") == 0))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003470 return _PyUnicode_AsLatin1String(unicode, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02003471#ifdef HAVE_MBCS
Victor Stinnerac931b12011-11-20 18:27:03 +01003472 else if (strcmp(lower, "mbcs") == 0)
3473 return PyUnicode_EncodeCodePage(CP_ACP, unicode, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003474#endif
Victor Stinner37296e82010-06-10 13:36:23 +00003475 else if (strcmp(lower, "ascii") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003476 return _PyUnicode_AsASCIIString(unicode, errors);
Victor Stinner37296e82010-06-10 13:36:23 +00003477 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003478
3479 /* Encode via the codec registry */
3480 v = PyCodec_Encode(unicode, encoding, errors);
3481 if (v == NULL)
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003482 return NULL;
3483
3484 /* The normal path */
3485 if (PyBytes_Check(v))
3486 return v;
3487
3488 /* If the codec returns a buffer, raise a warning and convert to bytes */
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003489 if (PyByteArray_Check(v)) {
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003490 int error;
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003491 PyObject *b;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003492
3493 error = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
3494 "encoder %s returned bytearray instead of bytes",
3495 encoding);
3496 if (error) {
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003497 Py_DECREF(v);
3498 return NULL;
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003499 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003500
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003501 b = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(v), Py_SIZE(v));
3502 Py_DECREF(v);
3503 return b;
3504 }
3505
3506 PyErr_Format(PyExc_TypeError,
3507 "encoder did not return a bytes object (type=%.400s)",
3508 Py_TYPE(v)->tp_name);
3509 Py_DECREF(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003510 return NULL;
3511}
3512
Alexander Belopolsky40018472011-02-26 01:02:56 +00003513PyObject *
3514PyUnicode_AsEncodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003515 const char *encoding,
3516 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003517{
3518 PyObject *v;
3519
3520 if (!PyUnicode_Check(unicode)) {
3521 PyErr_BadArgument();
3522 goto onError;
3523 }
3524
3525 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003526 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003527
3528 /* Encode via the codec registry */
3529 v = PyCodec_Encode(unicode, encoding, errors);
3530 if (v == NULL)
3531 goto onError;
3532 if (!PyUnicode_Check(v)) {
3533 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00003534 "encoder did not return an str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003535 Py_TYPE(v)->tp_name);
3536 Py_DECREF(v);
3537 goto onError;
3538 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003539 return v;
Tim Petersced69f82003-09-16 20:30:58 +00003540
Benjamin Peterson29060642009-01-31 22:14:21 +00003541 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003542 return NULL;
3543}
3544
Victor Stinner2f197072011-12-17 07:08:30 +01003545static size_t
3546mbstowcs_errorpos(const char *str, size_t len)
3547{
3548#ifdef HAVE_MBRTOWC
3549 const char *start = str;
3550 mbstate_t mbs;
3551 size_t converted;
3552 wchar_t ch;
3553
3554 memset(&mbs, 0, sizeof mbs);
3555 while (len)
3556 {
3557 converted = mbrtowc(&ch, (char*)str, len, &mbs);
3558 if (converted == 0)
3559 /* Reached end of string */
3560 break;
3561 if (converted == (size_t)-1 || converted == (size_t)-2) {
3562 /* Conversion error or incomplete character */
3563 return str - start;
3564 }
3565 else {
3566 str += converted;
3567 len -= converted;
3568 }
3569 }
3570 /* failed to find the undecodable byte sequence */
3571 return 0;
3572#endif
3573 return 0;
3574}
3575
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003576PyObject*
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003577PyUnicode_DecodeLocaleAndSize(const char *str, Py_ssize_t len,
Victor Stinner1b579672011-12-17 05:47:23 +01003578 const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003579{
3580 wchar_t smallbuf[256];
3581 size_t smallbuf_len = Py_ARRAY_LENGTH(smallbuf);
3582 wchar_t *wstr;
3583 size_t wlen, wlen2;
3584 PyObject *unicode;
Victor Stinner1b579672011-12-17 05:47:23 +01003585 int surrogateescape;
Victor Stinner2f197072011-12-17 07:08:30 +01003586 size_t error_pos;
3587 char *errmsg;
3588 PyObject *reason, *exc;
Victor Stinner1b579672011-12-17 05:47:23 +01003589
3590 if (locale_error_handler(errors, &surrogateescape) < 0)
3591 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003592
3593 if (str[len] != '\0' || len != strlen(str)) {
3594 PyErr_SetString(PyExc_TypeError, "embedded null character");
3595 return NULL;
3596 }
3597
3598 if (surrogateescape)
3599 {
3600 wstr = _Py_char2wchar(str, &wlen);
3601 if (wstr == NULL) {
3602 if (wlen == (size_t)-1)
3603 PyErr_NoMemory();
3604 else
3605 PyErr_SetFromErrno(PyExc_OSError);
3606 return NULL;
3607 }
3608
3609 unicode = PyUnicode_FromWideChar(wstr, wlen);
3610 PyMem_Free(wstr);
3611 }
3612 else {
3613#ifndef HAVE_BROKEN_MBSTOWCS
3614 wlen = mbstowcs(NULL, str, 0);
3615#else
3616 wlen = len;
3617#endif
Victor Stinner2f197072011-12-17 07:08:30 +01003618 if (wlen == (size_t)-1)
3619 goto decode_error;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003620 if (wlen+1 <= smallbuf_len) {
3621 wstr = smallbuf;
3622 }
3623 else {
3624 if (wlen > PY_SSIZE_T_MAX / sizeof(wchar_t) - 1)
3625 return PyErr_NoMemory();
3626
3627 wstr = PyMem_Malloc((wlen+1) * sizeof(wchar_t));
3628 if (!wstr)
3629 return PyErr_NoMemory();
3630 }
3631
3632 /* This shouldn't fail now */
3633 wlen2 = mbstowcs(wstr, str, wlen+1);
3634 if (wlen2 == (size_t)-1) {
3635 if (wstr != smallbuf)
3636 PyMem_Free(wstr);
Victor Stinner2f197072011-12-17 07:08:30 +01003637 goto decode_error;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003638 }
3639#ifdef HAVE_BROKEN_MBSTOWCS
3640 assert(wlen2 == wlen);
3641#endif
3642 unicode = PyUnicode_FromWideChar(wstr, wlen2);
3643 if (wstr != smallbuf)
3644 PyMem_Free(wstr);
3645 }
3646 return unicode;
Victor Stinner2f197072011-12-17 07:08:30 +01003647
3648decode_error:
3649 errmsg = strerror(errno);
3650 assert(errmsg != NULL);
3651
3652 error_pos = mbstowcs_errorpos(str, len);
3653 if (errmsg != NULL) {
3654 size_t errlen;
3655 wstr = _Py_char2wchar(errmsg, &errlen);
3656 if (wstr != NULL) {
3657 reason = PyUnicode_FromWideChar(wstr, errlen);
3658 PyMem_Free(wstr);
3659 } else
3660 errmsg = NULL;
3661 }
3662 if (errmsg == NULL)
3663 reason = PyUnicode_FromString(
3664 "mbstowcs() encountered an invalid multibyte sequence");
3665 if (reason == NULL)
3666 return NULL;
3667
3668 exc = PyObject_CallFunction(PyExc_UnicodeDecodeError, "sy#nnO",
3669 "locale", str, len,
3670 (Py_ssize_t)error_pos,
3671 (Py_ssize_t)(error_pos+1),
3672 reason);
3673 Py_DECREF(reason);
3674 if (exc != NULL) {
3675 PyCodec_StrictErrors(exc);
3676 Py_XDECREF(exc);
3677 }
3678 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003679}
3680
3681PyObject*
Victor Stinner1b579672011-12-17 05:47:23 +01003682PyUnicode_DecodeLocale(const char *str, const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003683{
3684 Py_ssize_t size = (Py_ssize_t)strlen(str);
Victor Stinner1b579672011-12-17 05:47:23 +01003685 return PyUnicode_DecodeLocaleAndSize(str, size, errors);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003686}
3687
3688
3689PyObject*
Christian Heimes5894ba72007-11-04 11:43:14 +00003690PyUnicode_DecodeFSDefault(const char *s) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003691 Py_ssize_t size = (Py_ssize_t)strlen(s);
Christian Heimes5894ba72007-11-04 11:43:14 +00003692 return PyUnicode_DecodeFSDefaultAndSize(s, size);
3693}
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003694
Christian Heimes5894ba72007-11-04 11:43:14 +00003695PyObject*
3696PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
3697{
Victor Stinner99b95382011-07-04 14:23:54 +02003698#ifdef HAVE_MBCS
Victor Stinnerad158722010-10-27 00:25:46 +00003699 return PyUnicode_DecodeMBCS(s, size, NULL);
3700#elif defined(__APPLE__)
Victor Stinnera1d12bb2011-12-11 21:53:09 +01003701 return PyUnicode_DecodeUTF8Stateful(s, size, "surrogateescape", NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003702#else
Victor Stinner793b5312011-04-27 00:24:21 +02003703 PyInterpreterState *interp = PyThreadState_GET()->interp;
3704 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3705 cannot use it to encode and decode filenames before it is loaded. Load
3706 the Python codec requires to encode at least its own filename. Use the C
3707 version of the locale codec until the codec registry is initialized and
3708 the Python codec is loaded.
3709
3710 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3711 cannot only rely on it: check also interp->fscodec_initialized for
3712 subinterpreters. */
3713 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003714 return PyUnicode_Decode(s, size,
3715 Py_FileSystemDefaultEncoding,
Victor Stinnerb9a20ad2010-04-30 16:37:52 +00003716 "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003717 }
3718 else {
Victor Stinner1b579672011-12-17 05:47:23 +01003719 return PyUnicode_DecodeLocaleAndSize(s, size, "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003720 }
Victor Stinnerad158722010-10-27 00:25:46 +00003721#endif
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003722}
3723
Martin v. Löwis011e8422009-05-05 04:43:17 +00003724
3725int
Antoine Pitrou13348842012-01-29 18:36:34 +01003726_PyUnicode_HasNULChars(PyObject* s)
3727{
3728 static PyObject *nul = NULL;
3729
3730 if (nul == NULL)
3731 nul = PyUnicode_FromStringAndSize("\0", 1);
3732 if (nul == NULL)
3733 return -1;
3734 return PyUnicode_Contains(s, nul);
3735}
3736
3737
3738int
Martin v. Löwis011e8422009-05-05 04:43:17 +00003739PyUnicode_FSConverter(PyObject* arg, void* addr)
3740{
3741 PyObject *output = NULL;
3742 Py_ssize_t size;
3743 void *data;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003744 if (arg == NULL) {
3745 Py_DECREF(*(PyObject**)addr);
3746 return 1;
3747 }
Victor Stinnerdcb24032010-04-22 12:08:36 +00003748 if (PyBytes_Check(arg)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00003749 output = arg;
3750 Py_INCREF(output);
3751 }
3752 else {
3753 arg = PyUnicode_FromObject(arg);
3754 if (!arg)
3755 return 0;
Victor Stinnerae6265f2010-05-15 16:27:27 +00003756 output = PyUnicode_EncodeFSDefault(arg);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003757 Py_DECREF(arg);
3758 if (!output)
3759 return 0;
3760 if (!PyBytes_Check(output)) {
3761 Py_DECREF(output);
3762 PyErr_SetString(PyExc_TypeError, "encoder failed to return bytes");
3763 return 0;
3764 }
3765 }
Victor Stinner0ea2a462010-04-30 00:22:08 +00003766 size = PyBytes_GET_SIZE(output);
3767 data = PyBytes_AS_STRING(output);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003768 if (size != strlen(data)) {
Benjamin Peterson7a6b44a2011-08-18 13:51:47 -05003769 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
Martin v. Löwis011e8422009-05-05 04:43:17 +00003770 Py_DECREF(output);
3771 return 0;
3772 }
3773 *(PyObject**)addr = output;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003774 return Py_CLEANUP_SUPPORTED;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003775}
3776
3777
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003778int
3779PyUnicode_FSDecoder(PyObject* arg, void* addr)
3780{
3781 PyObject *output = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003782 if (arg == NULL) {
3783 Py_DECREF(*(PyObject**)addr);
3784 return 1;
3785 }
3786 if (PyUnicode_Check(arg)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -05003787 if (PyUnicode_READY(arg) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003788 return 0;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003789 output = arg;
3790 Py_INCREF(output);
3791 }
3792 else {
3793 arg = PyBytes_FromObject(arg);
3794 if (!arg)
3795 return 0;
3796 output = PyUnicode_DecodeFSDefaultAndSize(PyBytes_AS_STRING(arg),
3797 PyBytes_GET_SIZE(arg));
3798 Py_DECREF(arg);
3799 if (!output)
3800 return 0;
3801 if (!PyUnicode_Check(output)) {
3802 Py_DECREF(output);
3803 PyErr_SetString(PyExc_TypeError, "decoder failed to return unicode");
3804 return 0;
3805 }
3806 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05003807 if (PyUnicode_READY(output) == -1) {
Victor Stinner065836e2011-10-27 01:56:33 +02003808 Py_DECREF(output);
3809 return 0;
3810 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003811 if (findchar(PyUnicode_DATA(output), PyUnicode_KIND(output),
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02003812 PyUnicode_GET_LENGTH(output), 0, 1) >= 0) {
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003813 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
3814 Py_DECREF(output);
3815 return 0;
3816 }
3817 *(PyObject**)addr = output;
3818 return Py_CLEANUP_SUPPORTED;
3819}
3820
3821
Martin v. Löwis5b222132007-06-10 09:51:05 +00003822char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003823PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *psize)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003824{
Christian Heimesf3863112007-11-22 07:46:41 +00003825 PyObject *bytes;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003826
Neal Norwitze0a0a6e2007-08-25 01:04:21 +00003827 if (!PyUnicode_Check(unicode)) {
3828 PyErr_BadArgument();
3829 return NULL;
3830 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003831 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003832 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003833
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003834 if (PyUnicode_UTF8(unicode) == NULL) {
3835 assert(!PyUnicode_IS_COMPACT_ASCII(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003836 bytes = _PyUnicode_AsUTF8String(unicode, "strict");
3837 if (bytes == NULL)
3838 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003839 _PyUnicode_UTF8(unicode) = PyObject_MALLOC(PyBytes_GET_SIZE(bytes) + 1);
3840 if (_PyUnicode_UTF8(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003841 Py_DECREF(bytes);
3842 return NULL;
3843 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003844 _PyUnicode_UTF8_LENGTH(unicode) = PyBytes_GET_SIZE(bytes);
3845 Py_MEMCPY(_PyUnicode_UTF8(unicode),
3846 PyBytes_AS_STRING(bytes),
3847 _PyUnicode_UTF8_LENGTH(unicode) + 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003848 Py_DECREF(bytes);
3849 }
3850
3851 if (psize)
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003852 *psize = PyUnicode_UTF8_LENGTH(unicode);
3853 return PyUnicode_UTF8(unicode);
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003854}
3855
3856char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003857PyUnicode_AsUTF8(PyObject *unicode)
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003858{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003859 return PyUnicode_AsUTF8AndSize(unicode, NULL);
3860}
3861
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003862Py_UNICODE *
3863PyUnicode_AsUnicodeAndSize(PyObject *unicode, Py_ssize_t *size)
3864{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003865 const unsigned char *one_byte;
3866#if SIZEOF_WCHAR_T == 4
3867 const Py_UCS2 *two_bytes;
3868#else
3869 const Py_UCS4 *four_bytes;
3870 const Py_UCS4 *ucs4_end;
3871 Py_ssize_t num_surrogates;
3872#endif
3873 wchar_t *w;
3874 wchar_t *wchar_end;
3875
3876 if (!PyUnicode_Check(unicode)) {
3877 PyErr_BadArgument();
3878 return NULL;
3879 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003880 if (_PyUnicode_WSTR(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003881 /* Non-ASCII compact unicode object */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003882 assert(_PyUnicode_KIND(unicode) != 0);
3883 assert(PyUnicode_IS_READY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003884
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003885 if (PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003886#if SIZEOF_WCHAR_T == 2
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003887 four_bytes = PyUnicode_4BYTE_DATA(unicode);
3888 ucs4_end = four_bytes + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003889 num_surrogates = 0;
3890
3891 for (; four_bytes < ucs4_end; ++four_bytes) {
3892 if (*four_bytes > 0xFFFF)
3893 ++num_surrogates;
3894 }
3895
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003896 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(
3897 sizeof(wchar_t) * (_PyUnicode_LENGTH(unicode) + 1 + num_surrogates));
3898 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003899 PyErr_NoMemory();
3900 return NULL;
3901 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003902 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode) + num_surrogates;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003903
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003904 w = _PyUnicode_WSTR(unicode);
3905 wchar_end = w + _PyUnicode_WSTR_LENGTH(unicode);
3906 four_bytes = PyUnicode_4BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003907 for (; four_bytes < ucs4_end; ++four_bytes, ++w) {
3908 if (*four_bytes > 0xFFFF) {
Victor Stinner8faf8212011-12-08 22:14:11 +01003909 assert(*four_bytes <= MAX_UNICODE);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003910 /* encode surrogate pair in this case */
Victor Stinner551ac952011-11-29 22:58:13 +01003911 *w++ = Py_UNICODE_HIGH_SURROGATE(*four_bytes);
3912 *w = Py_UNICODE_LOW_SURROGATE(*four_bytes);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003913 }
3914 else
3915 *w = *four_bytes;
3916
3917 if (w > wchar_end) {
3918 assert(0 && "Miscalculated string end");
3919 }
3920 }
3921 *w = 0;
3922#else
3923 /* sizeof(wchar_t) == 4 */
3924 Py_FatalError("Impossible unicode object state, wstr and str "
3925 "should share memory already.");
3926 return NULL;
3927#endif
3928 }
3929 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003930 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(sizeof(wchar_t) *
3931 (_PyUnicode_LENGTH(unicode) + 1));
3932 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003933 PyErr_NoMemory();
3934 return NULL;
3935 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003936 if (!PyUnicode_IS_COMPACT_ASCII(unicode))
3937 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode);
3938 w = _PyUnicode_WSTR(unicode);
3939 wchar_end = w + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003940
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003941 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND) {
3942 one_byte = PyUnicode_1BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003943 for (; w < wchar_end; ++one_byte, ++w)
3944 *w = *one_byte;
3945 /* null-terminate the wstr */
3946 *w = 0;
3947 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003948 else if (PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003949#if SIZEOF_WCHAR_T == 4
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003950 two_bytes = PyUnicode_2BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003951 for (; w < wchar_end; ++two_bytes, ++w)
3952 *w = *two_bytes;
3953 /* null-terminate the wstr */
3954 *w = 0;
3955#else
3956 /* sizeof(wchar_t) == 2 */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003957 PyObject_FREE(_PyUnicode_WSTR(unicode));
3958 _PyUnicode_WSTR(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003959 Py_FatalError("Impossible unicode object state, wstr "
3960 "and str should share memory already.");
3961 return NULL;
3962#endif
3963 }
3964 else {
3965 assert(0 && "This should never happen.");
3966 }
3967 }
3968 }
3969 if (size != NULL)
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003970 *size = PyUnicode_WSTR_LENGTH(unicode);
3971 return _PyUnicode_WSTR(unicode);
Martin v. Löwis5b222132007-06-10 09:51:05 +00003972}
3973
Alexander Belopolsky40018472011-02-26 01:02:56 +00003974Py_UNICODE *
3975PyUnicode_AsUnicode(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003976{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003977 return PyUnicode_AsUnicodeAndSize(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003978}
3979
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003980
Alexander Belopolsky40018472011-02-26 01:02:56 +00003981Py_ssize_t
3982PyUnicode_GetSize(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003983{
3984 if (!PyUnicode_Check(unicode)) {
3985 PyErr_BadArgument();
3986 goto onError;
3987 }
3988 return PyUnicode_GET_SIZE(unicode);
3989
Benjamin Peterson29060642009-01-31 22:14:21 +00003990 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003991 return -1;
3992}
3993
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003994Py_ssize_t
3995PyUnicode_GetLength(PyObject *unicode)
3996{
Victor Stinner07621332012-06-16 04:53:46 +02003997 if (!PyUnicode_Check(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003998 PyErr_BadArgument();
3999 return -1;
4000 }
Victor Stinner07621332012-06-16 04:53:46 +02004001 if (PyUnicode_READY(unicode) == -1)
4002 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004003 return PyUnicode_GET_LENGTH(unicode);
4004}
4005
4006Py_UCS4
4007PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
4008{
Victor Stinner2fe5ced2011-10-02 00:25:40 +02004009 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
4010 PyErr_BadArgument();
4011 return (Py_UCS4)-1;
4012 }
Victor Stinnerc4b49542011-12-11 22:44:26 +01004013 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinner2fe5ced2011-10-02 00:25:40 +02004014 PyErr_SetString(PyExc_IndexError, "string index out of range");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004015 return (Py_UCS4)-1;
4016 }
4017 return PyUnicode_READ_CHAR(unicode, index);
4018}
4019
4020int
4021PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 ch)
4022{
4023 if (!PyUnicode_Check(unicode) || !PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02004024 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004025 return -1;
4026 }
Victor Stinner488fa492011-12-12 00:01:39 +01004027 assert(PyUnicode_IS_READY(unicode));
Victor Stinnerc4b49542011-12-11 22:44:26 +01004028 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02004029 PyErr_SetString(PyExc_IndexError, "string index out of range");
4030 return -1;
4031 }
Victor Stinner488fa492011-12-12 00:01:39 +01004032 if (unicode_check_modifiable(unicode))
Victor Stinnercd9950f2011-10-02 00:34:53 +02004033 return -1;
Victor Stinnerc9590ad2012-03-04 01:34:37 +01004034 if (ch > PyUnicode_MAX_CHAR_VALUE(unicode)) {
4035 PyErr_SetString(PyExc_ValueError, "character out of range");
4036 return -1;
4037 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004038 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
4039 index, ch);
4040 return 0;
4041}
4042
Alexander Belopolsky40018472011-02-26 01:02:56 +00004043const char *
4044PyUnicode_GetDefaultEncoding(void)
Fred Drakee4315f52000-05-09 19:53:39 +00004045{
Victor Stinner42cb4622010-09-01 19:39:01 +00004046 return "utf-8";
Fred Drakee4315f52000-05-09 19:53:39 +00004047}
4048
Victor Stinner554f3f02010-06-16 23:33:54 +00004049/* create or adjust a UnicodeDecodeError */
4050static void
4051make_decode_exception(PyObject **exceptionObject,
4052 const char *encoding,
4053 const char *input, Py_ssize_t length,
4054 Py_ssize_t startpos, Py_ssize_t endpos,
4055 const char *reason)
4056{
4057 if (*exceptionObject == NULL) {
4058 *exceptionObject = PyUnicodeDecodeError_Create(
4059 encoding, input, length, startpos, endpos, reason);
4060 }
4061 else {
4062 if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
4063 goto onError;
4064 if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
4065 goto onError;
4066 if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
4067 goto onError;
4068 }
4069 return;
4070
4071onError:
4072 Py_DECREF(*exceptionObject);
4073 *exceptionObject = NULL;
4074}
4075
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004076/* error handling callback helper:
4077 build arguments, call the callback and check the arguments,
Fred Drakedb390c12005-10-28 14:39:47 +00004078 if no exception occurred, copy the replacement to the output
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004079 and adjust various state variables.
4080 return 0 on success, -1 on error
4081*/
4082
Alexander Belopolsky40018472011-02-26 01:02:56 +00004083static int
4084unicode_decode_call_errorhandler(const char *errors, PyObject **errorHandler,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004085 const char *encoding, const char *reason,
4086 const char **input, const char **inend, Py_ssize_t *startinpos,
4087 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004088 PyObject **output, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004089{
Benjamin Peterson142957c2008-07-04 19:55:29 +00004090 static char *argparse = "O!n;decoding error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004091
4092 PyObject *restuple = NULL;
4093 PyObject *repunicode = NULL;
Victor Stinner596a6c42011-11-09 00:02:18 +01004094 Py_ssize_t outsize;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004095 Py_ssize_t insize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004096 Py_ssize_t requiredsize;
4097 Py_ssize_t newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004098 PyObject *inputobj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004099 int res = -1;
4100
Victor Stinner596a6c42011-11-09 00:02:18 +01004101 if (_PyUnicode_KIND(*output) != PyUnicode_WCHAR_KIND)
4102 outsize = PyUnicode_GET_LENGTH(*output);
4103 else
4104 outsize = _PyUnicode_WSTR_LENGTH(*output);
4105
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004106 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004107 *errorHandler = PyCodec_LookupError(errors);
4108 if (*errorHandler == NULL)
4109 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004110 }
4111
Victor Stinner554f3f02010-06-16 23:33:54 +00004112 make_decode_exception(exceptionObject,
4113 encoding,
4114 *input, *inend - *input,
4115 *startinpos, *endinpos,
4116 reason);
4117 if (*exceptionObject == NULL)
4118 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004119
4120 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
4121 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004122 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004123 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00004124 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00004125 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004126 }
4127 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00004128 goto onError;
Benjamin Petersonbac79492012-01-14 13:34:47 -05004129 if (PyUnicode_READY(repunicode) == -1)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004130 goto onError;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004131
4132 /* Copy back the bytes variables, which might have been modified by the
4133 callback */
4134 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4135 if (!inputobj)
4136 goto onError;
Christian Heimes72b710a2008-05-26 13:28:38 +00004137 if (!PyBytes_Check(inputobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004138 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
Walter Dörwalde78178e2007-07-30 13:31:40 +00004139 }
Christian Heimes72b710a2008-05-26 13:28:38 +00004140 *input = PyBytes_AS_STRING(inputobj);
4141 insize = PyBytes_GET_SIZE(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004142 *inend = *input + insize;
Walter Dörwald36f938f2007-08-10 10:11:43 +00004143 /* we can DECREF safely, as the exception has another reference,
4144 so the object won't go away. */
4145 Py_DECREF(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004146
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004147 if (newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004148 newpos = insize+newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004149 if (newpos<0 || newpos>insize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004150 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
4151 goto onError;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004152 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004153
Victor Stinner596a6c42011-11-09 00:02:18 +01004154 if (_PyUnicode_KIND(*output) != PyUnicode_WCHAR_KIND) {
4155 /* need more space? (at least enough for what we
4156 have+the replacement+the rest of the string (starting
4157 at the new input position), so we won't have to check space
4158 when there are no errors in the rest of the string) */
4159 Py_ssize_t replen = PyUnicode_GET_LENGTH(repunicode);
4160 requiredsize = *outpos + replen + insize-newpos;
4161 if (requiredsize > outsize) {
4162 if (requiredsize<2*outsize)
4163 requiredsize = 2*outsize;
4164 if (unicode_resize(output, requiredsize) < 0)
4165 goto onError;
4166 }
Victor Stinner1b487b42012-05-03 12:29:04 +02004167 if (unicode_widen(output, *outpos,
4168 PyUnicode_MAX_CHAR_VALUE(repunicode)) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004169 goto onError;
Victor Stinnerd3f08822012-05-29 12:57:52 +02004170 _PyUnicode_FastCopyCharacters(*output, *outpos, repunicode, 0, replen);
Victor Stinner596a6c42011-11-09 00:02:18 +01004171 *outpos += replen;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004172 }
Victor Stinner596a6c42011-11-09 00:02:18 +01004173 else {
4174 wchar_t *repwstr;
4175 Py_ssize_t repwlen;
4176 repwstr = PyUnicode_AsUnicodeAndSize(repunicode, &repwlen);
4177 if (repwstr == NULL)
4178 goto onError;
4179 /* need more space? (at least enough for what we
4180 have+the replacement+the rest of the string (starting
4181 at the new input position), so we won't have to check space
4182 when there are no errors in the rest of the string) */
4183 requiredsize = *outpos + repwlen + insize-newpos;
4184 if (requiredsize > outsize) {
4185 if (requiredsize < 2*outsize)
4186 requiredsize = 2*outsize;
4187 if (unicode_resize(output, requiredsize) < 0)
4188 goto onError;
4189 }
4190 wcsncpy(_PyUnicode_WSTR(*output) + *outpos, repwstr, repwlen);
4191 *outpos += repwlen;
4192 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004193 *endinpos = newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004194 *inptr = *input + newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004195
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004196 /* we made it! */
4197 res = 0;
4198
Benjamin Peterson29060642009-01-31 22:14:21 +00004199 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004200 Py_XDECREF(restuple);
4201 return res;
4202}
4203
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004204/* --- UTF-7 Codec -------------------------------------------------------- */
4205
Antoine Pitrou244651a2009-05-04 18:56:13 +00004206/* See RFC2152 for details. We encode conservatively and decode liberally. */
4207
4208/* Three simple macros defining base-64. */
4209
4210/* Is c a base-64 character? */
4211
4212#define IS_BASE64(c) \
4213 (((c) >= 'A' && (c) <= 'Z') || \
4214 ((c) >= 'a' && (c) <= 'z') || \
4215 ((c) >= '0' && (c) <= '9') || \
4216 (c) == '+' || (c) == '/')
4217
4218/* given that c is a base-64 character, what is its base-64 value? */
4219
4220#define FROM_BASE64(c) \
4221 (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' : \
4222 ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 : \
4223 ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 : \
4224 (c) == '+' ? 62 : 63)
4225
4226/* What is the base-64 character of the bottom 6 bits of n? */
4227
4228#define TO_BASE64(n) \
4229 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
4230
4231/* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
4232 * decoded as itself. We are permissive on decoding; the only ASCII
4233 * byte not decoding to itself is the + which begins a base64
4234 * string. */
4235
4236#define DECODE_DIRECT(c) \
4237 ((c) <= 127 && (c) != '+')
4238
4239/* The UTF-7 encoder treats ASCII characters differently according to
4240 * whether they are Set D, Set O, Whitespace, or special (i.e. none of
4241 * the above). See RFC2152. This array identifies these different
4242 * sets:
4243 * 0 : "Set D"
4244 * alphanumeric and '(),-./:?
4245 * 1 : "Set O"
4246 * !"#$%&*;<=>@[]^_`{|}
4247 * 2 : "whitespace"
4248 * ht nl cr sp
4249 * 3 : special (must be base64 encoded)
4250 * everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
4251 */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004252
Tim Petersced69f82003-09-16 20:30:58 +00004253static
Antoine Pitrou244651a2009-05-04 18:56:13 +00004254char utf7_category[128] = {
4255/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
4256 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
4257/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
4258 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
4259/* sp ! " # $ % & ' ( ) * + , - . / */
4260 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
4261/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
4262 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
4263/* @ A B C D E F G H I J K L M N O */
4264 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4265/* P Q R S T U V W X Y Z [ \ ] ^ _ */
4266 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
4267/* ` a b c d e f g h i j k l m n o */
4268 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4269/* p q r s t u v w x y z { | } ~ del */
4270 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004271};
4272
Antoine Pitrou244651a2009-05-04 18:56:13 +00004273/* ENCODE_DIRECT: this character should be encoded as itself. The
4274 * answer depends on whether we are encoding set O as itself, and also
4275 * on whether we are encoding whitespace as itself. RFC2152 makes it
4276 * clear that the answers to these questions vary between
4277 * applications, so this code needs to be flexible. */
Marc-André Lemburge115ec82005-10-19 22:33:31 +00004278
Antoine Pitrou244651a2009-05-04 18:56:13 +00004279#define ENCODE_DIRECT(c, directO, directWS) \
4280 ((c) < 128 && (c) > 0 && \
4281 ((utf7_category[(c)] == 0) || \
4282 (directWS && (utf7_category[(c)] == 2)) || \
4283 (directO && (utf7_category[(c)] == 1))))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004284
Alexander Belopolsky40018472011-02-26 01:02:56 +00004285PyObject *
4286PyUnicode_DecodeUTF7(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004287 Py_ssize_t size,
4288 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004289{
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004290 return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
4291}
4292
Antoine Pitrou244651a2009-05-04 18:56:13 +00004293/* The decoder. The only state we preserve is our read position,
4294 * i.e. how many characters we have consumed. So if we end in the
4295 * middle of a shift sequence we have to back off the read position
4296 * and the output to the beginning of the sequence, otherwise we lose
4297 * all the shift state (seen bits, number of bits seen, high
4298 * surrogate). */
4299
Alexander Belopolsky40018472011-02-26 01:02:56 +00004300PyObject *
4301PyUnicode_DecodeUTF7Stateful(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004302 Py_ssize_t size,
4303 const char *errors,
4304 Py_ssize_t *consumed)
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004305{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004306 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004307 Py_ssize_t startinpos;
4308 Py_ssize_t endinpos;
4309 Py_ssize_t outpos;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004310 const char *e;
Victor Stinner7931d9a2011-11-04 00:22:48 +01004311 PyObject *unicode;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004312 const char *errmsg = "";
4313 int inShift = 0;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004314 Py_ssize_t shiftOutStart;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004315 unsigned int base64bits = 0;
4316 unsigned long base64buffer = 0;
Victor Stinner24729f32011-11-10 20:31:37 +01004317 Py_UCS4 surrogate = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004318 PyObject *errorHandler = NULL;
4319 PyObject *exc = NULL;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004320
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004321 /* Start off assuming it's all ASCII. Widen later as necessary. */
4322 unicode = PyUnicode_New(size, 127);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004323 if (!unicode)
4324 return NULL;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004325 if (size == 0) {
4326 if (consumed)
4327 *consumed = 0;
Victor Stinner7931d9a2011-11-04 00:22:48 +01004328 return unicode;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004329 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004330
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004331 shiftOutStart = outpos = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004332 e = s + size;
4333
4334 while (s < e) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004335 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00004336 restart:
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00004337 ch = (unsigned char) *s;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004338
Antoine Pitrou244651a2009-05-04 18:56:13 +00004339 if (inShift) { /* in a base-64 section */
4340 if (IS_BASE64(ch)) { /* consume a base-64 character */
4341 base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
4342 base64bits += 6;
4343 s++;
4344 if (base64bits >= 16) {
4345 /* we have enough bits for a UTF-16 value */
Victor Stinner24729f32011-11-10 20:31:37 +01004346 Py_UCS4 outCh = (Py_UCS4)(base64buffer >> (base64bits-16));
Antoine Pitrou244651a2009-05-04 18:56:13 +00004347 base64bits -= 16;
4348 base64buffer &= (1 << base64bits) - 1; /* clear high bits */
4349 if (surrogate) {
4350 /* expecting a second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004351 if (Py_UNICODE_IS_LOW_SURROGATE(outCh)) {
4352 Py_UCS4 ch2 = Py_UNICODE_JOIN_SURROGATES(surrogate, outCh);
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004353 if (unicode_putchar(&unicode, &outpos, ch2) < 0)
4354 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004355 surrogate = 0;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01004356 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004357 }
4358 else {
Antoine Pitrou78edf752011-11-15 01:44:16 +01004359 if (unicode_putchar(&unicode, &outpos, surrogate) < 0)
4360 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004361 surrogate = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004362 }
4363 }
Victor Stinner551ac952011-11-29 22:58:13 +01004364 if (Py_UNICODE_IS_HIGH_SURROGATE(outCh)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004365 /* first surrogate */
4366 surrogate = outCh;
4367 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004368 else {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004369 if (unicode_putchar(&unicode, &outpos, outCh) < 0)
4370 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004371 }
4372 }
4373 }
4374 else { /* now leaving a base-64 section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004375 inShift = 0;
4376 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004377 if (surrogate) {
Antoine Pitrou78edf752011-11-15 01:44:16 +01004378 if (unicode_putchar(&unicode, &outpos, surrogate) < 0)
4379 goto onError;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01004380 surrogate = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004381 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004382 if (base64bits > 0) { /* left-over bits */
4383 if (base64bits >= 6) {
4384 /* We've seen at least one base-64 character */
4385 errmsg = "partial character in shift sequence";
4386 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004387 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004388 else {
4389 /* Some bits remain; they should be zero */
4390 if (base64buffer != 0) {
4391 errmsg = "non-zero padding bits in shift sequence";
4392 goto utf7Error;
4393 }
4394 }
4395 }
4396 if (ch != '-') {
4397 /* '-' is absorbed; other terminating
4398 characters are preserved */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004399 if (unicode_putchar(&unicode, &outpos, ch) < 0)
4400 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004401 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004402 }
4403 }
4404 else if ( ch == '+' ) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004405 startinpos = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004406 s++; /* consume '+' */
4407 if (s < e && *s == '-') { /* '+-' encodes '+' */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004408 s++;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004409 if (unicode_putchar(&unicode, &outpos, '+') < 0)
4410 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004411 }
4412 else { /* begin base64-encoded section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004413 inShift = 1;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004414 shiftOutStart = outpos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004415 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004416 }
4417 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004418 else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004419 if (unicode_putchar(&unicode, &outpos, ch) < 0)
4420 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004421 s++;
4422 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004423 else {
4424 startinpos = s-starts;
4425 s++;
4426 errmsg = "unexpected special character";
4427 goto utf7Error;
4428 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004429 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004430utf7Error:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004431 endinpos = s-starts;
4432 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00004433 errors, &errorHandler,
4434 "utf7", errmsg,
4435 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004436 &unicode, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00004437 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004438 }
4439
Antoine Pitrou244651a2009-05-04 18:56:13 +00004440 /* end of string */
4441
4442 if (inShift && !consumed) { /* in shift sequence, no more to follow */
4443 /* if we're in an inconsistent state, that's an error */
4444 if (surrogate ||
4445 (base64bits >= 6) ||
4446 (base64bits > 0 && base64buffer != 0)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004447 endinpos = size;
4448 if (unicode_decode_call_errorhandler(
4449 errors, &errorHandler,
4450 "utf7", "unterminated shift sequence",
4451 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004452 &unicode, &outpos))
Antoine Pitrou244651a2009-05-04 18:56:13 +00004453 goto onError;
4454 if (s < e)
4455 goto restart;
4456 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004457 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004458
4459 /* return state */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004460 if (consumed) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004461 if (inShift) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004462 outpos = shiftOutStart; /* back off output */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004463 *consumed = startinpos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004464 }
4465 else {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004466 *consumed = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004467 }
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004468 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004469
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004470 if (unicode_resize(&unicode, outpos) < 0)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004471 goto onError;
4472
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004473 Py_XDECREF(errorHandler);
4474 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01004475 return unicode_result(unicode);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004476
Benjamin Peterson29060642009-01-31 22:14:21 +00004477 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004478 Py_XDECREF(errorHandler);
4479 Py_XDECREF(exc);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004480 Py_DECREF(unicode);
4481 return NULL;
4482}
4483
4484
Alexander Belopolsky40018472011-02-26 01:02:56 +00004485PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004486_PyUnicode_EncodeUTF7(PyObject *str,
4487 int base64SetO,
4488 int base64WhiteSpace,
4489 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004490{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004491 int kind;
4492 void *data;
4493 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004494 PyObject *v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004495 int inShift = 0;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004496 Py_ssize_t i;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004497 unsigned int base64bits = 0;
4498 unsigned long base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004499 char * out;
4500 char * start;
4501
Benjamin Petersonbac79492012-01-14 13:34:47 -05004502 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004503 return NULL;
4504 kind = PyUnicode_KIND(str);
4505 data = PyUnicode_DATA(str);
4506 len = PyUnicode_GET_LENGTH(str);
4507
4508 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004509 return PyBytes_FromStringAndSize(NULL, 0);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004510
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004511 /* It might be possible to tighten this worst case */
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004512 if (len > PY_SSIZE_T_MAX / 8)
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004513 return PyErr_NoMemory();
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004514 v = PyBytes_FromStringAndSize(NULL, len * 8);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004515 if (v == NULL)
4516 return NULL;
4517
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004518 start = out = PyBytes_AS_STRING(v);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004519 for (i = 0; i < len; ++i) {
Victor Stinner0e368262011-11-10 20:12:49 +01004520 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004521
Antoine Pitrou244651a2009-05-04 18:56:13 +00004522 if (inShift) {
4523 if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4524 /* shifting out */
4525 if (base64bits) { /* output remaining bits */
4526 *out++ = TO_BASE64(base64buffer << (6-base64bits));
4527 base64buffer = 0;
4528 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004529 }
4530 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004531 /* Characters not in the BASE64 set implicitly unshift the sequence
4532 so no '-' is required, except if the character is itself a '-' */
4533 if (IS_BASE64(ch) || ch == '-') {
4534 *out++ = '-';
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004535 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004536 *out++ = (char) ch;
4537 }
4538 else {
4539 goto encode_char;
Tim Petersced69f82003-09-16 20:30:58 +00004540 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004541 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004542 else { /* not in a shift sequence */
4543 if (ch == '+') {
4544 *out++ = '+';
4545 *out++ = '-';
4546 }
4547 else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4548 *out++ = (char) ch;
4549 }
4550 else {
4551 *out++ = '+';
4552 inShift = 1;
4553 goto encode_char;
4554 }
4555 }
4556 continue;
4557encode_char:
Antoine Pitrou244651a2009-05-04 18:56:13 +00004558 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01004559 assert(ch <= MAX_UNICODE);
Victor Stinner0d3721d2011-11-22 03:27:53 +01004560
Antoine Pitrou244651a2009-05-04 18:56:13 +00004561 /* code first surrogate */
4562 base64bits += 16;
4563 base64buffer = (base64buffer << 16) | 0xd800 | ((ch-0x10000) >> 10);
4564 while (base64bits >= 6) {
4565 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4566 base64bits -= 6;
4567 }
4568 /* prepare second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004569 ch = Py_UNICODE_LOW_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004570 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004571 base64bits += 16;
4572 base64buffer = (base64buffer << 16) | ch;
4573 while (base64bits >= 6) {
4574 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4575 base64bits -= 6;
4576 }
Hye-Shik Chang1bc09b72004-01-03 19:35:43 +00004577 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004578 if (base64bits)
4579 *out++= TO_BASE64(base64buffer << (6-base64bits) );
4580 if (inShift)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004581 *out++ = '-';
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004582 if (_PyBytes_Resize(&v, out - start) < 0)
4583 return NULL;
4584 return v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004585}
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004586PyObject *
4587PyUnicode_EncodeUTF7(const Py_UNICODE *s,
4588 Py_ssize_t size,
4589 int base64SetO,
4590 int base64WhiteSpace,
4591 const char *errors)
4592{
4593 PyObject *result;
4594 PyObject *tmp = PyUnicode_FromUnicode(s, size);
4595 if (tmp == NULL)
4596 return NULL;
Victor Stinner0e368262011-11-10 20:12:49 +01004597 result = _PyUnicode_EncodeUTF7(tmp, base64SetO,
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004598 base64WhiteSpace, errors);
4599 Py_DECREF(tmp);
4600 return result;
4601}
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004602
Antoine Pitrou244651a2009-05-04 18:56:13 +00004603#undef IS_BASE64
4604#undef FROM_BASE64
4605#undef TO_BASE64
4606#undef DECODE_DIRECT
4607#undef ENCODE_DIRECT
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004608
Guido van Rossumd57fd912000-03-10 22:53:23 +00004609/* --- UTF-8 Codec -------------------------------------------------------- */
4610
Alexander Belopolsky40018472011-02-26 01:02:56 +00004611PyObject *
4612PyUnicode_DecodeUTF8(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004613 Py_ssize_t size,
4614 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004615{
Walter Dörwald69652032004-09-07 20:24:22 +00004616 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
4617}
4618
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004619#include "stringlib/asciilib.h"
4620#include "stringlib/codecs.h"
4621#include "stringlib/undef.h"
4622
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004623#include "stringlib/ucs1lib.h"
4624#include "stringlib/codecs.h"
4625#include "stringlib/undef.h"
4626
4627#include "stringlib/ucs2lib.h"
4628#include "stringlib/codecs.h"
4629#include "stringlib/undef.h"
4630
4631#include "stringlib/ucs4lib.h"
4632#include "stringlib/codecs.h"
4633#include "stringlib/undef.h"
4634
Antoine Pitrouab868312009-01-10 15:40:25 +00004635/* Mask to quickly check whether a C 'long' contains a
4636 non-ASCII, UTF8-encoded char. */
4637#if (SIZEOF_LONG == 8)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004638# define ASCII_CHAR_MASK 0x8080808080808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004639#elif (SIZEOF_LONG == 4)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004640# define ASCII_CHAR_MASK 0x80808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004641#else
4642# error C 'long' size should be either 4 or 8!
4643#endif
4644
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004645static Py_ssize_t
4646ascii_decode(const char *start, const char *end, Py_UCS1 *dest)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004647{
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004648 const char *p = start;
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004649 const char *aligned_end = (const char *) _Py_ALIGN_DOWN(end, SIZEOF_LONG);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004650
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004651#if SIZEOF_LONG <= SIZEOF_VOID_P
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004652 assert(_Py_IS_ALIGNED(dest, SIZEOF_LONG));
4653 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004654 /* Fast path, see in STRINGLIB(utf8_decode) for
4655 an explanation. */
4656 /* Help register allocation */
4657 register const char *_p = p;
4658 register Py_UCS1 * q = dest;
4659 while (_p < aligned_end) {
4660 unsigned long value = *(const unsigned long *) _p;
4661 if (value & ASCII_CHAR_MASK)
Benjamin Peterson29060642009-01-31 22:14:21 +00004662 break;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004663 *((unsigned long *)q) = value;
4664 _p += SIZEOF_LONG;
4665 q += SIZEOF_LONG;
Benjamin Peterson14339b62009-01-31 16:36:08 +00004666 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004667 p = _p;
4668 while (p < end) {
4669 if ((unsigned char)*p & 0x80)
4670 break;
4671 *q++ = *p++;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004672 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004673 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004674 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004675#endif
4676 while (p < end) {
4677 /* Fast path, see in STRINGLIB(utf8_decode) in stringlib/codecs.h
4678 for an explanation. */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004679 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004680 /* Help register allocation */
4681 register const char *_p = p;
4682 while (_p < aligned_end) {
4683 unsigned long value = *(unsigned long *) _p;
4684 if (value & ASCII_CHAR_MASK)
4685 break;
4686 _p += SIZEOF_LONG;
4687 }
4688 p = _p;
4689 if (_p == end)
4690 break;
4691 }
4692 if ((unsigned char)*p & 0x80)
4693 break;
4694 ++p;
4695 }
4696 memcpy(dest, start, p - start);
4697 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004698}
Antoine Pitrouab868312009-01-10 15:40:25 +00004699
Victor Stinner785938e2011-12-11 20:09:03 +01004700PyObject *
4701PyUnicode_DecodeUTF8Stateful(const char *s,
4702 Py_ssize_t size,
4703 const char *errors,
4704 Py_ssize_t *consumed)
4705{
Victor Stinner785938e2011-12-11 20:09:03 +01004706 PyObject *unicode;
Victor Stinner785938e2011-12-11 20:09:03 +01004707 const char *starts = s;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004708 const char *end = s + size;
4709 Py_ssize_t outpos;
4710
4711 Py_ssize_t startinpos;
4712 Py_ssize_t endinpos;
4713 const char *errmsg = "";
4714 PyObject *errorHandler = NULL;
4715 PyObject *exc = NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01004716
4717 if (size == 0) {
4718 if (consumed)
4719 *consumed = 0;
Victor Stinner382955f2011-12-11 21:44:00 +01004720 Py_INCREF(unicode_empty);
4721 return unicode_empty;
Victor Stinner785938e2011-12-11 20:09:03 +01004722 }
4723
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004724 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
4725 if (size == 1 && (unsigned char)s[0] < 128) {
Victor Stinner785938e2011-12-11 20:09:03 +01004726 if (consumed)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004727 *consumed = 1;
4728 return get_latin1_char((unsigned char)s[0]);
Victor Stinner785938e2011-12-11 20:09:03 +01004729 }
4730
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004731 unicode = PyUnicode_New(size, 127);
Victor Stinner785938e2011-12-11 20:09:03 +01004732 if (!unicode)
4733 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01004734
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004735 outpos = ascii_decode(s, end, PyUnicode_1BYTE_DATA(unicode));
4736 s += outpos;
4737 while (s < end) {
4738 Py_UCS4 ch;
4739 int kind = PyUnicode_KIND(unicode);
4740 if (kind == PyUnicode_1BYTE_KIND) {
4741 if (PyUnicode_IS_ASCII(unicode))
4742 ch = asciilib_utf8_decode(&s, end,
4743 PyUnicode_1BYTE_DATA(unicode), &outpos);
4744 else
4745 ch = ucs1lib_utf8_decode(&s, end,
4746 PyUnicode_1BYTE_DATA(unicode), &outpos);
4747 } else if (kind == PyUnicode_2BYTE_KIND) {
4748 ch = ucs2lib_utf8_decode(&s, end,
4749 PyUnicode_2BYTE_DATA(unicode), &outpos);
4750 } else {
4751 assert(kind == PyUnicode_4BYTE_KIND);
4752 ch = ucs4lib_utf8_decode(&s, end,
4753 PyUnicode_4BYTE_DATA(unicode), &outpos);
4754 }
4755
4756 switch (ch) {
4757 case 0:
4758 if (s == end || consumed)
4759 goto End;
4760 errmsg = "unexpected end of data";
4761 startinpos = s - starts;
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004762 endinpos = end - starts;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004763 break;
4764 case 1:
4765 errmsg = "invalid start byte";
4766 startinpos = s - starts;
4767 endinpos = startinpos + 1;
4768 break;
4769 case 2:
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004770 case 3:
4771 case 4:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004772 errmsg = "invalid continuation byte";
4773 startinpos = s - starts;
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004774 endinpos = startinpos + ch - 1;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004775 break;
4776 default:
4777 if (unicode_putchar(&unicode, &outpos, ch) < 0)
4778 goto onError;
4779 continue;
4780 }
4781
4782 if (unicode_decode_call_errorhandler(
4783 errors, &errorHandler,
4784 "utf-8", errmsg,
4785 &starts, &end, &startinpos, &endinpos, &exc, &s,
4786 &unicode, &outpos))
4787 goto onError;
Victor Stinner785938e2011-12-11 20:09:03 +01004788 }
4789
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004790End:
4791 if (unicode_resize(&unicode, outpos) < 0)
4792 goto onError;
4793
4794 if (consumed)
4795 *consumed = s - starts;
4796
4797 Py_XDECREF(errorHandler);
4798 Py_XDECREF(exc);
4799 assert(_PyUnicode_CheckConsistency(unicode, 1));
4800 return unicode;
4801
4802onError:
4803 Py_XDECREF(errorHandler);
4804 Py_XDECREF(exc);
4805 Py_XDECREF(unicode);
4806 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01004807}
4808
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004809#ifdef __APPLE__
4810
4811/* Simplified UTF-8 decoder using surrogateescape error handler,
4812 used to decode the command line arguments on Mac OS X. */
4813
4814wchar_t*
4815_Py_DecodeUTF8_surrogateescape(const char *s, Py_ssize_t size)
4816{
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004817 const char *e;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004818 wchar_t *unicode;
4819 Py_ssize_t outpos;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004820
4821 /* Note: size will always be longer than the resulting Unicode
4822 character count */
4823 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < (size + 1)) {
4824 PyErr_NoMemory();
4825 return NULL;
4826 }
4827 unicode = PyMem_Malloc((size + 1) * sizeof(wchar_t));
4828 if (!unicode)
4829 return NULL;
4830
4831 /* Unpack UTF-8 encoded data */
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004832 e = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004833 outpos = 0;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004834 while (s < e) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004835 Py_UCS4 ch;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004836#if SIZEOF_WCHAR_T == 4
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004837 ch = ucs4lib_utf8_decode(&s, e, (Py_UCS4 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004838#else
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004839 ch = ucs2lib_utf8_decode(&s, e, (Py_UCS2 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004840#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004841 if (ch > 0xFF) {
4842#if SIZEOF_WCHAR_T == 4
4843 assert(0);
4844#else
4845 assert(Py_UNICODE_IS_SURROGATE(ch));
4846 /* compute and append the two surrogates: */
4847 unicode[outpos++] = (wchar_t)Py_UNICODE_HIGH_SURROGATE(ch);
4848 unicode[outpos++] = (wchar_t)Py_UNICODE_LOW_SURROGATE(ch);
4849#endif
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004850 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004851 else {
4852 if (!ch && s == e)
4853 break;
4854 /* surrogateescape */
4855 unicode[outpos++] = 0xDC00 + (unsigned char)*s++;
4856 }
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004857 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004858 unicode[outpos] = L'\0';
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004859 return unicode;
4860}
4861
4862#endif /* __APPLE__ */
Antoine Pitrouab868312009-01-10 15:40:25 +00004863
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004864/* Primary internal function which creates utf8 encoded bytes objects.
4865
4866 Allocation strategy: if the string is short, convert into a stack buffer
Tim Peters602f7402002-04-27 18:03:26 +00004867 and allocate exactly as much space needed at the end. Else allocate the
4868 maximum possible needed (4 result bytes per Unicode character), and return
4869 the excess memory at the end.
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004870*/
Tim Peters7e3d9612002-04-21 03:26:37 +00004871PyObject *
Victor Stinner7931d9a2011-11-04 00:22:48 +01004872_PyUnicode_AsUTF8String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004873{
Victor Stinner6099a032011-12-18 14:22:26 +01004874 enum PyUnicode_Kind kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004875 void *data;
4876 Py_ssize_t size;
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00004877
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004878 if (!PyUnicode_Check(unicode)) {
4879 PyErr_BadArgument();
4880 return NULL;
4881 }
4882
4883 if (PyUnicode_READY(unicode) == -1)
4884 return NULL;
4885
Victor Stinnere90fe6a2011-10-01 16:48:13 +02004886 if (PyUnicode_UTF8(unicode))
4887 return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode),
4888 PyUnicode_UTF8_LENGTH(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004889
4890 kind = PyUnicode_KIND(unicode);
4891 data = PyUnicode_DATA(unicode);
4892 size = PyUnicode_GET_LENGTH(unicode);
4893
Benjamin Petersonead6b532011-12-20 17:23:42 -06004894 switch (kind) {
Victor Stinner6099a032011-12-18 14:22:26 +01004895 default:
4896 assert(0);
4897 case PyUnicode_1BYTE_KIND:
4898 /* the string cannot be ASCII, or PyUnicode_UTF8() would be set */
4899 assert(!PyUnicode_IS_ASCII(unicode));
4900 return ucs1lib_utf8_encoder(unicode, data, size, errors);
4901 case PyUnicode_2BYTE_KIND:
4902 return ucs2lib_utf8_encoder(unicode, data, size, errors);
4903 case PyUnicode_4BYTE_KIND:
4904 return ucs4lib_utf8_encoder(unicode, data, size, errors);
Tim Peters602f7402002-04-27 18:03:26 +00004905 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004906}
4907
Alexander Belopolsky40018472011-02-26 01:02:56 +00004908PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004909PyUnicode_EncodeUTF8(const Py_UNICODE *s,
4910 Py_ssize_t size,
4911 const char *errors)
4912{
4913 PyObject *v, *unicode;
4914
4915 unicode = PyUnicode_FromUnicode(s, size);
4916 if (unicode == NULL)
4917 return NULL;
4918 v = _PyUnicode_AsUTF8String(unicode, errors);
4919 Py_DECREF(unicode);
4920 return v;
4921}
4922
4923PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00004924PyUnicode_AsUTF8String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004925{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004926 return _PyUnicode_AsUTF8String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004927}
4928
Walter Dörwald41980ca2007-08-16 21:55:45 +00004929/* --- UTF-32 Codec ------------------------------------------------------- */
4930
4931PyObject *
4932PyUnicode_DecodeUTF32(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004933 Py_ssize_t size,
4934 const char *errors,
4935 int *byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004936{
4937 return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
4938}
4939
4940PyObject *
4941PyUnicode_DecodeUTF32Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004942 Py_ssize_t size,
4943 const char *errors,
4944 int *byteorder,
4945 Py_ssize_t *consumed)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004946{
4947 const char *starts = s;
4948 Py_ssize_t startinpos;
4949 Py_ssize_t endinpos;
4950 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01004951 PyObject *unicode;
Mark Dickinson7db923c2010-06-12 09:10:14 +00004952 const unsigned char *q, *e;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004953 int bo = 0; /* assume native ordering by default */
4954 const char *errmsg = "";
Walter Dörwald41980ca2007-08-16 21:55:45 +00004955 /* Offsets from q for retrieving bytes in the right order. */
4956#ifdef BYTEORDER_IS_LITTLE_ENDIAN
4957 int iorder[] = {0, 1, 2, 3};
4958#else
4959 int iorder[] = {3, 2, 1, 0};
4960#endif
4961 PyObject *errorHandler = NULL;
4962 PyObject *exc = NULL;
Victor Stinner313a1202010-06-11 23:56:51 +00004963
Walter Dörwald41980ca2007-08-16 21:55:45 +00004964 q = (unsigned char *)s;
4965 e = q + size;
4966
4967 if (byteorder)
4968 bo = *byteorder;
4969
4970 /* Check for BOM marks (U+FEFF) in the input and adjust current
4971 byte order setting accordingly. In native mode, the leading BOM
4972 mark is skipped, in all other modes, it is copied to the output
4973 stream as-is (giving a ZWNBSP character). */
4974 if (bo == 0) {
4975 if (size >= 4) {
4976 const Py_UCS4 bom = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
Benjamin Peterson29060642009-01-31 22:14:21 +00004977 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00004978#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Benjamin Peterson29060642009-01-31 22:14:21 +00004979 if (bom == 0x0000FEFF) {
4980 q += 4;
4981 bo = -1;
4982 }
4983 else if (bom == 0xFFFE0000) {
4984 q += 4;
4985 bo = 1;
4986 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004987#else
Benjamin Peterson29060642009-01-31 22:14:21 +00004988 if (bom == 0x0000FEFF) {
4989 q += 4;
4990 bo = 1;
4991 }
4992 else if (bom == 0xFFFE0000) {
4993 q += 4;
4994 bo = -1;
4995 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004996#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00004997 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004998 }
4999
5000 if (bo == -1) {
5001 /* force LE */
5002 iorder[0] = 0;
5003 iorder[1] = 1;
5004 iorder[2] = 2;
5005 iorder[3] = 3;
5006 }
5007 else if (bo == 1) {
5008 /* force BE */
5009 iorder[0] = 3;
5010 iorder[1] = 2;
5011 iorder[2] = 1;
5012 iorder[3] = 0;
5013 }
5014
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005015 /* This might be one to much, because of a BOM */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005016 unicode = PyUnicode_New((size+3)/4, 127);
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005017 if (!unicode)
5018 return NULL;
5019 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01005020 return unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005021 outpos = 0;
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005022
Walter Dörwald41980ca2007-08-16 21:55:45 +00005023 while (q < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005024 Py_UCS4 ch;
5025 /* remaining bytes at the end? (size should be divisible by 4) */
5026 if (e-q<4) {
5027 if (consumed)
5028 break;
5029 errmsg = "truncated data";
5030 startinpos = ((const char *)q)-starts;
5031 endinpos = ((const char *)e)-starts;
5032 goto utf32Error;
5033 /* The remaining input chars are ignored if the callback
5034 chooses to skip the input */
5035 }
5036 ch = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
5037 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00005038
Benjamin Peterson29060642009-01-31 22:14:21 +00005039 if (ch >= 0x110000)
5040 {
5041 errmsg = "codepoint not in range(0x110000)";
5042 startinpos = ((const char *)q)-starts;
5043 endinpos = startinpos+4;
5044 goto utf32Error;
5045 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005046 if (unicode_putchar(&unicode, &outpos, ch) < 0)
5047 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005048 q += 4;
5049 continue;
5050 utf32Error:
Benjamin Peterson29060642009-01-31 22:14:21 +00005051 if (unicode_decode_call_errorhandler(
5052 errors, &errorHandler,
5053 "utf32", errmsg,
5054 &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005055 &unicode, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00005056 goto onError;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005057 }
5058
5059 if (byteorder)
5060 *byteorder = bo;
5061
5062 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005063 *consumed = (const char *)q-starts;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005064
5065 /* Adjust length */
Victor Stinner16e6a802011-12-12 13:24:15 +01005066 if (unicode_resize(&unicode, outpos) < 0)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005067 goto onError;
5068
5069 Py_XDECREF(errorHandler);
5070 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01005071 return unicode_result(unicode);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005072
Benjamin Peterson29060642009-01-31 22:14:21 +00005073 onError:
Walter Dörwald41980ca2007-08-16 21:55:45 +00005074 Py_DECREF(unicode);
5075 Py_XDECREF(errorHandler);
5076 Py_XDECREF(exc);
5077 return NULL;
5078}
5079
5080PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005081_PyUnicode_EncodeUTF32(PyObject *str,
5082 const char *errors,
5083 int byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005084{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005085 int kind;
5086 void *data;
5087 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005088 PyObject *v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005089 unsigned char *p;
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01005090 Py_ssize_t nsize, i;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005091 /* Offsets from p for storing byte pairs in the right order. */
5092#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5093 int iorder[] = {0, 1, 2, 3};
5094#else
5095 int iorder[] = {3, 2, 1, 0};
5096#endif
5097
Benjamin Peterson29060642009-01-31 22:14:21 +00005098#define STORECHAR(CH) \
5099 do { \
5100 p[iorder[3]] = ((CH) >> 24) & 0xff; \
5101 p[iorder[2]] = ((CH) >> 16) & 0xff; \
5102 p[iorder[1]] = ((CH) >> 8) & 0xff; \
5103 p[iorder[0]] = (CH) & 0xff; \
5104 p += 4; \
Walter Dörwald41980ca2007-08-16 21:55:45 +00005105 } while(0)
5106
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005107 if (!PyUnicode_Check(str)) {
5108 PyErr_BadArgument();
5109 return NULL;
5110 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005111 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005112 return NULL;
5113 kind = PyUnicode_KIND(str);
5114 data = PyUnicode_DATA(str);
5115 len = PyUnicode_GET_LENGTH(str);
5116
5117 nsize = len + (byteorder == 0);
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01005118 if (nsize > PY_SSIZE_T_MAX / 4)
Benjamin Peterson29060642009-01-31 22:14:21 +00005119 return PyErr_NoMemory();
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01005120 v = PyBytes_FromStringAndSize(NULL, nsize * 4);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005121 if (v == NULL)
5122 return NULL;
5123
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005124 p = (unsigned char *)PyBytes_AS_STRING(v);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005125 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005126 STORECHAR(0xFEFF);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005127 if (len == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005128 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005129
5130 if (byteorder == -1) {
5131 /* force LE */
5132 iorder[0] = 0;
5133 iorder[1] = 1;
5134 iorder[2] = 2;
5135 iorder[3] = 3;
5136 }
5137 else if (byteorder == 1) {
5138 /* force BE */
5139 iorder[0] = 3;
5140 iorder[1] = 2;
5141 iorder[2] = 1;
5142 iorder[3] = 0;
5143 }
5144
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005145 for (i = 0; i < len; i++)
5146 STORECHAR(PyUnicode_READ(kind, data, i));
Guido van Rossum98297ee2007-11-06 21:34:58 +00005147
5148 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005149 return v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005150#undef STORECHAR
5151}
5152
Alexander Belopolsky40018472011-02-26 01:02:56 +00005153PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005154PyUnicode_EncodeUTF32(const Py_UNICODE *s,
5155 Py_ssize_t size,
5156 const char *errors,
5157 int byteorder)
5158{
5159 PyObject *result;
5160 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5161 if (tmp == NULL)
5162 return NULL;
5163 result = _PyUnicode_EncodeUTF32(tmp, errors, byteorder);
5164 Py_DECREF(tmp);
5165 return result;
5166}
5167
5168PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005169PyUnicode_AsUTF32String(PyObject *unicode)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005170{
Victor Stinnerb960b342011-11-20 19:12:52 +01005171 return _PyUnicode_EncodeUTF32(unicode, NULL, 0);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005172}
5173
Guido van Rossumd57fd912000-03-10 22:53:23 +00005174/* --- UTF-16 Codec ------------------------------------------------------- */
5175
Tim Peters772747b2001-08-09 22:21:55 +00005176PyObject *
5177PyUnicode_DecodeUTF16(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005178 Py_ssize_t size,
5179 const char *errors,
5180 int *byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005181{
Walter Dörwald69652032004-09-07 20:24:22 +00005182 return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
5183}
5184
5185PyObject *
5186PyUnicode_DecodeUTF16Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005187 Py_ssize_t size,
5188 const char *errors,
5189 int *byteorder,
5190 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00005191{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005192 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005193 Py_ssize_t startinpos;
5194 Py_ssize_t endinpos;
5195 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01005196 PyObject *unicode;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005197 const unsigned char *q, *e;
Tim Peters772747b2001-08-09 22:21:55 +00005198 int bo = 0; /* assume native ordering by default */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005199 int native_ordering;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00005200 const char *errmsg = "";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005201 PyObject *errorHandler = NULL;
5202 PyObject *exc = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005203
Tim Peters772747b2001-08-09 22:21:55 +00005204 q = (unsigned char *)s;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005205 e = q + size;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005206
5207 if (byteorder)
Tim Peters772747b2001-08-09 22:21:55 +00005208 bo = *byteorder;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005209
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005210 /* Check for BOM marks (U+FEFF) in the input and adjust current
5211 byte order setting accordingly. In native mode, the leading BOM
5212 mark is skipped, in all other modes, it is copied to the output
5213 stream as-is (giving a ZWNBSP character). */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005214 if (bo == 0 && size >= 2) {
5215 const Py_UCS4 bom = (q[1] << 8) | q[0];
5216 if (bom == 0xFEFF) {
5217 q += 2;
5218 bo = -1;
Benjamin Peterson29060642009-01-31 22:14:21 +00005219 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005220 else if (bom == 0xFFFE) {
5221 q += 2;
5222 bo = 1;
5223 }
5224 if (byteorder)
5225 *byteorder = bo;
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005226 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005227
Antoine Pitrou63065d72012-05-15 23:48:04 +02005228 if (q == e) {
5229 if (consumed)
5230 *consumed = size;
5231 Py_INCREF(unicode_empty);
5232 return unicode_empty;
Tim Peters772747b2001-08-09 22:21:55 +00005233 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005234
Antoine Pitrouab868312009-01-10 15:40:25 +00005235#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Antoine Pitrou63065d72012-05-15 23:48:04 +02005236 native_ordering = bo <= 0;
Antoine Pitrouab868312009-01-10 15:40:25 +00005237#else
Antoine Pitrou63065d72012-05-15 23:48:04 +02005238 native_ordering = bo >= 0;
Antoine Pitrouab868312009-01-10 15:40:25 +00005239#endif
Tim Peters772747b2001-08-09 22:21:55 +00005240
Antoine Pitrou63065d72012-05-15 23:48:04 +02005241 /* Note: size will always be longer than the resulting Unicode
5242 character count */
5243 unicode = PyUnicode_New((e - q + 1) / 2, 127);
5244 if (!unicode)
5245 return NULL;
5246
5247 outpos = 0;
5248 while (1) {
5249 Py_UCS4 ch = 0;
5250 if (e - q >= 2) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005251 int kind = PyUnicode_KIND(unicode);
Antoine Pitrou63065d72012-05-15 23:48:04 +02005252 if (kind == PyUnicode_1BYTE_KIND) {
5253 if (PyUnicode_IS_ASCII(unicode))
5254 ch = asciilib_utf16_decode(&q, e,
5255 PyUnicode_1BYTE_DATA(unicode), &outpos,
5256 native_ordering);
5257 else
5258 ch = ucs1lib_utf16_decode(&q, e,
5259 PyUnicode_1BYTE_DATA(unicode), &outpos,
5260 native_ordering);
5261 } else if (kind == PyUnicode_2BYTE_KIND) {
5262 ch = ucs2lib_utf16_decode(&q, e,
5263 PyUnicode_2BYTE_DATA(unicode), &outpos,
5264 native_ordering);
5265 } else {
5266 assert(kind == PyUnicode_4BYTE_KIND);
5267 ch = ucs4lib_utf16_decode(&q, e,
5268 PyUnicode_4BYTE_DATA(unicode), &outpos,
5269 native_ordering);
Antoine Pitrouab868312009-01-10 15:40:25 +00005270 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005271 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005272
Antoine Pitrou63065d72012-05-15 23:48:04 +02005273 switch (ch)
5274 {
5275 case 0:
5276 /* remaining byte at the end? (size should be even) */
5277 if (q == e || consumed)
5278 goto End;
5279 errmsg = "truncated data";
5280 startinpos = ((const char *)q) - starts;
5281 endinpos = ((const char *)e) - starts;
5282 break;
5283 /* The remaining input chars are ignored if the callback
5284 chooses to skip the input */
5285 case 1:
5286 errmsg = "unexpected end of data";
5287 startinpos = ((const char *)q) - 2 - starts;
5288 endinpos = ((const char *)e) - starts;
5289 break;
5290 case 2:
5291 errmsg = "illegal encoding";
5292 startinpos = ((const char *)q) - 2 - starts;
5293 endinpos = startinpos + 2;
5294 break;
5295 case 3:
5296 errmsg = "illegal UTF-16 surrogate";
5297 startinpos = ((const char *)q) - 4 - starts;
5298 endinpos = startinpos + 2;
5299 break;
5300 default:
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005301 if (unicode_putchar(&unicode, &outpos, ch) < 0)
5302 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005303 continue;
5304 }
5305
Benjamin Peterson29060642009-01-31 22:14:21 +00005306 if (unicode_decode_call_errorhandler(
Antoine Pitrouab868312009-01-10 15:40:25 +00005307 errors,
5308 &errorHandler,
5309 "utf16", errmsg,
5310 &starts,
5311 (const char **)&e,
5312 &startinpos,
5313 &endinpos,
5314 &exc,
5315 (const char **)&q,
5316 &unicode,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005317 &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00005318 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005319 }
5320
Antoine Pitrou63065d72012-05-15 23:48:04 +02005321End:
Walter Dörwald69652032004-09-07 20:24:22 +00005322 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005323 *consumed = (const char *)q-starts;
Walter Dörwald69652032004-09-07 20:24:22 +00005324
Guido van Rossumd57fd912000-03-10 22:53:23 +00005325 /* Adjust length */
Victor Stinner16e6a802011-12-12 13:24:15 +01005326 if (unicode_resize(&unicode, outpos) < 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005327 goto onError;
5328
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005329 Py_XDECREF(errorHandler);
5330 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01005331 return unicode_result(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005332
Benjamin Peterson29060642009-01-31 22:14:21 +00005333 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00005334 Py_DECREF(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005335 Py_XDECREF(errorHandler);
5336 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005337 return NULL;
5338}
5339
Tim Peters772747b2001-08-09 22:21:55 +00005340PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005341_PyUnicode_EncodeUTF16(PyObject *str,
5342 const char *errors,
5343 int byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005344{
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005345 enum PyUnicode_Kind kind;
5346 const void *data;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005347 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005348 PyObject *v;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005349 unsigned short *out;
5350 Py_ssize_t bytesize;
5351 Py_ssize_t pairs;
5352#ifdef WORDS_BIGENDIAN
5353 int native_ordering = byteorder >= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005354#else
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005355 int native_ordering = byteorder <= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005356#endif
5357
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005358 if (!PyUnicode_Check(str)) {
5359 PyErr_BadArgument();
5360 return NULL;
5361 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005362 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005363 return NULL;
5364 kind = PyUnicode_KIND(str);
5365 data = PyUnicode_DATA(str);
5366 len = PyUnicode_GET_LENGTH(str);
Victor Stinner0e368262011-11-10 20:12:49 +01005367
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005368 pairs = 0;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005369 if (kind == PyUnicode_4BYTE_KIND) {
5370 const Py_UCS4 *in = (const Py_UCS4 *)data;
5371 const Py_UCS4 *end = in + len;
5372 while (in < end)
5373 if (*in++ >= 0x10000)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005374 pairs++;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005375 }
5376 if (len > PY_SSIZE_T_MAX / 2 - pairs - (byteorder == 0))
Benjamin Peterson29060642009-01-31 22:14:21 +00005377 return PyErr_NoMemory();
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005378 bytesize = (len + pairs + (byteorder == 0)) * 2;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005379 v = PyBytes_FromStringAndSize(NULL, bytesize);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005380 if (v == NULL)
5381 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005382
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005383 /* output buffer is 2-bytes aligned */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02005384 assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 2));
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005385 out = (unsigned short *)PyBytes_AS_STRING(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005386 if (byteorder == 0)
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005387 *out++ = 0xFEFF;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005388 if (len == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005389 goto done;
Tim Peters772747b2001-08-09 22:21:55 +00005390
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005391 switch (kind) {
5392 case PyUnicode_1BYTE_KIND: {
5393 ucs1lib_utf16_encode(out, (const Py_UCS1 *)data, len, native_ordering);
5394 break;
Tim Peters772747b2001-08-09 22:21:55 +00005395 }
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005396 case PyUnicode_2BYTE_KIND: {
5397 ucs2lib_utf16_encode(out, (const Py_UCS2 *)data, len, native_ordering);
5398 break;
Tim Peters772747b2001-08-09 22:21:55 +00005399 }
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005400 case PyUnicode_4BYTE_KIND: {
5401 ucs4lib_utf16_encode(out, (const Py_UCS4 *)data, len, native_ordering);
5402 break;
5403 }
5404 default:
5405 assert(0);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005406 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005407
5408 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005409 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005410}
5411
Alexander Belopolsky40018472011-02-26 01:02:56 +00005412PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005413PyUnicode_EncodeUTF16(const Py_UNICODE *s,
5414 Py_ssize_t size,
5415 const char *errors,
5416 int byteorder)
5417{
5418 PyObject *result;
5419 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5420 if (tmp == NULL)
5421 return NULL;
5422 result = _PyUnicode_EncodeUTF16(tmp, errors, byteorder);
5423 Py_DECREF(tmp);
5424 return result;
5425}
5426
5427PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005428PyUnicode_AsUTF16String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005429{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005430 return _PyUnicode_EncodeUTF16(unicode, NULL, 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005431}
5432
5433/* --- Unicode Escape Codec ----------------------------------------------- */
5434
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005435/* Helper function for PyUnicode_DecodeUnicodeEscape, determines
5436 if all the escapes in the string make it still a valid ASCII string.
5437 Returns -1 if any escapes were found which cause the string to
5438 pop out of ASCII range. Otherwise returns the length of the
5439 required buffer to hold the string.
5440 */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02005441static Py_ssize_t
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005442length_of_escaped_ascii_string(const char *s, Py_ssize_t size)
5443{
5444 const unsigned char *p = (const unsigned char *)s;
5445 const unsigned char *end = p + size;
5446 Py_ssize_t length = 0;
5447
5448 if (size < 0)
5449 return -1;
5450
5451 for (; p < end; ++p) {
5452 if (*p > 127) {
5453 /* Non-ASCII */
5454 return -1;
5455 }
5456 else if (*p != '\\') {
5457 /* Normal character */
5458 ++length;
5459 }
5460 else {
5461 /* Backslash-escape, check next char */
5462 ++p;
5463 /* Escape sequence reaches till end of string or
5464 non-ASCII follow-up. */
5465 if (p >= end || *p > 127)
5466 return -1;
5467 switch (*p) {
5468 case '\n':
5469 /* backslash + \n result in zero characters */
5470 break;
5471 case '\\': case '\'': case '\"':
5472 case 'b': case 'f': case 't':
5473 case 'n': case 'r': case 'v': case 'a':
5474 ++length;
5475 break;
5476 case '0': case '1': case '2': case '3':
5477 case '4': case '5': case '6': case '7':
5478 case 'x': case 'u': case 'U': case 'N':
5479 /* these do not guarantee ASCII characters */
5480 return -1;
5481 default:
5482 /* count the backslash + the other character */
5483 length += 2;
5484 }
5485 }
5486 }
5487 return length;
5488}
5489
Fredrik Lundh06d12682001-01-24 07:59:11 +00005490static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
Marc-André Lemburg0f774e32000-06-28 16:43:35 +00005491
Alexander Belopolsky40018472011-02-26 01:02:56 +00005492PyObject *
5493PyUnicode_DecodeUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005494 Py_ssize_t size,
Victor Stinnerc17f5402011-09-29 00:16:58 +02005495 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005496{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005497 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005498 Py_ssize_t startinpos;
5499 Py_ssize_t endinpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005500 int j;
Victor Stinner7931d9a2011-11-04 00:22:48 +01005501 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005502 const char *end;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005503 char* message;
5504 Py_UCS4 chr = 0xffffffff; /* in case 'getcode' messes up */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005505 PyObject *errorHandler = NULL;
5506 PyObject *exc = NULL;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005507 Py_ssize_t len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005508 Py_ssize_t i;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005509
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005510 len = length_of_escaped_ascii_string(s, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005511
5512 /* After length_of_escaped_ascii_string() there are two alternatives,
5513 either the string is pure ASCII with named escapes like \n, etc.
5514 and we determined it's exact size (common case)
5515 or it contains \x, \u, ... escape sequences. then we create a
5516 legacy wchar string and resize it at the end of this function. */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005517 if (len >= 0) {
5518 v = PyUnicode_New(len, 127);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005519 if (!v)
5520 goto onError;
5521 assert(PyUnicode_KIND(v) == PyUnicode_1BYTE_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005522 }
5523 else {
5524 /* Escaped strings will always be longer than the resulting
5525 Unicode string, so we start with size here and then reduce the
5526 length after conversion to the true value.
5527 (but if the error callback returns a long replacement string
5528 we'll have to allocate more space) */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005529 v = PyUnicode_New(size, 127);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005530 if (!v)
5531 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005532 len = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005533 }
5534
Guido van Rossumd57fd912000-03-10 22:53:23 +00005535 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01005536 return v;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005537 i = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005538 end = s + size;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005539
Guido van Rossumd57fd912000-03-10 22:53:23 +00005540 while (s < end) {
5541 unsigned char c;
Victor Stinner24729f32011-11-10 20:31:37 +01005542 Py_UCS4 x;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005543 int digits;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005544
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005545 /* The only case in which i == ascii_length is a backslash
5546 followed by a newline. */
5547 assert(i <= len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005548
Guido van Rossumd57fd912000-03-10 22:53:23 +00005549 /* Non-escape characters are interpreted as Unicode ordinals */
5550 if (*s != '\\') {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005551 if (unicode_putchar(&v, &i, (unsigned char) *s++) < 0)
5552 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005553 continue;
5554 }
5555
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005556 startinpos = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005557 /* \ - Escapes */
5558 s++;
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005559 c = *s++;
5560 if (s > end)
5561 c = '\0'; /* Invalid after \ */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005562
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005563 /* The only case in which i == ascii_length is a backslash
5564 followed by a newline. */
5565 assert(i < len || (i == len && c == '\n'));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005566
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005567 switch (c) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005568
Benjamin Peterson29060642009-01-31 22:14:21 +00005569 /* \x escapes */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005570#define WRITECHAR(ch) \
5571 do { \
5572 if (unicode_putchar(&v, &i, ch) < 0) \
5573 goto onError; \
5574 }while(0)
5575
Guido van Rossumd57fd912000-03-10 22:53:23 +00005576 case '\n': break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005577 case '\\': WRITECHAR('\\'); break;
5578 case '\'': WRITECHAR('\''); break;
5579 case '\"': WRITECHAR('\"'); break;
5580 case 'b': WRITECHAR('\b'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005581 /* FF */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005582 case 'f': WRITECHAR('\014'); break;
5583 case 't': WRITECHAR('\t'); break;
5584 case 'n': WRITECHAR('\n'); break;
5585 case 'r': WRITECHAR('\r'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005586 /* VT */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005587 case 'v': WRITECHAR('\013'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005588 /* BEL, not classic C */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005589 case 'a': WRITECHAR('\007'); break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005590
Benjamin Peterson29060642009-01-31 22:14:21 +00005591 /* \OOO (octal) escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005592 case '0': case '1': case '2': case '3':
5593 case '4': case '5': case '6': case '7':
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005594 x = s[-1] - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005595 if (s < end && '0' <= *s && *s <= '7') {
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005596 x = (x<<3) + *s++ - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005597 if (s < end && '0' <= *s && *s <= '7')
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005598 x = (x<<3) + *s++ - '0';
Guido van Rossumd57fd912000-03-10 22:53:23 +00005599 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005600 WRITECHAR(x);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005601 break;
5602
Benjamin Peterson29060642009-01-31 22:14:21 +00005603 /* hex escapes */
5604 /* \xXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005605 case 'x':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005606 digits = 2;
5607 message = "truncated \\xXX escape";
5608 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005609
Benjamin Peterson29060642009-01-31 22:14:21 +00005610 /* \uXXXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005611 case 'u':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005612 digits = 4;
5613 message = "truncated \\uXXXX escape";
5614 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005615
Benjamin Peterson29060642009-01-31 22:14:21 +00005616 /* \UXXXXXXXX */
Fredrik Lundhdf846752000-09-03 11:29:49 +00005617 case 'U':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005618 digits = 8;
5619 message = "truncated \\UXXXXXXXX escape";
5620 hexescape:
5621 chr = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005622 if (s+digits>end) {
5623 endinpos = size;
5624 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005625 errors, &errorHandler,
5626 "unicodeescape", "end of string in escape sequence",
5627 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005628 &v, &i))
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005629 goto onError;
5630 goto nextByte;
5631 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005632 for (j = 0; j < digits; ++j) {
5633 c = (unsigned char) s[j];
David Malcolm96960882010-11-05 17:23:41 +00005634 if (!Py_ISXDIGIT(c)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005635 endinpos = (s+j+1)-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005636 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005637 errors, &errorHandler,
5638 "unicodeescape", message,
5639 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005640 &v, &i))
Fredrik Lundhdf846752000-09-03 11:29:49 +00005641 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005642 len = PyUnicode_GET_LENGTH(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005643 goto nextByte;
Fredrik Lundhdf846752000-09-03 11:29:49 +00005644 }
5645 chr = (chr<<4) & ~0xF;
5646 if (c >= '0' && c <= '9')
5647 chr += c - '0';
5648 else if (c >= 'a' && c <= 'f')
5649 chr += 10 + c - 'a';
5650 else
5651 chr += 10 + c - 'A';
5652 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005653 s += j;
Jeremy Hylton504de6b2003-10-06 05:08:26 +00005654 if (chr == 0xffffffff && PyErr_Occurred())
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005655 /* _decoding_error will have already written into the
5656 target buffer. */
5657 break;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005658 store:
Fredrik Lundhdf846752000-09-03 11:29:49 +00005659 /* when we get here, chr is a 32-bit unicode character */
Victor Stinner8faf8212011-12-08 22:14:11 +01005660 if (chr <= MAX_UNICODE) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005661 WRITECHAR(chr);
Fredrik Lundhdf846752000-09-03 11:29:49 +00005662 } else {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005663 endinpos = s-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005664 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005665 errors, &errorHandler,
5666 "unicodeescape", "illegal Unicode character",
5667 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005668 &v, &i))
Fredrik Lundhdf846752000-09-03 11:29:49 +00005669 goto onError;
5670 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00005671 break;
5672
Benjamin Peterson29060642009-01-31 22:14:21 +00005673 /* \N{name} */
Fredrik Lundhccc74732001-02-18 22:13:49 +00005674 case 'N':
5675 message = "malformed \\N character escape";
5676 if (ucnhash_CAPI == NULL) {
5677 /* load the unicode data module */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005678 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
5679 PyUnicodeData_CAPSULE_NAME, 1);
Fredrik Lundhccc74732001-02-18 22:13:49 +00005680 if (ucnhash_CAPI == NULL)
5681 goto ucnhashError;
5682 }
5683 if (*s == '{') {
5684 const char *start = s+1;
5685 /* look for the closing brace */
5686 while (*s != '}' && s < end)
5687 s++;
5688 if (s > start && s < end && *s == '}') {
5689 /* found a name. look it up in the unicode database */
5690 message = "unknown Unicode character name";
5691 s++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005692 if (ucnhash_CAPI->getcode(NULL, start, (int)(s-start-1),
Ezio Melotti931b8aa2011-10-21 21:57:36 +03005693 &chr, 0))
Fredrik Lundhccc74732001-02-18 22:13:49 +00005694 goto store;
5695 }
5696 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005697 endinpos = s-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005698 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005699 errors, &errorHandler,
5700 "unicodeescape", message,
5701 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005702 &v, &i))
Fredrik Lundhccc74732001-02-18 22:13:49 +00005703 goto onError;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005704 break;
5705
5706 default:
Walter Dörwald8c077222002-03-25 11:16:18 +00005707 if (s > end) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005708 message = "\\ at end of string";
5709 s--;
5710 endinpos = s-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005711 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005712 errors, &errorHandler,
5713 "unicodeescape", message,
5714 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005715 &v, &i))
Walter Dörwald8c077222002-03-25 11:16:18 +00005716 goto onError;
5717 }
5718 else {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005719 WRITECHAR('\\');
5720 WRITECHAR(s[-1]);
Walter Dörwald8c077222002-03-25 11:16:18 +00005721 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00005722 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005723 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005724 nextByte:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005725 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005726 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005727#undef WRITECHAR
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005728
Victor Stinner16e6a802011-12-12 13:24:15 +01005729 if (unicode_resize(&v, i) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005730 goto onError;
Walter Dörwaldd4ade082003-08-15 15:00:26 +00005731 Py_XDECREF(errorHandler);
5732 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01005733 return unicode_result(v);
Walter Dörwald8c077222002-03-25 11:16:18 +00005734
Benjamin Peterson29060642009-01-31 22:14:21 +00005735 ucnhashError:
Fredrik Lundh06d12682001-01-24 07:59:11 +00005736 PyErr_SetString(
5737 PyExc_UnicodeError,
5738 "\\N escapes not supported (can't load unicodedata module)"
5739 );
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00005740 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005741 Py_XDECREF(errorHandler);
5742 Py_XDECREF(exc);
Fredrik Lundhf6056062001-01-20 11:15:25 +00005743 return NULL;
5744
Benjamin Peterson29060642009-01-31 22:14:21 +00005745 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00005746 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005747 Py_XDECREF(errorHandler);
5748 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005749 return NULL;
5750}
5751
5752/* Return a Unicode-Escape string version of the Unicode object.
5753
5754 If quotes is true, the string is enclosed in u"" or u'' quotes as
5755 appropriate.
5756
5757*/
5758
Alexander Belopolsky40018472011-02-26 01:02:56 +00005759PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005760PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005761{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005762 Py_ssize_t i, len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005763 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005764 char *p;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005765 int kind;
5766 void *data;
5767 Py_ssize_t expandsize = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005768
Ezio Melottie7f90372012-10-05 03:33:31 +03005769 /* Initial allocation is based on the longest-possible character
Thomas Wouters89f507f2006-12-13 04:49:30 +00005770 escape.
5771
Ezio Melottie7f90372012-10-05 03:33:31 +03005772 For UCS1 strings it's '\xxx', 4 bytes per source character.
5773 For UCS2 strings it's '\uxxxx', 6 bytes per source character.
5774 For UCS4 strings it's '\U00xxxxxx', 10 bytes per source character.
Thomas Wouters89f507f2006-12-13 04:49:30 +00005775 */
5776
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005777 if (!PyUnicode_Check(unicode)) {
5778 PyErr_BadArgument();
5779 return NULL;
5780 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005781 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005782 return NULL;
5783 len = PyUnicode_GET_LENGTH(unicode);
5784 kind = PyUnicode_KIND(unicode);
5785 data = PyUnicode_DATA(unicode);
Benjamin Petersonead6b532011-12-20 17:23:42 -06005786 switch (kind) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005787 case PyUnicode_1BYTE_KIND: expandsize = 4; break;
5788 case PyUnicode_2BYTE_KIND: expandsize = 6; break;
5789 case PyUnicode_4BYTE_KIND: expandsize = 10; break;
5790 }
5791
5792 if (len == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005793 return PyBytes_FromStringAndSize(NULL, 0);
5794
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005795 if (len > (PY_SSIZE_T_MAX - 2 - 1) / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005796 return PyErr_NoMemory();
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005797
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005798 repr = PyBytes_FromStringAndSize(NULL,
Benjamin Peterson29060642009-01-31 22:14:21 +00005799 2
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005800 + expandsize*len
Benjamin Peterson29060642009-01-31 22:14:21 +00005801 + 1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005802 if (repr == NULL)
5803 return NULL;
5804
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005805 p = PyBytes_AS_STRING(repr);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005806
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005807 for (i = 0; i < len; i++) {
Victor Stinner3326cb62011-11-10 20:15:25 +01005808 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005809
Walter Dörwald79e913e2007-05-12 11:08:06 +00005810 /* Escape backslashes */
5811 if (ch == '\\') {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005812 *p++ = '\\';
5813 *p++ = (char) ch;
Walter Dörwald79e913e2007-05-12 11:08:06 +00005814 continue;
Tim Petersced69f82003-09-16 20:30:58 +00005815 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005816
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005817 /* Map 21-bit characters to '\U00xxxxxx' */
5818 else if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01005819 assert(ch <= MAX_UNICODE);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005820 *p++ = '\\';
5821 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005822 *p++ = Py_hexdigits[(ch >> 28) & 0x0000000F];
5823 *p++ = Py_hexdigits[(ch >> 24) & 0x0000000F];
5824 *p++ = Py_hexdigits[(ch >> 20) & 0x0000000F];
5825 *p++ = Py_hexdigits[(ch >> 16) & 0x0000000F];
5826 *p++ = Py_hexdigits[(ch >> 12) & 0x0000000F];
5827 *p++ = Py_hexdigits[(ch >> 8) & 0x0000000F];
5828 *p++ = Py_hexdigits[(ch >> 4) & 0x0000000F];
5829 *p++ = Py_hexdigits[ch & 0x0000000F];
Benjamin Peterson29060642009-01-31 22:14:21 +00005830 continue;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005831 }
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005832
Guido van Rossumd57fd912000-03-10 22:53:23 +00005833 /* Map 16-bit characters to '\uxxxx' */
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005834 if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005835 *p++ = '\\';
5836 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005837 *p++ = Py_hexdigits[(ch >> 12) & 0x000F];
5838 *p++ = Py_hexdigits[(ch >> 8) & 0x000F];
5839 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
5840 *p++ = Py_hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00005841 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005842
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005843 /* Map special whitespace to '\t', \n', '\r' */
5844 else if (ch == '\t') {
5845 *p++ = '\\';
5846 *p++ = 't';
5847 }
5848 else if (ch == '\n') {
5849 *p++ = '\\';
5850 *p++ = 'n';
5851 }
5852 else if (ch == '\r') {
5853 *p++ = '\\';
5854 *p++ = 'r';
5855 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005856
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005857 /* Map non-printable US ASCII to '\xhh' */
Marc-André Lemburg11326de2001-11-28 12:56:20 +00005858 else if (ch < ' ' || ch >= 0x7F) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005859 *p++ = '\\';
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005860 *p++ = 'x';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005861 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
5862 *p++ = Py_hexdigits[ch & 0x000F];
Tim Petersced69f82003-09-16 20:30:58 +00005863 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005864
Guido van Rossumd57fd912000-03-10 22:53:23 +00005865 /* Copy everything else as-is */
5866 else
5867 *p++ = (char) ch;
5868 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005869
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005870 assert(p - PyBytes_AS_STRING(repr) > 0);
5871 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0)
5872 return NULL;
5873 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005874}
5875
Alexander Belopolsky40018472011-02-26 01:02:56 +00005876PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005877PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
5878 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005879{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005880 PyObject *result;
5881 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5882 if (tmp == NULL)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005883 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005884 result = PyUnicode_AsUnicodeEscapeString(tmp);
5885 Py_DECREF(tmp);
5886 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005887}
5888
5889/* --- Raw Unicode Escape Codec ------------------------------------------- */
5890
Alexander Belopolsky40018472011-02-26 01:02:56 +00005891PyObject *
5892PyUnicode_DecodeRawUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005893 Py_ssize_t size,
5894 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005895{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005896 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005897 Py_ssize_t startinpos;
5898 Py_ssize_t endinpos;
5899 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01005900 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005901 const char *end;
5902 const char *bs;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005903 PyObject *errorHandler = NULL;
5904 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00005905
Guido van Rossumd57fd912000-03-10 22:53:23 +00005906 /* Escaped strings will always be longer than the resulting
5907 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005908 length after conversion to the true value. (But decoding error
5909 handler might have to resize the string) */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005910 v = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005911 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005912 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005913 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01005914 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005915 outpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005916 end = s + size;
5917 while (s < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005918 unsigned char c;
5919 Py_UCS4 x;
5920 int i;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00005921 int count;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005922
Benjamin Peterson29060642009-01-31 22:14:21 +00005923 /* Non-escape characters are interpreted as Unicode ordinals */
5924 if (*s != '\\') {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005925 if (unicode_putchar(&v, &outpos, (unsigned char)*s++) < 0)
5926 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005927 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00005928 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005929 startinpos = s-starts;
5930
5931 /* \u-escapes are only interpreted iff the number of leading
5932 backslashes if odd */
5933 bs = s;
5934 for (;s < end;) {
5935 if (*s != '\\')
5936 break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005937 if (unicode_putchar(&v, &outpos, (unsigned char)*s++) < 0)
5938 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005939 }
5940 if (((s - bs) & 1) == 0 ||
5941 s >= end ||
5942 (*s != 'u' && *s != 'U')) {
5943 continue;
5944 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005945 outpos--;
Benjamin Peterson29060642009-01-31 22:14:21 +00005946 count = *s=='u' ? 4 : 8;
5947 s++;
5948
5949 /* \uXXXX with 4 hex digits, \Uxxxxxxxx with 8 */
Benjamin Peterson29060642009-01-31 22:14:21 +00005950 for (x = 0, i = 0; i < count; ++i, ++s) {
5951 c = (unsigned char)*s;
David Malcolm96960882010-11-05 17:23:41 +00005952 if (!Py_ISXDIGIT(c)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005953 endinpos = s-starts;
5954 if (unicode_decode_call_errorhandler(
5955 errors, &errorHandler,
5956 "rawunicodeescape", "truncated \\uXXXX",
5957 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005958 &v, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00005959 goto onError;
5960 goto nextByte;
5961 }
5962 x = (x<<4) & ~0xF;
5963 if (c >= '0' && c <= '9')
5964 x += c - '0';
5965 else if (c >= 'a' && c <= 'f')
5966 x += 10 + c - 'a';
5967 else
5968 x += 10 + c - 'A';
5969 }
Victor Stinner8faf8212011-12-08 22:14:11 +01005970 if (x <= MAX_UNICODE) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005971 if (unicode_putchar(&v, &outpos, x) < 0)
5972 goto onError;
Christian Heimesfe337bf2008-03-23 21:54:12 +00005973 } else {
5974 endinpos = s-starts;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00005975 if (unicode_decode_call_errorhandler(
5976 errors, &errorHandler,
5977 "rawunicodeescape", "\\Uxxxxxxxx out of range",
Benjamin Peterson29060642009-01-31 22:14:21 +00005978 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005979 &v, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00005980 goto onError;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00005981 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005982 nextByte:
5983 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005984 }
Victor Stinner16e6a802011-12-12 13:24:15 +01005985 if (unicode_resize(&v, outpos) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005986 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005987 Py_XDECREF(errorHandler);
5988 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01005989 return unicode_result(v);
Tim Petersced69f82003-09-16 20:30:58 +00005990
Benjamin Peterson29060642009-01-31 22:14:21 +00005991 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00005992 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005993 Py_XDECREF(errorHandler);
5994 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005995 return NULL;
5996}
5997
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005998
Alexander Belopolsky40018472011-02-26 01:02:56 +00005999PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006000PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006001{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006002 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006003 char *p;
6004 char *q;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006005 Py_ssize_t expandsize, pos;
6006 int kind;
6007 void *data;
6008 Py_ssize_t len;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006009
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006010 if (!PyUnicode_Check(unicode)) {
6011 PyErr_BadArgument();
6012 return NULL;
6013 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05006014 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006015 return NULL;
6016 kind = PyUnicode_KIND(unicode);
6017 data = PyUnicode_DATA(unicode);
6018 len = PyUnicode_GET_LENGTH(unicode);
Benjamin Peterson1518e872011-11-23 10:44:52 -06006019 /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6
6020 bytes, and 1 byte characters 4. */
6021 expandsize = kind * 2 + 2;
Victor Stinner0e368262011-11-10 20:12:49 +01006022
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006023 if (len > PY_SSIZE_T_MAX / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00006024 return PyErr_NoMemory();
Benjamin Peterson14339b62009-01-31 16:36:08 +00006025
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006026 repr = PyBytes_FromStringAndSize(NULL, expandsize * len);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006027 if (repr == NULL)
6028 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006029 if (len == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006030 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006031
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006032 p = q = PyBytes_AS_STRING(repr);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006033 for (pos = 0; pos < len; pos++) {
6034 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Benjamin Peterson29060642009-01-31 22:14:21 +00006035 /* Map 32-bit characters to '\Uxxxxxxxx' */
6036 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01006037 assert(ch <= MAX_UNICODE);
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006038 *p++ = '\\';
6039 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006040 *p++ = Py_hexdigits[(ch >> 28) & 0xf];
6041 *p++ = Py_hexdigits[(ch >> 24) & 0xf];
6042 *p++ = Py_hexdigits[(ch >> 20) & 0xf];
6043 *p++ = Py_hexdigits[(ch >> 16) & 0xf];
6044 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6045 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6046 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6047 *p++ = Py_hexdigits[ch & 15];
Tim Petersced69f82003-09-16 20:30:58 +00006048 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006049 /* Map 16-bit characters to '\uxxxx' */
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006050 else if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006051 *p++ = '\\';
6052 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006053 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6054 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6055 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6056 *p++ = Py_hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006057 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006058 /* Copy everything else as-is */
6059 else
Guido van Rossumd57fd912000-03-10 22:53:23 +00006060 *p++ = (char) ch;
6061 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00006062
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006063 assert(p > q);
6064 if (_PyBytes_Resize(&repr, p - q) < 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006065 return NULL;
6066 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006067}
6068
Alexander Belopolsky40018472011-02-26 01:02:56 +00006069PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006070PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
6071 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006072{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006073 PyObject *result;
6074 PyObject *tmp = PyUnicode_FromUnicode(s, size);
6075 if (tmp == NULL)
Walter Dörwald711005d2007-05-12 12:03:26 +00006076 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006077 result = PyUnicode_AsRawUnicodeEscapeString(tmp);
6078 Py_DECREF(tmp);
6079 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006080}
6081
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006082/* --- Unicode Internal Codec ------------------------------------------- */
6083
Alexander Belopolsky40018472011-02-26 01:02:56 +00006084PyObject *
6085_PyUnicode_DecodeUnicodeInternal(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006086 Py_ssize_t size,
6087 const char *errors)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006088{
6089 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006090 Py_ssize_t startinpos;
6091 Py_ssize_t endinpos;
6092 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01006093 PyObject *v;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006094 const char *end;
6095 const char *reason;
6096 PyObject *errorHandler = NULL;
6097 PyObject *exc = NULL;
6098
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006099 if (PyErr_WarnEx(PyExc_DeprecationWarning,
Ezio Melotti11060a42011-11-16 09:39:10 +02006100 "unicode_internal codec has been deprecated",
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006101 1))
6102 return NULL;
6103
Thomas Wouters89f507f2006-12-13 04:49:30 +00006104 /* XXX overflow detection missing */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006105 v = PyUnicode_New((size+Py_UNICODE_SIZE-1)/ Py_UNICODE_SIZE, 127);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006106 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006107 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006108 if (PyUnicode_GET_LENGTH(v) == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01006109 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006110 outpos = 0;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006111 end = s + size;
6112
6113 while (s < end) {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006114 Py_UNICODE uch;
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006115 Py_UCS4 ch;
6116 /* We copy the raw representation one byte at a time because the
6117 pointer may be unaligned (see test_codeccallbacks). */
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006118 ((char *) &uch)[0] = s[0];
6119 ((char *) &uch)[1] = s[1];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006120#ifdef Py_UNICODE_WIDE
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006121 ((char *) &uch)[2] = s[2];
6122 ((char *) &uch)[3] = s[3];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006123#endif
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006124 ch = uch;
6125
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006126 /* We have to sanity check the raw data, otherwise doom looms for
6127 some malformed UCS-4 data. */
6128 if (
Benjamin Peterson29060642009-01-31 22:14:21 +00006129#ifdef Py_UNICODE_WIDE
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006130 ch > 0x10ffff ||
Benjamin Peterson29060642009-01-31 22:14:21 +00006131#endif
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006132 end-s < Py_UNICODE_SIZE
6133 )
Benjamin Peterson29060642009-01-31 22:14:21 +00006134 {
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006135 startinpos = s - starts;
6136 if (end-s < Py_UNICODE_SIZE) {
6137 endinpos = end-starts;
6138 reason = "truncated input";
6139 }
6140 else {
6141 endinpos = s - starts + Py_UNICODE_SIZE;
6142 reason = "illegal code point (> 0x10FFFF)";
6143 }
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006144 if (unicode_decode_call_errorhandler(
6145 errors, &errorHandler,
6146 "unicode_internal", reason,
Walter Dörwalde78178e2007-07-30 13:31:40 +00006147 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006148 &v, &outpos))
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006149 goto onError;
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006150 continue;
6151 }
6152
6153 s += Py_UNICODE_SIZE;
6154#ifndef Py_UNICODE_WIDE
Victor Stinner551ac952011-11-29 22:58:13 +01006155 if (Py_UNICODE_IS_HIGH_SURROGATE(ch) && s < end)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006156 {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006157 Py_UNICODE uch2;
6158 ((char *) &uch2)[0] = s[0];
6159 ((char *) &uch2)[1] = s[1];
Victor Stinner551ac952011-11-29 22:58:13 +01006160 if (Py_UNICODE_IS_LOW_SURROGATE(uch2))
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006161 {
Victor Stinner551ac952011-11-29 22:58:13 +01006162 ch = Py_UNICODE_JOIN_SURROGATES(uch, uch2);
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006163 s += Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006164 }
6165 }
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006166#endif
6167
6168 if (unicode_putchar(&v, &outpos, ch) < 0)
6169 goto onError;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006170 }
6171
Victor Stinner16e6a802011-12-12 13:24:15 +01006172 if (unicode_resize(&v, outpos) < 0)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006173 goto onError;
6174 Py_XDECREF(errorHandler);
6175 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006176 return unicode_result(v);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006177
Benjamin Peterson29060642009-01-31 22:14:21 +00006178 onError:
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006179 Py_XDECREF(v);
6180 Py_XDECREF(errorHandler);
6181 Py_XDECREF(exc);
6182 return NULL;
6183}
6184
Guido van Rossumd57fd912000-03-10 22:53:23 +00006185/* --- Latin-1 Codec ------------------------------------------------------ */
6186
Alexander Belopolsky40018472011-02-26 01:02:56 +00006187PyObject *
6188PyUnicode_DecodeLatin1(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006189 Py_ssize_t size,
6190 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006191{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006192 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Victor Stinnere57b1c02011-09-28 22:20:48 +02006193 return _PyUnicode_FromUCS1((unsigned char*)s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006194}
6195
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006196/* create or adjust a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006197static void
6198make_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006199 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006200 PyObject *unicode,
6201 Py_ssize_t startpos, Py_ssize_t endpos,
6202 const char *reason)
6203{
6204 if (*exceptionObject == NULL) {
6205 *exceptionObject = PyObject_CallFunction(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006206 PyExc_UnicodeEncodeError, "sOnns",
Martin v. Löwis9e816682011-11-02 12:45:42 +01006207 encoding, unicode, startpos, endpos, reason);
6208 }
6209 else {
6210 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
6211 goto onError;
6212 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
6213 goto onError;
6214 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
6215 goto onError;
6216 return;
6217 onError:
6218 Py_DECREF(*exceptionObject);
6219 *exceptionObject = NULL;
6220 }
6221}
6222
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006223/* raises a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006224static void
6225raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006226 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006227 PyObject *unicode,
6228 Py_ssize_t startpos, Py_ssize_t endpos,
6229 const char *reason)
6230{
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006231 make_encode_exception(exceptionObject,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006232 encoding, unicode, startpos, endpos, reason);
6233 if (*exceptionObject != NULL)
6234 PyCodec_StrictErrors(*exceptionObject);
6235}
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006236
6237/* error handling callback helper:
6238 build arguments, call the callback and check the arguments,
6239 put the result into newpos and return the replacement string, which
6240 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006241static PyObject *
6242unicode_encode_call_errorhandler(const char *errors,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006243 PyObject **errorHandler,
6244 const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006245 PyObject *unicode, PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006246 Py_ssize_t startpos, Py_ssize_t endpos,
6247 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006248{
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006249 static char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006250 Py_ssize_t len;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006251 PyObject *restuple;
6252 PyObject *resunicode;
6253
6254 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006255 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006256 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006257 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006258 }
6259
Benjamin Petersonbac79492012-01-14 13:34:47 -05006260 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006261 return NULL;
6262 len = PyUnicode_GET_LENGTH(unicode);
6263
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006264 make_encode_exception(exceptionObject,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006265 encoding, unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006266 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006267 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006268
6269 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00006270 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006271 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006272 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006273 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006274 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00006275 Py_DECREF(restuple);
6276 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006277 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006278 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00006279 &resunicode, newpos)) {
6280 Py_DECREF(restuple);
6281 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006282 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006283 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
6284 PyErr_SetString(PyExc_TypeError, &argparse[3]);
6285 Py_DECREF(restuple);
6286 return NULL;
6287 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006288 if (*newpos<0)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006289 *newpos = len + *newpos;
6290 if (*newpos<0 || *newpos>len) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006291 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
6292 Py_DECREF(restuple);
6293 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00006294 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006295 Py_INCREF(resunicode);
6296 Py_DECREF(restuple);
6297 return resunicode;
6298}
6299
Alexander Belopolsky40018472011-02-26 01:02:56 +00006300static PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006301unicode_encode_ucs1(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006302 const char *errors,
Victor Stinnerfcd96532011-11-04 00:28:50 +01006303 unsigned int limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006304{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006305 /* input state */
6306 Py_ssize_t pos=0, size;
6307 int kind;
6308 void *data;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006309 /* output object */
6310 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006311 /* pointer into the output */
6312 char *str;
6313 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00006314 Py_ssize_t ressize;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006315 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
6316 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006317 PyObject *errorHandler = NULL;
6318 PyObject *exc = NULL;
6319 /* the following variable is used for caching string comparisons
6320 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
6321 int known_errorHandler = -1;
6322
Benjamin Petersonbac79492012-01-14 13:34:47 -05006323 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006324 return NULL;
6325 size = PyUnicode_GET_LENGTH(unicode);
6326 kind = PyUnicode_KIND(unicode);
6327 data = PyUnicode_DATA(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006328 /* allocate enough for a simple encoding without
6329 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00006330 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00006331 return PyBytes_FromStringAndSize(NULL, 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006332 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006333 if (res == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00006334 return NULL;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006335 str = PyBytes_AS_STRING(res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006336 ressize = size;
6337
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006338 while (pos < size) {
6339 Py_UCS4 c = PyUnicode_READ(kind, data, pos);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006340
Benjamin Peterson29060642009-01-31 22:14:21 +00006341 /* can we encode this? */
6342 if (c<limit) {
6343 /* no overflow check, because we know that the space is enough */
6344 *str++ = (char)c;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006345 ++pos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006346 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006347 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006348 Py_ssize_t requiredsize;
6349 PyObject *repunicode;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006350 Py_ssize_t repsize, newpos, respos, i;
Benjamin Peterson29060642009-01-31 22:14:21 +00006351 /* startpos for collecting unencodable chars */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006352 Py_ssize_t collstart = pos;
6353 Py_ssize_t collend = pos;
Benjamin Peterson29060642009-01-31 22:14:21 +00006354 /* find all unecodable characters */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006355 while ((collend < size) && (PyUnicode_READ(kind, data, collend)>=limit))
Benjamin Peterson29060642009-01-31 22:14:21 +00006356 ++collend;
6357 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
6358 if (known_errorHandler==-1) {
6359 if ((errors==NULL) || (!strcmp(errors, "strict")))
6360 known_errorHandler = 1;
6361 else if (!strcmp(errors, "replace"))
6362 known_errorHandler = 2;
6363 else if (!strcmp(errors, "ignore"))
6364 known_errorHandler = 3;
6365 else if (!strcmp(errors, "xmlcharrefreplace"))
6366 known_errorHandler = 4;
6367 else
6368 known_errorHandler = 0;
6369 }
6370 switch (known_errorHandler) {
6371 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006372 raise_encode_exception(&exc, encoding, unicode, collstart, collend, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006373 goto onError;
6374 case 2: /* replace */
6375 while (collstart++<collend)
6376 *str++ = '?'; /* fall through */
6377 case 3: /* ignore */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006378 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006379 break;
6380 case 4: /* xmlcharrefreplace */
6381 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006382 /* determine replacement size */
6383 for (i = collstart, repsize = 0; i < collend; ++i) {
6384 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
6385 if (ch < 10)
Benjamin Peterson29060642009-01-31 22:14:21 +00006386 repsize += 2+1+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006387 else if (ch < 100)
Benjamin Peterson29060642009-01-31 22:14:21 +00006388 repsize += 2+2+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006389 else if (ch < 1000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006390 repsize += 2+3+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006391 else if (ch < 10000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006392 repsize += 2+4+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006393 else if (ch < 100000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006394 repsize += 2+5+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006395 else if (ch < 1000000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006396 repsize += 2+6+1;
Victor Stinner0d3721d2011-11-22 03:27:53 +01006397 else {
Victor Stinner8faf8212011-12-08 22:14:11 +01006398 assert(ch <= MAX_UNICODE);
Benjamin Peterson29060642009-01-31 22:14:21 +00006399 repsize += 2+7+1;
Victor Stinner0d3721d2011-11-22 03:27:53 +01006400 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006401 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006402 requiredsize = respos+repsize+(size-collend);
Benjamin Peterson29060642009-01-31 22:14:21 +00006403 if (requiredsize > ressize) {
6404 if (requiredsize<2*ressize)
6405 requiredsize = 2*ressize;
6406 if (_PyBytes_Resize(&res, requiredsize))
6407 goto onError;
6408 str = PyBytes_AS_STRING(res) + respos;
6409 ressize = requiredsize;
6410 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006411 /* generate replacement */
6412 for (i = collstart; i < collend; ++i) {
6413 str += sprintf(str, "&#%d;", PyUnicode_READ(kind, data, i));
Benjamin Peterson29060642009-01-31 22:14:21 +00006414 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006415 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006416 break;
6417 default:
6418 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006419 encoding, reason, unicode, &exc,
6420 collstart, collend, &newpos);
6421 if (repunicode == NULL || (PyUnicode_Check(repunicode) &&
Benjamin Petersonbac79492012-01-14 13:34:47 -05006422 PyUnicode_READY(repunicode) == -1))
Benjamin Peterson29060642009-01-31 22:14:21 +00006423 goto onError;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006424 if (PyBytes_Check(repunicode)) {
6425 /* Directly copy bytes result to output. */
6426 repsize = PyBytes_Size(repunicode);
6427 if (repsize > 1) {
6428 /* Make room for all additional bytes. */
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006429 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006430 if (_PyBytes_Resize(&res, ressize+repsize-1)) {
6431 Py_DECREF(repunicode);
6432 goto onError;
6433 }
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006434 str = PyBytes_AS_STRING(res) + respos;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006435 ressize += repsize-1;
6436 }
6437 memcpy(str, PyBytes_AsString(repunicode), repsize);
6438 str += repsize;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006439 pos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006440 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006441 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006442 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006443 /* need more space? (at least enough for what we
6444 have+the replacement+the rest of the string, so
6445 we won't have to check space for encodable characters) */
6446 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006447 repsize = PyUnicode_GET_LENGTH(repunicode);
6448 requiredsize = respos+repsize+(size-collend);
Benjamin Peterson29060642009-01-31 22:14:21 +00006449 if (requiredsize > ressize) {
6450 if (requiredsize<2*ressize)
6451 requiredsize = 2*ressize;
6452 if (_PyBytes_Resize(&res, requiredsize)) {
6453 Py_DECREF(repunicode);
6454 goto onError;
6455 }
6456 str = PyBytes_AS_STRING(res) + respos;
6457 ressize = requiredsize;
6458 }
6459 /* check if there is anything unencodable in the replacement
6460 and copy it to the output */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006461 for (i = 0; repsize-->0; ++i, ++str) {
6462 c = PyUnicode_READ_CHAR(repunicode, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00006463 if (c >= limit) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006464 raise_encode_exception(&exc, encoding, unicode,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006465 pos, pos+1, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006466 Py_DECREF(repunicode);
6467 goto onError;
6468 }
6469 *str = (char)c;
6470 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006471 pos = newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006472 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006473 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00006474 }
6475 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006476 /* Resize if we allocated to much */
6477 size = str - PyBytes_AS_STRING(res);
6478 if (size < ressize) { /* If this falls res will be NULL */
Alexandre Vassalottibad1b922008-12-27 09:49:09 +00006479 assert(size >= 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006480 if (_PyBytes_Resize(&res, size) < 0)
6481 goto onError;
6482 }
6483
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006484 Py_XDECREF(errorHandler);
6485 Py_XDECREF(exc);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006486 return res;
6487
6488 onError:
6489 Py_XDECREF(res);
6490 Py_XDECREF(errorHandler);
6491 Py_XDECREF(exc);
6492 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006493}
6494
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006495/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006496PyObject *
6497PyUnicode_EncodeLatin1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006498 Py_ssize_t size,
6499 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006500{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006501 PyObject *result;
6502 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6503 if (unicode == NULL)
6504 return NULL;
6505 result = unicode_encode_ucs1(unicode, errors, 256);
6506 Py_DECREF(unicode);
6507 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006508}
6509
Alexander Belopolsky40018472011-02-26 01:02:56 +00006510PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006511_PyUnicode_AsLatin1String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006512{
6513 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006514 PyErr_BadArgument();
6515 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006516 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006517 if (PyUnicode_READY(unicode) == -1)
6518 return NULL;
6519 /* Fast path: if it is a one-byte string, construct
6520 bytes object directly. */
6521 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND)
6522 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6523 PyUnicode_GET_LENGTH(unicode));
6524 /* Non-Latin-1 characters present. Defer to above function to
6525 raise the exception. */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006526 return unicode_encode_ucs1(unicode, errors, 256);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006527}
6528
6529PyObject*
6530PyUnicode_AsLatin1String(PyObject *unicode)
6531{
6532 return _PyUnicode_AsLatin1String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006533}
6534
6535/* --- 7-bit ASCII Codec -------------------------------------------------- */
6536
Alexander Belopolsky40018472011-02-26 01:02:56 +00006537PyObject *
6538PyUnicode_DecodeASCII(const char *s,
6539 Py_ssize_t size,
6540 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006541{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006542 const char *starts = s;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006543 PyObject *unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006544 int kind;
6545 void *data;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006546 Py_ssize_t startinpos;
6547 Py_ssize_t endinpos;
6548 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006549 const char *e;
6550 PyObject *errorHandler = NULL;
6551 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006552
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006553 if (size == 0) {
6554 Py_INCREF(unicode_empty);
6555 return unicode_empty;
6556 }
6557
Guido van Rossumd57fd912000-03-10 22:53:23 +00006558 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Victor Stinner702c7342011-10-05 13:50:52 +02006559 if (size == 1 && (unsigned char)s[0] < 128)
6560 return get_latin1_char((unsigned char)s[0]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006561
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006562 unicode = PyUnicode_New(size, 127);
6563 if (unicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006564 goto onError;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006565
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006566 e = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006567 data = PyUnicode_1BYTE_DATA(unicode);
6568 outpos = ascii_decode(s, e, (Py_UCS1 *)data);
6569 if (outpos == size)
6570 return unicode;
6571
6572 s += outpos;
6573 kind = PyUnicode_1BYTE_KIND;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006574 while (s < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006575 register unsigned char c = (unsigned char)*s;
6576 if (c < 128) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006577 PyUnicode_WRITE(kind, data, outpos++, c);
Benjamin Peterson29060642009-01-31 22:14:21 +00006578 ++s;
6579 }
6580 else {
6581 startinpos = s-starts;
6582 endinpos = startinpos + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00006583 if (unicode_decode_call_errorhandler(
6584 errors, &errorHandler,
6585 "ascii", "ordinal not in range(128)",
6586 &starts, &e, &startinpos, &endinpos, &exc, &s,
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006587 &unicode, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00006588 goto onError;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006589 kind = PyUnicode_KIND(unicode);
6590 data = PyUnicode_DATA(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00006591 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006592 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006593 if (unicode_resize(&unicode, outpos) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006594 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006595 Py_XDECREF(errorHandler);
6596 Py_XDECREF(exc);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006597 assert(_PyUnicode_CheckConsistency(unicode, 1));
6598 return unicode;
Tim Petersced69f82003-09-16 20:30:58 +00006599
Benjamin Peterson29060642009-01-31 22:14:21 +00006600 onError:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006601 Py_XDECREF(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006602 Py_XDECREF(errorHandler);
6603 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006604 return NULL;
6605}
6606
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006607/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006608PyObject *
6609PyUnicode_EncodeASCII(const Py_UNICODE *p,
6610 Py_ssize_t size,
6611 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006612{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006613 PyObject *result;
6614 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6615 if (unicode == NULL)
6616 return NULL;
6617 result = unicode_encode_ucs1(unicode, errors, 128);
6618 Py_DECREF(unicode);
6619 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006620}
6621
Alexander Belopolsky40018472011-02-26 01:02:56 +00006622PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006623_PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006624{
6625 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006626 PyErr_BadArgument();
6627 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006628 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006629 if (PyUnicode_READY(unicode) == -1)
6630 return NULL;
6631 /* Fast path: if it is an ASCII-only string, construct bytes object
6632 directly. Else defer to above function to raise the exception. */
6633 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
6634 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6635 PyUnicode_GET_LENGTH(unicode));
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006636 return unicode_encode_ucs1(unicode, errors, 128);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006637}
6638
6639PyObject *
6640PyUnicode_AsASCIIString(PyObject *unicode)
6641{
6642 return _PyUnicode_AsASCIIString(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006643}
6644
Victor Stinner99b95382011-07-04 14:23:54 +02006645#ifdef HAVE_MBCS
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006646
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006647/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006648
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00006649#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006650#define NEED_RETRY
6651#endif
6652
Victor Stinner3a50e702011-10-18 21:21:00 +02006653#ifndef WC_ERR_INVALID_CHARS
6654# define WC_ERR_INVALID_CHARS 0x0080
6655#endif
6656
6657static char*
6658code_page_name(UINT code_page, PyObject **obj)
6659{
6660 *obj = NULL;
6661 if (code_page == CP_ACP)
6662 return "mbcs";
6663 if (code_page == CP_UTF7)
6664 return "CP_UTF7";
6665 if (code_page == CP_UTF8)
6666 return "CP_UTF8";
6667
6668 *obj = PyBytes_FromFormat("cp%u", code_page);
6669 if (*obj == NULL)
6670 return NULL;
6671 return PyBytes_AS_STRING(*obj);
6672}
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006673
Alexander Belopolsky40018472011-02-26 01:02:56 +00006674static int
Victor Stinner3a50e702011-10-18 21:21:00 +02006675is_dbcs_lead_byte(UINT code_page, const char *s, int offset)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006676{
6677 const char *curr = s + offset;
Victor Stinner3a50e702011-10-18 21:21:00 +02006678 const char *prev;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006679
Victor Stinner3a50e702011-10-18 21:21:00 +02006680 if (!IsDBCSLeadByteEx(code_page, *curr))
6681 return 0;
6682
6683 prev = CharPrevExA(code_page, s, curr, 0);
6684 if (prev == curr)
6685 return 1;
6686 /* FIXME: This code is limited to "true" double-byte encodings,
6687 as it assumes an incomplete character consists of a single
6688 byte. */
6689 if (curr - prev == 2)
6690 return 1;
6691 if (!IsDBCSLeadByteEx(code_page, *prev))
6692 return 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006693 return 0;
6694}
6695
Victor Stinner3a50e702011-10-18 21:21:00 +02006696static DWORD
6697decode_code_page_flags(UINT code_page)
6698{
6699 if (code_page == CP_UTF7) {
6700 /* The CP_UTF7 decoder only supports flags=0 */
6701 return 0;
6702 }
6703 else
6704 return MB_ERR_INVALID_CHARS;
6705}
6706
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006707/*
Victor Stinner3a50e702011-10-18 21:21:00 +02006708 * Decode a byte string from a Windows code page into unicode object in strict
6709 * mode.
6710 *
6711 * Returns consumed size if succeed, returns -2 on decode error, or raise a
6712 * WindowsError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006713 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006714static int
Victor Stinner3a50e702011-10-18 21:21:00 +02006715decode_code_page_strict(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01006716 PyObject **v,
Victor Stinner3a50e702011-10-18 21:21:00 +02006717 const char *in,
6718 int insize)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006719{
Victor Stinner3a50e702011-10-18 21:21:00 +02006720 const DWORD flags = decode_code_page_flags(code_page);
Victor Stinner24729f32011-11-10 20:31:37 +01006721 wchar_t *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02006722 DWORD outsize;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006723
6724 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02006725 assert(insize > 0);
6726 outsize = MultiByteToWideChar(code_page, flags, in, insize, NULL, 0);
6727 if (outsize <= 0)
6728 goto error;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006729
6730 if (*v == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006731 /* Create unicode object */
Victor Stinnerab595942011-12-17 04:59:06 +01006732 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01006733 *v = (PyObject*)_PyUnicode_New(outsize);
Benjamin Peterson29060642009-01-31 22:14:21 +00006734 if (*v == NULL)
6735 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02006736 out = PyUnicode_AS_UNICODE(*v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006737 }
6738 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006739 /* Extend unicode object */
Victor Stinner3a50e702011-10-18 21:21:00 +02006740 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
Victor Stinner16e6a802011-12-12 13:24:15 +01006741 if (unicode_resize(v, n + outsize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006742 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02006743 out = PyUnicode_AS_UNICODE(*v) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006744 }
6745
6746 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02006747 outsize = MultiByteToWideChar(code_page, flags, in, insize, out, outsize);
6748 if (outsize <= 0)
6749 goto error;
6750 return insize;
Victor Stinner554f3f02010-06-16 23:33:54 +00006751
Victor Stinner3a50e702011-10-18 21:21:00 +02006752error:
6753 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
6754 return -2;
6755 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00006756 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006757}
6758
Victor Stinner3a50e702011-10-18 21:21:00 +02006759/*
6760 * Decode a byte string from a code page into unicode object with an error
6761 * handler.
6762 *
6763 * Returns consumed size if succeed, or raise a WindowsError or
6764 * UnicodeDecodeError exception and returns -1 on error.
6765 */
6766static int
6767decode_code_page_errors(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01006768 PyObject **v,
6769 const char *in, const int size,
Victor Stinner3a50e702011-10-18 21:21:00 +02006770 const char *errors)
6771{
6772 const char *startin = in;
6773 const char *endin = in + size;
6774 const DWORD flags = decode_code_page_flags(code_page);
6775 /* Ideally, we should get reason from FormatMessage. This is the Windows
6776 2000 English version of the message. */
6777 const char *reason = "No mapping for the Unicode character exists "
6778 "in the target code page.";
6779 /* each step cannot decode more than 1 character, but a character can be
6780 represented as a surrogate pair */
6781 wchar_t buffer[2], *startout, *out;
6782 int insize, outsize;
6783 PyObject *errorHandler = NULL;
6784 PyObject *exc = NULL;
6785 PyObject *encoding_obj = NULL;
6786 char *encoding;
6787 DWORD err;
6788 int ret = -1;
6789
6790 assert(size > 0);
6791
6792 encoding = code_page_name(code_page, &encoding_obj);
6793 if (encoding == NULL)
6794 return -1;
6795
6796 if (errors == NULL || strcmp(errors, "strict") == 0) {
6797 /* The last error was ERROR_NO_UNICODE_TRANSLATION, then we raise a
6798 UnicodeDecodeError. */
6799 make_decode_exception(&exc, encoding, in, size, 0, 0, reason);
6800 if (exc != NULL) {
6801 PyCodec_StrictErrors(exc);
6802 Py_CLEAR(exc);
6803 }
6804 goto error;
6805 }
6806
6807 if (*v == NULL) {
6808 /* Create unicode object */
6809 if (size > PY_SSIZE_T_MAX / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
6810 PyErr_NoMemory();
6811 goto error;
6812 }
Victor Stinnerab595942011-12-17 04:59:06 +01006813 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01006814 *v = (PyObject*)_PyUnicode_New(size * Py_ARRAY_LENGTH(buffer));
Victor Stinner3a50e702011-10-18 21:21:00 +02006815 if (*v == NULL)
6816 goto error;
6817 startout = PyUnicode_AS_UNICODE(*v);
6818 }
6819 else {
6820 /* Extend unicode object */
6821 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
6822 if (size > (PY_SSIZE_T_MAX - n) / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
6823 PyErr_NoMemory();
6824 goto error;
6825 }
Victor Stinner16e6a802011-12-12 13:24:15 +01006826 if (unicode_resize(v, n + size * Py_ARRAY_LENGTH(buffer)) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02006827 goto error;
6828 startout = PyUnicode_AS_UNICODE(*v) + n;
6829 }
6830
6831 /* Decode the byte string character per character */
6832 out = startout;
6833 while (in < endin)
6834 {
6835 /* Decode a character */
6836 insize = 1;
6837 do
6838 {
6839 outsize = MultiByteToWideChar(code_page, flags,
6840 in, insize,
6841 buffer, Py_ARRAY_LENGTH(buffer));
6842 if (outsize > 0)
6843 break;
6844 err = GetLastError();
6845 if (err != ERROR_NO_UNICODE_TRANSLATION
6846 && err != ERROR_INSUFFICIENT_BUFFER)
6847 {
6848 PyErr_SetFromWindowsErr(0);
6849 goto error;
6850 }
6851 insize++;
6852 }
6853 /* 4=maximum length of a UTF-8 sequence */
6854 while (insize <= 4 && (in + insize) <= endin);
6855
6856 if (outsize <= 0) {
6857 Py_ssize_t startinpos, endinpos, outpos;
6858
6859 startinpos = in - startin;
6860 endinpos = startinpos + 1;
6861 outpos = out - PyUnicode_AS_UNICODE(*v);
6862 if (unicode_decode_call_errorhandler(
6863 errors, &errorHandler,
6864 encoding, reason,
6865 &startin, &endin, &startinpos, &endinpos, &exc, &in,
Victor Stinner596a6c42011-11-09 00:02:18 +01006866 v, &outpos))
Victor Stinner3a50e702011-10-18 21:21:00 +02006867 {
6868 goto error;
6869 }
Victor Stinner596a6c42011-11-09 00:02:18 +01006870 out = PyUnicode_AS_UNICODE(*v) + outpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02006871 }
6872 else {
6873 in += insize;
6874 memcpy(out, buffer, outsize * sizeof(wchar_t));
6875 out += outsize;
6876 }
6877 }
6878
6879 /* write a NUL character at the end */
6880 *out = 0;
6881
6882 /* Extend unicode object */
6883 outsize = out - startout;
6884 assert(outsize <= PyUnicode_WSTR_LENGTH(*v));
Victor Stinner16e6a802011-12-12 13:24:15 +01006885 if (unicode_resize(v, outsize) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02006886 goto error;
Victor Stinner76a31a62011-11-04 00:05:13 +01006887 ret = size;
Victor Stinner3a50e702011-10-18 21:21:00 +02006888
6889error:
6890 Py_XDECREF(encoding_obj);
6891 Py_XDECREF(errorHandler);
6892 Py_XDECREF(exc);
6893 return ret;
6894}
6895
Victor Stinner3a50e702011-10-18 21:21:00 +02006896static PyObject *
6897decode_code_page_stateful(int code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01006898 const char *s, Py_ssize_t size,
6899 const char *errors, Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006900{
Victor Stinner76a31a62011-11-04 00:05:13 +01006901 PyObject *v = NULL;
6902 int chunk_size, final, converted, done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006903
Victor Stinner3a50e702011-10-18 21:21:00 +02006904 if (code_page < 0) {
6905 PyErr_SetString(PyExc_ValueError, "invalid code page number");
6906 return NULL;
6907 }
6908
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006909 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00006910 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006911
Victor Stinner76a31a62011-11-04 00:05:13 +01006912 do
6913 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006914#ifdef NEED_RETRY
Victor Stinner76a31a62011-11-04 00:05:13 +01006915 if (size > INT_MAX) {
6916 chunk_size = INT_MAX;
6917 final = 0;
6918 done = 0;
6919 }
6920 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006921#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01006922 {
6923 chunk_size = (int)size;
6924 final = (consumed == NULL);
6925 done = 1;
6926 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006927
Victor Stinner76a31a62011-11-04 00:05:13 +01006928 /* Skip trailing lead-byte unless 'final' is set */
6929 if (!final && is_dbcs_lead_byte(code_page, s, chunk_size - 1))
6930 --chunk_size;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006931
Victor Stinner76a31a62011-11-04 00:05:13 +01006932 if (chunk_size == 0 && done) {
6933 if (v != NULL)
6934 break;
6935 Py_INCREF(unicode_empty);
6936 return unicode_empty;
6937 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006938
Victor Stinner76a31a62011-11-04 00:05:13 +01006939
6940 converted = decode_code_page_strict(code_page, &v,
6941 s, chunk_size);
6942 if (converted == -2)
6943 converted = decode_code_page_errors(code_page, &v,
6944 s, chunk_size,
6945 errors);
6946 assert(converted != 0);
6947
6948 if (converted < 0) {
6949 Py_XDECREF(v);
6950 return NULL;
6951 }
6952
6953 if (consumed)
6954 *consumed += converted;
6955
6956 s += converted;
6957 size -= converted;
6958 } while (!done);
Victor Stinner3a50e702011-10-18 21:21:00 +02006959
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006960 return unicode_result(v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006961}
6962
Alexander Belopolsky40018472011-02-26 01:02:56 +00006963PyObject *
Victor Stinner3a50e702011-10-18 21:21:00 +02006964PyUnicode_DecodeCodePageStateful(int code_page,
6965 const char *s,
6966 Py_ssize_t size,
6967 const char *errors,
6968 Py_ssize_t *consumed)
6969{
6970 return decode_code_page_stateful(code_page, s, size, errors, consumed);
6971}
6972
6973PyObject *
6974PyUnicode_DecodeMBCSStateful(const char *s,
6975 Py_ssize_t size,
6976 const char *errors,
6977 Py_ssize_t *consumed)
6978{
6979 return decode_code_page_stateful(CP_ACP, s, size, errors, consumed);
6980}
6981
6982PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00006983PyUnicode_DecodeMBCS(const char *s,
6984 Py_ssize_t size,
6985 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006986{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006987 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
6988}
6989
Victor Stinner3a50e702011-10-18 21:21:00 +02006990static DWORD
6991encode_code_page_flags(UINT code_page, const char *errors)
6992{
6993 if (code_page == CP_UTF8) {
6994 if (winver.dwMajorVersion >= 6)
6995 /* CP_UTF8 supports WC_ERR_INVALID_CHARS on Windows Vista
6996 and later */
6997 return WC_ERR_INVALID_CHARS;
6998 else
6999 /* CP_UTF8 only supports flags=0 on Windows older than Vista */
7000 return 0;
7001 }
7002 else if (code_page == CP_UTF7) {
7003 /* CP_UTF7 only supports flags=0 */
7004 return 0;
7005 }
7006 else {
7007 if (errors != NULL && strcmp(errors, "replace") == 0)
7008 return 0;
7009 else
7010 return WC_NO_BEST_FIT_CHARS;
7011 }
7012}
7013
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007014/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007015 * Encode a Unicode string to a Windows code page into a byte string in strict
7016 * mode.
7017 *
7018 * Returns consumed characters if succeed, returns -2 on encode error, or raise
7019 * a WindowsError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007020 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007021static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007022encode_code_page_strict(UINT code_page, PyObject **outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007023 PyObject *unicode, Py_ssize_t offset, int len,
Victor Stinner3a50e702011-10-18 21:21:00 +02007024 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007025{
Victor Stinner554f3f02010-06-16 23:33:54 +00007026 BOOL usedDefaultChar = FALSE;
Victor Stinner3a50e702011-10-18 21:21:00 +02007027 BOOL *pusedDefaultChar = &usedDefaultChar;
7028 int outsize;
Victor Stinner554f3f02010-06-16 23:33:54 +00007029 PyObject *exc = NULL;
Victor Stinner24729f32011-11-10 20:31:37 +01007030 wchar_t *p;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007031 Py_ssize_t size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007032 const DWORD flags = encode_code_page_flags(code_page, NULL);
7033 char *out;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007034 /* Create a substring so that we can get the UTF-16 representation
7035 of just the slice under consideration. */
7036 PyObject *substring;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007037
Martin v. Löwis3d325192011-11-04 18:23:06 +01007038 assert(len > 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007039
Victor Stinner3a50e702011-10-18 21:21:00 +02007040 if (code_page != CP_UTF8 && code_page != CP_UTF7)
Victor Stinner554f3f02010-06-16 23:33:54 +00007041 pusedDefaultChar = &usedDefaultChar;
Victor Stinner3a50e702011-10-18 21:21:00 +02007042 else
Victor Stinner554f3f02010-06-16 23:33:54 +00007043 pusedDefaultChar = NULL;
Victor Stinner554f3f02010-06-16 23:33:54 +00007044
Victor Stinner2fc507f2011-11-04 20:06:39 +01007045 substring = PyUnicode_Substring(unicode, offset, offset+len);
7046 if (substring == NULL)
7047 return -1;
7048 p = PyUnicode_AsUnicodeAndSize(substring, &size);
7049 if (p == NULL) {
7050 Py_DECREF(substring);
7051 return -1;
7052 }
Martin v. Löwis3d325192011-11-04 18:23:06 +01007053
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007054 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007055 outsize = WideCharToMultiByte(code_page, flags,
7056 p, size,
7057 NULL, 0,
7058 NULL, pusedDefaultChar);
7059 if (outsize <= 0)
7060 goto error;
7061 /* If we used a default char, then we failed! */
Victor Stinner2fc507f2011-11-04 20:06:39 +01007062 if (pusedDefaultChar && *pusedDefaultChar) {
7063 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007064 return -2;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007065 }
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007066
Victor Stinner3a50e702011-10-18 21:21:00 +02007067 if (*outbytes == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007068 /* Create string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007069 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007070 if (*outbytes == NULL) {
7071 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007072 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007073 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007074 out = PyBytes_AS_STRING(*outbytes);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007075 }
7076 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007077 /* Extend string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007078 const Py_ssize_t n = PyBytes_Size(*outbytes);
7079 if (outsize > PY_SSIZE_T_MAX - n) {
7080 PyErr_NoMemory();
Victor Stinner2fc507f2011-11-04 20:06:39 +01007081 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007082 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007083 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007084 if (_PyBytes_Resize(outbytes, n + outsize) < 0) {
7085 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007086 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007087 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007088 out = PyBytes_AS_STRING(*outbytes) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007089 }
7090
7091 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007092 outsize = WideCharToMultiByte(code_page, flags,
7093 p, size,
7094 out, outsize,
7095 NULL, pusedDefaultChar);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007096 Py_CLEAR(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007097 if (outsize <= 0)
7098 goto error;
7099 if (pusedDefaultChar && *pusedDefaultChar)
7100 return -2;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007101 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00007102
Victor Stinner3a50e702011-10-18 21:21:00 +02007103error:
Victor Stinner2fc507f2011-11-04 20:06:39 +01007104 Py_XDECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007105 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7106 return -2;
7107 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007108 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007109}
7110
Victor Stinner3a50e702011-10-18 21:21:00 +02007111/*
7112 * Encode a Unicode string to a Windows code page into a byte string using a
7113 * error handler.
7114 *
7115 * Returns consumed characters if succeed, or raise a WindowsError and returns
7116 * -1 on other error.
7117 */
7118static int
7119encode_code_page_errors(UINT code_page, PyObject **outbytes,
Victor Stinner7581cef2011-11-03 22:32:33 +01007120 PyObject *unicode, Py_ssize_t unicode_offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007121 Py_ssize_t insize, const char* errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007122{
Victor Stinner3a50e702011-10-18 21:21:00 +02007123 const DWORD flags = encode_code_page_flags(code_page, errors);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007124 Py_ssize_t pos = unicode_offset;
7125 Py_ssize_t endin = unicode_offset + insize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007126 /* Ideally, we should get reason from FormatMessage. This is the Windows
7127 2000 English version of the message. */
7128 const char *reason = "invalid character";
7129 /* 4=maximum length of a UTF-8 sequence */
7130 char buffer[4];
7131 BOOL usedDefaultChar = FALSE, *pusedDefaultChar;
7132 Py_ssize_t outsize;
7133 char *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007134 PyObject *errorHandler = NULL;
7135 PyObject *exc = NULL;
7136 PyObject *encoding_obj = NULL;
7137 char *encoding;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007138 Py_ssize_t newpos, newoutsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007139 PyObject *rep;
7140 int ret = -1;
7141
7142 assert(insize > 0);
7143
7144 encoding = code_page_name(code_page, &encoding_obj);
7145 if (encoding == NULL)
7146 return -1;
7147
7148 if (errors == NULL || strcmp(errors, "strict") == 0) {
7149 /* The last error was ERROR_NO_UNICODE_TRANSLATION,
7150 then we raise a UnicodeEncodeError. */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007151 make_encode_exception(&exc, encoding, unicode, 0, 0, reason);
Victor Stinner3a50e702011-10-18 21:21:00 +02007152 if (exc != NULL) {
7153 PyCodec_StrictErrors(exc);
7154 Py_DECREF(exc);
7155 }
7156 Py_XDECREF(encoding_obj);
7157 return -1;
7158 }
7159
7160 if (code_page != CP_UTF8 && code_page != CP_UTF7)
7161 pusedDefaultChar = &usedDefaultChar;
7162 else
7163 pusedDefaultChar = NULL;
7164
7165 if (Py_ARRAY_LENGTH(buffer) > PY_SSIZE_T_MAX / insize) {
7166 PyErr_NoMemory();
7167 goto error;
7168 }
7169 outsize = insize * Py_ARRAY_LENGTH(buffer);
7170
7171 if (*outbytes == NULL) {
7172 /* Create string object */
7173 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
7174 if (*outbytes == NULL)
7175 goto error;
7176 out = PyBytes_AS_STRING(*outbytes);
7177 }
7178 else {
7179 /* Extend string object */
7180 Py_ssize_t n = PyBytes_Size(*outbytes);
7181 if (n > PY_SSIZE_T_MAX - outsize) {
7182 PyErr_NoMemory();
7183 goto error;
7184 }
7185 if (_PyBytes_Resize(outbytes, n + outsize) < 0)
7186 goto error;
7187 out = PyBytes_AS_STRING(*outbytes) + n;
7188 }
7189
7190 /* Encode the string character per character */
Martin v. Löwis3d325192011-11-04 18:23:06 +01007191 while (pos < endin)
Victor Stinner3a50e702011-10-18 21:21:00 +02007192 {
Victor Stinner2fc507f2011-11-04 20:06:39 +01007193 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, pos);
7194 wchar_t chars[2];
7195 int charsize;
7196 if (ch < 0x10000) {
7197 chars[0] = (wchar_t)ch;
7198 charsize = 1;
7199 }
7200 else {
7201 ch -= 0x10000;
7202 chars[0] = 0xd800 + (ch >> 10);
7203 chars[1] = 0xdc00 + (ch & 0x3ff);
7204 charsize = 2;
7205 }
7206
Victor Stinner3a50e702011-10-18 21:21:00 +02007207 outsize = WideCharToMultiByte(code_page, flags,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007208 chars, charsize,
Victor Stinner3a50e702011-10-18 21:21:00 +02007209 buffer, Py_ARRAY_LENGTH(buffer),
7210 NULL, pusedDefaultChar);
7211 if (outsize > 0) {
7212 if (pusedDefaultChar == NULL || !(*pusedDefaultChar))
7213 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007214 pos++;
Victor Stinner3a50e702011-10-18 21:21:00 +02007215 memcpy(out, buffer, outsize);
7216 out += outsize;
7217 continue;
7218 }
7219 }
7220 else if (GetLastError() != ERROR_NO_UNICODE_TRANSLATION) {
7221 PyErr_SetFromWindowsErr(0);
7222 goto error;
7223 }
7224
Victor Stinner3a50e702011-10-18 21:21:00 +02007225 rep = unicode_encode_call_errorhandler(
7226 errors, &errorHandler, encoding, reason,
Victor Stinner7581cef2011-11-03 22:32:33 +01007227 unicode, &exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007228 pos, pos + 1, &newpos);
Victor Stinner3a50e702011-10-18 21:21:00 +02007229 if (rep == NULL)
7230 goto error;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007231 pos = newpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007232
7233 if (PyBytes_Check(rep)) {
7234 outsize = PyBytes_GET_SIZE(rep);
7235 if (outsize != 1) {
7236 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7237 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7238 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7239 Py_DECREF(rep);
7240 goto error;
7241 }
7242 out = PyBytes_AS_STRING(*outbytes) + offset;
7243 }
7244 memcpy(out, PyBytes_AS_STRING(rep), outsize);
7245 out += outsize;
7246 }
7247 else {
7248 Py_ssize_t i;
7249 enum PyUnicode_Kind kind;
7250 void *data;
7251
Benjamin Petersonbac79492012-01-14 13:34:47 -05007252 if (PyUnicode_READY(rep) == -1) {
Victor Stinner3a50e702011-10-18 21:21:00 +02007253 Py_DECREF(rep);
7254 goto error;
7255 }
7256
7257 outsize = PyUnicode_GET_LENGTH(rep);
7258 if (outsize != 1) {
7259 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7260 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7261 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7262 Py_DECREF(rep);
7263 goto error;
7264 }
7265 out = PyBytes_AS_STRING(*outbytes) + offset;
7266 }
7267 kind = PyUnicode_KIND(rep);
7268 data = PyUnicode_DATA(rep);
7269 for (i=0; i < outsize; i++) {
7270 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7271 if (ch > 127) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007272 raise_encode_exception(&exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007273 encoding, unicode,
7274 pos, pos + 1,
Victor Stinner3a50e702011-10-18 21:21:00 +02007275 "unable to encode error handler result to ASCII");
7276 Py_DECREF(rep);
7277 goto error;
7278 }
7279 *out = (unsigned char)ch;
7280 out++;
7281 }
7282 }
7283 Py_DECREF(rep);
7284 }
7285 /* write a NUL byte */
7286 *out = 0;
7287 outsize = out - PyBytes_AS_STRING(*outbytes);
7288 assert(outsize <= PyBytes_GET_SIZE(*outbytes));
7289 if (_PyBytes_Resize(outbytes, outsize) < 0)
7290 goto error;
7291 ret = 0;
7292
7293error:
7294 Py_XDECREF(encoding_obj);
7295 Py_XDECREF(errorHandler);
7296 Py_XDECREF(exc);
7297 return ret;
7298}
7299
Victor Stinner3a50e702011-10-18 21:21:00 +02007300static PyObject *
7301encode_code_page(int code_page,
Victor Stinner7581cef2011-11-03 22:32:33 +01007302 PyObject *unicode,
Victor Stinner3a50e702011-10-18 21:21:00 +02007303 const char *errors)
7304{
Martin v. Löwis3d325192011-11-04 18:23:06 +01007305 Py_ssize_t len;
Victor Stinner3a50e702011-10-18 21:21:00 +02007306 PyObject *outbytes = NULL;
Victor Stinner7581cef2011-11-03 22:32:33 +01007307 Py_ssize_t offset;
Victor Stinner76a31a62011-11-04 00:05:13 +01007308 int chunk_len, ret, done;
Victor Stinner7581cef2011-11-03 22:32:33 +01007309
Benjamin Petersonbac79492012-01-14 13:34:47 -05007310 if (PyUnicode_READY(unicode) == -1)
Victor Stinner2fc507f2011-11-04 20:06:39 +01007311 return NULL;
7312 len = PyUnicode_GET_LENGTH(unicode);
Guido van Rossum03e29f12000-05-04 15:52:20 +00007313
Victor Stinner3a50e702011-10-18 21:21:00 +02007314 if (code_page < 0) {
7315 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7316 return NULL;
7317 }
7318
Martin v. Löwis3d325192011-11-04 18:23:06 +01007319 if (len == 0)
Victor Stinner76a31a62011-11-04 00:05:13 +01007320 return PyBytes_FromStringAndSize(NULL, 0);
7321
Victor Stinner7581cef2011-11-03 22:32:33 +01007322 offset = 0;
7323 do
7324 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007325#ifdef NEED_RETRY
Victor Stinner2fc507f2011-11-04 20:06:39 +01007326 /* UTF-16 encoding may double the size, so use only INT_MAX/2
Martin v. Löwis3d325192011-11-04 18:23:06 +01007327 chunks. */
7328 if (len > INT_MAX/2) {
7329 chunk_len = INT_MAX/2;
Victor Stinner76a31a62011-11-04 00:05:13 +01007330 done = 0;
7331 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007332 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007333#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007334 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007335 chunk_len = (int)len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007336 done = 1;
7337 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007338
Victor Stinner76a31a62011-11-04 00:05:13 +01007339 ret = encode_code_page_strict(code_page, &outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007340 unicode, offset, chunk_len,
Victor Stinner76a31a62011-11-04 00:05:13 +01007341 errors);
7342 if (ret == -2)
7343 ret = encode_code_page_errors(code_page, &outbytes,
7344 unicode, offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007345 chunk_len, errors);
Victor Stinner7581cef2011-11-03 22:32:33 +01007346 if (ret < 0) {
7347 Py_XDECREF(outbytes);
7348 return NULL;
7349 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007350
Victor Stinner7581cef2011-11-03 22:32:33 +01007351 offset += chunk_len;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007352 len -= chunk_len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007353 } while (!done);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007354
Victor Stinner3a50e702011-10-18 21:21:00 +02007355 return outbytes;
7356}
7357
7358PyObject *
7359PyUnicode_EncodeMBCS(const Py_UNICODE *p,
7360 Py_ssize_t size,
7361 const char *errors)
7362{
Victor Stinner7581cef2011-11-03 22:32:33 +01007363 PyObject *unicode, *res;
7364 unicode = PyUnicode_FromUnicode(p, size);
7365 if (unicode == NULL)
7366 return NULL;
7367 res = encode_code_page(CP_ACP, unicode, errors);
7368 Py_DECREF(unicode);
7369 return res;
Victor Stinner3a50e702011-10-18 21:21:00 +02007370}
7371
7372PyObject *
7373PyUnicode_EncodeCodePage(int code_page,
7374 PyObject *unicode,
7375 const char *errors)
7376{
Victor Stinner7581cef2011-11-03 22:32:33 +01007377 return encode_code_page(code_page, unicode, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007378}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007379
Alexander Belopolsky40018472011-02-26 01:02:56 +00007380PyObject *
7381PyUnicode_AsMBCSString(PyObject *unicode)
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007382{
7383 if (!PyUnicode_Check(unicode)) {
7384 PyErr_BadArgument();
7385 return NULL;
7386 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007387 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007388}
7389
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007390#undef NEED_RETRY
7391
Victor Stinner99b95382011-07-04 14:23:54 +02007392#endif /* HAVE_MBCS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007393
Guido van Rossumd57fd912000-03-10 22:53:23 +00007394/* --- Character Mapping Codec -------------------------------------------- */
7395
Alexander Belopolsky40018472011-02-26 01:02:56 +00007396PyObject *
7397PyUnicode_DecodeCharmap(const char *s,
7398 Py_ssize_t size,
7399 PyObject *mapping,
7400 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007401{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007402 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007403 Py_ssize_t startinpos;
7404 Py_ssize_t endinpos;
7405 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007406 const char *e;
Victor Stinner7931d9a2011-11-04 00:22:48 +01007407 PyObject *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007408 Py_ssize_t extrachars = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007409 PyObject *errorHandler = NULL;
7410 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00007411
Guido van Rossumd57fd912000-03-10 22:53:23 +00007412 /* Default to Latin-1 */
7413 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007414 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007415
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007416 v = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007417 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007418 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007419 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01007420 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007421 outpos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007422 e = s + size;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007423 if (PyUnicode_CheckExact(mapping)) {
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007424 Py_ssize_t maplen;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007425 enum PyUnicode_Kind mapkind;
7426 void *mapdata;
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007427 Py_UCS4 x;
7428
Benjamin Petersonbac79492012-01-14 13:34:47 -05007429 if (PyUnicode_READY(mapping) == -1)
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007430 return NULL;
7431
7432 maplen = PyUnicode_GET_LENGTH(mapping);
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007433 mapdata = PyUnicode_DATA(mapping);
7434 mapkind = PyUnicode_KIND(mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00007435 while (s < e) {
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007436 unsigned char ch;
7437 if (mapkind == PyUnicode_2BYTE_KIND && maplen >= 256) {
7438 enum PyUnicode_Kind outkind = PyUnicode_KIND(v);
7439 if (outkind == PyUnicode_1BYTE_KIND) {
7440 void *outdata = PyUnicode_DATA(v);
7441 Py_UCS4 maxchar = PyUnicode_MAX_CHAR_VALUE(v);
7442 while (s < e) {
7443 unsigned char ch = *s;
7444 x = PyUnicode_READ(PyUnicode_2BYTE_KIND, mapdata, ch);
7445 if (x > maxchar)
7446 goto Error;
7447 PyUnicode_WRITE(PyUnicode_1BYTE_KIND, outdata, outpos++, x);
7448 ++s;
7449 }
7450 break;
7451 }
7452 else if (outkind == PyUnicode_2BYTE_KIND) {
7453 void *outdata = PyUnicode_DATA(v);
7454 while (s < e) {
7455 unsigned char ch = *s;
7456 x = PyUnicode_READ(PyUnicode_2BYTE_KIND, mapdata, ch);
7457 if (x == 0xFFFE)
7458 goto Error;
7459 PyUnicode_WRITE(PyUnicode_2BYTE_KIND, outdata, outpos++, x);
7460 ++s;
7461 }
7462 break;
7463 }
7464 }
7465 ch = *s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007466
Benjamin Peterson29060642009-01-31 22:14:21 +00007467 if (ch < maplen)
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007468 x = PyUnicode_READ(mapkind, mapdata, ch);
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007469 else
7470 x = 0xfffe; /* invalid value */
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007471Error:
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007472 if (x == 0xfffe)
7473 {
Benjamin Peterson29060642009-01-31 22:14:21 +00007474 /* undefined mapping */
Benjamin Peterson29060642009-01-31 22:14:21 +00007475 startinpos = s-starts;
7476 endinpos = startinpos+1;
7477 if (unicode_decode_call_errorhandler(
7478 errors, &errorHandler,
7479 "charmap", "character maps to <undefined>",
7480 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007481 &v, &outpos)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007482 goto onError;
7483 }
7484 continue;
7485 }
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007486
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007487 if (unicode_putchar(&v, &outpos, x) < 0)
7488 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00007489 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007490 }
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007491 }
7492 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007493 while (s < e) {
7494 unsigned char ch = *s;
7495 PyObject *w, *x;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007496
Benjamin Peterson29060642009-01-31 22:14:21 +00007497 /* Get mapping (char ordinal -> integer, Unicode char or None) */
7498 w = PyLong_FromLong((long)ch);
7499 if (w == NULL)
7500 goto onError;
7501 x = PyObject_GetItem(mapping, w);
7502 Py_DECREF(w);
7503 if (x == NULL) {
7504 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7505 /* No mapping found means: mapping is undefined. */
7506 PyErr_Clear();
7507 x = Py_None;
7508 Py_INCREF(x);
7509 } else
7510 goto onError;
7511 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007512
Benjamin Peterson29060642009-01-31 22:14:21 +00007513 /* Apply mapping */
7514 if (PyLong_Check(x)) {
7515 long value = PyLong_AS_LONG(x);
Antoine Pitroua1f76552012-09-23 20:00:04 +02007516 if (value < 0 || value > MAX_UNICODE) {
7517 PyErr_Format(PyExc_TypeError,
7518 "character mapping must be in range(0x%lx)",
7519 (unsigned long)MAX_UNICODE + 1);
Benjamin Peterson29060642009-01-31 22:14:21 +00007520 Py_DECREF(x);
7521 goto onError;
7522 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007523 if (unicode_putchar(&v, &outpos, value) < 0)
7524 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00007525 }
7526 else if (x == Py_None) {
7527 /* undefined mapping */
Benjamin Peterson29060642009-01-31 22:14:21 +00007528 startinpos = s-starts;
7529 endinpos = startinpos+1;
7530 if (unicode_decode_call_errorhandler(
7531 errors, &errorHandler,
7532 "charmap", "character maps to <undefined>",
7533 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007534 &v, &outpos)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007535 Py_DECREF(x);
7536 goto onError;
7537 }
7538 Py_DECREF(x);
7539 continue;
7540 }
7541 else if (PyUnicode_Check(x)) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007542 Py_ssize_t targetsize;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007543
Benjamin Petersonbac79492012-01-14 13:34:47 -05007544 if (PyUnicode_READY(x) == -1)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007545 goto onError;
7546 targetsize = PyUnicode_GET_LENGTH(x);
7547
7548 if (targetsize == 1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007549 /* 1-1 mapping */
Victor Stinner62aa4d02011-11-09 00:03:45 +01007550 if (unicode_putchar(&v, &outpos,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007551 PyUnicode_READ_CHAR(x, 0)) < 0)
7552 goto onError;
7553 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007554 else if (targetsize > 1) {
7555 /* 1-n mapping */
7556 if (targetsize > extrachars) {
7557 /* resize first */
Benjamin Peterson29060642009-01-31 22:14:21 +00007558 Py_ssize_t needed = (targetsize - extrachars) + \
7559 (targetsize << 2);
7560 extrachars += needed;
7561 /* XXX overflow detection missing */
Victor Stinner16e6a802011-12-12 13:24:15 +01007562 if (unicode_resize(&v,
7563 PyUnicode_GET_LENGTH(v) + needed) < 0)
7564 {
Benjamin Peterson29060642009-01-31 22:14:21 +00007565 Py_DECREF(x);
7566 goto onError;
7567 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007568 }
Victor Stinner1b487b42012-05-03 12:29:04 +02007569 if (unicode_widen(&v, outpos, PyUnicode_MAX_CHAR_VALUE(x)) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007570 goto onError;
7571 PyUnicode_CopyCharacters(v, outpos, x, 0, targetsize);
7572 outpos += targetsize;
Benjamin Peterson29060642009-01-31 22:14:21 +00007573 extrachars -= targetsize;
7574 }
7575 /* 1-0 mapping: skip the character */
7576 }
7577 else {
7578 /* wrong return value */
7579 PyErr_SetString(PyExc_TypeError,
7580 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00007581 Py_DECREF(x);
7582 goto onError;
7583 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007584 Py_DECREF(x);
7585 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007586 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00007587 }
Victor Stinner16e6a802011-12-12 13:24:15 +01007588 if (unicode_resize(&v, outpos) < 0)
Antoine Pitroua8f63c02011-11-08 18:37:16 +01007589 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007590 Py_XDECREF(errorHandler);
7591 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01007592 return unicode_result(v);
Tim Petersced69f82003-09-16 20:30:58 +00007593
Benjamin Peterson29060642009-01-31 22:14:21 +00007594 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007595 Py_XDECREF(errorHandler);
7596 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007597 Py_XDECREF(v);
7598 return NULL;
7599}
7600
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007601/* Charmap encoding: the lookup table */
7602
Alexander Belopolsky40018472011-02-26 01:02:56 +00007603struct encoding_map {
Benjamin Peterson29060642009-01-31 22:14:21 +00007604 PyObject_HEAD
7605 unsigned char level1[32];
7606 int count2, count3;
7607 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007608};
7609
7610static PyObject*
7611encoding_map_size(PyObject *obj, PyObject* args)
7612{
7613 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007614 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00007615 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007616}
7617
7618static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007619 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00007620 PyDoc_STR("Return the size (in bytes) of this object") },
7621 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007622};
7623
7624static void
7625encoding_map_dealloc(PyObject* o)
7626{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007627 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007628}
7629
7630static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007631 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007632 "EncodingMap", /*tp_name*/
7633 sizeof(struct encoding_map), /*tp_basicsize*/
7634 0, /*tp_itemsize*/
7635 /* methods */
7636 encoding_map_dealloc, /*tp_dealloc*/
7637 0, /*tp_print*/
7638 0, /*tp_getattr*/
7639 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00007640 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00007641 0, /*tp_repr*/
7642 0, /*tp_as_number*/
7643 0, /*tp_as_sequence*/
7644 0, /*tp_as_mapping*/
7645 0, /*tp_hash*/
7646 0, /*tp_call*/
7647 0, /*tp_str*/
7648 0, /*tp_getattro*/
7649 0, /*tp_setattro*/
7650 0, /*tp_as_buffer*/
7651 Py_TPFLAGS_DEFAULT, /*tp_flags*/
7652 0, /*tp_doc*/
7653 0, /*tp_traverse*/
7654 0, /*tp_clear*/
7655 0, /*tp_richcompare*/
7656 0, /*tp_weaklistoffset*/
7657 0, /*tp_iter*/
7658 0, /*tp_iternext*/
7659 encoding_map_methods, /*tp_methods*/
7660 0, /*tp_members*/
7661 0, /*tp_getset*/
7662 0, /*tp_base*/
7663 0, /*tp_dict*/
7664 0, /*tp_descr_get*/
7665 0, /*tp_descr_set*/
7666 0, /*tp_dictoffset*/
7667 0, /*tp_init*/
7668 0, /*tp_alloc*/
7669 0, /*tp_new*/
7670 0, /*tp_free*/
7671 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007672};
7673
7674PyObject*
7675PyUnicode_BuildEncodingMap(PyObject* string)
7676{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007677 PyObject *result;
7678 struct encoding_map *mresult;
7679 int i;
7680 int need_dict = 0;
7681 unsigned char level1[32];
7682 unsigned char level2[512];
7683 unsigned char *mlevel1, *mlevel2, *mlevel3;
7684 int count2 = 0, count3 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007685 int kind;
7686 void *data;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007687 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007688 Py_UCS4 ch;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007689
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007690 if (!PyUnicode_Check(string) || !PyUnicode_GET_LENGTH(string)) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007691 PyErr_BadArgument();
7692 return NULL;
7693 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007694 kind = PyUnicode_KIND(string);
7695 data = PyUnicode_DATA(string);
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007696 length = PyUnicode_GET_LENGTH(string);
7697 length = Py_MIN(length, 256);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007698 memset(level1, 0xFF, sizeof level1);
7699 memset(level2, 0xFF, sizeof level2);
7700
7701 /* If there isn't a one-to-one mapping of NULL to \0,
7702 or if there are non-BMP characters, we need to use
7703 a mapping dictionary. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007704 if (PyUnicode_READ(kind, data, 0) != 0)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007705 need_dict = 1;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007706 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007707 int l1, l2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007708 ch = PyUnicode_READ(kind, data, i);
7709 if (ch == 0 || ch > 0xFFFF) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007710 need_dict = 1;
7711 break;
7712 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007713 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007714 /* unmapped character */
7715 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007716 l1 = ch >> 11;
7717 l2 = ch >> 7;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007718 if (level1[l1] == 0xFF)
7719 level1[l1] = count2++;
7720 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00007721 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007722 }
7723
7724 if (count2 >= 0xFF || count3 >= 0xFF)
7725 need_dict = 1;
7726
7727 if (need_dict) {
7728 PyObject *result = PyDict_New();
7729 PyObject *key, *value;
7730 if (!result)
7731 return NULL;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007732 for (i = 0; i < length; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007733 key = PyLong_FromLong(PyUnicode_READ(kind, data, i));
Christian Heimes217cfd12007-12-02 14:31:20 +00007734 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007735 if (!key || !value)
7736 goto failed1;
7737 if (PyDict_SetItem(result, key, value) == -1)
7738 goto failed1;
7739 Py_DECREF(key);
7740 Py_DECREF(value);
7741 }
7742 return result;
7743 failed1:
7744 Py_XDECREF(key);
7745 Py_XDECREF(value);
7746 Py_DECREF(result);
7747 return NULL;
7748 }
7749
7750 /* Create a three-level trie */
7751 result = PyObject_MALLOC(sizeof(struct encoding_map) +
7752 16*count2 + 128*count3 - 1);
7753 if (!result)
7754 return PyErr_NoMemory();
7755 PyObject_Init(result, &EncodingMapType);
7756 mresult = (struct encoding_map*)result;
7757 mresult->count2 = count2;
7758 mresult->count3 = count3;
7759 mlevel1 = mresult->level1;
7760 mlevel2 = mresult->level23;
7761 mlevel3 = mresult->level23 + 16*count2;
7762 memcpy(mlevel1, level1, 32);
7763 memset(mlevel2, 0xFF, 16*count2);
7764 memset(mlevel3, 0, 128*count3);
7765 count3 = 0;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007766 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007767 int o1, o2, o3, i2, i3;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007768 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7769 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007770 /* unmapped character */
7771 continue;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007772 o1 = ch>>11;
7773 o2 = (ch>>7) & 0xF;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007774 i2 = 16*mlevel1[o1] + o2;
7775 if (mlevel2[i2] == 0xFF)
7776 mlevel2[i2] = count3++;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007777 o3 = ch & 0x7F;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007778 i3 = 128*mlevel2[i2] + o3;
7779 mlevel3[i3] = i;
7780 }
7781 return result;
7782}
7783
7784static int
Victor Stinner22168992011-11-20 17:09:18 +01007785encoding_map_lookup(Py_UCS4 c, PyObject *mapping)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007786{
7787 struct encoding_map *map = (struct encoding_map*)mapping;
7788 int l1 = c>>11;
7789 int l2 = (c>>7) & 0xF;
7790 int l3 = c & 0x7F;
7791 int i;
7792
Victor Stinner22168992011-11-20 17:09:18 +01007793 if (c > 0xFFFF)
Benjamin Peterson29060642009-01-31 22:14:21 +00007794 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007795 if (c == 0)
7796 return 0;
7797 /* level 1*/
7798 i = map->level1[l1];
7799 if (i == 0xFF) {
7800 return -1;
7801 }
7802 /* level 2*/
7803 i = map->level23[16*i+l2];
7804 if (i == 0xFF) {
7805 return -1;
7806 }
7807 /* level 3 */
7808 i = map->level23[16*map->count2 + 128*i + l3];
7809 if (i == 0) {
7810 return -1;
7811 }
7812 return i;
7813}
7814
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007815/* Lookup the character ch in the mapping. If the character
7816 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00007817 error occurred). */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007818static PyObject *
Victor Stinner22168992011-11-20 17:09:18 +01007819charmapencode_lookup(Py_UCS4 c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007820{
Christian Heimes217cfd12007-12-02 14:31:20 +00007821 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007822 PyObject *x;
7823
7824 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007825 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007826 x = PyObject_GetItem(mapping, w);
7827 Py_DECREF(w);
7828 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007829 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7830 /* No mapping found means: mapping is undefined. */
7831 PyErr_Clear();
7832 x = Py_None;
7833 Py_INCREF(x);
7834 return x;
7835 } else
7836 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007837 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00007838 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00007839 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00007840 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007841 long value = PyLong_AS_LONG(x);
7842 if (value < 0 || value > 255) {
7843 PyErr_SetString(PyExc_TypeError,
7844 "character mapping must be in range(256)");
7845 Py_DECREF(x);
7846 return NULL;
7847 }
7848 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007849 }
Christian Heimes72b710a2008-05-26 13:28:38 +00007850 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00007851 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007852 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007853 /* wrong return value */
7854 PyErr_Format(PyExc_TypeError,
7855 "character mapping must return integer, bytes or None, not %.400s",
7856 x->ob_type->tp_name);
7857 Py_DECREF(x);
7858 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007859 }
7860}
7861
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007862static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00007863charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007864{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007865 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
7866 /* exponentially overallocate to minimize reallocations */
7867 if (requiredsize < 2*outsize)
7868 requiredsize = 2*outsize;
7869 if (_PyBytes_Resize(outobj, requiredsize))
7870 return -1;
7871 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007872}
7873
Benjamin Peterson14339b62009-01-31 16:36:08 +00007874typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00007875 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Alexander Belopolsky40018472011-02-26 01:02:56 +00007876} charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007877/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00007878 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007879 space is available. Return a new reference to the object that
7880 was put in the output buffer, or Py_None, if the mapping was undefined
7881 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00007882 reallocation error occurred. The caller must decref the result */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007883static charmapencode_result
Victor Stinner22168992011-11-20 17:09:18 +01007884charmapencode_output(Py_UCS4 c, PyObject *mapping,
Alexander Belopolsky40018472011-02-26 01:02:56 +00007885 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007886{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007887 PyObject *rep;
7888 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00007889 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007890
Christian Heimes90aa7642007-12-19 02:45:37 +00007891 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007892 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00007893 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007894 if (res == -1)
7895 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00007896 if (outsize<requiredsize)
7897 if (charmapencode_resize(outobj, outpos, requiredsize))
7898 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00007899 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00007900 outstart[(*outpos)++] = (char)res;
7901 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007902 }
7903
7904 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007905 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007906 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007907 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007908 Py_DECREF(rep);
7909 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007910 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007911 if (PyLong_Check(rep)) {
7912 Py_ssize_t requiredsize = *outpos+1;
7913 if (outsize<requiredsize)
7914 if (charmapencode_resize(outobj, outpos, requiredsize)) {
7915 Py_DECREF(rep);
7916 return enc_EXCEPTION;
7917 }
Christian Heimes72b710a2008-05-26 13:28:38 +00007918 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00007919 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00007920 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007921 else {
7922 const char *repchars = PyBytes_AS_STRING(rep);
7923 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
7924 Py_ssize_t requiredsize = *outpos+repsize;
7925 if (outsize<requiredsize)
7926 if (charmapencode_resize(outobj, outpos, requiredsize)) {
7927 Py_DECREF(rep);
7928 return enc_EXCEPTION;
7929 }
Christian Heimes72b710a2008-05-26 13:28:38 +00007930 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00007931 memcpy(outstart + *outpos, repchars, repsize);
7932 *outpos += repsize;
7933 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007934 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007935 Py_DECREF(rep);
7936 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007937}
7938
7939/* handle an error in PyUnicode_EncodeCharmap
7940 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007941static int
7942charmap_encoding_error(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007943 PyObject *unicode, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007944 PyObject **exceptionObject,
Walter Dörwalde5402fb2003-08-14 20:25:29 +00007945 int *known_errorHandler, PyObject **errorHandler, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00007946 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007947{
7948 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007949 Py_ssize_t size, repsize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007950 Py_ssize_t newpos;
Victor Stinnerae4f7c82011-11-20 18:28:55 +01007951 enum PyUnicode_Kind kind;
7952 void *data;
7953 Py_ssize_t index;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007954 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00007955 Py_ssize_t collstartpos = *inpos;
7956 Py_ssize_t collendpos = *inpos+1;
7957 Py_ssize_t collpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007958 char *encoding = "charmap";
7959 char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007960 charmapencode_result x;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007961 Py_UCS4 ch;
Brian Curtin2787ea42011-11-02 15:09:37 -05007962 int val;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007963
Benjamin Petersonbac79492012-01-14 13:34:47 -05007964 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007965 return -1;
7966 size = PyUnicode_GET_LENGTH(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007967 /* find all unencodable characters */
7968 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007969 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00007970 if (Py_TYPE(mapping) == &EncodingMapType) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007971 ch = PyUnicode_READ_CHAR(unicode, collendpos);
Brian Curtin2787ea42011-11-02 15:09:37 -05007972 val = encoding_map_lookup(ch, mapping);
7973 if (val != -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00007974 break;
7975 ++collendpos;
7976 continue;
7977 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007978
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007979 ch = PyUnicode_READ_CHAR(unicode, collendpos);
7980 rep = charmapencode_lookup(ch, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00007981 if (rep==NULL)
7982 return -1;
7983 else if (rep!=Py_None) {
7984 Py_DECREF(rep);
7985 break;
7986 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007987 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00007988 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007989 }
7990 /* cache callback name lookup
7991 * (if not done yet, i.e. it's the first error) */
7992 if (*known_errorHandler==-1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007993 if ((errors==NULL) || (!strcmp(errors, "strict")))
7994 *known_errorHandler = 1;
7995 else if (!strcmp(errors, "replace"))
7996 *known_errorHandler = 2;
7997 else if (!strcmp(errors, "ignore"))
7998 *known_errorHandler = 3;
7999 else if (!strcmp(errors, "xmlcharrefreplace"))
8000 *known_errorHandler = 4;
8001 else
8002 *known_errorHandler = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008003 }
8004 switch (*known_errorHandler) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008005 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008006 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008007 return -1;
8008 case 2: /* replace */
8009 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008010 x = charmapencode_output('?', mapping, res, respos);
8011 if (x==enc_EXCEPTION) {
8012 return -1;
8013 }
8014 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008015 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008016 return -1;
8017 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008018 }
8019 /* fall through */
8020 case 3: /* ignore */
8021 *inpos = collendpos;
8022 break;
8023 case 4: /* xmlcharrefreplace */
8024 /* generate replacement (temporarily (mis)uses p) */
8025 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008026 char buffer[2+29+1+1];
8027 char *cp;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008028 sprintf(buffer, "&#%d;", (int)PyUnicode_READ_CHAR(unicode, collpos));
Benjamin Peterson29060642009-01-31 22:14:21 +00008029 for (cp = buffer; *cp; ++cp) {
8030 x = charmapencode_output(*cp, mapping, res, respos);
8031 if (x==enc_EXCEPTION)
8032 return -1;
8033 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008034 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008035 return -1;
8036 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008037 }
8038 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008039 *inpos = collendpos;
8040 break;
8041 default:
8042 repunicode = unicode_encode_call_errorhandler(errors, errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008043 encoding, reason, unicode, exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00008044 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008045 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008046 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00008047 if (PyBytes_Check(repunicode)) {
8048 /* Directly copy bytes result to output. */
8049 Py_ssize_t outsize = PyBytes_Size(*res);
8050 Py_ssize_t requiredsize;
8051 repsize = PyBytes_Size(repunicode);
8052 requiredsize = *respos + repsize;
8053 if (requiredsize > outsize)
8054 /* Make room for all additional bytes. */
8055 if (charmapencode_resize(res, respos, requiredsize)) {
8056 Py_DECREF(repunicode);
8057 return -1;
8058 }
8059 memcpy(PyBytes_AsString(*res) + *respos,
8060 PyBytes_AsString(repunicode), repsize);
8061 *respos += repsize;
8062 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008063 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00008064 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008065 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008066 /* generate replacement */
Benjamin Petersonbac79492012-01-14 13:34:47 -05008067 if (PyUnicode_READY(repunicode) == -1) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008068 Py_DECREF(repunicode);
8069 return -1;
8070 }
Victor Stinner9e30aa52011-11-21 02:49:52 +01008071 repsize = PyUnicode_GET_LENGTH(repunicode);
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008072 data = PyUnicode_DATA(repunicode);
8073 kind = PyUnicode_KIND(repunicode);
8074 for (index = 0; index < repsize; index++) {
8075 Py_UCS4 repch = PyUnicode_READ(kind, data, index);
8076 x = charmapencode_output(repch, mapping, res, respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008077 if (x==enc_EXCEPTION) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008078 Py_DECREF(repunicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00008079 return -1;
8080 }
8081 else if (x==enc_FAILED) {
8082 Py_DECREF(repunicode);
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008083 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008084 return -1;
8085 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008086 }
8087 *inpos = newpos;
8088 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008089 }
8090 return 0;
8091}
8092
Alexander Belopolsky40018472011-02-26 01:02:56 +00008093PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008094_PyUnicode_EncodeCharmap(PyObject *unicode,
8095 PyObject *mapping,
8096 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008097{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008098 /* output object */
8099 PyObject *res = NULL;
8100 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008101 Py_ssize_t inpos = 0;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008102 Py_ssize_t size;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008103 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008104 Py_ssize_t respos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008105 PyObject *errorHandler = NULL;
8106 PyObject *exc = NULL;
8107 /* the following variable is used for caching string comparisons
8108 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8109 * 3=ignore, 4=xmlcharrefreplace */
8110 int known_errorHandler = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008111
Benjamin Petersonbac79492012-01-14 13:34:47 -05008112 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008113 return NULL;
8114 size = PyUnicode_GET_LENGTH(unicode);
8115
Guido van Rossumd57fd912000-03-10 22:53:23 +00008116 /* Default to Latin-1 */
8117 if (mapping == NULL)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008118 return unicode_encode_ucs1(unicode, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008119
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008120 /* allocate enough for a simple encoding without
8121 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00008122 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008123 if (res == NULL)
8124 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00008125 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008126 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008127
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008128 while (inpos<size) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008129 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, inpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008130 /* try to encode it */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008131 charmapencode_result x = charmapencode_output(ch, mapping, &res, &respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008132 if (x==enc_EXCEPTION) /* error */
8133 goto onError;
8134 if (x==enc_FAILED) { /* unencodable character */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008135 if (charmap_encoding_error(unicode, &inpos, mapping,
Benjamin Peterson29060642009-01-31 22:14:21 +00008136 &exc,
8137 &known_errorHandler, &errorHandler, errors,
8138 &res, &respos)) {
8139 goto onError;
8140 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008141 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008142 else
8143 /* done with this character => adjust input position */
8144 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008145 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008146
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008147 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00008148 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00008149 if (_PyBytes_Resize(&res, respos) < 0)
8150 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00008151
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008152 Py_XDECREF(exc);
8153 Py_XDECREF(errorHandler);
8154 return res;
8155
Benjamin Peterson29060642009-01-31 22:14:21 +00008156 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008157 Py_XDECREF(res);
8158 Py_XDECREF(exc);
8159 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008160 return NULL;
8161}
8162
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008163/* Deprecated */
8164PyObject *
8165PyUnicode_EncodeCharmap(const Py_UNICODE *p,
8166 Py_ssize_t size,
8167 PyObject *mapping,
8168 const char *errors)
8169{
8170 PyObject *result;
8171 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8172 if (unicode == NULL)
8173 return NULL;
8174 result = _PyUnicode_EncodeCharmap(unicode, mapping, errors);
8175 Py_DECREF(unicode);
Victor Stinnerfc026c92011-11-04 00:24:51 +01008176 return result;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008177}
8178
Alexander Belopolsky40018472011-02-26 01:02:56 +00008179PyObject *
8180PyUnicode_AsCharmapString(PyObject *unicode,
8181 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008182{
8183 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008184 PyErr_BadArgument();
8185 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008186 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008187 return _PyUnicode_EncodeCharmap(unicode, mapping, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008188}
8189
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008190/* create or adjust a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008191static void
8192make_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008193 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008194 Py_ssize_t startpos, Py_ssize_t endpos,
8195 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008196{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008197 if (*exceptionObject == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008198 *exceptionObject = _PyUnicodeTranslateError_Create(
8199 unicode, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008200 }
8201 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008202 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
8203 goto onError;
8204 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
8205 goto onError;
8206 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
8207 goto onError;
8208 return;
8209 onError:
8210 Py_DECREF(*exceptionObject);
8211 *exceptionObject = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008212 }
8213}
8214
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008215/* raises a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008216static void
8217raise_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008218 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008219 Py_ssize_t startpos, Py_ssize_t endpos,
8220 const char *reason)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008221{
8222 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008223 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008224 if (*exceptionObject != NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008225 PyCodec_StrictErrors(*exceptionObject);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008226}
8227
8228/* error handling callback helper:
8229 build arguments, call the callback and check the arguments,
8230 put the result into newpos and return the replacement string, which
8231 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008232static PyObject *
8233unicode_translate_call_errorhandler(const char *errors,
8234 PyObject **errorHandler,
8235 const char *reason,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008236 PyObject *unicode, PyObject **exceptionObject,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008237 Py_ssize_t startpos, Py_ssize_t endpos,
8238 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008239{
Benjamin Peterson142957c2008-07-04 19:55:29 +00008240 static char *argparse = "O!n;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008241
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008242 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008243 PyObject *restuple;
8244 PyObject *resunicode;
8245
8246 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008247 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008248 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008249 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008250 }
8251
8252 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008253 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008254 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008255 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008256
8257 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00008258 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008259 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008260 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008261 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00008262 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00008263 Py_DECREF(restuple);
8264 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008265 }
8266 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type,
Benjamin Peterson29060642009-01-31 22:14:21 +00008267 &resunicode, &i_newpos)) {
8268 Py_DECREF(restuple);
8269 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008270 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00008271 if (i_newpos<0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008272 *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008273 else
8274 *newpos = i_newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008275 if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008276 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
8277 Py_DECREF(restuple);
8278 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00008279 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008280 Py_INCREF(resunicode);
8281 Py_DECREF(restuple);
8282 return resunicode;
8283}
8284
8285/* Lookup the character ch in the mapping and put the result in result,
8286 which must be decrefed by the caller.
8287 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008288static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008289charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008290{
Christian Heimes217cfd12007-12-02 14:31:20 +00008291 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008292 PyObject *x;
8293
8294 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008295 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008296 x = PyObject_GetItem(mapping, w);
8297 Py_DECREF(w);
8298 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008299 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8300 /* No mapping found means: use 1:1 mapping. */
8301 PyErr_Clear();
8302 *result = NULL;
8303 return 0;
8304 } else
8305 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008306 }
8307 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008308 *result = x;
8309 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008310 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008311 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008312 long value = PyLong_AS_LONG(x);
8313 long max = PyUnicode_GetMax();
8314 if (value < 0 || value > max) {
8315 PyErr_Format(PyExc_TypeError,
Guido van Rossum5a2f7e602007-10-24 21:13:09 +00008316 "character mapping must be in range(0x%x)", max+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00008317 Py_DECREF(x);
8318 return -1;
8319 }
8320 *result = x;
8321 return 0;
8322 }
8323 else if (PyUnicode_Check(x)) {
8324 *result = x;
8325 return 0;
8326 }
8327 else {
8328 /* wrong return value */
8329 PyErr_SetString(PyExc_TypeError,
8330 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00008331 Py_DECREF(x);
8332 return -1;
8333 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008334}
8335/* ensure that *outobj is at least requiredsize characters long,
Benjamin Peterson29060642009-01-31 22:14:21 +00008336 if not reallocate and adjust various state variables.
8337 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008338static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008339charmaptranslate_makespace(Py_UCS4 **outobj, Py_ssize_t *psize,
Benjamin Peterson29060642009-01-31 22:14:21 +00008340 Py_ssize_t requiredsize)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008341{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008342 Py_ssize_t oldsize = *psize;
Kristjan Valur Jonsson85634d72012-05-31 09:37:31 +00008343 Py_UCS4 *new_outobj;
Walter Dörwald4894c302003-10-24 14:25:28 +00008344 if (requiredsize > oldsize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008345 /* exponentially overallocate to minimize reallocations */
8346 if (requiredsize < 2 * oldsize)
8347 requiredsize = 2 * oldsize;
Kristjan Valur Jonsson85634d72012-05-31 09:37:31 +00008348 new_outobj = PyMem_Realloc(*outobj, requiredsize * sizeof(Py_UCS4));
8349 if (new_outobj == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008350 return -1;
Kristjan Valur Jonsson85634d72012-05-31 09:37:31 +00008351 *outobj = new_outobj;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008352 *psize = requiredsize;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008353 }
8354 return 0;
8355}
8356/* lookup the character, put the result in the output string and adjust
8357 various state variables. Return a new reference to the object that
8358 was put in the output buffer in *result, or Py_None, if the mapping was
8359 undefined (in which case no character was written).
8360 The called must decref result.
8361 Return 0 on success, -1 on error. */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008362static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008363charmaptranslate_output(PyObject *input, Py_ssize_t ipos,
8364 PyObject *mapping, Py_UCS4 **output,
8365 Py_ssize_t *osize, Py_ssize_t *opos,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008366 PyObject **res)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008367{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008368 Py_UCS4 curinp = PyUnicode_READ_CHAR(input, ipos);
8369 if (charmaptranslate_lookup(curinp, mapping, res))
Benjamin Peterson29060642009-01-31 22:14:21 +00008370 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008371 if (*res==NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008372 /* not found => default to 1:1 mapping */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008373 (*output)[(*opos)++] = curinp;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008374 }
8375 else if (*res==Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008376 ;
Christian Heimes217cfd12007-12-02 14:31:20 +00008377 else if (PyLong_Check(*res)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008378 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008379 (*output)[(*opos)++] = (Py_UCS4)PyLong_AS_LONG(*res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008380 }
8381 else if (PyUnicode_Check(*res)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008382 Py_ssize_t repsize;
8383 if (PyUnicode_READY(*res) == -1)
8384 return -1;
8385 repsize = PyUnicode_GET_LENGTH(*res);
Benjamin Peterson29060642009-01-31 22:14:21 +00008386 if (repsize==1) {
8387 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008388 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +00008389 }
8390 else if (repsize!=0) {
8391 /* more than one character */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008392 Py_ssize_t requiredsize = *opos +
8393 (PyUnicode_GET_LENGTH(input) - ipos) +
Benjamin Peterson29060642009-01-31 22:14:21 +00008394 repsize - 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008395 Py_ssize_t i;
8396 if (charmaptranslate_makespace(output, osize, requiredsize))
Benjamin Peterson29060642009-01-31 22:14:21 +00008397 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008398 for(i = 0; i < repsize; i++)
8399 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00008400 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008401 }
8402 else
Benjamin Peterson29060642009-01-31 22:14:21 +00008403 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008404 return 0;
8405}
8406
Alexander Belopolsky40018472011-02-26 01:02:56 +00008407PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008408_PyUnicode_TranslateCharmap(PyObject *input,
8409 PyObject *mapping,
8410 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008411{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008412 /* input object */
8413 char *idata;
8414 Py_ssize_t size, i;
8415 int kind;
8416 /* output buffer */
8417 Py_UCS4 *output = NULL;
8418 Py_ssize_t osize;
8419 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008420 /* current output position */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008421 Py_ssize_t opos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008422 char *reason = "character maps to <undefined>";
8423 PyObject *errorHandler = NULL;
8424 PyObject *exc = NULL;
8425 /* the following variable is used for caching string comparisons
8426 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8427 * 3=ignore, 4=xmlcharrefreplace */
8428 int known_errorHandler = -1;
8429
Guido van Rossumd57fd912000-03-10 22:53:23 +00008430 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008431 PyErr_BadArgument();
8432 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008433 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008434
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008435 if (PyUnicode_READY(input) == -1)
8436 return NULL;
8437 idata = (char*)PyUnicode_DATA(input);
8438 kind = PyUnicode_KIND(input);
8439 size = PyUnicode_GET_LENGTH(input);
8440 i = 0;
8441
8442 if (size == 0) {
8443 Py_INCREF(input);
8444 return input;
8445 }
8446
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008447 /* allocate enough for a simple 1:1 translation without
8448 replacements, if we need more, we'll resize */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008449 osize = size;
8450 output = PyMem_Malloc(osize * sizeof(Py_UCS4));
8451 opos = 0;
8452 if (output == NULL) {
8453 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00008454 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008455 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008456
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008457 while (i<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008458 /* try to encode it */
8459 PyObject *x = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008460 if (charmaptranslate_output(input, i, mapping,
8461 &output, &osize, &opos, &x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008462 Py_XDECREF(x);
8463 goto onError;
8464 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008465 Py_XDECREF(x);
Benjamin Peterson29060642009-01-31 22:14:21 +00008466 if (x!=Py_None) /* it worked => adjust input pointer */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008467 ++i;
Benjamin Peterson29060642009-01-31 22:14:21 +00008468 else { /* untranslatable character */
8469 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
8470 Py_ssize_t repsize;
8471 Py_ssize_t newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008472 Py_ssize_t uni2;
Benjamin Peterson29060642009-01-31 22:14:21 +00008473 /* startpos for collecting untranslatable chars */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008474 Py_ssize_t collstart = i;
8475 Py_ssize_t collend = i+1;
8476 Py_ssize_t coll;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008477
Benjamin Peterson29060642009-01-31 22:14:21 +00008478 /* find all untranslatable characters */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008479 while (collend < size) {
8480 if (charmaptranslate_lookup(PyUnicode_READ(kind,idata, collend), mapping, &x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008481 goto onError;
8482 Py_XDECREF(x);
8483 if (x!=Py_None)
8484 break;
8485 ++collend;
8486 }
8487 /* cache callback name lookup
8488 * (if not done yet, i.e. it's the first error) */
8489 if (known_errorHandler==-1) {
8490 if ((errors==NULL) || (!strcmp(errors, "strict")))
8491 known_errorHandler = 1;
8492 else if (!strcmp(errors, "replace"))
8493 known_errorHandler = 2;
8494 else if (!strcmp(errors, "ignore"))
8495 known_errorHandler = 3;
8496 else if (!strcmp(errors, "xmlcharrefreplace"))
8497 known_errorHandler = 4;
8498 else
8499 known_errorHandler = 0;
8500 }
8501 switch (known_errorHandler) {
8502 case 1: /* strict */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008503 raise_translate_exception(&exc, input, collstart,
8504 collend, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008505 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00008506 case 2: /* replace */
8507 /* No need to check for space, this is a 1:1 replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008508 for (coll = collstart; coll<collend; coll++)
8509 output[opos++] = '?';
Benjamin Peterson29060642009-01-31 22:14:21 +00008510 /* fall through */
8511 case 3: /* ignore */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008512 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008513 break;
8514 case 4: /* xmlcharrefreplace */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008515 /* generate replacement (temporarily (mis)uses i) */
8516 for (i = collstart; i < collend; ++i) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008517 char buffer[2+29+1+1];
8518 char *cp;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008519 sprintf(buffer, "&#%d;", PyUnicode_READ(kind, idata, i));
8520 if (charmaptranslate_makespace(&output, &osize,
8521 opos+strlen(buffer)+(size-collend)))
Benjamin Peterson29060642009-01-31 22:14:21 +00008522 goto onError;
8523 for (cp = buffer; *cp; ++cp)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008524 output[opos++] = *cp;
Benjamin Peterson29060642009-01-31 22:14:21 +00008525 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008526 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008527 break;
8528 default:
8529 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008530 reason, input, &exc,
8531 collstart, collend, &newpos);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008532 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008533 goto onError;
Benjamin Peterson9ca3ffa2012-01-01 16:04:29 -06008534 if (PyUnicode_READY(repunicode) == -1) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008535 Py_DECREF(repunicode);
8536 goto onError;
8537 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008538 /* generate replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008539 repsize = PyUnicode_GET_LENGTH(repunicode);
8540 if (charmaptranslate_makespace(&output, &osize,
8541 opos+repsize+(size-collend))) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008542 Py_DECREF(repunicode);
8543 goto onError;
8544 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008545 for (uni2 = 0; repsize-->0; ++uni2)
8546 output[opos++] = PyUnicode_READ_CHAR(repunicode, uni2);
8547 i = newpos;
Benjamin Peterson29060642009-01-31 22:14:21 +00008548 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008549 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008550 }
8551 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008552 res = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND, output, opos);
8553 if (!res)
8554 goto onError;
8555 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008556 Py_XDECREF(exc);
8557 Py_XDECREF(errorHandler);
8558 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008559
Benjamin Peterson29060642009-01-31 22:14:21 +00008560 onError:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008561 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008562 Py_XDECREF(exc);
8563 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008564 return NULL;
8565}
8566
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008567/* Deprecated. Use PyUnicode_Translate instead. */
8568PyObject *
8569PyUnicode_TranslateCharmap(const Py_UNICODE *p,
8570 Py_ssize_t size,
8571 PyObject *mapping,
8572 const char *errors)
8573{
Christian Heimes5f520f42012-09-11 14:03:25 +02008574 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008575 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8576 if (!unicode)
8577 return NULL;
Christian Heimes5f520f42012-09-11 14:03:25 +02008578 result = _PyUnicode_TranslateCharmap(unicode, mapping, errors);
8579 Py_DECREF(unicode);
8580 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008581}
8582
Alexander Belopolsky40018472011-02-26 01:02:56 +00008583PyObject *
8584PyUnicode_Translate(PyObject *str,
8585 PyObject *mapping,
8586 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008587{
8588 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +00008589
Guido van Rossumd57fd912000-03-10 22:53:23 +00008590 str = PyUnicode_FromObject(str);
8591 if (str == NULL)
Christian Heimes5f520f42012-09-11 14:03:25 +02008592 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008593 result = _PyUnicode_TranslateCharmap(str, mapping, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008594 Py_DECREF(str);
8595 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008596}
Tim Petersced69f82003-09-16 20:30:58 +00008597
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008598static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02008599fix_decimal_and_space_to_ascii(PyObject *self)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008600{
8601 /* No need to call PyUnicode_READY(self) because this function is only
8602 called as a callback from fixup() which does it already. */
8603 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
8604 const int kind = PyUnicode_KIND(self);
8605 void *data = PyUnicode_DATA(self);
Victor Stinnere6abb482012-05-02 01:15:40 +02008606 Py_UCS4 maxchar = 127, ch, fixed;
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008607 int modified = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008608 Py_ssize_t i;
8609
8610 for (i = 0; i < len; ++i) {
8611 ch = PyUnicode_READ(kind, data, i);
8612 fixed = 0;
8613 if (ch > 127) {
8614 if (Py_UNICODE_ISSPACE(ch))
8615 fixed = ' ';
8616 else {
8617 const int decimal = Py_UNICODE_TODECIMAL(ch);
8618 if (decimal >= 0)
8619 fixed = '0' + decimal;
8620 }
8621 if (fixed != 0) {
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008622 modified = 1;
Victor Stinnere6abb482012-05-02 01:15:40 +02008623 maxchar = MAX_MAXCHAR(maxchar, fixed);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008624 PyUnicode_WRITE(kind, data, i, fixed);
8625 }
Victor Stinnere6abb482012-05-02 01:15:40 +02008626 else
8627 maxchar = MAX_MAXCHAR(maxchar, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008628 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008629 }
8630
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008631 return (modified) ? maxchar : 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008632}
8633
8634PyObject *
8635_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
8636{
8637 if (!PyUnicode_Check(unicode)) {
8638 PyErr_BadInternalCall();
8639 return NULL;
8640 }
8641 if (PyUnicode_READY(unicode) == -1)
8642 return NULL;
8643 if (PyUnicode_MAX_CHAR_VALUE(unicode) <= 127) {
8644 /* If the string is already ASCII, just return the same string */
8645 Py_INCREF(unicode);
8646 return unicode;
8647 }
Victor Stinner9310abb2011-10-05 00:59:23 +02008648 return fixup(unicode, fix_decimal_and_space_to_ascii);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008649}
8650
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008651PyObject *
8652PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
8653 Py_ssize_t length)
8654{
Victor Stinnerf0124502011-11-21 23:12:56 +01008655 PyObject *decimal;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008656 Py_ssize_t i;
Victor Stinnerf0124502011-11-21 23:12:56 +01008657 Py_UCS4 maxchar;
8658 enum PyUnicode_Kind kind;
8659 void *data;
8660
Victor Stinner99d7ad02012-02-22 13:37:39 +01008661 maxchar = 127;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008662 for (i = 0; i < length; i++) {
Victor Stinnerf0124502011-11-21 23:12:56 +01008663 Py_UNICODE ch = s[i];
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008664 if (ch > 127) {
8665 int decimal = Py_UNICODE_TODECIMAL(ch);
8666 if (decimal >= 0)
Victor Stinnerf0124502011-11-21 23:12:56 +01008667 ch = '0' + decimal;
Victor Stinnere6abb482012-05-02 01:15:40 +02008668 maxchar = MAX_MAXCHAR(maxchar, ch);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008669 }
8670 }
Victor Stinnerf0124502011-11-21 23:12:56 +01008671
8672 /* Copy to a new string */
8673 decimal = PyUnicode_New(length, maxchar);
8674 if (decimal == NULL)
8675 return decimal;
8676 kind = PyUnicode_KIND(decimal);
8677 data = PyUnicode_DATA(decimal);
8678 /* Iterate over code points */
8679 for (i = 0; i < length; i++) {
8680 Py_UNICODE ch = s[i];
8681 if (ch > 127) {
8682 int decimal = Py_UNICODE_TODECIMAL(ch);
8683 if (decimal >= 0)
8684 ch = '0' + decimal;
8685 }
8686 PyUnicode_WRITE(kind, data, i, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008687 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008688 return unicode_result(decimal);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008689}
Guido van Rossum9e896b32000-04-05 20:11:21 +00008690/* --- Decimal Encoder ---------------------------------------------------- */
8691
Alexander Belopolsky40018472011-02-26 01:02:56 +00008692int
8693PyUnicode_EncodeDecimal(Py_UNICODE *s,
8694 Py_ssize_t length,
8695 char *output,
8696 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00008697{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008698 PyObject *unicode;
Victor Stinner6345be92011-11-25 20:09:01 +01008699 Py_ssize_t i;
Victor Stinner42bf7752011-11-21 22:52:58 +01008700 enum PyUnicode_Kind kind;
8701 void *data;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008702
8703 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008704 PyErr_BadArgument();
8705 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008706 }
8707
Victor Stinner42bf7752011-11-21 22:52:58 +01008708 unicode = PyUnicode_FromUnicode(s, length);
8709 if (unicode == NULL)
8710 return -1;
8711
Benjamin Petersonbac79492012-01-14 13:34:47 -05008712 if (PyUnicode_READY(unicode) == -1) {
Victor Stinner6345be92011-11-25 20:09:01 +01008713 Py_DECREF(unicode);
8714 return -1;
8715 }
Victor Stinner42bf7752011-11-21 22:52:58 +01008716 kind = PyUnicode_KIND(unicode);
8717 data = PyUnicode_DATA(unicode);
8718
Victor Stinnerb84d7232011-11-22 01:50:07 +01008719 for (i=0; i < length; ) {
Victor Stinner6345be92011-11-25 20:09:01 +01008720 PyObject *exc;
8721 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00008722 int decimal;
Victor Stinner6345be92011-11-25 20:09:01 +01008723 Py_ssize_t startpos;
8724
8725 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +00008726
Benjamin Peterson29060642009-01-31 22:14:21 +00008727 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008728 *output++ = ' ';
Victor Stinnerb84d7232011-11-22 01:50:07 +01008729 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00008730 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008731 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008732 decimal = Py_UNICODE_TODECIMAL(ch);
8733 if (decimal >= 0) {
8734 *output++ = '0' + decimal;
Victor Stinnerb84d7232011-11-22 01:50:07 +01008735 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00008736 continue;
8737 }
8738 if (0 < ch && ch < 256) {
8739 *output++ = (char)ch;
Victor Stinnerb84d7232011-11-22 01:50:07 +01008740 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00008741 continue;
8742 }
Victor Stinner6345be92011-11-25 20:09:01 +01008743
Victor Stinner42bf7752011-11-21 22:52:58 +01008744 startpos = i;
Victor Stinner6345be92011-11-25 20:09:01 +01008745 exc = NULL;
8746 raise_encode_exception(&exc, "decimal", unicode,
8747 startpos, startpos+1,
8748 "invalid decimal Unicode string");
8749 Py_XDECREF(exc);
8750 Py_DECREF(unicode);
8751 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008752 }
8753 /* 0-terminate the output string */
8754 *output++ = '\0';
Victor Stinner42bf7752011-11-21 22:52:58 +01008755 Py_DECREF(unicode);
Guido van Rossum9e896b32000-04-05 20:11:21 +00008756 return 0;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008757}
8758
Guido van Rossumd57fd912000-03-10 22:53:23 +00008759/* --- Helpers ------------------------------------------------------------ */
8760
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008761static Py_ssize_t
Victor Stinner794d5672011-10-10 03:21:36 +02008762any_find_slice(int direction, PyObject* s1, PyObject* s2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008763 Py_ssize_t start,
8764 Py_ssize_t end)
8765{
8766 int kind1, kind2, kind;
8767 void *buf1, *buf2;
8768 Py_ssize_t len1, len2, result;
8769
8770 kind1 = PyUnicode_KIND(s1);
8771 kind2 = PyUnicode_KIND(s2);
8772 kind = kind1 > kind2 ? kind1 : kind2;
8773 buf1 = PyUnicode_DATA(s1);
8774 buf2 = PyUnicode_DATA(s2);
8775 if (kind1 != kind)
8776 buf1 = _PyUnicode_AsKind(s1, kind);
8777 if (!buf1)
8778 return -2;
8779 if (kind2 != kind)
8780 buf2 = _PyUnicode_AsKind(s2, kind);
8781 if (!buf2) {
8782 if (kind1 != kind) PyMem_Free(buf1);
8783 return -2;
8784 }
8785 len1 = PyUnicode_GET_LENGTH(s1);
8786 len2 = PyUnicode_GET_LENGTH(s2);
8787
Victor Stinner794d5672011-10-10 03:21:36 +02008788 if (direction > 0) {
Benjamin Petersonead6b532011-12-20 17:23:42 -06008789 switch (kind) {
Victor Stinner794d5672011-10-10 03:21:36 +02008790 case PyUnicode_1BYTE_KIND:
8791 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
8792 result = asciilib_find_slice(buf1, len1, buf2, len2, start, end);
8793 else
8794 result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end);
8795 break;
8796 case PyUnicode_2BYTE_KIND:
8797 result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end);
8798 break;
8799 case PyUnicode_4BYTE_KIND:
8800 result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end);
8801 break;
8802 default:
8803 assert(0); result = -2;
8804 }
8805 }
8806 else {
Benjamin Petersonead6b532011-12-20 17:23:42 -06008807 switch (kind) {
Victor Stinner794d5672011-10-10 03:21:36 +02008808 case PyUnicode_1BYTE_KIND:
8809 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
8810 result = asciilib_rfind_slice(buf1, len1, buf2, len2, start, end);
8811 else
8812 result = ucs1lib_rfind_slice(buf1, len1, buf2, len2, start, end);
8813 break;
8814 case PyUnicode_2BYTE_KIND:
8815 result = ucs2lib_rfind_slice(buf1, len1, buf2, len2, start, end);
8816 break;
8817 case PyUnicode_4BYTE_KIND:
8818 result = ucs4lib_rfind_slice(buf1, len1, buf2, len2, start, end);
8819 break;
8820 default:
8821 assert(0); result = -2;
8822 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008823 }
8824
8825 if (kind1 != kind)
8826 PyMem_Free(buf1);
8827 if (kind2 != kind)
8828 PyMem_Free(buf2);
8829
8830 return result;
8831}
8832
8833Py_ssize_t
Victor Stinner41a863c2012-02-24 00:37:51 +01008834_PyUnicode_InsertThousandsGrouping(
8835 PyObject *unicode, Py_ssize_t index,
8836 Py_ssize_t n_buffer,
8837 void *digits, Py_ssize_t n_digits,
8838 Py_ssize_t min_width,
8839 const char *grouping, PyObject *thousands_sep,
8840 Py_UCS4 *maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008841{
Victor Stinner41a863c2012-02-24 00:37:51 +01008842 unsigned int kind, thousands_sep_kind;
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008843 char *data, *thousands_sep_data;
Victor Stinner41a863c2012-02-24 00:37:51 +01008844 Py_ssize_t thousands_sep_len;
8845 Py_ssize_t len;
8846
8847 if (unicode != NULL) {
8848 kind = PyUnicode_KIND(unicode);
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008849 data = (char *) PyUnicode_DATA(unicode) + index * kind;
Victor Stinner41a863c2012-02-24 00:37:51 +01008850 }
8851 else {
8852 kind = PyUnicode_1BYTE_KIND;
8853 data = NULL;
8854 }
8855 thousands_sep_kind = PyUnicode_KIND(thousands_sep);
8856 thousands_sep_data = PyUnicode_DATA(thousands_sep);
8857 thousands_sep_len = PyUnicode_GET_LENGTH(thousands_sep);
8858 if (unicode != NULL && thousands_sep_kind != kind) {
Victor Stinner90f50d42012-02-24 01:44:47 +01008859 if (thousands_sep_kind < kind) {
8860 thousands_sep_data = _PyUnicode_AsKind(thousands_sep, kind);
8861 if (!thousands_sep_data)
8862 return -1;
8863 }
8864 else {
8865 data = _PyUnicode_AsKind(unicode, thousands_sep_kind);
8866 if (!data)
8867 return -1;
8868 }
Victor Stinner41a863c2012-02-24 00:37:51 +01008869 }
8870
Benjamin Petersonead6b532011-12-20 17:23:42 -06008871 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008872 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02008873 if (unicode != NULL && PyUnicode_IS_ASCII(unicode))
Victor Stinner41a863c2012-02-24 00:37:51 +01008874 len = asciilib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008875 (Py_UCS1 *) data, n_buffer, (Py_UCS1 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01008876 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008877 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinnerc3cec782011-10-05 21:24:08 +02008878 else
Victor Stinner41a863c2012-02-24 00:37:51 +01008879 len = ucs1lib_InsertThousandsGrouping(
Victor Stinnerc3cec782011-10-05 21:24:08 +02008880 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01008881 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008882 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01008883 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008884 case PyUnicode_2BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01008885 len = ucs2lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008886 (Py_UCS2 *) data, n_buffer, (Py_UCS2 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01008887 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008888 (Py_UCS2 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01008889 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008890 case PyUnicode_4BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01008891 len = ucs4lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008892 (Py_UCS4 *) data, n_buffer, (Py_UCS4 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01008893 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008894 (Py_UCS4 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01008895 break;
8896 default:
8897 assert(0);
8898 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008899 }
Victor Stinner90f50d42012-02-24 01:44:47 +01008900 if (unicode != NULL && thousands_sep_kind != kind) {
8901 if (thousands_sep_kind < kind)
8902 PyMem_Free(thousands_sep_data);
8903 else
8904 PyMem_Free(data);
8905 }
Victor Stinner41a863c2012-02-24 00:37:51 +01008906 if (unicode == NULL) {
8907 *maxchar = 127;
8908 if (len != n_digits) {
Victor Stinnere6abb482012-05-02 01:15:40 +02008909 *maxchar = MAX_MAXCHAR(*maxchar,
8910 PyUnicode_MAX_CHAR_VALUE(thousands_sep));
Victor Stinner41a863c2012-02-24 00:37:51 +01008911 }
8912 }
8913 return len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008914}
8915
8916
Thomas Wouters477c8d52006-05-27 19:21:47 +00008917/* helper macro to fixup start/end slice values */
Antoine Pitrouf2c54842010-01-13 08:07:53 +00008918#define ADJUST_INDICES(start, end, len) \
8919 if (end > len) \
8920 end = len; \
8921 else if (end < 0) { \
8922 end += len; \
8923 if (end < 0) \
8924 end = 0; \
8925 } \
8926 if (start < 0) { \
8927 start += len; \
8928 if (start < 0) \
8929 start = 0; \
8930 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00008931
Alexander Belopolsky40018472011-02-26 01:02:56 +00008932Py_ssize_t
8933PyUnicode_Count(PyObject *str,
8934 PyObject *substr,
8935 Py_ssize_t start,
8936 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008937{
Martin v. Löwis18e16552006-02-15 17:27:45 +00008938 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02008939 PyObject* str_obj;
8940 PyObject* sub_obj;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008941 int kind1, kind2, kind;
8942 void *buf1 = NULL, *buf2 = NULL;
8943 Py_ssize_t len1, len2;
Tim Petersced69f82003-09-16 20:30:58 +00008944
Victor Stinner9db1a8b2011-10-23 20:04:37 +02008945 str_obj = PyUnicode_FromObject(str);
Benjamin Peterson22a29702012-01-02 09:00:30 -06008946 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +00008947 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02008948 sub_obj = PyUnicode_FromObject(substr);
Benjamin Peterson22a29702012-01-02 09:00:30 -06008949 if (!sub_obj) {
8950 Py_DECREF(str_obj);
8951 return -1;
8952 }
Benjamin Peterson4c13a4a2012-01-02 09:07:38 -06008953 if (PyUnicode_READY(sub_obj) == -1 || PyUnicode_READY(str_obj) == -1) {
Benjamin Peterson5e458f52012-01-02 10:12:13 -06008954 Py_DECREF(sub_obj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008955 Py_DECREF(str_obj);
8956 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008957 }
Tim Petersced69f82003-09-16 20:30:58 +00008958
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008959 kind1 = PyUnicode_KIND(str_obj);
8960 kind2 = PyUnicode_KIND(sub_obj);
Antoine Pitroue45c0c52012-05-12 15:49:07 +02008961 kind = kind1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008962 buf1 = PyUnicode_DATA(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008963 buf2 = PyUnicode_DATA(sub_obj);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -05008964 if (kind2 != kind) {
Antoine Pitrou758153b2012-05-12 15:51:51 +02008965 if (kind2 > kind) {
8966 Py_DECREF(sub_obj);
8967 Py_DECREF(str_obj);
Antoine Pitroue45c0c52012-05-12 15:49:07 +02008968 return 0;
Antoine Pitrou758153b2012-05-12 15:51:51 +02008969 }
Victor Stinner7931d9a2011-11-04 00:22:48 +01008970 buf2 = _PyUnicode_AsKind(sub_obj, kind);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -05008971 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008972 if (!buf2)
8973 goto onError;
8974 len1 = PyUnicode_GET_LENGTH(str_obj);
8975 len2 = PyUnicode_GET_LENGTH(sub_obj);
8976
8977 ADJUST_INDICES(start, end, len1);
Benjamin Petersonead6b532011-12-20 17:23:42 -06008978 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008979 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02008980 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sub_obj))
8981 result = asciilib_count(
8982 ((Py_UCS1*)buf1) + start, end - start,
8983 buf2, len2, PY_SSIZE_T_MAX
8984 );
8985 else
8986 result = ucs1lib_count(
8987 ((Py_UCS1*)buf1) + start, end - start,
8988 buf2, len2, PY_SSIZE_T_MAX
8989 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008990 break;
8991 case PyUnicode_2BYTE_KIND:
8992 result = ucs2lib_count(
8993 ((Py_UCS2*)buf1) + start, end - start,
8994 buf2, len2, PY_SSIZE_T_MAX
8995 );
8996 break;
8997 case PyUnicode_4BYTE_KIND:
8998 result = ucs4lib_count(
8999 ((Py_UCS4*)buf1) + start, end - start,
9000 buf2, len2, PY_SSIZE_T_MAX
9001 );
9002 break;
9003 default:
9004 assert(0); result = 0;
9005 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009006
9007 Py_DECREF(sub_obj);
9008 Py_DECREF(str_obj);
9009
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009010 if (kind2 != kind)
9011 PyMem_Free(buf2);
9012
Guido van Rossumd57fd912000-03-10 22:53:23 +00009013 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009014 onError:
9015 Py_DECREF(sub_obj);
9016 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009017 if (kind2 != kind && buf2)
9018 PyMem_Free(buf2);
9019 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009020}
9021
Alexander Belopolsky40018472011-02-26 01:02:56 +00009022Py_ssize_t
9023PyUnicode_Find(PyObject *str,
9024 PyObject *sub,
9025 Py_ssize_t start,
9026 Py_ssize_t end,
9027 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009028{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009029 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009030
Guido van Rossumd57fd912000-03-10 22:53:23 +00009031 str = PyUnicode_FromObject(str);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009032 if (!str)
Benjamin Peterson29060642009-01-31 22:14:21 +00009033 return -2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009034 sub = PyUnicode_FromObject(sub);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009035 if (!sub) {
9036 Py_DECREF(str);
9037 return -2;
9038 }
9039 if (PyUnicode_READY(sub) == -1 || PyUnicode_READY(str) == -1) {
9040 Py_DECREF(sub);
Benjamin Peterson29060642009-01-31 22:14:21 +00009041 Py_DECREF(str);
9042 return -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009043 }
Tim Petersced69f82003-09-16 20:30:58 +00009044
Victor Stinner794d5672011-10-10 03:21:36 +02009045 result = any_find_slice(direction,
9046 str, sub, start, end
9047 );
Thomas Wouters477c8d52006-05-27 19:21:47 +00009048
Guido van Rossumd57fd912000-03-10 22:53:23 +00009049 Py_DECREF(str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009050 Py_DECREF(sub);
9051
Guido van Rossumd57fd912000-03-10 22:53:23 +00009052 return result;
9053}
9054
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009055Py_ssize_t
9056PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
9057 Py_ssize_t start, Py_ssize_t end,
9058 int direction)
9059{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009060 int kind;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009061 Py_ssize_t result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009062 if (PyUnicode_READY(str) == -1)
9063 return -2;
Victor Stinner267aa242011-10-02 01:08:37 +02009064 if (start < 0 || end < 0) {
9065 PyErr_SetString(PyExc_IndexError, "string index out of range");
9066 return -2;
9067 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009068 if (end > PyUnicode_GET_LENGTH(str))
9069 end = PyUnicode_GET_LENGTH(str);
9070 kind = PyUnicode_KIND(str);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009071 result = findchar(PyUnicode_1BYTE_DATA(str) + kind*start,
9072 kind, end-start, ch, direction);
9073 if (result == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009074 return -1;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009075 else
9076 return start + result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009077}
9078
Alexander Belopolsky40018472011-02-26 01:02:56 +00009079static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009080tailmatch(PyObject *self,
9081 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009082 Py_ssize_t start,
9083 Py_ssize_t end,
9084 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009085{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009086 int kind_self;
9087 int kind_sub;
9088 void *data_self;
9089 void *data_sub;
9090 Py_ssize_t offset;
9091 Py_ssize_t i;
9092 Py_ssize_t end_sub;
9093
9094 if (PyUnicode_READY(self) == -1 ||
9095 PyUnicode_READY(substring) == -1)
9096 return 0;
9097
9098 if (PyUnicode_GET_LENGTH(substring) == 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009099 return 1;
9100
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009101 ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
9102 end -= PyUnicode_GET_LENGTH(substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009103 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00009104 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009105
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009106 kind_self = PyUnicode_KIND(self);
9107 data_self = PyUnicode_DATA(self);
9108 kind_sub = PyUnicode_KIND(substring);
9109 data_sub = PyUnicode_DATA(substring);
9110 end_sub = PyUnicode_GET_LENGTH(substring) - 1;
9111
9112 if (direction > 0)
9113 offset = end;
9114 else
9115 offset = start;
9116
9117 if (PyUnicode_READ(kind_self, data_self, offset) ==
9118 PyUnicode_READ(kind_sub, data_sub, 0) &&
9119 PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
9120 PyUnicode_READ(kind_sub, data_sub, end_sub)) {
9121 /* If both are of the same kind, memcmp is sufficient */
9122 if (kind_self == kind_sub) {
9123 return ! memcmp((char *)data_self +
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009124 (offset * PyUnicode_KIND(substring)),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009125 data_sub,
9126 PyUnicode_GET_LENGTH(substring) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009127 PyUnicode_KIND(substring));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009128 }
9129 /* otherwise we have to compare each character by first accesing it */
9130 else {
9131 /* We do not need to compare 0 and len(substring)-1 because
9132 the if statement above ensured already that they are equal
9133 when we end up here. */
Antoine Pitrou057119b2012-09-02 17:56:33 +02009134 /* TODO: honor direction and do a forward or backwards search */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009135 for (i = 1; i < end_sub; ++i) {
9136 if (PyUnicode_READ(kind_self, data_self, offset + i) !=
9137 PyUnicode_READ(kind_sub, data_sub, i))
9138 return 0;
9139 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009140 return 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009141 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009142 }
9143
9144 return 0;
9145}
9146
Alexander Belopolsky40018472011-02-26 01:02:56 +00009147Py_ssize_t
9148PyUnicode_Tailmatch(PyObject *str,
9149 PyObject *substr,
9150 Py_ssize_t start,
9151 Py_ssize_t end,
9152 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009153{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009154 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009155
Guido van Rossumd57fd912000-03-10 22:53:23 +00009156 str = PyUnicode_FromObject(str);
9157 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009158 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009159 substr = PyUnicode_FromObject(substr);
9160 if (substr == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009161 Py_DECREF(str);
9162 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009163 }
Tim Petersced69f82003-09-16 20:30:58 +00009164
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009165 result = tailmatch(str, substr,
Benjamin Peterson29060642009-01-31 22:14:21 +00009166 start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009167 Py_DECREF(str);
9168 Py_DECREF(substr);
9169 return result;
9170}
9171
Guido van Rossumd57fd912000-03-10 22:53:23 +00009172/* Apply fixfct filter to the Unicode object self and return a
9173 reference to the modified object */
9174
Alexander Belopolsky40018472011-02-26 01:02:56 +00009175static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009176fixup(PyObject *self,
9177 Py_UCS4 (*fixfct)(PyObject *s))
Guido van Rossumd57fd912000-03-10 22:53:23 +00009178{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009179 PyObject *u;
9180 Py_UCS4 maxchar_old, maxchar_new = 0;
Victor Stinnereaab6042011-12-11 22:22:39 +01009181 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009182
Victor Stinnerbf6e5602011-12-12 01:53:47 +01009183 u = _PyUnicode_Copy(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009184 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009185 return NULL;
Victor Stinner87af4f22011-11-21 23:03:47 +01009186 maxchar_old = PyUnicode_MAX_CHAR_VALUE(u);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009187
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009188 /* fix functions return the new maximum character in a string,
9189 if the kind of the resulting unicode object does not change,
9190 everything is fine. Otherwise we need to change the string kind
9191 and re-run the fix function. */
Victor Stinner9310abb2011-10-05 00:59:23 +02009192 maxchar_new = fixfct(u);
Victor Stinnereaab6042011-12-11 22:22:39 +01009193
9194 if (maxchar_new == 0) {
9195 /* no changes */;
9196 if (PyUnicode_CheckExact(self)) {
9197 Py_DECREF(u);
9198 Py_INCREF(self);
9199 return self;
9200 }
9201 else
9202 return u;
9203 }
9204
Victor Stinnere6abb482012-05-02 01:15:40 +02009205 maxchar_new = align_maxchar(maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009206
Victor Stinnereaab6042011-12-11 22:22:39 +01009207 if (maxchar_new == maxchar_old)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009208 return u;
Victor Stinnereaab6042011-12-11 22:22:39 +01009209
9210 /* In case the maximum character changed, we need to
9211 convert the string to the new category. */
9212 v = PyUnicode_New(PyUnicode_GET_LENGTH(self), maxchar_new);
9213 if (v == NULL) {
9214 Py_DECREF(u);
9215 return NULL;
9216 }
9217 if (maxchar_new > maxchar_old) {
9218 /* If the maxchar increased so that the kind changed, not all
9219 characters are representable anymore and we need to fix the
9220 string again. This only happens in very few cases. */
Victor Stinnerd3f08822012-05-29 12:57:52 +02009221 _PyUnicode_FastCopyCharacters(v, 0,
9222 self, 0, PyUnicode_GET_LENGTH(self));
Victor Stinnereaab6042011-12-11 22:22:39 +01009223 maxchar_old = fixfct(v);
9224 assert(maxchar_old > 0 && maxchar_old <= maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009225 }
9226 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02009227 _PyUnicode_FastCopyCharacters(v, 0,
9228 u, 0, PyUnicode_GET_LENGTH(self));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009229 }
Victor Stinnereaab6042011-12-11 22:22:39 +01009230 Py_DECREF(u);
9231 assert(_PyUnicode_CheckConsistency(v, 1));
9232 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009233}
9234
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009235static PyObject *
9236ascii_upper_or_lower(PyObject *self, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009237{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009238 Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9239 char *resdata, *data = PyUnicode_DATA(self);
9240 PyObject *res;
Tim Petersced69f82003-09-16 20:30:58 +00009241
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009242 res = PyUnicode_New(len, 127);
9243 if (res == NULL)
9244 return NULL;
9245 resdata = PyUnicode_DATA(res);
9246 if (lower)
9247 _Py_bytes_lower(resdata, data, len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009248 else
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009249 _Py_bytes_upper(resdata, data, len);
9250 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009251}
9252
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009253static Py_UCS4
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009254handle_capital_sigma(int kind, void *data, Py_ssize_t length, Py_ssize_t i)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009255{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009256 Py_ssize_t j;
9257 int final_sigma;
9258 Py_UCS4 c;
9259 /* U+03A3 is in the Final_Sigma context when, it is found like this:
Tim Petersced69f82003-09-16 20:30:58 +00009260
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009261 \p{cased}\p{case-ignorable}*U+03A3!(\p{case-ignorable}*\p{cased})
9262
9263 where ! is a negation and \p{xxx} is a character with property xxx.
9264 */
9265 for (j = i - 1; j >= 0; j--) {
9266 c = PyUnicode_READ(kind, data, j);
9267 if (!_PyUnicode_IsCaseIgnorable(c))
9268 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009269 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009270 final_sigma = j >= 0 && _PyUnicode_IsCased(c);
9271 if (final_sigma) {
9272 for (j = i + 1; j < length; j++) {
9273 c = PyUnicode_READ(kind, data, j);
9274 if (!_PyUnicode_IsCaseIgnorable(c))
9275 break;
9276 }
9277 final_sigma = j == length || !_PyUnicode_IsCased(c);
9278 }
9279 return (final_sigma) ? 0x3C2 : 0x3C3;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009280}
9281
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009282static int
9283lower_ucs4(int kind, void *data, Py_ssize_t length, Py_ssize_t i,
9284 Py_UCS4 c, Py_UCS4 *mapped)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009285{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009286 /* Obscure special case. */
9287 if (c == 0x3A3) {
9288 mapped[0] = handle_capital_sigma(kind, data, length, i);
9289 return 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009290 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009291 return _PyUnicode_ToLowerFull(c, mapped);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009292}
9293
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009294static Py_ssize_t
9295do_capitalize(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009296{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009297 Py_ssize_t i, k = 0;
9298 int n_res, j;
9299 Py_UCS4 c, mapped[3];
Tim Petersced69f82003-09-16 20:30:58 +00009300
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009301 c = PyUnicode_READ(kind, data, 0);
9302 n_res = _PyUnicode_ToUpperFull(c, mapped);
9303 for (j = 0; j < n_res; j++) {
Victor Stinnere6abb482012-05-02 01:15:40 +02009304 *maxchar = MAX_MAXCHAR(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009305 res[k++] = mapped[j];
Guido van Rossumd57fd912000-03-10 22:53:23 +00009306 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009307 for (i = 1; i < length; i++) {
9308 c = PyUnicode_READ(kind, data, i);
9309 n_res = lower_ucs4(kind, data, length, i, 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];
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009313 }
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009314 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009315 return k;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009316}
9317
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009318static Py_ssize_t
9319do_swapcase(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar) {
9320 Py_ssize_t i, k = 0;
9321
9322 for (i = 0; i < length; i++) {
9323 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9324 int n_res, j;
9325 if (Py_UNICODE_ISUPPER(c)) {
9326 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9327 }
9328 else if (Py_UNICODE_ISLOWER(c)) {
9329 n_res = _PyUnicode_ToUpperFull(c, mapped);
9330 }
9331 else {
9332 n_res = 1;
9333 mapped[0] = c;
9334 }
9335 for (j = 0; j < n_res; j++) {
Victor Stinnere6abb482012-05-02 01:15:40 +02009336 *maxchar = MAX_MAXCHAR(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009337 res[k++] = mapped[j];
9338 }
9339 }
9340 return k;
9341}
9342
9343static Py_ssize_t
9344do_upper_or_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res,
9345 Py_UCS4 *maxchar, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009346{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009347 Py_ssize_t i, k = 0;
9348
9349 for (i = 0; i < length; i++) {
9350 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9351 int n_res, j;
9352 if (lower)
9353 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9354 else
9355 n_res = _PyUnicode_ToUpperFull(c, mapped);
9356 for (j = 0; j < n_res; j++) {
Victor Stinnere6abb482012-05-02 01:15:40 +02009357 *maxchar = MAX_MAXCHAR(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009358 res[k++] = mapped[j];
9359 }
9360 }
9361 return k;
9362}
9363
9364static Py_ssize_t
9365do_upper(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9366{
9367 return do_upper_or_lower(kind, data, length, res, maxchar, 0);
9368}
9369
9370static Py_ssize_t
9371do_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9372{
9373 return do_upper_or_lower(kind, data, length, res, maxchar, 1);
9374}
9375
Benjamin Petersone51757f2012-01-12 21:10:29 -05009376static Py_ssize_t
Benjamin Petersond5890c82012-01-14 13:23:30 -05009377do_casefold(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9378{
9379 Py_ssize_t i, k = 0;
9380
9381 for (i = 0; i < length; i++) {
9382 Py_UCS4 c = PyUnicode_READ(kind, data, i);
9383 Py_UCS4 mapped[3];
9384 int j, n_res = _PyUnicode_ToFoldedFull(c, mapped);
9385 for (j = 0; j < n_res; j++) {
Victor Stinnere6abb482012-05-02 01:15:40 +02009386 *maxchar = MAX_MAXCHAR(*maxchar, mapped[j]);
Benjamin Petersond5890c82012-01-14 13:23:30 -05009387 res[k++] = mapped[j];
9388 }
9389 }
9390 return k;
9391}
9392
9393static Py_ssize_t
Benjamin Petersone51757f2012-01-12 21:10:29 -05009394do_title(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9395{
9396 Py_ssize_t i, k = 0;
9397 int previous_is_cased;
9398
9399 previous_is_cased = 0;
9400 for (i = 0; i < length; i++) {
9401 const Py_UCS4 c = PyUnicode_READ(kind, data, i);
9402 Py_UCS4 mapped[3];
9403 int n_res, j;
9404
9405 if (previous_is_cased)
9406 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9407 else
9408 n_res = _PyUnicode_ToTitleFull(c, mapped);
9409
9410 for (j = 0; j < n_res; j++) {
Victor Stinnere6abb482012-05-02 01:15:40 +02009411 *maxchar = MAX_MAXCHAR(*maxchar, mapped[j]);
Benjamin Petersone51757f2012-01-12 21:10:29 -05009412 res[k++] = mapped[j];
9413 }
9414
9415 previous_is_cased = _PyUnicode_IsCased(c);
9416 }
9417 return k;
9418}
9419
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009420static PyObject *
9421case_operation(PyObject *self,
9422 Py_ssize_t (*perform)(int, void *, Py_ssize_t, Py_UCS4 *, Py_UCS4 *))
9423{
9424 PyObject *res = NULL;
9425 Py_ssize_t length, newlength = 0;
9426 int kind, outkind;
9427 void *data, *outdata;
9428 Py_UCS4 maxchar = 0, *tmp, *tmpend;
9429
Benjamin Petersoneea48462012-01-16 14:28:50 -05009430 assert(PyUnicode_IS_READY(self));
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009431
9432 kind = PyUnicode_KIND(self);
9433 data = PyUnicode_DATA(self);
9434 length = PyUnicode_GET_LENGTH(self);
9435 tmp = PyMem_MALLOC(sizeof(Py_UCS4) * 3 * length);
9436 if (tmp == NULL)
9437 return PyErr_NoMemory();
9438 newlength = perform(kind, data, length, tmp, &maxchar);
9439 res = PyUnicode_New(newlength, maxchar);
9440 if (res == NULL)
9441 goto leave;
9442 tmpend = tmp + newlength;
9443 outdata = PyUnicode_DATA(res);
9444 outkind = PyUnicode_KIND(res);
9445 switch (outkind) {
9446 case PyUnicode_1BYTE_KIND:
9447 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, tmp, tmpend, outdata);
9448 break;
9449 case PyUnicode_2BYTE_KIND:
9450 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, tmp, tmpend, outdata);
9451 break;
9452 case PyUnicode_4BYTE_KIND:
9453 memcpy(outdata, tmp, sizeof(Py_UCS4) * newlength);
9454 break;
9455 default:
9456 assert(0);
9457 break;
9458 }
9459 leave:
9460 PyMem_FREE(tmp);
9461 return res;
9462}
9463
Tim Peters8ce9f162004-08-27 01:49:32 +00009464PyObject *
9465PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009466{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009467 PyObject *sep = NULL;
Victor Stinnerdd077322011-10-07 17:02:31 +02009468 Py_ssize_t seplen;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009469 PyObject *res = NULL; /* the result */
Tim Peters05eba1f2004-08-27 21:32:02 +00009470 PyObject *fseq; /* PySequence_Fast(seq) */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009471 Py_ssize_t seqlen; /* len(fseq) -- number of items in sequence */
9472 PyObject **items;
Tim Peters8ce9f162004-08-27 01:49:32 +00009473 PyObject *item;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009474 Py_ssize_t sz, i, res_offset;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009475 Py_UCS4 maxchar;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009476 Py_UCS4 item_maxchar;
Victor Stinnerdd077322011-10-07 17:02:31 +02009477 int use_memcpy;
9478 unsigned char *res_data = NULL, *sep_data = NULL;
9479 PyObject *last_obj;
9480 unsigned int kind = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009481
Tim Peters05eba1f2004-08-27 21:32:02 +00009482 fseq = PySequence_Fast(seq, "");
9483 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009484 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00009485 }
9486
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009487 /* NOTE: the following code can't call back into Python code,
9488 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00009489 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009490
Tim Peters05eba1f2004-08-27 21:32:02 +00009491 seqlen = PySequence_Fast_GET_SIZE(fseq);
9492 /* If empty sequence, return u"". */
9493 if (seqlen == 0) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009494 Py_DECREF(fseq);
9495 Py_INCREF(unicode_empty);
9496 res = unicode_empty;
9497 return res;
Tim Peters05eba1f2004-08-27 21:32:02 +00009498 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009499
Tim Peters05eba1f2004-08-27 21:32:02 +00009500 /* If singleton sequence with an exact Unicode, return that. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009501 last_obj = NULL;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009502 items = PySequence_Fast_ITEMS(fseq);
Victor Stinneracf47b82011-10-06 12:32:37 +02009503 if (seqlen == 1) {
9504 if (PyUnicode_CheckExact(items[0])) {
9505 res = items[0];
9506 Py_INCREF(res);
9507 Py_DECREF(fseq);
9508 return res;
9509 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009510 seplen = 0;
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009511 maxchar = 0;
Tim Peters8ce9f162004-08-27 01:49:32 +00009512 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009513 else {
Victor Stinneracf47b82011-10-06 12:32:37 +02009514 /* Set up sep and seplen */
9515 if (separator == NULL) {
9516 /* fall back to a blank space separator */
9517 sep = PyUnicode_FromOrdinal(' ');
9518 if (!sep)
9519 goto onError;
Victor Stinnerdd077322011-10-07 17:02:31 +02009520 seplen = 1;
Victor Stinneracf47b82011-10-06 12:32:37 +02009521 maxchar = 32;
Tim Peters05eba1f2004-08-27 21:32:02 +00009522 }
Victor Stinneracf47b82011-10-06 12:32:37 +02009523 else {
9524 if (!PyUnicode_Check(separator)) {
9525 PyErr_Format(PyExc_TypeError,
9526 "separator: expected str instance,"
9527 " %.80s found",
9528 Py_TYPE(separator)->tp_name);
9529 goto onError;
9530 }
9531 if (PyUnicode_READY(separator))
9532 goto onError;
9533 sep = separator;
9534 seplen = PyUnicode_GET_LENGTH(separator);
9535 maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
9536 /* inc refcount to keep this code path symmetric with the
9537 above case of a blank separator */
9538 Py_INCREF(sep);
9539 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009540 last_obj = sep;
Tim Peters05eba1f2004-08-27 21:32:02 +00009541 }
9542
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009543 /* There are at least two things to join, or else we have a subclass
9544 * of str in the sequence.
9545 * Do a pre-pass to figure out the total amount of space we'll
9546 * need (sz), and see whether all argument are strings.
9547 */
9548 sz = 0;
Victor Stinnerdd077322011-10-07 17:02:31 +02009549#ifdef Py_DEBUG
9550 use_memcpy = 0;
9551#else
9552 use_memcpy = 1;
9553#endif
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009554 for (i = 0; i < seqlen; i++) {
9555 const Py_ssize_t old_sz = sz;
9556 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009557 if (!PyUnicode_Check(item)) {
9558 PyErr_Format(PyExc_TypeError,
9559 "sequence item %zd: expected str instance,"
9560 " %.80s found",
9561 i, Py_TYPE(item)->tp_name);
9562 goto onError;
9563 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009564 if (PyUnicode_READY(item) == -1)
9565 goto onError;
9566 sz += PyUnicode_GET_LENGTH(item);
9567 item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
Victor Stinnere6abb482012-05-02 01:15:40 +02009568 maxchar = MAX_MAXCHAR(maxchar, item_maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009569 if (i != 0)
9570 sz += seplen;
9571 if (sz < old_sz || sz > PY_SSIZE_T_MAX) {
9572 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009573 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009574 goto onError;
9575 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009576 if (use_memcpy && last_obj != NULL) {
9577 if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
9578 use_memcpy = 0;
9579 }
9580 last_obj = item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009581 }
Tim Petersced69f82003-09-16 20:30:58 +00009582
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009583 res = PyUnicode_New(sz, maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009584 if (res == NULL)
9585 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +00009586
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009587 /* Catenate everything. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009588#ifdef Py_DEBUG
9589 use_memcpy = 0;
9590#else
9591 if (use_memcpy) {
9592 res_data = PyUnicode_1BYTE_DATA(res);
9593 kind = PyUnicode_KIND(res);
9594 if (seplen != 0)
9595 sep_data = PyUnicode_1BYTE_DATA(sep);
9596 }
9597#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009598 for (i = 0, res_offset = 0; i < seqlen; ++i) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009599 Py_ssize_t itemlen;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009600 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009601 /* Copy item, and maybe the separator. */
Victor Stinner9ce5a832011-10-03 23:36:02 +02009602 if (i && seplen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009603 if (use_memcpy) {
9604 Py_MEMCPY(res_data,
9605 sep_data,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009606 kind * seplen);
9607 res_data += kind * seplen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009608 }
9609 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02009610 _PyUnicode_FastCopyCharacters(res, res_offset, sep, 0, seplen);
Victor Stinnerdd077322011-10-07 17:02:31 +02009611 res_offset += seplen;
9612 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009613 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009614 itemlen = PyUnicode_GET_LENGTH(item);
9615 if (itemlen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009616 if (use_memcpy) {
9617 Py_MEMCPY(res_data,
9618 PyUnicode_DATA(item),
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009619 kind * itemlen);
9620 res_data += kind * itemlen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009621 }
9622 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02009623 _PyUnicode_FastCopyCharacters(res, res_offset, item, 0, itemlen);
Victor Stinnerdd077322011-10-07 17:02:31 +02009624 res_offset += itemlen;
9625 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009626 }
Tim Peters05eba1f2004-08-27 21:32:02 +00009627 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009628 if (use_memcpy)
9629 assert(res_data == PyUnicode_1BYTE_DATA(res)
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009630 + kind * PyUnicode_GET_LENGTH(res));
Victor Stinnerdd077322011-10-07 17:02:31 +02009631 else
9632 assert(res_offset == PyUnicode_GET_LENGTH(res));
Tim Peters8ce9f162004-08-27 01:49:32 +00009633
Tim Peters05eba1f2004-08-27 21:32:02 +00009634 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009635 Py_XDECREF(sep);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009636 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009637 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009638
Benjamin Peterson29060642009-01-31 22:14:21 +00009639 onError:
Tim Peters05eba1f2004-08-27 21:32:02 +00009640 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009641 Py_XDECREF(sep);
Tim Peters8ce9f162004-08-27 01:49:32 +00009642 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009643 return NULL;
9644}
9645
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009646#define FILL(kind, data, value, start, length) \
9647 do { \
9648 Py_ssize_t i_ = 0; \
9649 assert(kind != PyUnicode_WCHAR_KIND); \
9650 switch ((kind)) { \
9651 case PyUnicode_1BYTE_KIND: { \
9652 unsigned char * to_ = (unsigned char *)((data)) + (start); \
Victor Stinnerf2c76aa2012-05-03 13:10:40 +02009653 memset(to_, (unsigned char)value, (length)); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009654 break; \
9655 } \
9656 case PyUnicode_2BYTE_KIND: { \
9657 Py_UCS2 * to_ = (Py_UCS2 *)((data)) + (start); \
9658 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9659 break; \
9660 } \
Benjamin Petersone157cf12012-01-01 15:56:20 -06009661 case PyUnicode_4BYTE_KIND: { \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009662 Py_UCS4 * to_ = (Py_UCS4 *)((data)) + (start); \
9663 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9664 break; \
Benjamin Petersone157cf12012-01-01 15:56:20 -06009665 default: assert(0); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009666 } \
9667 } \
9668 } while (0)
9669
Victor Stinnerd3f08822012-05-29 12:57:52 +02009670void
9671_PyUnicode_FastFill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
9672 Py_UCS4 fill_char)
9673{
9674 const enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
9675 const void *data = PyUnicode_DATA(unicode);
9676 assert(PyUnicode_IS_READY(unicode));
9677 assert(unicode_modifiable(unicode));
9678 assert(fill_char <= PyUnicode_MAX_CHAR_VALUE(unicode));
9679 assert(start >= 0);
9680 assert(start + length <= PyUnicode_GET_LENGTH(unicode));
9681 FILL(kind, data, fill_char, start, length);
9682}
9683
Victor Stinner3fe55312012-01-04 00:33:50 +01009684Py_ssize_t
9685PyUnicode_Fill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
9686 Py_UCS4 fill_char)
9687{
9688 Py_ssize_t maxlen;
Victor Stinner3fe55312012-01-04 00:33:50 +01009689
9690 if (!PyUnicode_Check(unicode)) {
9691 PyErr_BadInternalCall();
9692 return -1;
9693 }
9694 if (PyUnicode_READY(unicode) == -1)
9695 return -1;
9696 if (unicode_check_modifiable(unicode))
9697 return -1;
9698
Victor Stinnerd3f08822012-05-29 12:57:52 +02009699 if (start < 0) {
9700 PyErr_SetString(PyExc_IndexError, "string index out of range");
9701 return -1;
9702 }
Victor Stinner3fe55312012-01-04 00:33:50 +01009703 if (fill_char > PyUnicode_MAX_CHAR_VALUE(unicode)) {
9704 PyErr_SetString(PyExc_ValueError,
9705 "fill character is bigger than "
9706 "the string maximum character");
9707 return -1;
9708 }
9709
9710 maxlen = PyUnicode_GET_LENGTH(unicode) - start;
9711 length = Py_MIN(maxlen, length);
9712 if (length <= 0)
9713 return 0;
9714
Victor Stinnerd3f08822012-05-29 12:57:52 +02009715 _PyUnicode_FastFill(unicode, start, length, fill_char);
Victor Stinner3fe55312012-01-04 00:33:50 +01009716 return length;
9717}
9718
Victor Stinner9310abb2011-10-05 00:59:23 +02009719static PyObject *
9720pad(PyObject *self,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009721 Py_ssize_t left,
9722 Py_ssize_t right,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009723 Py_UCS4 fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009724{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009725 PyObject *u;
9726 Py_UCS4 maxchar;
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009727 int kind;
9728 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009729
9730 if (left < 0)
9731 left = 0;
9732 if (right < 0)
9733 right = 0;
9734
Victor Stinnerc4b49542011-12-11 22:44:26 +01009735 if (left == 0 && right == 0)
9736 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009737
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009738 if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
9739 right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +00009740 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
9741 return NULL;
9742 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009743 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Victor Stinnere6abb482012-05-02 01:15:40 +02009744 maxchar = MAX_MAXCHAR(maxchar, fill);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009745 u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009746 if (!u)
9747 return NULL;
9748
9749 kind = PyUnicode_KIND(u);
9750 data = PyUnicode_DATA(u);
9751 if (left)
9752 FILL(kind, data, fill, 0, left);
9753 if (right)
9754 FILL(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
Victor Stinnerd3f08822012-05-29 12:57:52 +02009755 _PyUnicode_FastCopyCharacters(u, left, self, 0, _PyUnicode_LENGTH(self));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009756 assert(_PyUnicode_CheckConsistency(u, 1));
9757 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009758}
9759
Alexander Belopolsky40018472011-02-26 01:02:56 +00009760PyObject *
9761PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009762{
Guido van Rossumd57fd912000-03-10 22:53:23 +00009763 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009764
9765 string = PyUnicode_FromObject(string);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009766 if (string == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009767 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -06009768 if (PyUnicode_READY(string) == -1) {
9769 Py_DECREF(string);
9770 return NULL;
9771 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009772
Benjamin Petersonead6b532011-12-20 17:23:42 -06009773 switch (PyUnicode_KIND(string)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009774 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009775 if (PyUnicode_IS_ASCII(string))
9776 list = asciilib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009777 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009778 PyUnicode_GET_LENGTH(string), keepends);
9779 else
9780 list = ucs1lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009781 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009782 PyUnicode_GET_LENGTH(string), keepends);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009783 break;
9784 case PyUnicode_2BYTE_KIND:
9785 list = ucs2lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009786 string, PyUnicode_2BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009787 PyUnicode_GET_LENGTH(string), keepends);
9788 break;
9789 case PyUnicode_4BYTE_KIND:
9790 list = ucs4lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009791 string, PyUnicode_4BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009792 PyUnicode_GET_LENGTH(string), keepends);
9793 break;
9794 default:
9795 assert(0);
9796 list = 0;
9797 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009798 Py_DECREF(string);
9799 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009800}
9801
Alexander Belopolsky40018472011-02-26 01:02:56 +00009802static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009803split(PyObject *self,
9804 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009805 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009806{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009807 int kind1, kind2, kind;
9808 void *buf1, *buf2;
9809 Py_ssize_t len1, len2;
9810 PyObject* out;
9811
Guido van Rossumd57fd912000-03-10 22:53:23 +00009812 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00009813 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009814
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009815 if (PyUnicode_READY(self) == -1)
9816 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009817
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009818 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -06009819 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009820 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009821 if (PyUnicode_IS_ASCII(self))
9822 return asciilib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009823 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009824 PyUnicode_GET_LENGTH(self), maxcount
9825 );
9826 else
9827 return ucs1lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009828 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009829 PyUnicode_GET_LENGTH(self), maxcount
9830 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009831 case PyUnicode_2BYTE_KIND:
9832 return ucs2lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009833 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009834 PyUnicode_GET_LENGTH(self), maxcount
9835 );
9836 case PyUnicode_4BYTE_KIND:
9837 return ucs4lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009838 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009839 PyUnicode_GET_LENGTH(self), maxcount
9840 );
9841 default:
9842 assert(0);
9843 return NULL;
9844 }
9845
9846 if (PyUnicode_READY(substring) == -1)
9847 return NULL;
9848
9849 kind1 = PyUnicode_KIND(self);
9850 kind2 = PyUnicode_KIND(substring);
9851 kind = kind1 > kind2 ? kind1 : kind2;
9852 buf1 = PyUnicode_DATA(self);
9853 buf2 = PyUnicode_DATA(substring);
9854 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009855 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009856 if (!buf1)
9857 return NULL;
9858 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009859 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009860 if (!buf2) {
9861 if (kind1 != kind) PyMem_Free(buf1);
9862 return NULL;
9863 }
9864 len1 = PyUnicode_GET_LENGTH(self);
9865 len2 = PyUnicode_GET_LENGTH(substring);
9866
Benjamin Petersonead6b532011-12-20 17:23:42 -06009867 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009868 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009869 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
9870 out = asciilib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009871 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +02009872 else
9873 out = ucs1lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009874 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009875 break;
9876 case PyUnicode_2BYTE_KIND:
9877 out = ucs2lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009878 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009879 break;
9880 case PyUnicode_4BYTE_KIND:
9881 out = ucs4lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009882 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009883 break;
9884 default:
9885 out = NULL;
9886 }
9887 if (kind1 != kind)
9888 PyMem_Free(buf1);
9889 if (kind2 != kind)
9890 PyMem_Free(buf2);
9891 return out;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009892}
9893
Alexander Belopolsky40018472011-02-26 01:02:56 +00009894static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009895rsplit(PyObject *self,
9896 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009897 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009898{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009899 int kind1, kind2, kind;
9900 void *buf1, *buf2;
9901 Py_ssize_t len1, len2;
9902 PyObject* out;
9903
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009904 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00009905 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009906
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009907 if (PyUnicode_READY(self) == -1)
9908 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009909
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009910 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -06009911 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009912 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009913 if (PyUnicode_IS_ASCII(self))
9914 return asciilib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009915 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009916 PyUnicode_GET_LENGTH(self), maxcount
9917 );
9918 else
9919 return ucs1lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009920 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009921 PyUnicode_GET_LENGTH(self), maxcount
9922 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009923 case PyUnicode_2BYTE_KIND:
9924 return ucs2lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009925 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009926 PyUnicode_GET_LENGTH(self), maxcount
9927 );
9928 case PyUnicode_4BYTE_KIND:
9929 return ucs4lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009930 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009931 PyUnicode_GET_LENGTH(self), maxcount
9932 );
9933 default:
9934 assert(0);
9935 return NULL;
9936 }
9937
9938 if (PyUnicode_READY(substring) == -1)
9939 return NULL;
9940
9941 kind1 = PyUnicode_KIND(self);
9942 kind2 = PyUnicode_KIND(substring);
9943 kind = kind1 > kind2 ? kind1 : kind2;
9944 buf1 = PyUnicode_DATA(self);
9945 buf2 = PyUnicode_DATA(substring);
9946 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009947 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009948 if (!buf1)
9949 return NULL;
9950 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009951 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009952 if (!buf2) {
9953 if (kind1 != kind) PyMem_Free(buf1);
9954 return NULL;
9955 }
9956 len1 = PyUnicode_GET_LENGTH(self);
9957 len2 = PyUnicode_GET_LENGTH(substring);
9958
Benjamin Petersonead6b532011-12-20 17:23:42 -06009959 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009960 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009961 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
9962 out = asciilib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009963 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +02009964 else
9965 out = ucs1lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009966 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009967 break;
9968 case PyUnicode_2BYTE_KIND:
9969 out = ucs2lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009970 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009971 break;
9972 case PyUnicode_4BYTE_KIND:
9973 out = ucs4lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009974 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009975 break;
9976 default:
9977 out = NULL;
9978 }
9979 if (kind1 != kind)
9980 PyMem_Free(buf1);
9981 if (kind2 != kind)
9982 PyMem_Free(buf2);
9983 return out;
9984}
9985
9986static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +02009987anylib_find(int kind, PyObject *str1, void *buf1, Py_ssize_t len1,
9988 PyObject *str2, void *buf2, Py_ssize_t len2, Py_ssize_t offset)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009989{
Benjamin Petersonead6b532011-12-20 17:23:42 -06009990 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009991 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009992 if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
9993 return asciilib_find(buf1, len1, buf2, len2, offset);
9994 else
9995 return ucs1lib_find(buf1, len1, buf2, len2, offset);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009996 case PyUnicode_2BYTE_KIND:
9997 return ucs2lib_find(buf1, len1, buf2, len2, offset);
9998 case PyUnicode_4BYTE_KIND:
9999 return ucs4lib_find(buf1, len1, buf2, len2, offset);
10000 }
10001 assert(0);
10002 return -1;
10003}
10004
10005static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010006anylib_count(int kind, PyObject *sstr, void* sbuf, Py_ssize_t slen,
10007 PyObject *str1, void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010008{
Benjamin Petersonc0b95d12011-12-20 17:24:05 -060010009 switch (kind) {
10010 case PyUnicode_1BYTE_KIND:
10011 if (PyUnicode_IS_ASCII(sstr) && PyUnicode_IS_ASCII(str1))
10012 return asciilib_count(sbuf, slen, buf1, len1, maxcount);
10013 else
10014 return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
10015 case PyUnicode_2BYTE_KIND:
10016 return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
10017 case PyUnicode_4BYTE_KIND:
10018 return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
10019 }
10020 assert(0);
10021 return 0;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010022}
10023
Alexander Belopolsky40018472011-02-26 01:02:56 +000010024static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010025replace(PyObject *self, PyObject *str1,
10026 PyObject *str2, Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010027{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010028 PyObject *u;
10029 char *sbuf = PyUnicode_DATA(self);
10030 char *buf1 = PyUnicode_DATA(str1);
10031 char *buf2 = PyUnicode_DATA(str2);
10032 int srelease = 0, release1 = 0, release2 = 0;
10033 int skind = PyUnicode_KIND(self);
10034 int kind1 = PyUnicode_KIND(str1);
10035 int kind2 = PyUnicode_KIND(str2);
10036 Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
10037 Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
10038 Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010039 int mayshrink;
10040 Py_UCS4 maxchar, maxchar_str2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010041
10042 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010043 maxcount = PY_SSIZE_T_MAX;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010044 else if (maxcount == 0 || slen == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010045 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010046
Victor Stinner59de0ee2011-10-07 10:01:28 +020010047 if (str1 == str2)
10048 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010049 if (skind < kind1)
10050 /* substring too wide to be present */
10051 goto nothing;
10052
Victor Stinner49a0a212011-10-12 23:46:10 +020010053 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
10054 maxchar_str2 = PyUnicode_MAX_CHAR_VALUE(str2);
10055 /* Replacing str1 with str2 may cause a maxchar reduction in the
10056 result string. */
10057 mayshrink = (maxchar_str2 < maxchar);
Victor Stinnere6abb482012-05-02 01:15:40 +020010058 maxchar = MAX_MAXCHAR(maxchar, maxchar_str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010059
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010060 if (len1 == len2) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010061 /* same length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010062 if (len1 == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010063 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010064 if (len1 == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010065 /* replace characters */
Victor Stinner49a0a212011-10-12 23:46:10 +020010066 Py_UCS4 u1, u2;
10067 int rkind;
Victor Stinnerf6441102011-12-18 02:43:08 +010010068 Py_ssize_t index, pos;
10069 char *src;
10070
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010071 u1 = PyUnicode_READ_CHAR(str1, 0);
Victor Stinnerf6441102011-12-18 02:43:08 +010010072 pos = findchar(sbuf, PyUnicode_KIND(self), slen, u1, 1);
10073 if (pos < 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010074 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010075 u2 = PyUnicode_READ_CHAR(str2, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010076 u = PyUnicode_New(slen, maxchar);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010077 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010078 goto error;
Victor Stinnerd3f08822012-05-29 12:57:52 +020010079 _PyUnicode_FastCopyCharacters(u, 0, self, 0, slen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010080 rkind = PyUnicode_KIND(u);
Victor Stinnerf6441102011-12-18 02:43:08 +010010081
10082 PyUnicode_WRITE(rkind, PyUnicode_DATA(u), pos, u2);
10083 index = 0;
10084 src = sbuf;
10085 while (--maxcount)
10086 {
10087 pos++;
10088 src += pos * PyUnicode_KIND(self);
10089 slen -= pos;
10090 index += pos;
10091 pos = findchar(src, PyUnicode_KIND(self), slen, u1, 1);
10092 if (pos < 0)
10093 break;
10094 PyUnicode_WRITE(rkind, PyUnicode_DATA(u), index + pos, u2);
10095 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010096 }
10097 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010098 int rkind = skind;
10099 char *res;
Victor Stinnerf6441102011-12-18 02:43:08 +010010100 Py_ssize_t i;
Victor Stinner25a4b292011-10-06 12:31:55 +020010101
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010102 if (kind1 < rkind) {
10103 /* widen substring */
10104 buf1 = _PyUnicode_AsKind(str1, rkind);
10105 if (!buf1) goto error;
10106 release1 = 1;
10107 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010108 i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010109 if (i < 0)
10110 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010111 if (rkind > kind2) {
10112 /* widen replacement */
10113 buf2 = _PyUnicode_AsKind(str2, rkind);
10114 if (!buf2) goto error;
10115 release2 = 1;
10116 }
10117 else if (rkind < kind2) {
10118 /* widen self and buf1 */
10119 rkind = kind2;
10120 if (release1) PyMem_Free(buf1);
10121 sbuf = _PyUnicode_AsKind(self, rkind);
10122 if (!sbuf) goto error;
10123 srelease = 1;
10124 buf1 = _PyUnicode_AsKind(str1, rkind);
10125 if (!buf1) goto error;
10126 release1 = 1;
10127 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010128 u = PyUnicode_New(slen, maxchar);
10129 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010130 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010131 assert(PyUnicode_KIND(u) == rkind);
10132 res = PyUnicode_DATA(u);
Victor Stinner25a4b292011-10-06 12:31:55 +020010133
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010134 memcpy(res, sbuf, rkind * slen);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010135 /* change everything in-place, starting with this one */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010136 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010137 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010138 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010139 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010140
10141 while ( --maxcount > 0) {
Victor Stinnerc3cec782011-10-05 21:24:08 +020010142 i = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010143 sbuf+rkind*i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010144 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010145 if (i == -1)
10146 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010147 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010148 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010149 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010150 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010151 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010152 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010153 }
10154 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010155 Py_ssize_t n, i, j, ires;
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010156 Py_ssize_t new_size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010157 int rkind = skind;
10158 char *res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010159
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010160 if (kind1 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010161 /* widen substring */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010162 buf1 = _PyUnicode_AsKind(str1, rkind);
10163 if (!buf1) goto error;
10164 release1 = 1;
10165 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010166 n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010167 if (n == 0)
10168 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010169 if (kind2 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010170 /* widen replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010171 buf2 = _PyUnicode_AsKind(str2, rkind);
10172 if (!buf2) goto error;
10173 release2 = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010174 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010175 else if (kind2 > rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010176 /* widen self and buf1 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010177 rkind = kind2;
10178 sbuf = _PyUnicode_AsKind(self, rkind);
10179 if (!sbuf) goto error;
10180 srelease = 1;
10181 if (release1) PyMem_Free(buf1);
10182 buf1 = _PyUnicode_AsKind(str1, rkind);
10183 if (!buf1) goto error;
10184 release1 = 1;
10185 }
10186 /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
10187 PyUnicode_GET_LENGTH(str1))); */
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010188 if (len2 > len1 && len2 - len1 > (PY_SSIZE_T_MAX - slen) / n) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010189 PyErr_SetString(PyExc_OverflowError,
10190 "replace string is too long");
10191 goto error;
10192 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010193 new_size = slen + n * (len2 - len1);
Victor Stinner49a0a212011-10-12 23:46:10 +020010194 if (new_size == 0) {
10195 Py_INCREF(unicode_empty);
10196 u = unicode_empty;
10197 goto done;
10198 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010199 if (new_size > (PY_SSIZE_T_MAX >> (rkind-1))) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010200 PyErr_SetString(PyExc_OverflowError,
10201 "replace string is too long");
10202 goto error;
10203 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010204 u = PyUnicode_New(new_size, maxchar);
10205 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010206 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010207 assert(PyUnicode_KIND(u) == rkind);
10208 res = PyUnicode_DATA(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010209 ires = i = 0;
10210 if (len1 > 0) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010211 while (n-- > 0) {
10212 /* look for next match */
Victor Stinnerc3cec782011-10-05 21:24:08 +020010213 j = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010214 sbuf + rkind * i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010215 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010216 if (j == -1)
10217 break;
10218 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010219 /* copy unchanged part [i:j] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010220 memcpy(res + rkind * ires,
10221 sbuf + rkind * i,
10222 rkind * (j-i));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010223 ires += j - i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010224 }
10225 /* copy substitution string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010226 if (len2 > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010227 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010228 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010229 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010230 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010231 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010232 i = j + len1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010233 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010234 if (i < slen)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010235 /* copy tail [i:] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010236 memcpy(res + rkind * ires,
10237 sbuf + rkind * i,
10238 rkind * (slen-i));
Victor Stinner49a0a212011-10-12 23:46:10 +020010239 }
10240 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010241 /* interleave */
10242 while (n > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010243 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010244 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010245 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010246 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010247 if (--n <= 0)
10248 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010249 memcpy(res + rkind * ires,
10250 sbuf + rkind * i,
10251 rkind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010252 ires++;
10253 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010254 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010255 memcpy(res + rkind * ires,
10256 sbuf + rkind * i,
10257 rkind * (slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +000010258 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010259 }
10260
10261 if (mayshrink) {
Victor Stinner25a4b292011-10-06 12:31:55 +020010262 unicode_adjust_maxchar(&u);
10263 if (u == NULL)
10264 goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010265 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010266
10267 done:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010268 if (srelease)
10269 PyMem_FREE(sbuf);
10270 if (release1)
10271 PyMem_FREE(buf1);
10272 if (release2)
10273 PyMem_FREE(buf2);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010274 assert(_PyUnicode_CheckConsistency(u, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010275 return u;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010276
Benjamin Peterson29060642009-01-31 22:14:21 +000010277 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +000010278 /* nothing to replace; return original string (when possible) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010279 if (srelease)
10280 PyMem_FREE(sbuf);
10281 if (release1)
10282 PyMem_FREE(buf1);
10283 if (release2)
10284 PyMem_FREE(buf2);
Victor Stinnerc4b49542011-12-11 22:44:26 +010010285 return unicode_result_unchanged(self);
10286
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010287 error:
10288 if (srelease && sbuf)
10289 PyMem_FREE(sbuf);
10290 if (release1 && buf1)
10291 PyMem_FREE(buf1);
10292 if (release2 && buf2)
10293 PyMem_FREE(buf2);
10294 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010295}
10296
10297/* --- Unicode Object Methods --------------------------------------------- */
10298
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010299PyDoc_STRVAR(title__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010300 "S.title() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010301\n\
10302Return a titlecased version of S, i.e. words start with title case\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010303characters, all remaining cased characters have lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010304
10305static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010306unicode_title(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010307{
Benjamin Petersoneea48462012-01-16 14:28:50 -050010308 if (PyUnicode_READY(self) == -1)
10309 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010310 return case_operation(self, do_title);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010311}
10312
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010313PyDoc_STRVAR(capitalize__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010314 "S.capitalize() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010315\n\
10316Return a capitalized version of S, i.e. make the first character\n\
Senthil Kumarane51ee8a2010-07-05 12:00:56 +000010317have upper case and the rest lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010318
10319static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010320unicode_capitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010321{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050010322 if (PyUnicode_READY(self) == -1)
10323 return NULL;
10324 if (PyUnicode_GET_LENGTH(self) == 0)
10325 return unicode_result_unchanged(self);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010326 return case_operation(self, do_capitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010327}
10328
Benjamin Petersond5890c82012-01-14 13:23:30 -050010329PyDoc_STRVAR(casefold__doc__,
10330 "S.casefold() -> str\n\
10331\n\
10332Return a version of S suitable for caseless comparisons.");
10333
10334static PyObject *
10335unicode_casefold(PyObject *self)
10336{
10337 if (PyUnicode_READY(self) == -1)
10338 return NULL;
10339 if (PyUnicode_IS_ASCII(self))
10340 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010341 return case_operation(self, do_casefold);
Benjamin Petersond5890c82012-01-14 13:23:30 -050010342}
10343
10344
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010345/* Argument converter. Coerces to a single unicode character */
10346
10347static int
10348convert_uc(PyObject *obj, void *addr)
10349{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010350 Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010351 PyObject *uniobj;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010352
Benjamin Peterson14339b62009-01-31 16:36:08 +000010353 uniobj = PyUnicode_FromObject(obj);
10354 if (uniobj == NULL) {
10355 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010356 "The fill character cannot be converted to Unicode");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010357 return 0;
10358 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010359 if (PyUnicode_GET_LENGTH(uniobj) != 1) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010360 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010361 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010362 Py_DECREF(uniobj);
10363 return 0;
10364 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010365 *fillcharloc = PyUnicode_READ_CHAR(uniobj, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010366 Py_DECREF(uniobj);
10367 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010368}
10369
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010370PyDoc_STRVAR(center__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010371 "S.center(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010372\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010373Return S centered in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010374done using the specified fill character (default is a space)");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010375
10376static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010377unicode_center(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010378{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010379 Py_ssize_t marg, left;
10380 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010381 Py_UCS4 fillchar = ' ';
10382
Victor Stinnere9a29352011-10-01 02:14:59 +020010383 if (!PyArg_ParseTuple(args, "n|O&:center", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010384 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010385
Benjamin Petersonbac79492012-01-14 13:34:47 -050010386 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010387 return NULL;
10388
Victor Stinnerc4b49542011-12-11 22:44:26 +010010389 if (PyUnicode_GET_LENGTH(self) >= width)
10390 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010391
Victor Stinnerc4b49542011-12-11 22:44:26 +010010392 marg = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010393 left = marg / 2 + (marg & width & 1);
10394
Victor Stinner9310abb2011-10-05 00:59:23 +020010395 return pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010396}
10397
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010398/* This function assumes that str1 and str2 are readied by the caller. */
10399
Marc-André Lemburge5034372000-08-08 08:04:29 +000010400static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010401unicode_compare(PyObject *str1, PyObject *str2)
Marc-André Lemburge5034372000-08-08 08:04:29 +000010402{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010403 int kind1, kind2;
10404 void *data1, *data2;
10405 Py_ssize_t len1, len2, i;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010406
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010407 kind1 = PyUnicode_KIND(str1);
10408 kind2 = PyUnicode_KIND(str2);
10409 data1 = PyUnicode_DATA(str1);
10410 data2 = PyUnicode_DATA(str2);
10411 len1 = PyUnicode_GET_LENGTH(str1);
10412 len2 = PyUnicode_GET_LENGTH(str2);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010413
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010414 for (i = 0; i < len1 && i < len2; ++i) {
10415 Py_UCS4 c1, c2;
10416 c1 = PyUnicode_READ(kind1, data1, i);
10417 c2 = PyUnicode_READ(kind2, data2, i);
Fredrik Lundh45714e92001-06-26 16:39:36 +000010418
10419 if (c1 != c2)
10420 return (c1 < c2) ? -1 : 1;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010421 }
10422
10423 return (len1 < len2) ? -1 : (len1 != len2);
10424}
10425
Alexander Belopolsky40018472011-02-26 01:02:56 +000010426int
10427PyUnicode_Compare(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010428{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010429 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10430 if (PyUnicode_READY(left) == -1 ||
10431 PyUnicode_READY(right) == -1)
10432 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010433 return unicode_compare(left, right);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010434 }
Guido van Rossum09dc34f2007-05-04 04:17:33 +000010435 PyErr_Format(PyExc_TypeError,
10436 "Can't compare %.100s and %.100s",
10437 left->ob_type->tp_name,
10438 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010439 return -1;
10440}
10441
Martin v. Löwis5b222132007-06-10 09:51:05 +000010442int
10443PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
10444{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010445 Py_ssize_t i;
10446 int kind;
10447 void *data;
10448 Py_UCS4 chr;
10449
Victor Stinner910337b2011-10-03 03:20:16 +020010450 assert(_PyUnicode_CHECK(uni));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010451 if (PyUnicode_READY(uni) == -1)
10452 return -1;
10453 kind = PyUnicode_KIND(uni);
10454 data = PyUnicode_DATA(uni);
Martin v. Löwis5b222132007-06-10 09:51:05 +000010455 /* Compare Unicode string and source character set string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010456 for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
10457 if (chr != str[i])
10458 return (chr < (unsigned char)(str[i])) ? -1 : 1;
Benjamin Peterson8667a9b2010-01-09 21:45:28 +000010459 /* This check keeps Python strings that end in '\0' from comparing equal
10460 to C strings identical up to that point. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010461 if (PyUnicode_GET_LENGTH(uni) != i || chr)
Benjamin Peterson29060642009-01-31 22:14:21 +000010462 return 1; /* uni is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010463 if (str[i])
Benjamin Peterson29060642009-01-31 22:14:21 +000010464 return -1; /* str is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010465 return 0;
10466}
10467
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010468
Benjamin Peterson29060642009-01-31 22:14:21 +000010469#define TEST_COND(cond) \
Benjamin Peterson14339b62009-01-31 16:36:08 +000010470 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010471
Alexander Belopolsky40018472011-02-26 01:02:56 +000010472PyObject *
10473PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010474{
10475 int result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010476
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010477 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10478 PyObject *v;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010479 if (PyUnicode_READY(left) == -1 ||
10480 PyUnicode_READY(right) == -1)
10481 return NULL;
10482 if (PyUnicode_GET_LENGTH(left) != PyUnicode_GET_LENGTH(right) ||
10483 PyUnicode_KIND(left) != PyUnicode_KIND(right)) {
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010484 if (op == Py_EQ) {
10485 Py_INCREF(Py_False);
10486 return Py_False;
10487 }
10488 if (op == Py_NE) {
10489 Py_INCREF(Py_True);
10490 return Py_True;
10491 }
10492 }
10493 if (left == right)
10494 result = 0;
10495 else
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010496 result = unicode_compare(left, right);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010497
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010498 /* Convert the return value to a Boolean */
10499 switch (op) {
10500 case Py_EQ:
10501 v = TEST_COND(result == 0);
10502 break;
10503 case Py_NE:
10504 v = TEST_COND(result != 0);
10505 break;
10506 case Py_LE:
10507 v = TEST_COND(result <= 0);
10508 break;
10509 case Py_GE:
10510 v = TEST_COND(result >= 0);
10511 break;
10512 case Py_LT:
10513 v = TEST_COND(result == -1);
10514 break;
10515 case Py_GT:
10516 v = TEST_COND(result == 1);
10517 break;
10518 default:
10519 PyErr_BadArgument();
10520 return NULL;
10521 }
10522 Py_INCREF(v);
10523 return v;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010524 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000010525
Brian Curtindfc80e32011-08-10 20:28:54 -050010526 Py_RETURN_NOTIMPLEMENTED;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010527}
10528
Alexander Belopolsky40018472011-02-26 01:02:56 +000010529int
10530PyUnicode_Contains(PyObject *container, PyObject *element)
Guido van Rossum403d68b2000-03-13 15:55:09 +000010531{
Thomas Wouters477c8d52006-05-27 19:21:47 +000010532 PyObject *str, *sub;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010533 int kind1, kind2, kind;
10534 void *buf1, *buf2;
10535 Py_ssize_t len1, len2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010536 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010537
10538 /* Coerce the two arguments */
Thomas Wouters477c8d52006-05-27 19:21:47 +000010539 sub = PyUnicode_FromObject(element);
10540 if (!sub) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010541 PyErr_Format(PyExc_TypeError,
10542 "'in <string>' requires string as left operand, not %s",
10543 element->ob_type->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010544 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010545 }
10546
Thomas Wouters477c8d52006-05-27 19:21:47 +000010547 str = PyUnicode_FromObject(container);
Benjamin Peterson22a29702012-01-02 09:00:30 -060010548 if (!str) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010549 Py_DECREF(sub);
10550 return -1;
10551 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060010552 if (PyUnicode_READY(sub) == -1 || PyUnicode_READY(str) == -1) {
10553 Py_DECREF(sub);
10554 Py_DECREF(str);
10555 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000010556
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010557 kind1 = PyUnicode_KIND(str);
10558 kind2 = PyUnicode_KIND(sub);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010559 kind = kind1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010560 buf1 = PyUnicode_DATA(str);
10561 buf2 = PyUnicode_DATA(sub);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010562 if (kind2 != kind) {
Antoine Pitrou758153b2012-05-12 15:51:51 +020010563 if (kind2 > kind) {
10564 Py_DECREF(sub);
10565 Py_DECREF(str);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010566 return 0;
Antoine Pitrou758153b2012-05-12 15:51:51 +020010567 }
Victor Stinner7931d9a2011-11-04 00:22:48 +010010568 buf2 = _PyUnicode_AsKind(sub, kind);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010569 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010570 if (!buf2) {
10571 Py_DECREF(sub);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010572 Py_DECREF(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010573 return -1;
10574 }
10575 len1 = PyUnicode_GET_LENGTH(str);
10576 len2 = PyUnicode_GET_LENGTH(sub);
10577
Benjamin Petersonead6b532011-12-20 17:23:42 -060010578 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010579 case PyUnicode_1BYTE_KIND:
10580 result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
10581 break;
10582 case PyUnicode_2BYTE_KIND:
10583 result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
10584 break;
10585 case PyUnicode_4BYTE_KIND:
10586 result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
10587 break;
10588 default:
10589 result = -1;
10590 assert(0);
10591 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000010592
10593 Py_DECREF(str);
10594 Py_DECREF(sub);
10595
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010596 if (kind2 != kind)
10597 PyMem_Free(buf2);
10598
Guido van Rossum403d68b2000-03-13 15:55:09 +000010599 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010600}
10601
Guido van Rossumd57fd912000-03-10 22:53:23 +000010602/* Concat to string or Unicode object giving a new Unicode object. */
10603
Alexander Belopolsky40018472011-02-26 01:02:56 +000010604PyObject *
10605PyUnicode_Concat(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010606{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010607 PyObject *u = NULL, *v = NULL, *w;
Victor Stinner127226b2011-10-13 01:12:34 +020010608 Py_UCS4 maxchar, maxchar2;
Victor Stinner488fa492011-12-12 00:01:39 +010010609 Py_ssize_t u_len, v_len, new_len;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010610
10611 /* Coerce the two arguments */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010612 u = PyUnicode_FromObject(left);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010613 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010614 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010615 v = PyUnicode_FromObject(right);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010616 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010617 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010618
10619 /* Shortcuts */
Victor Stinnera464fc12011-10-02 20:39:30 +020010620 if (v == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010621 Py_DECREF(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010622 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010623 }
Victor Stinnera464fc12011-10-02 20:39:30 +020010624 if (u == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010625 Py_DECREF(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010626 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010627 }
10628
Victor Stinner488fa492011-12-12 00:01:39 +010010629 u_len = PyUnicode_GET_LENGTH(u);
10630 v_len = PyUnicode_GET_LENGTH(v);
10631 if (u_len > PY_SSIZE_T_MAX - v_len) {
10632 PyErr_SetString(PyExc_OverflowError,
10633 "strings are too large to concat");
10634 goto onError;
10635 }
10636 new_len = u_len + v_len;
10637
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010638 maxchar = PyUnicode_MAX_CHAR_VALUE(u);
Victor Stinner127226b2011-10-13 01:12:34 +020010639 maxchar2 = PyUnicode_MAX_CHAR_VALUE(v);
Victor Stinnere6abb482012-05-02 01:15:40 +020010640 maxchar = MAX_MAXCHAR(maxchar, maxchar2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010641
Guido van Rossumd57fd912000-03-10 22:53:23 +000010642 /* Concat the two Unicode strings */
Victor Stinner488fa492011-12-12 00:01:39 +010010643 w = PyUnicode_New(new_len, maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010644 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010645 goto onError;
Victor Stinnerd3f08822012-05-29 12:57:52 +020010646 _PyUnicode_FastCopyCharacters(w, 0, u, 0, u_len);
10647 _PyUnicode_FastCopyCharacters(w, u_len, v, 0, v_len);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010648 Py_DECREF(u);
10649 Py_DECREF(v);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010650 assert(_PyUnicode_CheckConsistency(w, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010651 return w;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010652
Benjamin Peterson29060642009-01-31 22:14:21 +000010653 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000010654 Py_XDECREF(u);
10655 Py_XDECREF(v);
10656 return NULL;
10657}
10658
Walter Dörwald1ab83302007-05-18 17:15:44 +000010659void
Victor Stinner23e56682011-10-03 03:54:37 +020010660PyUnicode_Append(PyObject **p_left, PyObject *right)
Walter Dörwald1ab83302007-05-18 17:15:44 +000010661{
Victor Stinner23e56682011-10-03 03:54:37 +020010662 PyObject *left, *res;
Victor Stinner488fa492011-12-12 00:01:39 +010010663 Py_UCS4 maxchar, maxchar2;
10664 Py_ssize_t left_len, right_len, new_len;
Victor Stinner23e56682011-10-03 03:54:37 +020010665
10666 if (p_left == NULL) {
10667 if (!PyErr_Occurred())
10668 PyErr_BadInternalCall();
Benjamin Peterson14339b62009-01-31 16:36:08 +000010669 return;
10670 }
Victor Stinner23e56682011-10-03 03:54:37 +020010671 left = *p_left;
10672 if (right == NULL || !PyUnicode_Check(left)) {
10673 if (!PyErr_Occurred())
10674 PyErr_BadInternalCall();
10675 goto error;
10676 }
10677
Benjamin Petersonbac79492012-01-14 13:34:47 -050010678 if (PyUnicode_READY(left) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020010679 goto error;
Benjamin Petersonbac79492012-01-14 13:34:47 -050010680 if (PyUnicode_READY(right) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020010681 goto error;
10682
Victor Stinner488fa492011-12-12 00:01:39 +010010683 /* Shortcuts */
10684 if (left == unicode_empty) {
10685 Py_DECREF(left);
10686 Py_INCREF(right);
10687 *p_left = right;
10688 return;
10689 }
10690 if (right == unicode_empty)
10691 return;
10692
10693 left_len = PyUnicode_GET_LENGTH(left);
10694 right_len = PyUnicode_GET_LENGTH(right);
10695 if (left_len > PY_SSIZE_T_MAX - right_len) {
10696 PyErr_SetString(PyExc_OverflowError,
10697 "strings are too large to concat");
10698 goto error;
10699 }
10700 new_len = left_len + right_len;
10701
10702 if (unicode_modifiable(left)
10703 && PyUnicode_CheckExact(right)
10704 && PyUnicode_KIND(right) <= PyUnicode_KIND(left)
Victor Stinnerb0923652011-10-04 01:17:31 +020010705 /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
10706 to change the structure size, but characters are stored just after
Georg Brandl7597add2011-10-05 16:36:47 +020010707 the structure, and so it requires to move all characters which is
Victor Stinnerb0923652011-10-04 01:17:31 +020010708 not so different than duplicating the string. */
Victor Stinner488fa492011-12-12 00:01:39 +010010709 && !(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
10710 {
10711 /* append inplace */
10712 if (unicode_resize(p_left, new_len) != 0) {
10713 /* XXX if _PyUnicode_Resize() fails, 'left' has been
10714 * deallocated so it cannot be put back into
10715 * 'variable'. The MemoryError is raised when there
10716 * is no value in 'variable', which might (very
10717 * remotely) be a cause of incompatibilities.
10718 */
10719 goto error;
Victor Stinner23e56682011-10-03 03:54:37 +020010720 }
Victor Stinner488fa492011-12-12 00:01:39 +010010721 /* copy 'right' into the newly allocated area of 'left' */
Victor Stinnerd3f08822012-05-29 12:57:52 +020010722 _PyUnicode_FastCopyCharacters(*p_left, left_len, right, 0, right_len);
Victor Stinner23e56682011-10-03 03:54:37 +020010723 }
Victor Stinner488fa492011-12-12 00:01:39 +010010724 else {
10725 maxchar = PyUnicode_MAX_CHAR_VALUE(left);
10726 maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
Victor Stinnere6abb482012-05-02 01:15:40 +020010727 maxchar = MAX_MAXCHAR(maxchar, maxchar2);
Victor Stinner23e56682011-10-03 03:54:37 +020010728
Victor Stinner488fa492011-12-12 00:01:39 +010010729 /* Concat the two Unicode strings */
10730 res = PyUnicode_New(new_len, maxchar);
10731 if (res == NULL)
10732 goto error;
Victor Stinnerd3f08822012-05-29 12:57:52 +020010733 _PyUnicode_FastCopyCharacters(res, 0, left, 0, left_len);
10734 _PyUnicode_FastCopyCharacters(res, left_len, right, 0, right_len);
Victor Stinner488fa492011-12-12 00:01:39 +010010735 Py_DECREF(left);
10736 *p_left = res;
10737 }
10738 assert(_PyUnicode_CheckConsistency(*p_left, 1));
Victor Stinner23e56682011-10-03 03:54:37 +020010739 return;
10740
10741error:
Victor Stinner488fa492011-12-12 00:01:39 +010010742 Py_CLEAR(*p_left);
Walter Dörwald1ab83302007-05-18 17:15:44 +000010743}
10744
10745void
10746PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
10747{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010748 PyUnicode_Append(pleft, right);
10749 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +000010750}
10751
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010752PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010753 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010754\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000010755Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010756string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010757interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010758
10759static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010760unicode_count(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010761{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010762 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010763 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010764 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010765 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010766 int kind1, kind2, kind;
10767 void *buf1, *buf2;
10768 Py_ssize_t len1, len2, iresult;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010769
Jesus Ceaac451502011-04-20 17:09:23 +020010770 if (!stringlib_parse_args_finds_unicode("count", args, &substring,
10771 &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000010772 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000010773
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010774 kind1 = PyUnicode_KIND(self);
10775 kind2 = PyUnicode_KIND(substring);
Benjamin Petersonb63f49f2012-05-03 18:31:07 -040010776 if (kind2 > kind1)
10777 return PyLong_FromLong(0);
10778 kind = kind1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010779 buf1 = PyUnicode_DATA(self);
10780 buf2 = PyUnicode_DATA(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010781 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010782 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010783 if (!buf2) {
10784 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010785 return NULL;
10786 }
10787 len1 = PyUnicode_GET_LENGTH(self);
10788 len2 = PyUnicode_GET_LENGTH(substring);
10789
10790 ADJUST_INDICES(start, end, len1);
Benjamin Petersonead6b532011-12-20 17:23:42 -060010791 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010792 case PyUnicode_1BYTE_KIND:
10793 iresult = ucs1lib_count(
10794 ((Py_UCS1*)buf1) + start, end - start,
10795 buf2, len2, PY_SSIZE_T_MAX
10796 );
10797 break;
10798 case PyUnicode_2BYTE_KIND:
10799 iresult = ucs2lib_count(
10800 ((Py_UCS2*)buf1) + start, end - start,
10801 buf2, len2, PY_SSIZE_T_MAX
10802 );
10803 break;
10804 case PyUnicode_4BYTE_KIND:
10805 iresult = ucs4lib_count(
10806 ((Py_UCS4*)buf1) + start, end - start,
10807 buf2, len2, PY_SSIZE_T_MAX
10808 );
10809 break;
10810 default:
10811 assert(0); iresult = 0;
10812 }
10813
10814 result = PyLong_FromSsize_t(iresult);
10815
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010816 if (kind2 != kind)
10817 PyMem_Free(buf2);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010818
10819 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010820
Guido van Rossumd57fd912000-03-10 22:53:23 +000010821 return result;
10822}
10823
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010824PyDoc_STRVAR(encode__doc__,
Victor Stinnerc911bbf2010-11-07 19:04:46 +000010825 "S.encode(encoding='utf-8', errors='strict') -> bytes\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010826\n\
Victor Stinnere14e2122010-11-07 18:41:46 +000010827Encode S using the codec registered for encoding. Default encoding\n\
10828is 'utf-8'. errors may be given to set a different error\n\
Fred Drakee4315f52000-05-09 19:53:39 +000010829handling scheme. Default is 'strict' meaning that encoding errors raise\n\
Walter Dörwald3aeb6322002-09-02 13:14:32 +000010830a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
10831'xmlcharrefreplace' as well as any other name registered with\n\
10832codecs.register_error that can handle UnicodeEncodeErrors.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010833
10834static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010835unicode_encode(PyObject *self, PyObject *args, PyObject *kwargs)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010836{
Benjamin Peterson308d6372009-09-18 21:42:35 +000010837 static char *kwlist[] = {"encoding", "errors", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000010838 char *encoding = NULL;
10839 char *errors = NULL;
Guido van Rossum35d94282007-08-27 18:20:11 +000010840
Benjamin Peterson308d6372009-09-18 21:42:35 +000010841 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:encode",
10842 kwlist, &encoding, &errors))
Guido van Rossumd57fd912000-03-10 22:53:23 +000010843 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010844 return PyUnicode_AsEncodedString(self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +000010845}
10846
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010847PyDoc_STRVAR(expandtabs__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010848 "S.expandtabs([tabsize]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010849\n\
10850Return a copy of S where all tab characters are expanded using spaces.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010851If tabsize is not given, a tab size of 8 characters is assumed.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010852
10853static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010854unicode_expandtabs(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010855{
Antoine Pitroue71d5742011-10-04 15:55:09 +020010856 Py_ssize_t i, j, line_pos, src_len, incr;
10857 Py_UCS4 ch;
10858 PyObject *u;
10859 void *src_data, *dest_data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010860 int tabsize = 8;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010861 int kind;
Antoine Pitroue19aa382011-10-04 16:04:01 +020010862 int found;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010863
10864 if (!PyArg_ParseTuple(args, "|i:expandtabs", &tabsize))
Benjamin Peterson29060642009-01-31 22:14:21 +000010865 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010866
Antoine Pitrou22425222011-10-04 19:10:51 +020010867 if (PyUnicode_READY(self) == -1)
10868 return NULL;
10869
Thomas Wouters7e474022000-07-16 12:04:32 +000010870 /* First pass: determine size of output string */
Antoine Pitroue71d5742011-10-04 15:55:09 +020010871 src_len = PyUnicode_GET_LENGTH(self);
10872 i = j = line_pos = 0;
10873 kind = PyUnicode_KIND(self);
10874 src_data = PyUnicode_DATA(self);
Antoine Pitroue19aa382011-10-04 16:04:01 +020010875 found = 0;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010876 for (; i < src_len; i++) {
10877 ch = PyUnicode_READ(kind, src_data, i);
10878 if (ch == '\t') {
Antoine Pitroue19aa382011-10-04 16:04:01 +020010879 found = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000010880 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020010881 incr = tabsize - (line_pos % tabsize); /* cannot overflow */
Benjamin Peterson29060642009-01-31 22:14:21 +000010882 if (j > PY_SSIZE_T_MAX - incr)
Antoine Pitroue71d5742011-10-04 15:55:09 +020010883 goto overflow;
10884 line_pos += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000010885 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010886 }
Benjamin Peterson29060642009-01-31 22:14:21 +000010887 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010888 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000010889 if (j > PY_SSIZE_T_MAX - 1)
Antoine Pitroue71d5742011-10-04 15:55:09 +020010890 goto overflow;
10891 line_pos++;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010892 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010893 if (ch == '\n' || ch == '\r')
10894 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010895 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020010896 }
Victor Stinnerc4b49542011-12-11 22:44:26 +010010897 if (!found)
10898 return unicode_result_unchanged(self);
Guido van Rossumcd16bf62007-06-13 18:07:49 +000010899
Guido van Rossumd57fd912000-03-10 22:53:23 +000010900 /* Second pass: create output string and fill it */
Antoine Pitroue71d5742011-10-04 15:55:09 +020010901 u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +000010902 if (!u)
10903 return NULL;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010904 dest_data = PyUnicode_DATA(u);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010905
Antoine Pitroue71d5742011-10-04 15:55:09 +020010906 i = j = line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010907
Antoine Pitroue71d5742011-10-04 15:55:09 +020010908 for (; i < src_len; i++) {
10909 ch = PyUnicode_READ(kind, src_data, i);
10910 if (ch == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +000010911 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020010912 incr = tabsize - (line_pos % tabsize);
10913 line_pos += incr;
Victor Stinnerda79e632012-02-22 13:37:04 +010010914 FILL(kind, dest_data, ' ', j, incr);
10915 j += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000010916 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000010917 }
Benjamin Peterson29060642009-01-31 22:14:21 +000010918 else {
Antoine Pitroue71d5742011-10-04 15:55:09 +020010919 line_pos++;
10920 PyUnicode_WRITE(kind, dest_data, j, ch);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010921 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010922 if (ch == '\n' || ch == '\r')
10923 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010924 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020010925 }
10926 assert (j == PyUnicode_GET_LENGTH(u));
Victor Stinnerd3df8ab2011-11-22 01:22:34 +010010927 return unicode_result(u);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010928
Antoine Pitroue71d5742011-10-04 15:55:09 +020010929 overflow:
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010930 PyErr_SetString(PyExc_OverflowError, "new string is too long");
10931 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010932}
10933
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010934PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010935 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010936\n\
10937Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080010938such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010939arguments start and end are interpreted as in slice notation.\n\
10940\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010941Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010942
10943static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010944unicode_find(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010945{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010946 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000010947 Py_ssize_t start;
10948 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010949 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010950
Jesus Ceaac451502011-04-20 17:09:23 +020010951 if (!stringlib_parse_args_finds_unicode("find", args, &substring,
10952 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000010953 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010954
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010955 if (PyUnicode_READY(self) == -1)
10956 return NULL;
10957 if (PyUnicode_READY(substring) == -1)
10958 return NULL;
10959
Victor Stinner7931d9a2011-11-04 00:22:48 +010010960 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010961
10962 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010963
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010964 if (result == -2)
10965 return NULL;
10966
Christian Heimes217cfd12007-12-02 14:31:20 +000010967 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010968}
10969
10970static PyObject *
Victor Stinner2fe5ced2011-10-02 00:25:40 +020010971unicode_getitem(PyObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010972{
Victor Stinnerb6cd0142012-05-03 02:17:04 +020010973 void *data;
10974 enum PyUnicode_Kind kind;
10975 Py_UCS4 ch;
10976 PyObject *res;
10977
10978 if (!PyUnicode_Check(self) || PyUnicode_READY(self) == -1) {
10979 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010980 return NULL;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020010981 }
10982 if (index < 0 || index >= PyUnicode_GET_LENGTH(self)) {
10983 PyErr_SetString(PyExc_IndexError, "string index out of range");
10984 return NULL;
10985 }
10986 kind = PyUnicode_KIND(self);
10987 data = PyUnicode_DATA(self);
10988 ch = PyUnicode_READ(kind, data, index);
10989 if (ch < 256)
10990 return get_latin1_char(ch);
10991
10992 res = PyUnicode_New(1, ch);
10993 if (res == NULL)
10994 return NULL;
10995 kind = PyUnicode_KIND(res);
10996 data = PyUnicode_DATA(res);
10997 PyUnicode_WRITE(kind, data, 0, ch);
10998 assert(_PyUnicode_CheckConsistency(res, 1));
10999 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011000}
11001
Guido van Rossumc2504932007-09-18 19:42:40 +000011002/* Believe it or not, this produces the same value for ASCII strings
Mark Dickinson57e683e2011-09-24 18:18:40 +010011003 as bytes_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +000011004static Py_hash_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011005unicode_hash(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011006{
Guido van Rossumc2504932007-09-18 19:42:40 +000011007 Py_ssize_t len;
Mark Dickinson57e683e2011-09-24 18:18:40 +010011008 Py_uhash_t x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011009
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011010#ifdef Py_DEBUG
Benjamin Peterson69e97272012-02-21 11:08:50 -050011011 assert(_Py_HashSecret_Initialized);
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011012#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011013 if (_PyUnicode_HASH(self) != -1)
11014 return _PyUnicode_HASH(self);
11015 if (PyUnicode_READY(self) == -1)
11016 return -1;
11017 len = PyUnicode_GET_LENGTH(self);
Georg Brandl16fa2a12012-02-21 00:50:13 +010011018 /*
11019 We make the hash of the empty string be 0, rather than using
11020 (prefix ^ suffix), since this slightly obfuscates the hash secret
11021 */
11022 if (len == 0) {
11023 _PyUnicode_HASH(self) = 0;
11024 return 0;
11025 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011026
11027 /* The hash function as a macro, gets expanded three times below. */
Georg Brandl2fb477c2012-02-21 00:33:36 +010011028#define HASH(P) \
11029 x ^= (Py_uhash_t) *P << 7; \
11030 while (--len >= 0) \
11031 x = (_PyHASH_MULTIPLIER * x) ^ (Py_uhash_t) *P++; \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011032
Georg Brandl2fb477c2012-02-21 00:33:36 +010011033 x = (Py_uhash_t) _Py_HashSecret.prefix;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011034 switch (PyUnicode_KIND(self)) {
11035 case PyUnicode_1BYTE_KIND: {
11036 const unsigned char *c = PyUnicode_1BYTE_DATA(self);
11037 HASH(c);
11038 break;
11039 }
11040 case PyUnicode_2BYTE_KIND: {
11041 const Py_UCS2 *s = PyUnicode_2BYTE_DATA(self);
11042 HASH(s);
11043 break;
11044 }
11045 default: {
11046 Py_UCS4 *l;
11047 assert(PyUnicode_KIND(self) == PyUnicode_4BYTE_KIND &&
11048 "Impossible switch case in unicode_hash");
11049 l = PyUnicode_4BYTE_DATA(self);
11050 HASH(l);
11051 break;
11052 }
11053 }
Georg Brandl2fb477c2012-02-21 00:33:36 +010011054 x ^= (Py_uhash_t) PyUnicode_GET_LENGTH(self);
11055 x ^= (Py_uhash_t) _Py_HashSecret.suffix;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011056
Guido van Rossumc2504932007-09-18 19:42:40 +000011057 if (x == -1)
11058 x = -2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011059 _PyUnicode_HASH(self) = x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011060 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011061}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011062#undef HASH
Guido van Rossumd57fd912000-03-10 22:53:23 +000011063
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011064PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011065 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011066\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011067Like S.find() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011068
11069static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011070unicode_index(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011071{
Martin v. Löwis18e16552006-02-15 17:27:45 +000011072 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011073 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011074 Py_ssize_t start;
11075 Py_ssize_t end;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011076
Jesus Ceaac451502011-04-20 17:09:23 +020011077 if (!stringlib_parse_args_finds_unicode("index", args, &substring,
11078 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011079 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011080
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011081 if (PyUnicode_READY(self) == -1)
11082 return NULL;
11083 if (PyUnicode_READY(substring) == -1)
11084 return NULL;
11085
Victor Stinner7931d9a2011-11-04 00:22:48 +010011086 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011087
11088 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011089
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011090 if (result == -2)
11091 return NULL;
11092
Guido van Rossumd57fd912000-03-10 22:53:23 +000011093 if (result < 0) {
11094 PyErr_SetString(PyExc_ValueError, "substring not found");
11095 return NULL;
11096 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011097
Christian Heimes217cfd12007-12-02 14:31:20 +000011098 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011099}
11100
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011101PyDoc_STRVAR(islower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011102 "S.islower() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011103\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011104Return True if all cased characters in S are lowercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011105at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011106
11107static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011108unicode_islower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011109{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011110 Py_ssize_t i, length;
11111 int kind;
11112 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011113 int cased;
11114
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011115 if (PyUnicode_READY(self) == -1)
11116 return NULL;
11117 length = PyUnicode_GET_LENGTH(self);
11118 kind = PyUnicode_KIND(self);
11119 data = PyUnicode_DATA(self);
11120
Guido van Rossumd57fd912000-03-10 22:53:23 +000011121 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011122 if (length == 1)
11123 return PyBool_FromLong(
11124 Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011125
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011126 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011127 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011128 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011129
Guido van Rossumd57fd912000-03-10 22:53:23 +000011130 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011131 for (i = 0; i < length; i++) {
11132 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011133
Benjamin Peterson29060642009-01-31 22:14:21 +000011134 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
11135 return PyBool_FromLong(0);
11136 else if (!cased && Py_UNICODE_ISLOWER(ch))
11137 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011138 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011139 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011140}
11141
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011142PyDoc_STRVAR(isupper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011143 "S.isupper() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011144\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011145Return True if all cased characters in S are uppercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011146at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011147
11148static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011149unicode_isupper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011150{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011151 Py_ssize_t i, length;
11152 int kind;
11153 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011154 int cased;
11155
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011156 if (PyUnicode_READY(self) == -1)
11157 return NULL;
11158 length = PyUnicode_GET_LENGTH(self);
11159 kind = PyUnicode_KIND(self);
11160 data = PyUnicode_DATA(self);
11161
Guido van Rossumd57fd912000-03-10 22:53:23 +000011162 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011163 if (length == 1)
11164 return PyBool_FromLong(
11165 Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011166
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011167 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011168 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011169 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011170
Guido van Rossumd57fd912000-03-10 22:53:23 +000011171 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011172 for (i = 0; i < length; i++) {
11173 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011174
Benjamin Peterson29060642009-01-31 22:14:21 +000011175 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
11176 return PyBool_FromLong(0);
11177 else if (!cased && Py_UNICODE_ISUPPER(ch))
11178 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011179 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011180 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011181}
11182
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011183PyDoc_STRVAR(istitle__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011184 "S.istitle() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011185\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011186Return True if S is a titlecased string and there is at least one\n\
11187character in S, i.e. upper- and titlecase characters may only\n\
11188follow uncased characters and lowercase characters only cased ones.\n\
11189Return False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011190
11191static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011192unicode_istitle(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011193{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011194 Py_ssize_t i, length;
11195 int kind;
11196 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011197 int cased, previous_is_cased;
11198
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011199 if (PyUnicode_READY(self) == -1)
11200 return NULL;
11201 length = PyUnicode_GET_LENGTH(self);
11202 kind = PyUnicode_KIND(self);
11203 data = PyUnicode_DATA(self);
11204
Guido van Rossumd57fd912000-03-10 22:53:23 +000011205 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011206 if (length == 1) {
11207 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11208 return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
11209 (Py_UNICODE_ISUPPER(ch) != 0));
11210 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011211
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011212 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011213 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011214 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011215
Guido van Rossumd57fd912000-03-10 22:53:23 +000011216 cased = 0;
11217 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011218 for (i = 0; i < length; i++) {
11219 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011220
Benjamin Peterson29060642009-01-31 22:14:21 +000011221 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
11222 if (previous_is_cased)
11223 return PyBool_FromLong(0);
11224 previous_is_cased = 1;
11225 cased = 1;
11226 }
11227 else if (Py_UNICODE_ISLOWER(ch)) {
11228 if (!previous_is_cased)
11229 return PyBool_FromLong(0);
11230 previous_is_cased = 1;
11231 cased = 1;
11232 }
11233 else
11234 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011235 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011236 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011237}
11238
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011239PyDoc_STRVAR(isspace__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011240 "S.isspace() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011241\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011242Return True if all characters in S are whitespace\n\
11243and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011244
11245static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011246unicode_isspace(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011247{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011248 Py_ssize_t i, length;
11249 int kind;
11250 void *data;
11251
11252 if (PyUnicode_READY(self) == -1)
11253 return NULL;
11254 length = PyUnicode_GET_LENGTH(self);
11255 kind = PyUnicode_KIND(self);
11256 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011257
Guido van Rossumd57fd912000-03-10 22:53:23 +000011258 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011259 if (length == 1)
11260 return PyBool_FromLong(
11261 Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011262
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011263 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011264 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011265 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011266
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011267 for (i = 0; i < length; i++) {
11268 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011269 if (!Py_UNICODE_ISSPACE(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011270 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011271 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011272 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011273}
11274
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011275PyDoc_STRVAR(isalpha__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011276 "S.isalpha() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011277\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011278Return True if all characters in S are alphabetic\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011279and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011280
11281static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011282unicode_isalpha(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011283{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011284 Py_ssize_t i, length;
11285 int kind;
11286 void *data;
11287
11288 if (PyUnicode_READY(self) == -1)
11289 return NULL;
11290 length = PyUnicode_GET_LENGTH(self);
11291 kind = PyUnicode_KIND(self);
11292 data = PyUnicode_DATA(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011293
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011294 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011295 if (length == 1)
11296 return PyBool_FromLong(
11297 Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011298
11299 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011300 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011301 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011302
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011303 for (i = 0; i < length; i++) {
11304 if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011305 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011306 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011307 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011308}
11309
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011310PyDoc_STRVAR(isalnum__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011311 "S.isalnum() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011312\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011313Return True if all characters in S are alphanumeric\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011314and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011315
11316static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011317unicode_isalnum(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011318{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011319 int kind;
11320 void *data;
11321 Py_ssize_t len, i;
11322
11323 if (PyUnicode_READY(self) == -1)
11324 return NULL;
11325
11326 kind = PyUnicode_KIND(self);
11327 data = PyUnicode_DATA(self);
11328 len = PyUnicode_GET_LENGTH(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011329
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011330 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011331 if (len == 1) {
11332 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11333 return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
11334 }
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011335
11336 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011337 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011338 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011339
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011340 for (i = 0; i < len; i++) {
11341 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011342 if (!Py_UNICODE_ISALNUM(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011343 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011344 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011345 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011346}
11347
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011348PyDoc_STRVAR(isdecimal__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011349 "S.isdecimal() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011350\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011351Return True if there are only decimal characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011352False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011353
11354static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011355unicode_isdecimal(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011356{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011357 Py_ssize_t i, length;
11358 int kind;
11359 void *data;
11360
11361 if (PyUnicode_READY(self) == -1)
11362 return NULL;
11363 length = PyUnicode_GET_LENGTH(self);
11364 kind = PyUnicode_KIND(self);
11365 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011366
Guido van Rossumd57fd912000-03-10 22:53:23 +000011367 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011368 if (length == 1)
11369 return PyBool_FromLong(
11370 Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011371
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011372 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011373 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011374 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011375
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011376 for (i = 0; i < length; i++) {
11377 if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011378 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011379 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011380 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011381}
11382
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011383PyDoc_STRVAR(isdigit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011384 "S.isdigit() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011385\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011386Return True if all characters in S are digits\n\
11387and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011388
11389static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011390unicode_isdigit(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011391{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011392 Py_ssize_t i, length;
11393 int kind;
11394 void *data;
11395
11396 if (PyUnicode_READY(self) == -1)
11397 return NULL;
11398 length = PyUnicode_GET_LENGTH(self);
11399 kind = PyUnicode_KIND(self);
11400 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011401
Guido van Rossumd57fd912000-03-10 22:53:23 +000011402 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011403 if (length == 1) {
11404 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11405 return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
11406 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011407
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011408 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011409 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011410 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011411
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011412 for (i = 0; i < length; i++) {
11413 if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011414 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011415 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011416 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011417}
11418
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011419PyDoc_STRVAR(isnumeric__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011420 "S.isnumeric() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011421\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011422Return True if there are only numeric characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011423False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011424
11425static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011426unicode_isnumeric(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011427{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011428 Py_ssize_t i, length;
11429 int kind;
11430 void *data;
11431
11432 if (PyUnicode_READY(self) == -1)
11433 return NULL;
11434 length = PyUnicode_GET_LENGTH(self);
11435 kind = PyUnicode_KIND(self);
11436 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011437
Guido van Rossumd57fd912000-03-10 22:53:23 +000011438 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011439 if (length == 1)
11440 return PyBool_FromLong(
11441 Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011442
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011443 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011444 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011445 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011446
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011447 for (i = 0; i < length; i++) {
11448 if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011449 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011450 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011451 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011452}
11453
Martin v. Löwis47383402007-08-15 07:32:56 +000011454int
11455PyUnicode_IsIdentifier(PyObject *self)
11456{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011457 int kind;
11458 void *data;
11459 Py_ssize_t i;
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011460 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +000011461
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011462 if (PyUnicode_READY(self) == -1) {
11463 Py_FatalError("identifier not ready");
Benjamin Peterson29060642009-01-31 22:14:21 +000011464 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011465 }
11466
11467 /* Special case for empty strings */
11468 if (PyUnicode_GET_LENGTH(self) == 0)
11469 return 0;
11470 kind = PyUnicode_KIND(self);
11471 data = PyUnicode_DATA(self);
Martin v. Löwis47383402007-08-15 07:32:56 +000011472
11473 /* PEP 3131 says that the first character must be in
11474 XID_Start and subsequent characters in XID_Continue,
11475 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +000011476 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +000011477 letters, digits, underscore). However, given the current
11478 definition of XID_Start and XID_Continue, it is sufficient
11479 to check just for these, except that _ must be allowed
11480 as starting an identifier. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011481 first = PyUnicode_READ(kind, data, 0);
Benjamin Petersonf413b802011-08-12 22:17:18 -050011482 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +000011483 return 0;
11484
Benjamin Peterson9c6e6a02011-09-28 08:09:05 -040011485 for (i = 1; i < PyUnicode_GET_LENGTH(self); i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011486 if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011487 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +000011488 return 1;
11489}
11490
11491PyDoc_STRVAR(isidentifier__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011492 "S.isidentifier() -> bool\n\
Martin v. Löwis47383402007-08-15 07:32:56 +000011493\n\
11494Return True if S is a valid identifier according\n\
11495to the language definition.");
11496
11497static PyObject*
11498unicode_isidentifier(PyObject *self)
11499{
11500 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
11501}
11502
Georg Brandl559e5d72008-06-11 18:37:52 +000011503PyDoc_STRVAR(isprintable__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011504 "S.isprintable() -> bool\n\
Georg Brandl559e5d72008-06-11 18:37:52 +000011505\n\
11506Return True if all characters in S are considered\n\
11507printable in repr() or S is empty, False otherwise.");
11508
11509static PyObject*
11510unicode_isprintable(PyObject *self)
11511{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011512 Py_ssize_t i, length;
11513 int kind;
11514 void *data;
11515
11516 if (PyUnicode_READY(self) == -1)
11517 return NULL;
11518 length = PyUnicode_GET_LENGTH(self);
11519 kind = PyUnicode_KIND(self);
11520 data = PyUnicode_DATA(self);
Georg Brandl559e5d72008-06-11 18:37:52 +000011521
11522 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011523 if (length == 1)
11524 return PyBool_FromLong(
11525 Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
Georg Brandl559e5d72008-06-11 18:37:52 +000011526
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011527 for (i = 0; i < length; i++) {
11528 if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
Georg Brandl559e5d72008-06-11 18:37:52 +000011529 Py_RETURN_FALSE;
11530 }
11531 }
11532 Py_RETURN_TRUE;
11533}
11534
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011535PyDoc_STRVAR(join__doc__,
Georg Brandl495f7b52009-10-27 15:28:25 +000011536 "S.join(iterable) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011537\n\
11538Return a string which is the concatenation of the strings in the\n\
Georg Brandl495f7b52009-10-27 15:28:25 +000011539iterable. The separator between elements is S.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011540
11541static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011542unicode_join(PyObject *self, PyObject *data)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011543{
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011544 return PyUnicode_Join(self, data);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011545}
11546
Martin v. Löwis18e16552006-02-15 17:27:45 +000011547static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011548unicode_length(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011549{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011550 if (PyUnicode_READY(self) == -1)
11551 return -1;
11552 return PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011553}
11554
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011555PyDoc_STRVAR(ljust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011556 "S.ljust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011557\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000011558Return S left-justified in a Unicode string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011559done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011560
11561static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020011562unicode_ljust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011563{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011564 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011565 Py_UCS4 fillchar = ' ';
11566
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011567 if (!PyArg_ParseTuple(args, "n|O&:ljust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011568 return NULL;
11569
Benjamin Petersonbac79492012-01-14 13:34:47 -050011570 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010011571 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011572
Victor Stinnerc4b49542011-12-11 22:44:26 +010011573 if (PyUnicode_GET_LENGTH(self) >= width)
11574 return unicode_result_unchanged(self);
11575
11576 return pad(self, 0, width - PyUnicode_GET_LENGTH(self), fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011577}
11578
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011579PyDoc_STRVAR(lower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011580 "S.lower() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011581\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011582Return a copy of the string S converted to lowercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011583
11584static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020011585unicode_lower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011586{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050011587 if (PyUnicode_READY(self) == -1)
11588 return NULL;
11589 if (PyUnicode_IS_ASCII(self))
11590 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010011591 return case_operation(self, do_lower);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011592}
11593
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011594#define LEFTSTRIP 0
11595#define RIGHTSTRIP 1
11596#define BOTHSTRIP 2
11597
11598/* Arrays indexed by above */
11599static const char *stripformat[] = {"|O:lstrip", "|O:rstrip", "|O:strip"};
11600
11601#define STRIPNAME(i) (stripformat[i]+3)
11602
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011603/* externally visible for str.strip(unicode) */
11604PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011605_PyUnicode_XStrip(PyObject *self, int striptype, PyObject *sepobj)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011606{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011607 void *data;
11608 int kind;
11609 Py_ssize_t i, j, len;
11610 BLOOM_MASK sepmask;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011611
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011612 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
11613 return NULL;
11614
11615 kind = PyUnicode_KIND(self);
11616 data = PyUnicode_DATA(self);
11617 len = PyUnicode_GET_LENGTH(self);
11618 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
11619 PyUnicode_DATA(sepobj),
11620 PyUnicode_GET_LENGTH(sepobj));
Thomas Wouters477c8d52006-05-27 19:21:47 +000011621
Benjamin Peterson14339b62009-01-31 16:36:08 +000011622 i = 0;
11623 if (striptype != RIGHTSTRIP) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011624 while (i < len &&
11625 BLOOM_MEMBER(sepmask, PyUnicode_READ(kind, data, i), sepobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011626 i++;
11627 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011628 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011629
Benjamin Peterson14339b62009-01-31 16:36:08 +000011630 j = len;
11631 if (striptype != LEFTSTRIP) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011632 do {
11633 j--;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011634 } while (j >= i &&
11635 BLOOM_MEMBER(sepmask, PyUnicode_READ(kind, data, j), sepobj));
Benjamin Peterson29060642009-01-31 22:14:21 +000011636 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011637 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011638
Victor Stinner7931d9a2011-11-04 00:22:48 +010011639 return PyUnicode_Substring(self, i, j);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011640}
11641
11642PyObject*
11643PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
11644{
11645 unsigned char *data;
11646 int kind;
Victor Stinner12bab6d2011-10-01 01:53:49 +020011647 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011648
Victor Stinnerde636f32011-10-01 03:55:54 +020011649 if (PyUnicode_READY(self) == -1)
11650 return NULL;
11651
Victor Stinner684d5fd2012-05-03 02:32:34 +020011652 length = PyUnicode_GET_LENGTH(self);
11653 end = Py_MIN(end, length);
Victor Stinnerde636f32011-10-01 03:55:54 +020011654
Victor Stinner684d5fd2012-05-03 02:32:34 +020011655 if (start == 0 && end == length)
Victor Stinnerc4b49542011-12-11 22:44:26 +010011656 return unicode_result_unchanged(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011657
Victor Stinnerde636f32011-10-01 03:55:54 +020011658 if (start < 0 || end < 0) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020011659 PyErr_SetString(PyExc_IndexError, "string index out of range");
11660 return NULL;
11661 }
Victor Stinner684d5fd2012-05-03 02:32:34 +020011662 if (start >= length || end < start) {
Victor Stinner3a7f7972012-05-03 03:36:40 +020011663 Py_INCREF(unicode_empty);
11664 return unicode_empty;
Victor Stinner684d5fd2012-05-03 02:32:34 +020011665 }
Victor Stinner12bab6d2011-10-01 01:53:49 +020011666
Victor Stinner684d5fd2012-05-03 02:32:34 +020011667 length = end - start;
Victor Stinnerb9275c12011-10-05 14:01:42 +020011668 if (PyUnicode_IS_ASCII(self)) {
Victor Stinnerb9275c12011-10-05 14:01:42 +020011669 data = PyUnicode_1BYTE_DATA(self);
Victor Stinnerd3f08822012-05-29 12:57:52 +020011670 return _PyUnicode_FromASCII((char*)(data + start), length);
Victor Stinnerb9275c12011-10-05 14:01:42 +020011671 }
11672 else {
11673 kind = PyUnicode_KIND(self);
11674 data = PyUnicode_1BYTE_DATA(self);
11675 return PyUnicode_FromKindAndData(kind,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020011676 data + kind * start,
Victor Stinnerb9275c12011-10-05 14:01:42 +020011677 length);
11678 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011679}
Guido van Rossumd57fd912000-03-10 22:53:23 +000011680
11681static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011682do_strip(PyObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011683{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011684 int kind;
11685 void *data;
11686 Py_ssize_t len, i, j;
11687
11688 if (PyUnicode_READY(self) == -1)
11689 return NULL;
11690
11691 kind = PyUnicode_KIND(self);
11692 data = PyUnicode_DATA(self);
11693 len = PyUnicode_GET_LENGTH(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011694
Benjamin Peterson14339b62009-01-31 16:36:08 +000011695 i = 0;
11696 if (striptype != RIGHTSTRIP) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011697 while (i < len && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, i))) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000011698 i++;
11699 }
11700 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011701
Benjamin Peterson14339b62009-01-31 16:36:08 +000011702 j = len;
11703 if (striptype != LEFTSTRIP) {
11704 do {
11705 j--;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011706 } while (j >= i && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, j)));
Benjamin Peterson14339b62009-01-31 16:36:08 +000011707 j++;
11708 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011709
Victor Stinner7931d9a2011-11-04 00:22:48 +010011710 return PyUnicode_Substring(self, i, j);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011711}
11712
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011713
11714static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011715do_argstrip(PyObject *self, int striptype, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011716{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011717 PyObject *sep = NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011718
Benjamin Peterson14339b62009-01-31 16:36:08 +000011719 if (!PyArg_ParseTuple(args, (char *)stripformat[striptype], &sep))
11720 return NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011721
Benjamin Peterson14339b62009-01-31 16:36:08 +000011722 if (sep != NULL && sep != Py_None) {
11723 if (PyUnicode_Check(sep))
11724 return _PyUnicode_XStrip(self, striptype, sep);
11725 else {
11726 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000011727 "%s arg must be None or str",
11728 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +000011729 return NULL;
11730 }
11731 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011732
Benjamin Peterson14339b62009-01-31 16:36:08 +000011733 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011734}
11735
11736
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011737PyDoc_STRVAR(strip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011738 "S.strip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011739\n\
11740Return a copy of the string S with leading and trailing\n\
11741whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011742If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011743
11744static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011745unicode_strip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011746{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011747 if (PyTuple_GET_SIZE(args) == 0)
11748 return do_strip(self, BOTHSTRIP); /* Common case */
11749 else
11750 return do_argstrip(self, BOTHSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011751}
11752
11753
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011754PyDoc_STRVAR(lstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011755 "S.lstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011756\n\
11757Return a copy of the string S with leading whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011758If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011759
11760static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011761unicode_lstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011762{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011763 if (PyTuple_GET_SIZE(args) == 0)
11764 return do_strip(self, LEFTSTRIP); /* Common case */
11765 else
11766 return do_argstrip(self, LEFTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011767}
11768
11769
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011770PyDoc_STRVAR(rstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011771 "S.rstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011772\n\
11773Return a copy of the string S with trailing whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011774If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011775
11776static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011777unicode_rstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011778{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011779 if (PyTuple_GET_SIZE(args) == 0)
11780 return do_strip(self, RIGHTSTRIP); /* Common case */
11781 else
11782 return do_argstrip(self, RIGHTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011783}
11784
11785
Guido van Rossumd57fd912000-03-10 22:53:23 +000011786static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011787unicode_repeat(PyObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011788{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011789 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011790 Py_ssize_t nchars, n;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011791
Georg Brandl222de0f2009-04-12 12:01:50 +000011792 if (len < 1) {
11793 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +020011794 return unicode_empty;
Georg Brandl222de0f2009-04-12 12:01:50 +000011795 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011796
Victor Stinnerc4b49542011-12-11 22:44:26 +010011797 /* no repeat, return original string */
11798 if (len == 1)
11799 return unicode_result_unchanged(str);
Tim Peters8f422462000-09-09 06:13:41 +000011800
Benjamin Petersonbac79492012-01-14 13:34:47 -050011801 if (PyUnicode_READY(str) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011802 return NULL;
11803
Victor Stinnerc759f3e2011-10-01 03:09:58 +020011804 if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
Victor Stinner67ca64c2011-10-01 02:47:29 +020011805 PyErr_SetString(PyExc_OverflowError,
11806 "repeated string is too long");
11807 return NULL;
11808 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011809 nchars = len * PyUnicode_GET_LENGTH(str);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011810
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011811 u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011812 if (!u)
11813 return NULL;
Victor Stinner67ca64c2011-10-01 02:47:29 +020011814 assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011815
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011816 if (PyUnicode_GET_LENGTH(str) == 1) {
11817 const int kind = PyUnicode_KIND(str);
11818 const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
Victor Stinner73f53b52011-12-18 03:26:31 +010011819 if (kind == PyUnicode_1BYTE_KIND) {
11820 void *to = PyUnicode_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011821 memset(to, (unsigned char)fill_char, len);
Victor Stinner73f53b52011-12-18 03:26:31 +010011822 }
11823 else if (kind == PyUnicode_2BYTE_KIND) {
11824 Py_UCS2 *ucs2 = PyUnicode_2BYTE_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011825 for (n = 0; n < len; ++n)
Victor Stinner73f53b52011-12-18 03:26:31 +010011826 ucs2[n] = fill_char;
11827 } else {
11828 Py_UCS4 *ucs4 = PyUnicode_4BYTE_DATA(u);
11829 assert(kind == PyUnicode_4BYTE_KIND);
11830 for (n = 0; n < len; ++n)
11831 ucs4[n] = fill_char;
Victor Stinner67ca64c2011-10-01 02:47:29 +020011832 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011833 }
11834 else {
11835 /* number of characters copied this far */
11836 Py_ssize_t done = PyUnicode_GET_LENGTH(str);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020011837 const Py_ssize_t char_size = PyUnicode_KIND(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011838 char *to = (char *) PyUnicode_DATA(u);
11839 Py_MEMCPY(to, PyUnicode_DATA(str),
11840 PyUnicode_GET_LENGTH(str) * char_size);
Benjamin Peterson29060642009-01-31 22:14:21 +000011841 while (done < nchars) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011842 n = (done <= nchars-done) ? done : nchars-done;
11843 Py_MEMCPY(to + (done * char_size), to, n * char_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011844 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +000011845 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011846 }
11847
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020011848 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011849 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011850}
11851
Alexander Belopolsky40018472011-02-26 01:02:56 +000011852PyObject *
11853PyUnicode_Replace(PyObject *obj,
11854 PyObject *subobj,
11855 PyObject *replobj,
11856 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011857{
11858 PyObject *self;
11859 PyObject *str1;
11860 PyObject *str2;
11861 PyObject *result;
11862
11863 self = PyUnicode_FromObject(obj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060011864 if (self == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000011865 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011866 str1 = PyUnicode_FromObject(subobj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060011867 if (str1 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011868 Py_DECREF(self);
11869 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011870 }
11871 str2 = PyUnicode_FromObject(replobj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060011872 if (str2 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011873 Py_DECREF(self);
11874 Py_DECREF(str1);
11875 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011876 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060011877 if (PyUnicode_READY(self) == -1 ||
11878 PyUnicode_READY(str1) == -1 ||
11879 PyUnicode_READY(str2) == -1)
11880 result = NULL;
11881 else
11882 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011883 Py_DECREF(self);
11884 Py_DECREF(str1);
11885 Py_DECREF(str2);
11886 return result;
11887}
11888
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011889PyDoc_STRVAR(replace__doc__,
Ezio Melottic1897e72010-06-26 18:50:39 +000011890 "S.replace(old, new[, count]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011891\n\
11892Return a copy of S with all occurrences of substring\n\
Georg Brandlf08a9dd2008-06-10 16:57:31 +000011893old replaced by new. If the optional argument count is\n\
11894given, only the first count occurrences are replaced.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011895
11896static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011897unicode_replace(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011898{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011899 PyObject *str1;
11900 PyObject *str2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011901 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011902 PyObject *result;
11903
Martin v. Löwis18e16552006-02-15 17:27:45 +000011904 if (!PyArg_ParseTuple(args, "OO|n:replace", &str1, &str2, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011905 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060011906 if (PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000011907 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011908 str1 = PyUnicode_FromObject(str1);
Benjamin Peterson22a29702012-01-02 09:00:30 -060011909 if (str1 == NULL)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011910 return NULL;
11911 str2 = PyUnicode_FromObject(str2);
Benjamin Peterson22a29702012-01-02 09:00:30 -060011912 if (str2 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011913 Py_DECREF(str1);
11914 return NULL;
Walter Dörwaldf6b56ae2003-02-09 23:42:56 +000011915 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060011916 if (PyUnicode_READY(str1) == -1 || PyUnicode_READY(str2) == -1)
11917 result = NULL;
11918 else
11919 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011920
11921 Py_DECREF(str1);
11922 Py_DECREF(str2);
11923 return result;
11924}
11925
Alexander Belopolsky40018472011-02-26 01:02:56 +000011926static PyObject *
11927unicode_repr(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011928{
Walter Dörwald79e913e2007-05-12 11:08:06 +000011929 PyObject *repr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011930 Py_ssize_t isize;
11931 Py_ssize_t osize, squote, dquote, i, o;
11932 Py_UCS4 max, quote;
11933 int ikind, okind;
11934 void *idata, *odata;
Walter Dörwald79e913e2007-05-12 11:08:06 +000011935
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011936 if (PyUnicode_READY(unicode) == -1)
Walter Dörwald79e913e2007-05-12 11:08:06 +000011937 return NULL;
11938
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011939 isize = PyUnicode_GET_LENGTH(unicode);
11940 idata = PyUnicode_DATA(unicode);
Walter Dörwald79e913e2007-05-12 11:08:06 +000011941
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011942 /* Compute length of output, quote characters, and
11943 maximum character */
11944 osize = 2; /* quotes */
11945 max = 127;
11946 squote = dquote = 0;
11947 ikind = PyUnicode_KIND(unicode);
11948 for (i = 0; i < isize; i++) {
11949 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
11950 switch (ch) {
11951 case '\'': squote++; osize++; break;
11952 case '"': dquote++; osize++; break;
11953 case '\\': case '\t': case '\r': case '\n':
11954 osize += 2; break;
11955 default:
11956 /* Fast-path ASCII */
11957 if (ch < ' ' || ch == 0x7f)
11958 osize += 4; /* \xHH */
11959 else if (ch < 0x7f)
11960 osize++;
11961 else if (Py_UNICODE_ISPRINTABLE(ch)) {
11962 osize++;
11963 max = ch > max ? ch : max;
11964 }
11965 else if (ch < 0x100)
11966 osize += 4; /* \xHH */
11967 else if (ch < 0x10000)
11968 osize += 6; /* \uHHHH */
11969 else
11970 osize += 10; /* \uHHHHHHHH */
11971 }
11972 }
11973
11974 quote = '\'';
11975 if (squote) {
11976 if (dquote)
11977 /* Both squote and dquote present. Use squote,
11978 and escape them */
11979 osize += squote;
11980 else
11981 quote = '"';
11982 }
11983
11984 repr = PyUnicode_New(osize, max);
11985 if (repr == NULL)
11986 return NULL;
11987 okind = PyUnicode_KIND(repr);
11988 odata = PyUnicode_DATA(repr);
11989
11990 PyUnicode_WRITE(okind, odata, 0, quote);
11991 PyUnicode_WRITE(okind, odata, osize-1, quote);
11992
11993 for (i = 0, o = 1; i < isize; i++) {
11994 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Walter Dörwald79e913e2007-05-12 11:08:06 +000011995
11996 /* Escape quotes and backslashes */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011997 if ((ch == quote) || (ch == '\\')) {
11998 PyUnicode_WRITE(okind, odata, o++, '\\');
11999 PyUnicode_WRITE(okind, odata, o++, ch);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012000 continue;
12001 }
12002
Benjamin Peterson29060642009-01-31 22:14:21 +000012003 /* Map special whitespace to '\t', \n', '\r' */
Georg Brandl559e5d72008-06-11 18:37:52 +000012004 if (ch == '\t') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012005 PyUnicode_WRITE(okind, odata, o++, '\\');
12006 PyUnicode_WRITE(okind, odata, o++, 't');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012007 }
12008 else if (ch == '\n') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012009 PyUnicode_WRITE(okind, odata, o++, '\\');
12010 PyUnicode_WRITE(okind, odata, o++, 'n');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012011 }
12012 else if (ch == '\r') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012013 PyUnicode_WRITE(okind, odata, o++, '\\');
12014 PyUnicode_WRITE(okind, odata, o++, 'r');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012015 }
12016
12017 /* Map non-printable US ASCII to '\xhh' */
Georg Brandl559e5d72008-06-11 18:37:52 +000012018 else if (ch < ' ' || ch == 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012019 PyUnicode_WRITE(okind, odata, o++, '\\');
12020 PyUnicode_WRITE(okind, odata, o++, 'x');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012021 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12022 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012023 }
12024
Georg Brandl559e5d72008-06-11 18:37:52 +000012025 /* Copy ASCII characters as-is */
12026 else if (ch < 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012027 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000012028 }
12029
Benjamin Peterson29060642009-01-31 22:14:21 +000012030 /* Non-ASCII characters */
Georg Brandl559e5d72008-06-11 18:37:52 +000012031 else {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012032 /* Map Unicode whitespace and control characters
Georg Brandl559e5d72008-06-11 18:37:52 +000012033 (categories Z* and C* except ASCII space)
12034 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012035 if (!Py_UNICODE_ISPRINTABLE(ch)) {
Kristján Valur Jónsson55e5dc82012-06-06 21:58:08 +000012036 PyUnicode_WRITE(okind, odata, o++, '\\');
Georg Brandl559e5d72008-06-11 18:37:52 +000012037 /* Map 8-bit characters to '\xhh' */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012038 if (ch <= 0xff) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012039 PyUnicode_WRITE(okind, odata, o++, 'x');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012040 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12041 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012042 }
Kristján Valur Jónsson55e5dc82012-06-06 21:58:08 +000012043 /* Map 16-bit characters to '\uxxxx' */
12044 else if (ch <= 0xffff) {
12045 PyUnicode_WRITE(okind, odata, o++, 'u');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012046 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12047 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12048 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12049 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012050 }
Kristján Valur Jónsson55e5dc82012-06-06 21:58:08 +000012051 /* Map 21-bit characters to '\U00xxxxxx' */
Georg Brandl559e5d72008-06-11 18:37:52 +000012052 else {
Kristján Valur Jónsson55e5dc82012-06-06 21:58:08 +000012053 PyUnicode_WRITE(okind, odata, o++, 'U');
12054 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 28) & 0xF]);
12055 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 24) & 0xF]);
12056 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 20) & 0xF]);
12057 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 16) & 0xF]);
Victor Stinnerf5cff562011-10-14 02:13:11 +020012058 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12059 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12060 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12061 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012062 }
12063 }
12064 /* Copy characters as-is */
12065 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012066 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000012067 }
12068 }
Walter Dörwald79e913e2007-05-12 11:08:06 +000012069 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012070 /* Closing quote already added at the beginning */
Victor Stinner05d11892011-10-06 01:13:58 +020012071 assert(_PyUnicode_CheckConsistency(repr, 1));
Walter Dörwald79e913e2007-05-12 11:08:06 +000012072 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012073}
12074
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012075PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012076 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012077\n\
12078Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080012079such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012080arguments start and end are interpreted as in slice notation.\n\
12081\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012082Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012083
12084static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012085unicode_rfind(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012086{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012087 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012088 Py_ssize_t start;
12089 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012090 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012091
Jesus Ceaac451502011-04-20 17:09:23 +020012092 if (!stringlib_parse_args_finds_unicode("rfind", args, &substring,
12093 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012094 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012095
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012096 if (PyUnicode_READY(self) == -1)
12097 return NULL;
12098 if (PyUnicode_READY(substring) == -1)
12099 return NULL;
12100
Victor Stinner7931d9a2011-11-04 00:22:48 +010012101 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012102
12103 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012104
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012105 if (result == -2)
12106 return NULL;
12107
Christian Heimes217cfd12007-12-02 14:31:20 +000012108 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012109}
12110
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012111PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012112 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012113\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012114Like S.rfind() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012115
12116static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012117unicode_rindex(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012118{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012119 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012120 Py_ssize_t start;
12121 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012122 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012123
Jesus Ceaac451502011-04-20 17:09:23 +020012124 if (!stringlib_parse_args_finds_unicode("rindex", args, &substring,
12125 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012126 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012127
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012128 if (PyUnicode_READY(self) == -1)
12129 return NULL;
12130 if (PyUnicode_READY(substring) == -1)
12131 return NULL;
12132
Victor Stinner7931d9a2011-11-04 00:22:48 +010012133 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012134
12135 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012136
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012137 if (result == -2)
12138 return NULL;
12139
Guido van Rossumd57fd912000-03-10 22:53:23 +000012140 if (result < 0) {
12141 PyErr_SetString(PyExc_ValueError, "substring not found");
12142 return NULL;
12143 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012144
Christian Heimes217cfd12007-12-02 14:31:20 +000012145 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012146}
12147
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012148PyDoc_STRVAR(rjust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012149 "S.rjust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012150\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012151Return S right-justified in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012152done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012153
12154static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012155unicode_rjust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012156{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012157 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012158 Py_UCS4 fillchar = ' ';
12159
Victor Stinnere9a29352011-10-01 02:14:59 +020012160 if (!PyArg_ParseTuple(args, "n|O&:rjust", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012161 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012162
Benjamin Petersonbac79492012-01-14 13:34:47 -050012163 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012164 return NULL;
12165
Victor Stinnerc4b49542011-12-11 22:44:26 +010012166 if (PyUnicode_GET_LENGTH(self) >= width)
12167 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012168
Victor Stinnerc4b49542011-12-11 22:44:26 +010012169 return pad(self, width - PyUnicode_GET_LENGTH(self), 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012170}
12171
Alexander Belopolsky40018472011-02-26 01:02:56 +000012172PyObject *
12173PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012174{
12175 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +000012176
Guido van Rossumd57fd912000-03-10 22:53:23 +000012177 s = PyUnicode_FromObject(s);
12178 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012179 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012180 if (sep != NULL) {
12181 sep = PyUnicode_FromObject(sep);
12182 if (sep == NULL) {
12183 Py_DECREF(s);
12184 return NULL;
12185 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012186 }
12187
Victor Stinner9310abb2011-10-05 00:59:23 +020012188 result = split(s, sep, maxsplit);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012189
12190 Py_DECREF(s);
12191 Py_XDECREF(sep);
12192 return result;
12193}
12194
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012195PyDoc_STRVAR(split__doc__,
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012196 "S.split(sep=None, maxsplit=-1) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012197\n\
12198Return a list of the words in S, using sep as the\n\
12199delimiter string. If maxsplit is given, at most maxsplit\n\
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000012200splits are done. If sep is not specified or is None, any\n\
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +000012201whitespace string is a separator and empty strings are\n\
12202removed from the result.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012203
12204static PyObject*
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012205unicode_split(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012206{
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012207 static char *kwlist[] = {"sep", "maxsplit", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000012208 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012209 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012210
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012211 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:split",
12212 kwlist, &substring, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012213 return NULL;
12214
12215 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012216 return split(self, NULL, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012217 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012218 return split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012219 else
Victor Stinner7931d9a2011-11-04 00:22:48 +010012220 return PyUnicode_Split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012221}
12222
Thomas Wouters477c8d52006-05-27 19:21:47 +000012223PyObject *
12224PyUnicode_Partition(PyObject *str_in, PyObject *sep_in)
12225{
12226 PyObject* str_obj;
12227 PyObject* sep_obj;
12228 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012229 int kind1, kind2, kind;
12230 void *buf1 = NULL, *buf2 = NULL;
12231 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012232
12233 str_obj = PyUnicode_FromObject(str_in);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012234 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012235 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012236 sep_obj = PyUnicode_FromObject(sep_in);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012237 if (!sep_obj) {
12238 Py_DECREF(str_obj);
12239 return NULL;
12240 }
12241 if (PyUnicode_READY(sep_obj) == -1 || PyUnicode_READY(str_obj) == -1) {
12242 Py_DECREF(sep_obj);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012243 Py_DECREF(str_obj);
12244 return NULL;
12245 }
12246
Victor Stinner14f8f022011-10-05 20:58:25 +020012247 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012248 kind2 = PyUnicode_KIND(sep_obj);
Victor Stinner14f8f022011-10-05 20:58:25 +020012249 kind = Py_MAX(kind1, kind2);
12250 buf1 = PyUnicode_DATA(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012251 if (kind1 != kind)
Victor Stinner14f8f022011-10-05 20:58:25 +020012252 buf1 = _PyUnicode_AsKind(str_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012253 if (!buf1)
12254 goto onError;
12255 buf2 = PyUnicode_DATA(sep_obj);
12256 if (kind2 != kind)
12257 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12258 if (!buf2)
12259 goto onError;
12260 len1 = PyUnicode_GET_LENGTH(str_obj);
12261 len2 = PyUnicode_GET_LENGTH(sep_obj);
12262
Benjamin Petersonead6b532011-12-20 17:23:42 -060012263 switch (PyUnicode_KIND(str_obj)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012264 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012265 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12266 out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12267 else
12268 out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012269 break;
12270 case PyUnicode_2BYTE_KIND:
12271 out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12272 break;
12273 case PyUnicode_4BYTE_KIND:
12274 out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12275 break;
12276 default:
12277 assert(0);
12278 out = 0;
12279 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012280
12281 Py_DECREF(sep_obj);
12282 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012283 if (kind1 != kind)
12284 PyMem_Free(buf1);
12285 if (kind2 != kind)
12286 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012287
12288 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012289 onError:
12290 Py_DECREF(sep_obj);
12291 Py_DECREF(str_obj);
12292 if (kind1 != kind && buf1)
12293 PyMem_Free(buf1);
12294 if (kind2 != kind && buf2)
12295 PyMem_Free(buf2);
12296 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012297}
12298
12299
12300PyObject *
12301PyUnicode_RPartition(PyObject *str_in, PyObject *sep_in)
12302{
12303 PyObject* str_obj;
12304 PyObject* sep_obj;
12305 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012306 int kind1, kind2, kind;
12307 void *buf1 = NULL, *buf2 = NULL;
12308 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012309
12310 str_obj = PyUnicode_FromObject(str_in);
12311 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012312 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012313 sep_obj = PyUnicode_FromObject(sep_in);
12314 if (!sep_obj) {
12315 Py_DECREF(str_obj);
12316 return NULL;
12317 }
12318
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012319 kind1 = PyUnicode_KIND(str_in);
12320 kind2 = PyUnicode_KIND(sep_obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +020012321 kind = Py_MAX(kind1, kind2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012322 buf1 = PyUnicode_DATA(str_in);
12323 if (kind1 != kind)
12324 buf1 = _PyUnicode_AsKind(str_in, kind);
12325 if (!buf1)
12326 goto onError;
12327 buf2 = PyUnicode_DATA(sep_obj);
12328 if (kind2 != kind)
12329 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12330 if (!buf2)
12331 goto onError;
12332 len1 = PyUnicode_GET_LENGTH(str_obj);
12333 len2 = PyUnicode_GET_LENGTH(sep_obj);
12334
Benjamin Petersonead6b532011-12-20 17:23:42 -060012335 switch (PyUnicode_KIND(str_in)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012336 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012337 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12338 out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12339 else
12340 out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012341 break;
12342 case PyUnicode_2BYTE_KIND:
12343 out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12344 break;
12345 case PyUnicode_4BYTE_KIND:
12346 out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12347 break;
12348 default:
12349 assert(0);
12350 out = 0;
12351 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012352
12353 Py_DECREF(sep_obj);
12354 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012355 if (kind1 != kind)
12356 PyMem_Free(buf1);
12357 if (kind2 != kind)
12358 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012359
12360 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012361 onError:
12362 Py_DECREF(sep_obj);
12363 Py_DECREF(str_obj);
12364 if (kind1 != kind && buf1)
12365 PyMem_Free(buf1);
12366 if (kind2 != kind && buf2)
12367 PyMem_Free(buf2);
12368 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012369}
12370
12371PyDoc_STRVAR(partition__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012372 "S.partition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012373\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012374Search for the separator sep in S, and return the part before it,\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012375the separator itself, and the part after it. If the separator is not\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012376found, return S and two empty strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012377
12378static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012379unicode_partition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012380{
Victor Stinner9310abb2011-10-05 00:59:23 +020012381 return PyUnicode_Partition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012382}
12383
12384PyDoc_STRVAR(rpartition__doc__,
Ezio Melotti5b2b2422010-01-25 11:58:28 +000012385 "S.rpartition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012386\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012387Search for the separator sep in S, starting at the end of S, and return\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012388the part before it, the separator itself, and the part after it. If the\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012389separator is not found, return two empty strings and S.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012390
12391static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012392unicode_rpartition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012393{
Victor Stinner9310abb2011-10-05 00:59:23 +020012394 return PyUnicode_RPartition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012395}
12396
Alexander Belopolsky40018472011-02-26 01:02:56 +000012397PyObject *
12398PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012399{
12400 PyObject *result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012401
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012402 s = PyUnicode_FromObject(s);
12403 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012404 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012405 if (sep != NULL) {
12406 sep = PyUnicode_FromObject(sep);
12407 if (sep == NULL) {
12408 Py_DECREF(s);
12409 return NULL;
12410 }
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012411 }
12412
Victor Stinner9310abb2011-10-05 00:59:23 +020012413 result = rsplit(s, sep, maxsplit);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012414
12415 Py_DECREF(s);
12416 Py_XDECREF(sep);
12417 return result;
12418}
12419
12420PyDoc_STRVAR(rsplit__doc__,
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012421 "S.rsplit(sep=None, maxsplit=-1) -> list of strings\n\
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012422\n\
12423Return a list of the words in S, using sep as the\n\
12424delimiter string, starting at the end of the string and\n\
12425working to the front. If maxsplit is given, at most maxsplit\n\
12426splits are done. If sep is not specified, any whitespace string\n\
12427is a separator.");
12428
12429static PyObject*
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012430unicode_rsplit(PyObject *self, PyObject *args, PyObject *kwds)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012431{
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012432 static char *kwlist[] = {"sep", "maxsplit", 0};
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012433 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012434 Py_ssize_t maxcount = -1;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012435
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012436 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:rsplit",
12437 kwlist, &substring, &maxcount))
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012438 return NULL;
12439
12440 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012441 return rsplit(self, NULL, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012442 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012443 return rsplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012444 else
Victor Stinner9310abb2011-10-05 00:59:23 +020012445 return PyUnicode_RSplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012446}
12447
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012448PyDoc_STRVAR(splitlines__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012449 "S.splitlines([keepends]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012450\n\
12451Return a list of the lines in S, breaking at line boundaries.\n\
Guido van Rossum86662912000-04-11 15:38:46 +000012452Line breaks are not included in the resulting list unless keepends\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012453is given and true.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012454
12455static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012456unicode_splitlines(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012457{
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012458 static char *kwlist[] = {"keepends", 0};
Guido van Rossum86662912000-04-11 15:38:46 +000012459 int keepends = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012460
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012461 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:splitlines",
12462 kwlist, &keepends))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012463 return NULL;
12464
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012465 return PyUnicode_Splitlines(self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012466}
12467
12468static
Guido van Rossumf15a29f2007-05-04 00:41:39 +000012469PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012470{
Victor Stinnerc4b49542011-12-11 22:44:26 +010012471 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012472}
12473
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012474PyDoc_STRVAR(swapcase__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012475 "S.swapcase() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012476\n\
12477Return a copy of S with uppercase characters converted to lowercase\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012478and vice versa.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012479
12480static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012481unicode_swapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012482{
Benjamin Petersoneea48462012-01-16 14:28:50 -050012483 if (PyUnicode_READY(self) == -1)
12484 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010012485 return case_operation(self, do_swapcase);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012486}
12487
Georg Brandlceee0772007-11-27 23:48:05 +000012488PyDoc_STRVAR(maketrans__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012489 "str.maketrans(x[, y[, z]]) -> dict (static method)\n\
Georg Brandlceee0772007-11-27 23:48:05 +000012490\n\
12491Return a translation table usable for str.translate().\n\
12492If there is only one argument, it must be a dictionary mapping Unicode\n\
12493ordinals (integers) or characters to Unicode ordinals, strings or None.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012494Character keys will be then converted to ordinals.\n\
Georg Brandlceee0772007-11-27 23:48:05 +000012495If there are two arguments, they must be strings of equal length, and\n\
12496in the resulting dictionary, each character in x will be mapped to the\n\
12497character at the same position in y. If there is a third argument, it\n\
12498must be a string, whose characters will be mapped to None in the result.");
12499
12500static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012501unicode_maketrans(PyObject *null, PyObject *args)
Georg Brandlceee0772007-11-27 23:48:05 +000012502{
12503 PyObject *x, *y = NULL, *z = NULL;
12504 PyObject *new = NULL, *key, *value;
12505 Py_ssize_t i = 0;
12506 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012507
Georg Brandlceee0772007-11-27 23:48:05 +000012508 if (!PyArg_ParseTuple(args, "O|UU:maketrans", &x, &y, &z))
12509 return NULL;
12510 new = PyDict_New();
12511 if (!new)
12512 return NULL;
12513 if (y != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012514 int x_kind, y_kind, z_kind;
12515 void *x_data, *y_data, *z_data;
12516
Georg Brandlceee0772007-11-27 23:48:05 +000012517 /* x must be a string too, of equal length */
Georg Brandlceee0772007-11-27 23:48:05 +000012518 if (!PyUnicode_Check(x)) {
12519 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
12520 "be a string if there is a second argument");
12521 goto err;
12522 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012523 if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012524 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
12525 "arguments must have equal length");
12526 goto err;
12527 }
12528 /* create entries for translating chars in x to those in y */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012529 x_kind = PyUnicode_KIND(x);
12530 y_kind = PyUnicode_KIND(y);
12531 x_data = PyUnicode_DATA(x);
12532 y_data = PyUnicode_DATA(y);
12533 for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
12534 key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060012535 if (!key)
Georg Brandlceee0772007-11-27 23:48:05 +000012536 goto err;
Benjamin Peterson822c7902011-12-20 13:32:50 -060012537 value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060012538 if (!value) {
12539 Py_DECREF(key);
12540 goto err;
12541 }
Georg Brandlceee0772007-11-27 23:48:05 +000012542 res = PyDict_SetItem(new, key, value);
12543 Py_DECREF(key);
12544 Py_DECREF(value);
12545 if (res < 0)
12546 goto err;
12547 }
12548 /* create entries for deleting chars in z */
12549 if (z != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012550 z_kind = PyUnicode_KIND(z);
12551 z_data = PyUnicode_DATA(z);
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012552 for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012553 key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000012554 if (!key)
12555 goto err;
12556 res = PyDict_SetItem(new, key, Py_None);
12557 Py_DECREF(key);
12558 if (res < 0)
12559 goto err;
12560 }
12561 }
12562 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012563 int kind;
12564 void *data;
12565
Georg Brandlceee0772007-11-27 23:48:05 +000012566 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +000012567 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012568 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
12569 "to maketrans it must be a dict");
12570 goto err;
12571 }
12572 /* copy entries into the new dict, converting string keys to int keys */
12573 while (PyDict_Next(x, &i, &key, &value)) {
12574 if (PyUnicode_Check(key)) {
12575 /* convert string keys to integer keys */
12576 PyObject *newkey;
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012577 if (PyUnicode_GET_LENGTH(key) != 1) {
Georg Brandlceee0772007-11-27 23:48:05 +000012578 PyErr_SetString(PyExc_ValueError, "string keys in translate "
12579 "table must be of length 1");
12580 goto err;
12581 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012582 kind = PyUnicode_KIND(key);
12583 data = PyUnicode_DATA(key);
12584 newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
Georg Brandlceee0772007-11-27 23:48:05 +000012585 if (!newkey)
12586 goto err;
12587 res = PyDict_SetItem(new, newkey, value);
12588 Py_DECREF(newkey);
12589 if (res < 0)
12590 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +000012591 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012592 /* just keep integer keys */
12593 if (PyDict_SetItem(new, key, value) < 0)
12594 goto err;
12595 } else {
12596 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
12597 "be strings or integers");
12598 goto err;
12599 }
12600 }
12601 }
12602 return new;
12603 err:
12604 Py_DECREF(new);
12605 return NULL;
12606}
12607
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012608PyDoc_STRVAR(translate__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012609 "S.translate(table) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012610\n\
12611Return a copy of the string S, where all characters have been mapped\n\
12612through the given translation table, which must be a mapping of\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012613Unicode ordinals to Unicode ordinals, strings, or None.\n\
Walter Dörwald5c1ee172002-09-04 20:31:32 +000012614Unmapped characters are left untouched. Characters mapped to None\n\
12615are deleted.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012616
12617static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012618unicode_translate(PyObject *self, PyObject *table)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012619{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012620 return _PyUnicode_TranslateCharmap(self, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012621}
12622
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012623PyDoc_STRVAR(upper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012624 "S.upper() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012625\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012626Return a copy of S converted to uppercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012627
12628static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012629unicode_upper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012630{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050012631 if (PyUnicode_READY(self) == -1)
12632 return NULL;
12633 if (PyUnicode_IS_ASCII(self))
12634 return ascii_upper_or_lower(self, 0);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010012635 return case_operation(self, do_upper);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012636}
12637
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012638PyDoc_STRVAR(zfill__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012639 "S.zfill(width) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012640\n\
Benjamin Peterson9aa42992008-09-10 21:57:34 +000012641Pad a numeric string S with zeros on the left, to fill a field\n\
12642of the specified width. The string S is never truncated.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012643
12644static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012645unicode_zfill(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012646{
Martin v. Löwis18e16552006-02-15 17:27:45 +000012647 Py_ssize_t fill;
Victor Stinner9310abb2011-10-05 00:59:23 +020012648 PyObject *u;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012649 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012650 int kind;
12651 void *data;
12652 Py_UCS4 chr;
12653
Martin v. Löwis18e16552006-02-15 17:27:45 +000012654 if (!PyArg_ParseTuple(args, "n:zfill", &width))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012655 return NULL;
12656
Benjamin Petersonbac79492012-01-14 13:34:47 -050012657 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010012658 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012659
Victor Stinnerc4b49542011-12-11 22:44:26 +010012660 if (PyUnicode_GET_LENGTH(self) >= width)
12661 return unicode_result_unchanged(self);
12662
12663 fill = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012664
12665 u = pad(self, fill, 0, '0');
12666
Walter Dörwald068325e2002-04-15 13:36:47 +000012667 if (u == NULL)
12668 return NULL;
12669
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012670 kind = PyUnicode_KIND(u);
12671 data = PyUnicode_DATA(u);
12672 chr = PyUnicode_READ(kind, data, fill);
12673
12674 if (chr == '+' || chr == '-') {
Guido van Rossumd57fd912000-03-10 22:53:23 +000012675 /* move sign to beginning of string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012676 PyUnicode_WRITE(kind, data, 0, chr);
12677 PyUnicode_WRITE(kind, data, fill, '0');
Guido van Rossumd57fd912000-03-10 22:53:23 +000012678 }
12679
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012680 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +010012681 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012682}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012683
12684#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012685static PyObject *
12686unicode__decimal2ascii(PyObject *self)
12687{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012688 return PyUnicode_TransformDecimalAndSpaceToASCII(self);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012689}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012690#endif
12691
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012692PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012693 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012694\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000012695Return True if S starts with the specified prefix, False otherwise.\n\
12696With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012697With optional end, stop comparing S at that position.\n\
12698prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012699
12700static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012701unicode_startswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000012702 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012703{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012704 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012705 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012706 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012707 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012708 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012709
Jesus Ceaac451502011-04-20 17:09:23 +020012710 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000012711 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012712 if (PyTuple_Check(subobj)) {
12713 Py_ssize_t i;
12714 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012715 substring = PyUnicode_FromObject(PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012716 if (substring == NULL)
12717 return NULL;
12718 result = tailmatch(self, substring, start, end, -1);
12719 Py_DECREF(substring);
12720 if (result) {
12721 Py_RETURN_TRUE;
12722 }
12723 }
12724 /* nothing matched */
12725 Py_RETURN_FALSE;
12726 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012727 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030012728 if (substring == NULL) {
12729 if (PyErr_ExceptionMatches(PyExc_TypeError))
12730 PyErr_Format(PyExc_TypeError, "startswith first arg must be str or "
12731 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000012732 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030012733 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012734 result = tailmatch(self, substring, start, end, -1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012735 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012736 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012737}
12738
12739
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012740PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012741 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012742\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000012743Return True if S ends with the specified suffix, False otherwise.\n\
12744With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012745With optional end, stop comparing S at that position.\n\
12746suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012747
12748static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012749unicode_endswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000012750 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012751{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012752 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012753 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012754 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012755 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012756 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012757
Jesus Ceaac451502011-04-20 17:09:23 +020012758 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000012759 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012760 if (PyTuple_Check(subobj)) {
12761 Py_ssize_t i;
12762 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012763 substring = PyUnicode_FromObject(
Benjamin Peterson29060642009-01-31 22:14:21 +000012764 PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012765 if (substring == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000012766 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012767 result = tailmatch(self, substring, start, end, +1);
12768 Py_DECREF(substring);
12769 if (result) {
12770 Py_RETURN_TRUE;
12771 }
12772 }
12773 Py_RETURN_FALSE;
12774 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012775 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030012776 if (substring == NULL) {
12777 if (PyErr_ExceptionMatches(PyExc_TypeError))
12778 PyErr_Format(PyExc_TypeError, "endswith first arg must be str or "
12779 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000012780 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030012781 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012782 result = tailmatch(self, substring, start, end, +1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012783 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012784 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012785}
12786
Victor Stinner202fdca2012-05-07 12:47:02 +020012787Py_LOCAL_INLINE(void)
Victor Stinner3b1a74a2012-05-09 22:25:00 +020012788_PyUnicodeWriter_Update(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020012789{
Victor Stinnerd3f08822012-05-29 12:57:52 +020012790 writer->size = PyUnicode_GET_LENGTH(writer->buffer);
Victor Stinner202fdca2012-05-07 12:47:02 +020012791 writer->maxchar = PyUnicode_MAX_CHAR_VALUE(writer->buffer);
12792 writer->data = PyUnicode_DATA(writer->buffer);
12793 writer->kind = PyUnicode_KIND(writer->buffer);
12794}
12795
Victor Stinnerd3f08822012-05-29 12:57:52 +020012796void
12797_PyUnicodeWriter_Init(_PyUnicodeWriter *writer, Py_ssize_t min_length)
Victor Stinner202fdca2012-05-07 12:47:02 +020012798{
Victor Stinnerd3f08822012-05-29 12:57:52 +020012799 memset(writer, 0, sizeof(*writer));
12800#ifdef Py_DEBUG
12801 writer->kind = 5; /* invalid kind */
12802#endif
12803 writer->min_length = Py_MAX(min_length, 100);
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012804 writer->overallocate = (min_length > 0);
Victor Stinner202fdca2012-05-07 12:47:02 +020012805}
12806
Victor Stinnerd3f08822012-05-29 12:57:52 +020012807int
12808_PyUnicodeWriter_PrepareInternal(_PyUnicodeWriter *writer,
12809 Py_ssize_t length, Py_UCS4 maxchar)
Victor Stinner202fdca2012-05-07 12:47:02 +020012810{
12811 Py_ssize_t newlen;
12812 PyObject *newbuffer;
12813
Victor Stinnerd3f08822012-05-29 12:57:52 +020012814 assert(length > 0);
12815
Victor Stinner202fdca2012-05-07 12:47:02 +020012816 if (length > PY_SSIZE_T_MAX - writer->pos) {
12817 PyErr_NoMemory();
12818 return -1;
12819 }
12820 newlen = writer->pos + length;
12821
Victor Stinnerd3f08822012-05-29 12:57:52 +020012822 if (writer->buffer == NULL) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012823 if (writer->overallocate) {
Victor Stinnerd3f08822012-05-29 12:57:52 +020012824 /* overallocate 25% to limit the number of resize */
12825 if (newlen <= (PY_SSIZE_T_MAX - newlen / 4))
12826 newlen += newlen / 4;
12827 if (newlen < writer->min_length)
12828 newlen = writer->min_length;
12829 }
12830 writer->buffer = PyUnicode_New(newlen, maxchar);
12831 if (writer->buffer == NULL)
12832 return -1;
12833 _PyUnicodeWriter_Update(writer);
12834 return 0;
12835 }
Victor Stinner202fdca2012-05-07 12:47:02 +020012836
Victor Stinnerd3f08822012-05-29 12:57:52 +020012837 if (newlen > writer->size) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012838 if (writer->overallocate) {
Victor Stinnerd3f08822012-05-29 12:57:52 +020012839 /* overallocate 25% to limit the number of resize */
12840 if (newlen <= (PY_SSIZE_T_MAX - newlen / 4))
12841 newlen += newlen / 4;
12842 if (newlen < writer->min_length)
12843 newlen = writer->min_length;
12844 }
12845
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012846 if (maxchar > writer->maxchar || writer->readonly) {
Victor Stinner202fdca2012-05-07 12:47:02 +020012847 /* resize + widen */
12848 newbuffer = PyUnicode_New(newlen, maxchar);
12849 if (newbuffer == NULL)
12850 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020012851 _PyUnicode_FastCopyCharacters(newbuffer, 0,
12852 writer->buffer, 0, writer->pos);
Victor Stinner202fdca2012-05-07 12:47:02 +020012853 Py_DECREF(writer->buffer);
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012854 writer->readonly = 0;
Victor Stinner202fdca2012-05-07 12:47:02 +020012855 }
12856 else {
12857 newbuffer = resize_compact(writer->buffer, newlen);
12858 if (newbuffer == NULL)
12859 return -1;
12860 }
12861 writer->buffer = newbuffer;
Victor Stinner3b1a74a2012-05-09 22:25:00 +020012862 _PyUnicodeWriter_Update(writer);
Victor Stinner202fdca2012-05-07 12:47:02 +020012863 }
12864 else if (maxchar > writer->maxchar) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012865 assert(!writer->readonly);
Victor Stinnerd3f08822012-05-29 12:57:52 +020012866 newbuffer = PyUnicode_New(writer->size, maxchar);
12867 if (newbuffer == NULL)
Victor Stinner202fdca2012-05-07 12:47:02 +020012868 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020012869 _PyUnicode_FastCopyCharacters(newbuffer, 0,
12870 writer->buffer, 0, writer->pos);
12871 Py_DECREF(writer->buffer);
12872 writer->buffer = newbuffer;
Victor Stinner3b1a74a2012-05-09 22:25:00 +020012873 _PyUnicodeWriter_Update(writer);
Victor Stinner202fdca2012-05-07 12:47:02 +020012874 }
12875 return 0;
12876}
12877
Victor Stinnerd3f08822012-05-29 12:57:52 +020012878int
12879_PyUnicodeWriter_WriteStr(_PyUnicodeWriter *writer, PyObject *str)
12880{
12881 Py_UCS4 maxchar;
12882 Py_ssize_t len;
12883
12884 if (PyUnicode_READY(str) == -1)
12885 return -1;
12886 len = PyUnicode_GET_LENGTH(str);
12887 if (len == 0)
12888 return 0;
12889 maxchar = PyUnicode_MAX_CHAR_VALUE(str);
12890 if (maxchar > writer->maxchar || len > writer->size - writer->pos) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012891 if (writer->buffer == NULL && !writer->overallocate) {
Victor Stinnerd3f08822012-05-29 12:57:52 +020012892 Py_INCREF(str);
12893 writer->buffer = str;
12894 _PyUnicodeWriter_Update(writer);
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012895 writer->readonly = 1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020012896 writer->size = 0;
12897 writer->pos += len;
12898 return 0;
12899 }
12900 if (_PyUnicodeWriter_PrepareInternal(writer, len, maxchar) == -1)
12901 return -1;
12902 }
12903 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
12904 str, 0, len);
12905 writer->pos += len;
12906 return 0;
12907}
12908
12909PyObject *
Victor Stinner3b1a74a2012-05-09 22:25:00 +020012910_PyUnicodeWriter_Finish(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020012911{
Victor Stinnerd3f08822012-05-29 12:57:52 +020012912 if (writer->pos == 0) {
12913 Py_XDECREF(writer->buffer);
12914 Py_INCREF(unicode_empty);
12915 return unicode_empty;
12916 }
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012917 if (writer->readonly) {
Victor Stinnerd3f08822012-05-29 12:57:52 +020012918 assert(PyUnicode_GET_LENGTH(writer->buffer) == writer->pos);
12919 return writer->buffer;
12920 }
12921 if (PyUnicode_GET_LENGTH(writer->buffer) != writer->pos) {
12922 PyObject *newbuffer;
12923 newbuffer = resize_compact(writer->buffer, writer->pos);
12924 if (newbuffer == NULL) {
12925 Py_DECREF(writer->buffer);
12926 return NULL;
12927 }
12928 writer->buffer = newbuffer;
Victor Stinner202fdca2012-05-07 12:47:02 +020012929 }
Victor Stinnerf59c28c2012-05-09 03:24:14 +020012930 assert(_PyUnicode_CheckConsistency(writer->buffer, 1));
Victor Stinner202fdca2012-05-07 12:47:02 +020012931 return writer->buffer;
12932}
12933
Victor Stinnerd3f08822012-05-29 12:57:52 +020012934void
Victor Stinner3b1a74a2012-05-09 22:25:00 +020012935_PyUnicodeWriter_Dealloc(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020012936{
12937 Py_CLEAR(writer->buffer);
12938}
12939
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012940#include "stringlib/unicode_format.h"
Eric Smith8c663262007-08-25 02:26:07 +000012941
12942PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012943 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000012944\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012945Return a formatted version of S, using substitutions from args and kwargs.\n\
12946The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +000012947
Eric Smith27bbca62010-11-04 17:06:58 +000012948PyDoc_STRVAR(format_map__doc__,
12949 "S.format_map(mapping) -> str\n\
12950\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012951Return a formatted version of S, using substitutions from mapping.\n\
12952The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +000012953
Eric Smith4a7d76d2008-05-30 18:10:19 +000012954static PyObject *
12955unicode__format__(PyObject* self, PyObject* args)
12956{
Victor Stinnerd3f08822012-05-29 12:57:52 +020012957 PyObject *format_spec;
12958 _PyUnicodeWriter writer;
12959 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +000012960
12961 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
12962 return NULL;
12963
Victor Stinnerd3f08822012-05-29 12:57:52 +020012964 if (PyUnicode_READY(self) == -1)
12965 return NULL;
12966 _PyUnicodeWriter_Init(&writer, 0);
12967 ret = _PyUnicode_FormatAdvancedWriter(&writer,
12968 self, format_spec, 0,
12969 PyUnicode_GET_LENGTH(format_spec));
12970 if (ret == -1) {
12971 _PyUnicodeWriter_Dealloc(&writer);
12972 return NULL;
12973 }
12974 return _PyUnicodeWriter_Finish(&writer);
Eric Smith4a7d76d2008-05-30 18:10:19 +000012975}
12976
Eric Smith8c663262007-08-25 02:26:07 +000012977PyDoc_STRVAR(p_format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012978 "S.__format__(format_spec) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000012979\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012980Return a formatted version of S as described by format_spec.");
Eric Smith8c663262007-08-25 02:26:07 +000012981
12982static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012983unicode__sizeof__(PyObject *v)
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012984{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012985 Py_ssize_t size;
12986
12987 /* If it's a compact object, account for base structure +
12988 character data. */
12989 if (PyUnicode_IS_COMPACT_ASCII(v))
12990 size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(v) + 1;
12991 else if (PyUnicode_IS_COMPACT(v))
12992 size = sizeof(PyCompactUnicodeObject) +
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012993 (PyUnicode_GET_LENGTH(v) + 1) * PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012994 else {
12995 /* If it is a two-block object, account for base object, and
12996 for character block if present. */
12997 size = sizeof(PyUnicodeObject);
Victor Stinnerc3c74152011-10-02 20:39:55 +020012998 if (_PyUnicode_DATA_ANY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012999 size += (PyUnicode_GET_LENGTH(v) + 1) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013000 PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013001 }
13002 /* If the wstr pointer is present, account for it unless it is shared
Victor Stinnera3be6132011-10-03 02:16:37 +020013003 with the data pointer. Check if the data is not shared. */
Victor Stinner03490912011-10-03 23:45:12 +020013004 if (_PyUnicode_HAS_WSTR_MEMORY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013005 size += (PyUnicode_WSTR_LENGTH(v) + 1) * sizeof(wchar_t);
Victor Stinner829c0ad2011-10-03 01:08:02 +020013006 if (_PyUnicode_HAS_UTF8_MEMORY(v))
Victor Stinnere90fe6a2011-10-01 16:48:13 +020013007 size += PyUnicode_UTF8_LENGTH(v) + 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013008
13009 return PyLong_FromSsize_t(size);
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013010}
13011
13012PyDoc_STRVAR(sizeof__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013013 "S.__sizeof__() -> size of S in memory, in bytes");
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013014
13015static PyObject *
Victor Stinner034f6cf2011-09-30 02:26:44 +020013016unicode_getnewargs(PyObject *v)
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013017{
Victor Stinnerbf6e5602011-12-12 01:53:47 +010013018 PyObject *copy = _PyUnicode_Copy(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013019 if (!copy)
13020 return NULL;
13021 return Py_BuildValue("(N)", copy);
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013022}
13023
Guido van Rossumd57fd912000-03-10 22:53:23 +000013024static PyMethodDef unicode_methods[] = {
Benjamin Peterson28a4dce2010-12-12 01:33:04 +000013025 {"encode", (PyCFunction) unicode_encode, METH_VARARGS | METH_KEYWORDS, encode__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013026 {"replace", (PyCFunction) unicode_replace, METH_VARARGS, replace__doc__},
Ezio Melotticda6b6d2012-02-26 09:39:55 +020013027 {"split", (PyCFunction) unicode_split, METH_VARARGS | METH_KEYWORDS, split__doc__},
13028 {"rsplit", (PyCFunction) unicode_rsplit, METH_VARARGS | METH_KEYWORDS, rsplit__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013029 {"join", (PyCFunction) unicode_join, METH_O, join__doc__},
13030 {"capitalize", (PyCFunction) unicode_capitalize, METH_NOARGS, capitalize__doc__},
Benjamin Petersond5890c82012-01-14 13:23:30 -050013031 {"casefold", (PyCFunction) unicode_casefold, METH_NOARGS, casefold__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013032 {"title", (PyCFunction) unicode_title, METH_NOARGS, title__doc__},
13033 {"center", (PyCFunction) unicode_center, METH_VARARGS, center__doc__},
13034 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
13035 {"expandtabs", (PyCFunction) unicode_expandtabs, METH_VARARGS, expandtabs__doc__},
13036 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013037 {"partition", (PyCFunction) unicode_partition, METH_O, partition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013038 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
13039 {"ljust", (PyCFunction) unicode_ljust, METH_VARARGS, ljust__doc__},
13040 {"lower", (PyCFunction) unicode_lower, METH_NOARGS, lower__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013041 {"lstrip", (PyCFunction) unicode_lstrip, METH_VARARGS, lstrip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013042 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
13043 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
13044 {"rjust", (PyCFunction) unicode_rjust, METH_VARARGS, rjust__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013045 {"rstrip", (PyCFunction) unicode_rstrip, METH_VARARGS, rstrip__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013046 {"rpartition", (PyCFunction) unicode_rpartition, METH_O, rpartition__doc__},
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010013047 {"splitlines", (PyCFunction) unicode_splitlines, METH_VARARGS | METH_KEYWORDS, splitlines__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013048 {"strip", (PyCFunction) unicode_strip, METH_VARARGS, strip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013049 {"swapcase", (PyCFunction) unicode_swapcase, METH_NOARGS, swapcase__doc__},
13050 {"translate", (PyCFunction) unicode_translate, METH_O, translate__doc__},
13051 {"upper", (PyCFunction) unicode_upper, METH_NOARGS, upper__doc__},
13052 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
13053 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
13054 {"islower", (PyCFunction) unicode_islower, METH_NOARGS, islower__doc__},
13055 {"isupper", (PyCFunction) unicode_isupper, METH_NOARGS, isupper__doc__},
13056 {"istitle", (PyCFunction) unicode_istitle, METH_NOARGS, istitle__doc__},
13057 {"isspace", (PyCFunction) unicode_isspace, METH_NOARGS, isspace__doc__},
13058 {"isdecimal", (PyCFunction) unicode_isdecimal, METH_NOARGS, isdecimal__doc__},
13059 {"isdigit", (PyCFunction) unicode_isdigit, METH_NOARGS, isdigit__doc__},
13060 {"isnumeric", (PyCFunction) unicode_isnumeric, METH_NOARGS, isnumeric__doc__},
13061 {"isalpha", (PyCFunction) unicode_isalpha, METH_NOARGS, isalpha__doc__},
13062 {"isalnum", (PyCFunction) unicode_isalnum, METH_NOARGS, isalnum__doc__},
Martin v. Löwis47383402007-08-15 07:32:56 +000013063 {"isidentifier", (PyCFunction) unicode_isidentifier, METH_NOARGS, isidentifier__doc__},
Georg Brandl559e5d72008-06-11 18:37:52 +000013064 {"isprintable", (PyCFunction) unicode_isprintable, METH_NOARGS, isprintable__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013065 {"zfill", (PyCFunction) unicode_zfill, METH_VARARGS, zfill__doc__},
Eric Smith9cd1e092007-08-31 18:39:38 +000013066 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +000013067 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
Eric Smith4a7d76d2008-05-30 18:10:19 +000013068 {"__format__", (PyCFunction) unicode__format__, METH_VARARGS, p_format__doc__},
Georg Brandlceee0772007-11-27 23:48:05 +000013069 {"maketrans", (PyCFunction) unicode_maketrans,
13070 METH_VARARGS | METH_STATIC, maketrans__doc__},
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013071 {"__sizeof__", (PyCFunction) unicode__sizeof__, METH_NOARGS, sizeof__doc__},
Walter Dörwald068325e2002-04-15 13:36:47 +000013072#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013073 /* These methods are just used for debugging the implementation. */
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013074 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013075#endif
13076
Benjamin Peterson14339b62009-01-31 16:36:08 +000013077 {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013078 {NULL, NULL}
13079};
13080
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013081static PyObject *
13082unicode_mod(PyObject *v, PyObject *w)
13083{
Brian Curtindfc80e32011-08-10 20:28:54 -050013084 if (!PyUnicode_Check(v))
13085 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson29060642009-01-31 22:14:21 +000013086 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013087}
13088
13089static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013090 0, /*nb_add*/
13091 0, /*nb_subtract*/
13092 0, /*nb_multiply*/
13093 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013094};
13095
Guido van Rossumd57fd912000-03-10 22:53:23 +000013096static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013097 (lenfunc) unicode_length, /* sq_length */
13098 PyUnicode_Concat, /* sq_concat */
13099 (ssizeargfunc) unicode_repeat, /* sq_repeat */
13100 (ssizeargfunc) unicode_getitem, /* sq_item */
13101 0, /* sq_slice */
13102 0, /* sq_ass_item */
13103 0, /* sq_ass_slice */
13104 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013105};
13106
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013107static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013108unicode_subscript(PyObject* self, PyObject* item)
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013109{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013110 if (PyUnicode_READY(self) == -1)
13111 return NULL;
13112
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000013113 if (PyIndex_Check(item)) {
13114 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013115 if (i == -1 && PyErr_Occurred())
13116 return NULL;
13117 if (i < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013118 i += PyUnicode_GET_LENGTH(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013119 return unicode_getitem(self, i);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013120 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000013121 Py_ssize_t start, stop, step, slicelength, cur, i;
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013122 PyObject *result;
13123 void *src_data, *dest_data;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013124 int src_kind, dest_kind;
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013125 Py_UCS4 ch, max_char, kind_limit;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013126
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013127 if (PySlice_GetIndicesEx(item, PyUnicode_GET_LENGTH(self),
Benjamin Peterson29060642009-01-31 22:14:21 +000013128 &start, &stop, &step, &slicelength) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013129 return NULL;
13130 }
13131
13132 if (slicelength <= 0) {
Victor Stinner382955f2011-12-11 21:44:00 +010013133 Py_INCREF(unicode_empty);
13134 return unicode_empty;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013135 } else if (start == 0 && step == 1 &&
Victor Stinnerc4b49542011-12-11 22:44:26 +010013136 slicelength == PyUnicode_GET_LENGTH(self)) {
13137 return unicode_result_unchanged(self);
Thomas Woutersed03b412007-08-28 21:37:11 +000013138 } else if (step == 1) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013139 return PyUnicode_Substring(self,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013140 start, start + slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013141 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013142 /* General case */
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013143 src_kind = PyUnicode_KIND(self);
13144 src_data = PyUnicode_DATA(self);
Victor Stinner55c99112011-10-13 01:17:06 +020013145 if (!PyUnicode_IS_ASCII(self)) {
13146 kind_limit = kind_maxchar_limit(src_kind);
13147 max_char = 0;
13148 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
13149 ch = PyUnicode_READ(src_kind, src_data, cur);
13150 if (ch > max_char) {
13151 max_char = ch;
13152 if (max_char >= kind_limit)
13153 break;
13154 }
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013155 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013156 }
Victor Stinner55c99112011-10-13 01:17:06 +020013157 else
13158 max_char = 127;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013159 result = PyUnicode_New(slicelength, max_char);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013160 if (result == NULL)
13161 return NULL;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013162 dest_kind = PyUnicode_KIND(result);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013163 dest_data = PyUnicode_DATA(result);
13164
13165 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013166 Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
13167 PyUnicode_WRITE(dest_kind, dest_data, i, ch);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013168 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013169 assert(_PyUnicode_CheckConsistency(result, 1));
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013170 return result;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013171 } else {
13172 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
13173 return NULL;
13174 }
13175}
13176
13177static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013178 (lenfunc)unicode_length, /* mp_length */
13179 (binaryfunc)unicode_subscript, /* mp_subscript */
13180 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013181};
13182
Guido van Rossumd57fd912000-03-10 22:53:23 +000013183
Guido van Rossumd57fd912000-03-10 22:53:23 +000013184/* Helpers for PyUnicode_Format() */
13185
13186static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +000013187getnextarg(PyObject *args, Py_ssize_t arglen, Py_ssize_t *p_argidx)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013188{
Martin v. Löwis18e16552006-02-15 17:27:45 +000013189 Py_ssize_t argidx = *p_argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013190 if (argidx < arglen) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013191 (*p_argidx)++;
13192 if (arglen < 0)
13193 return args;
13194 else
13195 return PyTuple_GetItem(args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013196 }
13197 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013198 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013199 return NULL;
13200}
13201
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013202/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013203
Victor Stinnerd3f08822012-05-29 12:57:52 +020013204static int
13205formatfloat(PyObject *v, int flags, int prec, int type,
13206 PyObject **p_output, _PyUnicodeWriter *writer)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013207{
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013208 char *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013209 double x;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013210 Py_ssize_t len;
Tim Petersced69f82003-09-16 20:30:58 +000013211
Guido van Rossumd57fd912000-03-10 22:53:23 +000013212 x = PyFloat_AsDouble(v);
13213 if (x == -1.0 && PyErr_Occurred())
Victor Stinnerd3f08822012-05-29 12:57:52 +020013214 return -1;
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013215
Guido van Rossumd57fd912000-03-10 22:53:23 +000013216 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000013217 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +000013218
Eric Smith0923d1d2009-04-16 20:16:10 +000013219 p = PyOS_double_to_string(x, type, prec,
13220 (flags & F_ALT) ? Py_DTSF_ALT : 0, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013221 if (p == NULL)
Victor Stinnerd3f08822012-05-29 12:57:52 +020013222 return -1;
13223 len = strlen(p);
13224 if (writer) {
Christian Heimesf4f99392012-09-10 11:48:41 +020013225 if (_PyUnicodeWriter_Prepare(writer, len, 127) == -1) {
13226 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013227 return -1;
Christian Heimesf4f99392012-09-10 11:48:41 +020013228 }
Victor Stinner184252a2012-06-16 02:57:41 +020013229 unicode_write_cstr(writer->buffer, writer->pos, p, len);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013230 writer->pos += len;
13231 }
13232 else
13233 *p_output = _PyUnicode_FromASCII(p, len);
Eric Smith0923d1d2009-04-16 20:16:10 +000013234 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013235 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013236}
13237
Victor Stinnerd0880d52012-04-27 23:40:13 +020013238/* formatlong() emulates the format codes d, u, o, x and X, and
13239 * the F_ALT flag, for Python's long (unbounded) ints. It's not used for
13240 * Python's regular ints.
13241 * Return value: a new PyUnicodeObject*, or NULL if error.
13242 * The output string is of the form
13243 * "-"? ("0x" | "0X")? digit+
13244 * "0x"/"0X" are present only for x and X conversions, with F_ALT
13245 * set in flags. The case of hex digits will be correct,
13246 * There will be at least prec digits, zero-filled on the left if
13247 * necessary to get that many.
13248 * val object to be converted
13249 * flags bitmask of format flags; only F_ALT is looked at
13250 * prec minimum number of digits; 0-fill on left if needed
13251 * type a character in [duoxX]; u acts the same as d
13252 *
13253 * CAUTION: o, x and X conversions on regular ints can never
13254 * produce a '-' sign, but can for Python's unbounded ints.
13255 */
Tim Peters38fd5b62000-09-21 05:43:11 +000013256static PyObject*
13257formatlong(PyObject *val, int flags, int prec, int type)
13258{
Victor Stinnerd0880d52012-04-27 23:40:13 +020013259 PyObject *result = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013260 char *buf;
Victor Stinnerd0880d52012-04-27 23:40:13 +020013261 Py_ssize_t i;
13262 int sign; /* 1 if '-', else 0 */
13263 int len; /* number of characters */
13264 Py_ssize_t llen;
13265 int numdigits; /* len == numnondigits + numdigits */
13266 int numnondigits = 0;
Tim Peters38fd5b62000-09-21 05:43:11 +000013267
Victor Stinnerd0880d52012-04-27 23:40:13 +020013268 /* Avoid exceeding SSIZE_T_MAX */
13269 if (prec > INT_MAX-3) {
13270 PyErr_SetString(PyExc_OverflowError,
13271 "precision too large");
Benjamin Peterson14339b62009-01-31 16:36:08 +000013272 return NULL;
Victor Stinnerd0880d52012-04-27 23:40:13 +020013273 }
13274
13275 assert(PyLong_Check(val));
13276
13277 switch (type) {
13278 case 'd':
13279 case 'u':
13280 /* Special-case boolean: we want 0/1 */
Victor Stinnerb11d91d2012-04-28 00:25:34 +020013281 if (PyBool_Check(val))
13282 result = PyNumber_ToBase(val, 10);
13283 else
13284 result = Py_TYPE(val)->tp_str(val);
Victor Stinnerd0880d52012-04-27 23:40:13 +020013285 break;
13286 case 'o':
13287 numnondigits = 2;
13288 result = PyNumber_ToBase(val, 8);
13289 break;
13290 case 'x':
13291 case 'X':
13292 numnondigits = 2;
13293 result = PyNumber_ToBase(val, 16);
13294 break;
13295 default:
13296 assert(!"'type' not in [duoxX]");
13297 }
13298 if (!result)
13299 return NULL;
13300
13301 assert(unicode_modifiable(result));
13302 assert(PyUnicode_IS_READY(result));
13303 assert(PyUnicode_IS_ASCII(result));
13304
13305 /* To modify the string in-place, there can only be one reference. */
13306 if (Py_REFCNT(result) != 1) {
13307 PyErr_BadInternalCall();
13308 return NULL;
13309 }
13310 buf = PyUnicode_DATA(result);
13311 llen = PyUnicode_GET_LENGTH(result);
13312 if (llen > INT_MAX) {
13313 PyErr_SetString(PyExc_ValueError,
13314 "string too large in _PyBytes_FormatLong");
13315 return NULL;
13316 }
13317 len = (int)llen;
13318 sign = buf[0] == '-';
13319 numnondigits += sign;
13320 numdigits = len - numnondigits;
13321 assert(numdigits > 0);
13322
13323 /* Get rid of base marker unless F_ALT */
13324 if (((flags & F_ALT) == 0 &&
13325 (type == 'o' || type == 'x' || type == 'X'))) {
13326 assert(buf[sign] == '0');
13327 assert(buf[sign+1] == 'x' || buf[sign+1] == 'X' ||
13328 buf[sign+1] == 'o');
13329 numnondigits -= 2;
13330 buf += 2;
13331 len -= 2;
13332 if (sign)
13333 buf[0] = '-';
13334 assert(len == numnondigits + numdigits);
13335 assert(numdigits > 0);
13336 }
13337
13338 /* Fill with leading zeroes to meet minimum width. */
13339 if (prec > numdigits) {
13340 PyObject *r1 = PyBytes_FromStringAndSize(NULL,
13341 numnondigits + prec);
13342 char *b1;
13343 if (!r1) {
13344 Py_DECREF(result);
13345 return NULL;
13346 }
13347 b1 = PyBytes_AS_STRING(r1);
13348 for (i = 0; i < numnondigits; ++i)
13349 *b1++ = *buf++;
13350 for (i = 0; i < prec - numdigits; i++)
13351 *b1++ = '0';
13352 for (i = 0; i < numdigits; i++)
13353 *b1++ = *buf++;
13354 *b1 = '\0';
13355 Py_DECREF(result);
13356 result = r1;
13357 buf = PyBytes_AS_STRING(result);
13358 len = numnondigits + prec;
13359 }
13360
13361 /* Fix up case for hex conversions. */
13362 if (type == 'X') {
13363 /* Need to convert all lower case letters to upper case.
13364 and need to convert 0x to 0X (and -0x to -0X). */
13365 for (i = 0; i < len; i++)
13366 if (buf[i] >= 'a' && buf[i] <= 'x')
13367 buf[i] -= 'a'-'A';
13368 }
13369 if (!PyUnicode_Check(result) || len != PyUnicode_GET_LENGTH(result)) {
13370 PyObject *unicode;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013371 unicode = _PyUnicode_FromASCII(buf, len);
Victor Stinnerd0880d52012-04-27 23:40:13 +020013372 Py_DECREF(result);
13373 result = unicode;
13374 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000013375 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +000013376}
13377
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013378static Py_UCS4
13379formatchar(PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013380{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000013381 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000013382 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013383 if (PyUnicode_GET_LENGTH(v) == 1) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013384 return PyUnicode_READ_CHAR(v, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +000013385 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013386 goto onError;
13387 }
13388 else {
13389 /* Integer input truncated to a character */
13390 long x;
13391 x = PyLong_AsLong(v);
13392 if (x == -1 && PyErr_Occurred())
13393 goto onError;
13394
Victor Stinner8faf8212011-12-08 22:14:11 +010013395 if (x < 0 || x > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013396 PyErr_SetString(PyExc_OverflowError,
13397 "%c arg not in range(0x110000)");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013398 return (Py_UCS4) -1;
Benjamin Peterson29060642009-01-31 22:14:21 +000013399 }
13400
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013401 return (Py_UCS4) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013402 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000013403
Benjamin Peterson29060642009-01-31 22:14:21 +000013404 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000013405 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013406 "%c requires int or char");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013407 return (Py_UCS4) -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013408}
13409
Alexander Belopolsky40018472011-02-26 01:02:56 +000013410PyObject *
13411PyUnicode_Format(PyObject *format, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013412{
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013413 Py_ssize_t fmtcnt, fmtpos, arglen, argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013414 int args_owned = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013415 PyObject *dict = NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013416 PyObject *temp = NULL;
13417 PyObject *second = NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013418 PyObject *uformat;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013419 void *fmt;
13420 enum PyUnicode_Kind kind, fmtkind;
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013421 _PyUnicodeWriter writer;
Victor Stinneree4544c2012-05-09 22:24:08 +020013422 Py_ssize_t sublen;
13423 Py_UCS4 maxchar;
Tim Petersced69f82003-09-16 20:30:58 +000013424
Guido van Rossumd57fd912000-03-10 22:53:23 +000013425 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013426 PyErr_BadInternalCall();
13427 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013428 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013429 uformat = PyUnicode_FromObject(format);
Benjamin Peterson22a29702012-01-02 09:00:30 -060013430 if (uformat == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000013431 return NULL;
Victor Stinner19294072012-10-05 00:09:33 +020013432 if (PyUnicode_READY(uformat) == -1) {
Benjamin Peterson22a29702012-01-02 09:00:30 -060013433 Py_DECREF(uformat);
Victor Stinner19294072012-10-05 00:09:33 +020013434 return NULL;
13435 }
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013436
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013437 fmt = PyUnicode_DATA(uformat);
13438 fmtkind = PyUnicode_KIND(uformat);
13439 fmtcnt = PyUnicode_GET_LENGTH(uformat);
13440 fmtpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013441
Victor Stinnerd3f08822012-05-29 12:57:52 +020013442 _PyUnicodeWriter_Init(&writer, fmtcnt + 100);
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013443
Guido van Rossumd57fd912000-03-10 22:53:23 +000013444 if (PyTuple_Check(args)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013445 arglen = PyTuple_Size(args);
13446 argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013447 }
13448 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013449 arglen = -1;
13450 argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013451 }
Benjamin Peterson28a6cfa2012-08-28 17:55:35 -040013452 if (PyMapping_Check(args) && !PyTuple_Check(args) && !PyUnicode_Check(args))
Benjamin Peterson29060642009-01-31 22:14:21 +000013453 dict = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013454
13455 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013456 if (PyUnicode_READ(fmtkind, fmt, fmtpos) != '%') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013457 Py_ssize_t nonfmtpos;
13458 nonfmtpos = fmtpos++;
13459 while (fmtcnt >= 0 &&
13460 PyUnicode_READ(fmtkind, fmt, fmtpos) != '%') {
13461 fmtpos++;
13462 fmtcnt--;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013463 }
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013464 if (fmtcnt < 0)
13465 fmtpos--;
Victor Stinneree4544c2012-05-09 22:24:08 +020013466 sublen = fmtpos - nonfmtpos;
13467 maxchar = _PyUnicode_FindMaxChar(uformat,
13468 nonfmtpos, nonfmtpos + sublen);
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013469 if (_PyUnicodeWriter_Prepare(&writer, sublen, maxchar) == -1)
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013470 goto onError;
Victor Stinneree4544c2012-05-09 22:24:08 +020013471
Victor Stinnerd3f08822012-05-29 12:57:52 +020013472 _PyUnicode_FastCopyCharacters(writer.buffer, writer.pos,
13473 uformat, nonfmtpos, sublen);
Victor Stinneree4544c2012-05-09 22:24:08 +020013474 writer.pos += sublen;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013475 }
13476 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013477 /* Got a format specifier */
13478 int flags = 0;
13479 Py_ssize_t width = -1;
13480 int prec = -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013481 Py_UCS4 c = '\0';
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013482 Py_UCS4 fill;
13483 int sign;
13484 Py_UCS4 signchar;
Benjamin Peterson29060642009-01-31 22:14:21 +000013485 int isnumok;
13486 PyObject *v = NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013487 void *pbuf = NULL;
13488 Py_ssize_t pindex, len;
Victor Stinneree4544c2012-05-09 22:24:08 +020013489 Py_UCS4 bufmaxchar;
13490 Py_ssize_t buflen;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013491
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013492 fmtpos++;
Victor Stinner438106b2012-05-02 00:41:57 +020013493 c = PyUnicode_READ(fmtkind, fmt, fmtpos);
13494 if (c == '(') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013495 Py_ssize_t keystart;
Benjamin Peterson29060642009-01-31 22:14:21 +000013496 Py_ssize_t keylen;
13497 PyObject *key;
13498 int pcount = 1;
Christian Heimesa612dc02008-02-24 13:08:18 +000013499
Benjamin Peterson29060642009-01-31 22:14:21 +000013500 if (dict == NULL) {
13501 PyErr_SetString(PyExc_TypeError,
13502 "format requires a mapping");
13503 goto onError;
13504 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013505 ++fmtpos;
Benjamin Peterson29060642009-01-31 22:14:21 +000013506 --fmtcnt;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013507 keystart = fmtpos;
Benjamin Peterson29060642009-01-31 22:14:21 +000013508 /* Skip over balanced parentheses */
13509 while (pcount > 0 && --fmtcnt >= 0) {
Victor Stinnerbff7c962012-05-03 01:44:59 +020013510 c = PyUnicode_READ(fmtkind, fmt, fmtpos);
13511 if (c == ')')
Benjamin Peterson29060642009-01-31 22:14:21 +000013512 --pcount;
Victor Stinnerbff7c962012-05-03 01:44:59 +020013513 else if (c == '(')
Benjamin Peterson29060642009-01-31 22:14:21 +000013514 ++pcount;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013515 fmtpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +000013516 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013517 keylen = fmtpos - keystart - 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000013518 if (fmtcnt < 0 || pcount > 0) {
13519 PyErr_SetString(PyExc_ValueError,
13520 "incomplete format key");
13521 goto onError;
13522 }
Victor Stinner7931d9a2011-11-04 00:22:48 +010013523 key = PyUnicode_Substring(uformat,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013524 keystart, keystart + keylen);
Benjamin Peterson29060642009-01-31 22:14:21 +000013525 if (key == NULL)
13526 goto onError;
13527 if (args_owned) {
13528 Py_DECREF(args);
13529 args_owned = 0;
13530 }
13531 args = PyObject_GetItem(dict, key);
13532 Py_DECREF(key);
13533 if (args == NULL) {
13534 goto onError;
13535 }
13536 args_owned = 1;
13537 arglen = -1;
13538 argidx = -2;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013539 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013540 while (--fmtcnt >= 0) {
Victor Stinner438106b2012-05-02 00:41:57 +020013541 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
13542 switch (c) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013543 case '-': flags |= F_LJUST; continue;
13544 case '+': flags |= F_SIGN; continue;
13545 case ' ': flags |= F_BLANK; continue;
13546 case '#': flags |= F_ALT; continue;
13547 case '0': flags |= F_ZERO; continue;
13548 }
13549 break;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013550 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013551 if (c == '*') {
13552 v = getnextarg(args, arglen, &argidx);
13553 if (v == NULL)
13554 goto onError;
13555 if (!PyLong_Check(v)) {
13556 PyErr_SetString(PyExc_TypeError,
13557 "* wants int");
13558 goto onError;
13559 }
13560 width = PyLong_AsLong(v);
13561 if (width == -1 && PyErr_Occurred())
13562 goto onError;
13563 if (width < 0) {
13564 flags |= F_LJUST;
13565 width = -width;
13566 }
13567 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013568 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013569 }
13570 else if (c >= '0' && c <= '9') {
13571 width = c - '0';
13572 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013573 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013574 if (c < '0' || c > '9')
13575 break;
Martin v. Löwisb05c0732012-05-15 13:45:49 +020013576 /* Since c is unsigned, the RHS would end up as unsigned,
13577 mixing signed and unsigned comparison. Since c is between
13578 '0' and '9', casting to int is safe. */
13579 if (width > (PY_SSIZE_T_MAX - ((int)c - '0')) / 10) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013580 PyErr_SetString(PyExc_ValueError,
13581 "width too big");
Benjamin Peterson14339b62009-01-31 16:36:08 +000013582 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +000013583 }
13584 width = width*10 + (c - '0');
13585 }
13586 }
13587 if (c == '.') {
13588 prec = 0;
13589 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013590 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013591 if (c == '*') {
13592 v = getnextarg(args, arglen, &argidx);
13593 if (v == NULL)
13594 goto onError;
13595 if (!PyLong_Check(v)) {
13596 PyErr_SetString(PyExc_TypeError,
13597 "* wants int");
13598 goto onError;
13599 }
13600 prec = PyLong_AsLong(v);
13601 if (prec == -1 && PyErr_Occurred())
13602 goto onError;
13603 if (prec < 0)
13604 prec = 0;
13605 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013606 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013607 }
13608 else if (c >= '0' && c <= '9') {
13609 prec = c - '0';
13610 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013611 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013612 if (c < '0' || c > '9')
13613 break;
Martin v. Löwisb05c0732012-05-15 13:45:49 +020013614 if (prec > (INT_MAX - ((int)c - '0')) / 10) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013615 PyErr_SetString(PyExc_ValueError,
13616 "prec too big");
13617 goto onError;
13618 }
13619 prec = prec*10 + (c - '0');
13620 }
13621 }
13622 } /* prec */
13623 if (fmtcnt >= 0) {
13624 if (c == 'h' || c == 'l' || c == 'L') {
13625 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013626 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013627 }
13628 }
13629 if (fmtcnt < 0) {
13630 PyErr_SetString(PyExc_ValueError,
13631 "incomplete format");
13632 goto onError;
13633 }
Victor Stinnerd3f08822012-05-29 12:57:52 +020013634 if (fmtcnt == 0)
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013635 writer.overallocate = 0;
Victor Stinneraff3cc62012-04-30 05:19:21 +020013636
13637 if (c == '%') {
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013638 if (_PyUnicodeWriter_Prepare(&writer, 1, '%') == -1)
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013639 goto onError;
Victor Stinneree4544c2012-05-09 22:24:08 +020013640 PyUnicode_WRITE(writer.kind, writer.data, writer.pos, '%');
13641 writer.pos += 1;
Victor Stinneraff3cc62012-04-30 05:19:21 +020013642 continue;
Benjamin Peterson29060642009-01-31 22:14:21 +000013643 }
Victor Stinneraff3cc62012-04-30 05:19:21 +020013644
Victor Stinneraff3cc62012-04-30 05:19:21 +020013645 v = getnextarg(args, arglen, &argidx);
13646 if (v == NULL)
13647 goto onError;
13648
Benjamin Peterson29060642009-01-31 22:14:21 +000013649 sign = 0;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013650 signchar = '\0';
Benjamin Peterson29060642009-01-31 22:14:21 +000013651 fill = ' ';
13652 switch (c) {
13653
Benjamin Peterson29060642009-01-31 22:14:21 +000013654 case 's':
13655 case 'r':
13656 case 'a':
Victor Stinnerd3f08822012-05-29 12:57:52 +020013657 if (PyLong_CheckExact(v) && width == -1 && prec == -1) {
13658 /* Fast path */
13659 if (_PyLong_FormatWriter(&writer, v, 10, flags & F_ALT) == -1)
13660 goto onError;
13661 goto nextarg;
13662 }
13663
Victor Stinner808fc0a2010-03-22 12:50:40 +000013664 if (PyUnicode_CheckExact(v) && c == 's') {
Benjamin Peterson29060642009-01-31 22:14:21 +000013665 temp = v;
13666 Py_INCREF(temp);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013667 }
13668 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013669 if (c == 's')
13670 temp = PyObject_Str(v);
13671 else if (c == 'r')
13672 temp = PyObject_Repr(v);
13673 else
13674 temp = PyObject_ASCII(v);
Benjamin Peterson29060642009-01-31 22:14:21 +000013675 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013676 break;
13677
13678 case 'i':
13679 case 'd':
13680 case 'u':
13681 case 'o':
13682 case 'x':
13683 case 'X':
Victor Stinnerd3f08822012-05-29 12:57:52 +020013684 if (PyLong_CheckExact(v)
13685 && width == -1 && prec == -1
13686 && !(flags & (F_SIGN | F_BLANK)))
13687 {
13688 /* Fast path */
13689 switch(c)
13690 {
13691 case 'd':
13692 case 'i':
13693 case 'u':
13694 if (_PyLong_FormatWriter(&writer, v, 10, flags & F_ALT) == -1)
13695 goto onError;
13696 goto nextarg;
13697 case 'x':
13698 if (_PyLong_FormatWriter(&writer, v, 16, flags & F_ALT) == -1)
13699 goto onError;
13700 goto nextarg;
13701 case 'o':
13702 if (_PyLong_FormatWriter(&writer, v, 8, flags & F_ALT) == -1)
13703 goto onError;
13704 goto nextarg;
13705 default:
13706 break;
13707 }
13708 }
13709
Benjamin Peterson29060642009-01-31 22:14:21 +000013710 isnumok = 0;
13711 if (PyNumber_Check(v)) {
13712 PyObject *iobj=NULL;
13713
13714 if (PyLong_Check(v)) {
13715 iobj = v;
13716 Py_INCREF(iobj);
13717 }
13718 else {
13719 iobj = PyNumber_Long(v);
13720 }
13721 if (iobj!=NULL) {
13722 if (PyLong_Check(iobj)) {
13723 isnumok = 1;
Victor Stinneraff3cc62012-04-30 05:19:21 +020013724 sign = 1;
Senthil Kumaran9ebe08d2011-07-03 21:03:16 -070013725 temp = formatlong(iobj, flags, prec, (c == 'i'? 'd': c));
Benjamin Peterson29060642009-01-31 22:14:21 +000013726 Py_DECREF(iobj);
Benjamin Peterson29060642009-01-31 22:14:21 +000013727 }
13728 else {
13729 Py_DECREF(iobj);
13730 }
13731 }
13732 }
13733 if (!isnumok) {
13734 PyErr_Format(PyExc_TypeError,
13735 "%%%c format: a number is required, "
13736 "not %.200s", (char)c, Py_TYPE(v)->tp_name);
13737 goto onError;
13738 }
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013739 if (flags & F_ZERO)
Benjamin Peterson29060642009-01-31 22:14:21 +000013740 fill = '0';
13741 break;
13742
13743 case 'e':
13744 case 'E':
13745 case 'f':
13746 case 'F':
13747 case 'g':
13748 case 'G':
Victor Stinnerd3f08822012-05-29 12:57:52 +020013749 if (width == -1 && prec == -1
13750 && !(flags & (F_SIGN | F_BLANK)))
13751 {
13752 /* Fast path */
13753 if (formatfloat(v, flags, prec, c, NULL, &writer) == -1)
13754 goto onError;
13755 goto nextarg;
13756 }
13757
Benjamin Peterson29060642009-01-31 22:14:21 +000013758 sign = 1;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013759 if (flags & F_ZERO)
Benjamin Peterson29060642009-01-31 22:14:21 +000013760 fill = '0';
Victor Stinnerd3f08822012-05-29 12:57:52 +020013761 if (formatfloat(v, flags, prec, c, &temp, NULL) == -1)
13762 temp = NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000013763 break;
13764
13765 case 'c':
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013766 {
13767 Py_UCS4 ch = formatchar(v);
13768 if (ch == (Py_UCS4) -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000013769 goto onError;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013770 if (width == -1 && prec == -1) {
13771 /* Fast path */
13772 if (_PyUnicodeWriter_Prepare(&writer, 1, ch) == -1)
13773 goto onError;
13774 PyUnicode_WRITE(writer.kind, writer.data, writer.pos, ch);
13775 writer.pos += 1;
13776 goto nextarg;
13777 }
Victor Stinnerb5c3ea32012-05-02 00:29:36 +020013778 temp = PyUnicode_FromOrdinal(ch);
Benjamin Peterson29060642009-01-31 22:14:21 +000013779 break;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013780 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013781
13782 default:
13783 PyErr_Format(PyExc_ValueError,
13784 "unsupported format character '%c' (0x%x) "
13785 "at index %zd",
13786 (31<=c && c<=126) ? (char)c : '?',
13787 (int)c,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013788 fmtpos - 1);
Benjamin Peterson29060642009-01-31 22:14:21 +000013789 goto onError;
13790 }
Victor Stinneraff3cc62012-04-30 05:19:21 +020013791 if (temp == NULL)
13792 goto onError;
13793 assert (PyUnicode_Check(temp));
Victor Stinnerd3f08822012-05-29 12:57:52 +020013794
13795 if (width == -1 && prec == -1
13796 && !(flags & (F_SIGN | F_BLANK)))
13797 {
13798 /* Fast path */
13799 if (_PyUnicodeWriter_WriteStr(&writer, temp) == -1)
13800 goto onError;
13801 goto nextarg;
13802 }
13803
Victor Stinneraff3cc62012-04-30 05:19:21 +020013804 if (PyUnicode_READY(temp) == -1) {
13805 Py_CLEAR(temp);
13806 goto onError;
13807 }
13808 kind = PyUnicode_KIND(temp);
13809 pbuf = PyUnicode_DATA(temp);
13810 len = PyUnicode_GET_LENGTH(temp);
13811
13812 if (c == 's' || c == 'r' || c == 'a') {
13813 if (prec >= 0 && len > prec)
13814 len = prec;
13815 }
13816
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013817 /* pbuf is initialized here. */
13818 pindex = 0;
Benjamin Peterson29060642009-01-31 22:14:21 +000013819 if (sign) {
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013820 Py_UCS4 ch = PyUnicode_READ(kind, pbuf, pindex);
13821 if (ch == '-' || ch == '+') {
13822 signchar = ch;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013823 len--;
13824 pindex++;
Benjamin Peterson29060642009-01-31 22:14:21 +000013825 }
13826 else if (flags & F_SIGN)
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013827 signchar = '+';
Benjamin Peterson29060642009-01-31 22:14:21 +000013828 else if (flags & F_BLANK)
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013829 signchar = ' ';
Benjamin Peterson29060642009-01-31 22:14:21 +000013830 else
13831 sign = 0;
13832 }
13833 if (width < len)
13834 width = len;
Victor Stinneree4544c2012-05-09 22:24:08 +020013835
13836 /* Compute the length and maximum character of the
13837 written characters */
13838 bufmaxchar = 127;
13839 if (!(flags & F_LJUST)) {
13840 if (sign) {
13841 if ((width-1) > len)
Victor Stinnerd3f08822012-05-29 12:57:52 +020013842 bufmaxchar = MAX_MAXCHAR(bufmaxchar, fill);
Victor Stinneree4544c2012-05-09 22:24:08 +020013843 }
13844 else {
13845 if (width > len)
Victor Stinnerd3f08822012-05-29 12:57:52 +020013846 bufmaxchar = MAX_MAXCHAR(bufmaxchar, fill);
Victor Stinneree4544c2012-05-09 22:24:08 +020013847 }
13848 }
13849 maxchar = _PyUnicode_FindMaxChar(temp, 0, pindex+len);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013850 bufmaxchar = MAX_MAXCHAR(bufmaxchar, maxchar);
Victor Stinneree4544c2012-05-09 22:24:08 +020013851
13852 buflen = width;
13853 if (sign && len == width)
13854 buflen++;
13855
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013856 if (_PyUnicodeWriter_Prepare(&writer, buflen, bufmaxchar) == -1)
Victor Stinneree4544c2012-05-09 22:24:08 +020013857 goto onError;
13858
13859 /* Write characters */
Benjamin Peterson29060642009-01-31 22:14:21 +000013860 if (sign) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013861 if (fill != ' ') {
Victor Stinneree4544c2012-05-09 22:24:08 +020013862 PyUnicode_WRITE(writer.kind, writer.data, writer.pos, signchar);
13863 writer.pos += 1;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013864 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013865 if (width > len)
13866 width--;
13867 }
13868 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013869 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013870 assert(PyUnicode_READ(kind, pbuf, pindex + 1) == c);
Benjamin Peterson29060642009-01-31 22:14:21 +000013871 if (fill != ' ') {
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013872 PyUnicode_WRITE(writer.kind, writer.data, writer.pos, '0');
13873 PyUnicode_WRITE(writer.kind, writer.data, writer.pos+1, c);
13874 writer.pos += 2;
13875 pindex += 2;
Benjamin Peterson29060642009-01-31 22:14:21 +000013876 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013877 width -= 2;
13878 if (width < 0)
13879 width = 0;
13880 len -= 2;
13881 }
13882 if (width > len && !(flags & F_LJUST)) {
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013883 sublen = width - len;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013884 FILL(writer.kind, writer.data, fill, writer.pos, sublen);
13885 writer.pos += sublen;
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013886 width = len;
Benjamin Peterson29060642009-01-31 22:14:21 +000013887 }
13888 if (fill == ' ') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013889 if (sign) {
Victor Stinneree4544c2012-05-09 22:24:08 +020013890 PyUnicode_WRITE(writer.kind, writer.data, writer.pos, signchar);
13891 writer.pos += 1;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013892 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013893 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013894 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
13895 assert(PyUnicode_READ(kind, pbuf, pindex+1) == c);
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013896 PyUnicode_WRITE(writer.kind, writer.data, writer.pos, '0');
13897 PyUnicode_WRITE(writer.kind, writer.data, writer.pos+1, c);
13898 writer.pos += 2;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013899 pindex += 2;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013900 }
13901 }
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013902
Victor Stinnerc9d369f2012-06-16 02:22:37 +020013903 if (len) {
13904 _PyUnicode_FastCopyCharacters(writer.buffer, writer.pos,
13905 temp, pindex, len);
13906 writer.pos += len;
13907 }
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013908 if (width > len) {
Victor Stinneree4544c2012-05-09 22:24:08 +020013909 sublen = width - len;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013910 FILL(writer.kind, writer.data, ' ', writer.pos, sublen);
13911 writer.pos += sublen;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013912 }
Victor Stinneree4544c2012-05-09 22:24:08 +020013913
Victor Stinnerd3f08822012-05-29 12:57:52 +020013914nextarg:
Benjamin Peterson29060642009-01-31 22:14:21 +000013915 if (dict && (argidx < arglen) && c != '%') {
13916 PyErr_SetString(PyExc_TypeError,
13917 "not all arguments converted during string formatting");
Benjamin Peterson29060642009-01-31 22:14:21 +000013918 goto onError;
13919 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013920 Py_CLEAR(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013921 } /* '%' */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013922 } /* until end */
13923 if (argidx < arglen && !dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013924 PyErr_SetString(PyExc_TypeError,
13925 "not all arguments converted during string formatting");
13926 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013927 }
13928
13929 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013930 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013931 }
13932 Py_DECREF(uformat);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013933 Py_XDECREF(temp);
13934 Py_XDECREF(second);
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013935 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013936
Benjamin Peterson29060642009-01-31 22:14:21 +000013937 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000013938 Py_DECREF(uformat);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013939 Py_XDECREF(temp);
13940 Py_XDECREF(second);
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013941 _PyUnicodeWriter_Dealloc(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013942 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013943 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013944 }
13945 return NULL;
13946}
13947
Jeremy Hylton938ace62002-07-17 16:30:39 +000013948static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +000013949unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
13950
Tim Peters6d6c1a32001-08-02 04:15:00 +000013951static PyObject *
13952unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
13953{
Benjamin Peterson29060642009-01-31 22:14:21 +000013954 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013955 static char *kwlist[] = {"object", "encoding", "errors", 0};
13956 char *encoding = NULL;
13957 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000013958
Benjamin Peterson14339b62009-01-31 16:36:08 +000013959 if (type != &PyUnicode_Type)
13960 return unicode_subtype_new(type, args, kwds);
13961 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +000013962 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +000013963 return NULL;
Victor Stinner382955f2011-12-11 21:44:00 +010013964 if (x == NULL) {
13965 Py_INCREF(unicode_empty);
13966 return unicode_empty;
13967 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000013968 if (encoding == NULL && errors == NULL)
13969 return PyObject_Str(x);
13970 else
Benjamin Peterson29060642009-01-31 22:14:21 +000013971 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +000013972}
13973
Guido van Rossume023fe02001-08-30 03:12:59 +000013974static PyObject *
13975unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
13976{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013977 PyObject *unicode, *self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013978 Py_ssize_t length, char_size;
13979 int share_wstr, share_utf8;
13980 unsigned int kind;
13981 void *data;
Guido van Rossume023fe02001-08-30 03:12:59 +000013982
Benjamin Peterson14339b62009-01-31 16:36:08 +000013983 assert(PyType_IsSubtype(type, &PyUnicode_Type));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013984
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013985 unicode = unicode_new(&PyUnicode_Type, args, kwds);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013986 if (unicode == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000013987 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020013988 assert(_PyUnicode_CHECK(unicode));
Benjamin Petersonbac79492012-01-14 13:34:47 -050013989 if (PyUnicode_READY(unicode) == -1) {
Benjamin Peterson22a29702012-01-02 09:00:30 -060013990 Py_DECREF(unicode);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013991 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060013992 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013993
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013994 self = type->tp_alloc(type, 0);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013995 if (self == NULL) {
13996 Py_DECREF(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013997 return NULL;
13998 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013999 kind = PyUnicode_KIND(unicode);
14000 length = PyUnicode_GET_LENGTH(unicode);
14001
14002 _PyUnicode_LENGTH(self) = length;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014003#ifdef Py_DEBUG
14004 _PyUnicode_HASH(self) = -1;
14005#else
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014006 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014007#endif
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014008 _PyUnicode_STATE(self).interned = 0;
14009 _PyUnicode_STATE(self).kind = kind;
14010 _PyUnicode_STATE(self).compact = 0;
Victor Stinner3cf46372011-10-03 14:42:15 +020014011 _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014012 _PyUnicode_STATE(self).ready = 1;
14013 _PyUnicode_WSTR(self) = NULL;
14014 _PyUnicode_UTF8_LENGTH(self) = 0;
14015 _PyUnicode_UTF8(self) = NULL;
14016 _PyUnicode_WSTR_LENGTH(self) = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +020014017 _PyUnicode_DATA_ANY(self) = NULL;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014018
14019 share_utf8 = 0;
14020 share_wstr = 0;
14021 if (kind == PyUnicode_1BYTE_KIND) {
14022 char_size = 1;
14023 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
14024 share_utf8 = 1;
14025 }
14026 else if (kind == PyUnicode_2BYTE_KIND) {
14027 char_size = 2;
14028 if (sizeof(wchar_t) == 2)
14029 share_wstr = 1;
14030 }
14031 else {
14032 assert(kind == PyUnicode_4BYTE_KIND);
14033 char_size = 4;
14034 if (sizeof(wchar_t) == 4)
14035 share_wstr = 1;
14036 }
14037
14038 /* Ensure we won't overflow the length. */
14039 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
14040 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014041 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014042 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014043 data = PyObject_MALLOC((length + 1) * char_size);
14044 if (data == NULL) {
14045 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014046 goto onError;
14047 }
14048
Victor Stinnerc3c74152011-10-02 20:39:55 +020014049 _PyUnicode_DATA_ANY(self) = data;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014050 if (share_utf8) {
14051 _PyUnicode_UTF8_LENGTH(self) = length;
14052 _PyUnicode_UTF8(self) = data;
14053 }
14054 if (share_wstr) {
14055 _PyUnicode_WSTR_LENGTH(self) = length;
14056 _PyUnicode_WSTR(self) = (wchar_t *)data;
14057 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014058
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014059 Py_MEMCPY(data, PyUnicode_DATA(unicode),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020014060 kind * (length + 1));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020014061 assert(_PyUnicode_CheckConsistency(self, 1));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014062#ifdef Py_DEBUG
14063 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
14064#endif
Victor Stinnerdd18d3a2011-10-22 11:08:10 +020014065 Py_DECREF(unicode);
Victor Stinner7931d9a2011-11-04 00:22:48 +010014066 return self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014067
14068onError:
14069 Py_DECREF(unicode);
14070 Py_DECREF(self);
14071 return NULL;
Guido van Rossume023fe02001-08-30 03:12:59 +000014072}
14073
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000014074PyDoc_STRVAR(unicode_doc,
Chris Jerdonek83fe2e12012-10-07 14:48:36 -070014075"str(object='') -> str\n\
14076str(bytes_or_buffer[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +000014077\n\
Nick Coghlan573b1fd2012-08-16 14:13:07 +100014078Create a new string object from the given object. If encoding or\n\
14079errors is specified, then the object must expose a data buffer\n\
14080that will be decoded using the given encoding and error handler.\n\
14081Otherwise, returns the result of object.__str__() (if defined)\n\
14082or repr(object).\n\
14083encoding defaults to sys.getdefaultencoding().\n\
14084errors defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +000014085
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014086static PyObject *unicode_iter(PyObject *seq);
14087
Guido van Rossumd57fd912000-03-10 22:53:23 +000014088PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000014089 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Benjamin Peterson14339b62009-01-31 16:36:08 +000014090 "str", /* tp_name */
14091 sizeof(PyUnicodeObject), /* tp_size */
14092 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014093 /* Slots */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014094 (destructor)unicode_dealloc, /* tp_dealloc */
14095 0, /* tp_print */
14096 0, /* tp_getattr */
14097 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000014098 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014099 unicode_repr, /* tp_repr */
14100 &unicode_as_number, /* tp_as_number */
14101 &unicode_as_sequence, /* tp_as_sequence */
14102 &unicode_as_mapping, /* tp_as_mapping */
14103 (hashfunc) unicode_hash, /* tp_hash*/
14104 0, /* tp_call*/
14105 (reprfunc) unicode_str, /* tp_str */
14106 PyObject_GenericGetAttr, /* tp_getattro */
14107 0, /* tp_setattro */
14108 0, /* tp_as_buffer */
14109 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Benjamin Peterson29060642009-01-31 22:14:21 +000014110 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014111 unicode_doc, /* tp_doc */
14112 0, /* tp_traverse */
14113 0, /* tp_clear */
14114 PyUnicode_RichCompare, /* tp_richcompare */
14115 0, /* tp_weaklistoffset */
14116 unicode_iter, /* tp_iter */
14117 0, /* tp_iternext */
14118 unicode_methods, /* tp_methods */
14119 0, /* tp_members */
14120 0, /* tp_getset */
14121 &PyBaseObject_Type, /* tp_base */
14122 0, /* tp_dict */
14123 0, /* tp_descr_get */
14124 0, /* tp_descr_set */
14125 0, /* tp_dictoffset */
14126 0, /* tp_init */
14127 0, /* tp_alloc */
14128 unicode_new, /* tp_new */
14129 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014130};
14131
14132/* Initialize the Unicode implementation */
14133
Victor Stinner3a50e702011-10-18 21:21:00 +020014134int _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014135{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014136 int i;
14137
Thomas Wouters477c8d52006-05-27 19:21:47 +000014138 /* XXX - move this array to unicodectype.c ? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014139 Py_UCS2 linebreak[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +000014140 0x000A, /* LINE FEED */
14141 0x000D, /* CARRIAGE RETURN */
14142 0x001C, /* FILE SEPARATOR */
14143 0x001D, /* GROUP SEPARATOR */
14144 0x001E, /* RECORD SEPARATOR */
14145 0x0085, /* NEXT LINE */
14146 0x2028, /* LINE SEPARATOR */
14147 0x2029, /* PARAGRAPH SEPARATOR */
14148 };
14149
Fred Drakee4315f52000-05-09 19:53:39 +000014150 /* Init the implementation */
Victor Stinnera464fc12011-10-02 20:39:30 +020014151 unicode_empty = PyUnicode_New(0, 0);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014152 if (!unicode_empty)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014153 Py_FatalError("Can't create empty string");
Victor Stinnerd3df8ab2011-11-22 01:22:34 +010014154 assert(_PyUnicode_CheckConsistency(unicode_empty, 1));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014155
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014156 for (i = 0; i < 256; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +000014157 unicode_latin1[i] = NULL;
Guido van Rossumcacfc072002-05-24 19:01:59 +000014158 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000014159 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +000014160
14161 /* initialize the linebreak bloom filter */
14162 bloom_linebreak = make_bloom_mask(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014163 PyUnicode_2BYTE_KIND, linebreak,
Victor Stinner63941882011-09-29 00:42:28 +020014164 Py_ARRAY_LENGTH(linebreak));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014165
14166 PyType_Ready(&EncodingMapType);
Victor Stinner3a50e702011-10-18 21:21:00 +020014167
Benjamin Petersonc4311282012-10-30 23:21:10 -040014168 if (PyType_Ready(&PyFieldNameIter_Type) < 0)
14169 Py_FatalError("Can't initialize field name iterator type");
14170
14171 if (PyType_Ready(&PyFormatterIter_Type) < 0)
14172 Py_FatalError("Can't initialize formatter iter type");
Benjamin Petersone8ea97f2012-10-30 23:27:52 -040014173
Victor Stinner3a50e702011-10-18 21:21:00 +020014174#ifdef HAVE_MBCS
14175 winver.dwOSVersionInfoSize = sizeof(winver);
14176 if (!GetVersionEx((OSVERSIONINFO*)&winver)) {
14177 PyErr_SetFromWindowsErr(0);
14178 return -1;
14179 }
14180#endif
14181 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014182}
14183
14184/* Finalize the Unicode implementation */
14185
Christian Heimesa156e092008-02-16 07:38:31 +000014186int
14187PyUnicode_ClearFreeList(void)
14188{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014189 return 0;
Christian Heimesa156e092008-02-16 07:38:31 +000014190}
14191
Guido van Rossumd57fd912000-03-10 22:53:23 +000014192void
Thomas Wouters78890102000-07-22 19:25:51 +000014193_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014194{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014195 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014196
Guido van Rossum4ae8ef82000-10-03 18:09:04 +000014197 Py_XDECREF(unicode_empty);
14198 unicode_empty = NULL;
Barry Warsaw5b4c2282000-10-03 20:45:26 +000014199
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014200 for (i = 0; i < 256; i++) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014201 if (unicode_latin1[i]) {
14202 Py_DECREF(unicode_latin1[i]);
14203 unicode_latin1[i] = NULL;
14204 }
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014205 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020014206 _PyUnicode_ClearStaticStrings();
Christian Heimesa156e092008-02-16 07:38:31 +000014207 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +000014208}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000014209
Walter Dörwald16807132007-05-25 13:52:07 +000014210void
14211PyUnicode_InternInPlace(PyObject **p)
14212{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014213 register PyObject *s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014214 PyObject *t;
Victor Stinner4fae54c2011-10-03 02:01:52 +020014215#ifdef Py_DEBUG
14216 assert(s != NULL);
14217 assert(_PyUnicode_CHECK(s));
14218#else
Benjamin Peterson14339b62009-01-31 16:36:08 +000014219 if (s == NULL || !PyUnicode_Check(s))
Victor Stinner4fae54c2011-10-03 02:01:52 +020014220 return;
14221#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000014222 /* If it's a subclass, we don't really know what putting
14223 it in the interned dict might do. */
14224 if (!PyUnicode_CheckExact(s))
14225 return;
14226 if (PyUnicode_CHECK_INTERNED(s))
14227 return;
14228 if (interned == NULL) {
14229 interned = PyDict_New();
14230 if (interned == NULL) {
14231 PyErr_Clear(); /* Don't leave an exception */
14232 return;
14233 }
14234 }
14235 /* It might be that the GetItem call fails even
14236 though the key is present in the dictionary,
14237 namely when this happens during a stack overflow. */
14238 Py_ALLOW_RECURSION
Victor Stinner7931d9a2011-11-04 00:22:48 +010014239 t = PyDict_GetItem(interned, s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014240 Py_END_ALLOW_RECURSION
Martin v. Löwis5b222132007-06-10 09:51:05 +000014241
Benjamin Peterson29060642009-01-31 22:14:21 +000014242 if (t) {
14243 Py_INCREF(t);
14244 Py_DECREF(*p);
14245 *p = t;
14246 return;
14247 }
Walter Dörwald16807132007-05-25 13:52:07 +000014248
Benjamin Peterson14339b62009-01-31 16:36:08 +000014249 PyThreadState_GET()->recursion_critical = 1;
Victor Stinner7931d9a2011-11-04 00:22:48 +010014250 if (PyDict_SetItem(interned, s, s) < 0) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014251 PyErr_Clear();
14252 PyThreadState_GET()->recursion_critical = 0;
14253 return;
14254 }
14255 PyThreadState_GET()->recursion_critical = 0;
14256 /* The two references in interned are not counted by refcnt.
14257 The deallocator will take care of this */
14258 Py_REFCNT(s) -= 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014259 _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000014260}
14261
14262void
14263PyUnicode_InternImmortal(PyObject **p)
14264{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014265 PyUnicode_InternInPlace(p);
14266 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
Victor Stinneraf9e4b82011-10-23 20:07:00 +020014267 _PyUnicode_STATE(*p).interned = SSTATE_INTERNED_IMMORTAL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014268 Py_INCREF(*p);
14269 }
Walter Dörwald16807132007-05-25 13:52:07 +000014270}
14271
14272PyObject *
14273PyUnicode_InternFromString(const char *cp)
14274{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014275 PyObject *s = PyUnicode_FromString(cp);
14276 if (s == NULL)
14277 return NULL;
14278 PyUnicode_InternInPlace(&s);
14279 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000014280}
14281
Alexander Belopolsky40018472011-02-26 01:02:56 +000014282void
14283_Py_ReleaseInternedUnicodeStrings(void)
Walter Dörwald16807132007-05-25 13:52:07 +000014284{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014285 PyObject *keys;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014286 PyObject *s;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014287 Py_ssize_t i, n;
14288 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000014289
Benjamin Peterson14339b62009-01-31 16:36:08 +000014290 if (interned == NULL || !PyDict_Check(interned))
14291 return;
14292 keys = PyDict_Keys(interned);
14293 if (keys == NULL || !PyList_Check(keys)) {
14294 PyErr_Clear();
14295 return;
14296 }
Walter Dörwald16807132007-05-25 13:52:07 +000014297
Benjamin Peterson14339b62009-01-31 16:36:08 +000014298 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
14299 detector, interned unicode strings are not forcibly deallocated;
14300 rather, we give them their stolen references back, and then clear
14301 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000014302
Benjamin Peterson14339b62009-01-31 16:36:08 +000014303 n = PyList_GET_SIZE(keys);
14304 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000014305 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014306 for (i = 0; i < n; i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014307 s = PyList_GET_ITEM(keys, i);
Victor Stinner6b56a7f2011-10-04 20:04:52 +020014308 if (PyUnicode_READY(s) == -1) {
14309 assert(0 && "could not ready string");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014310 fprintf(stderr, "could not ready string\n");
Victor Stinner6b56a7f2011-10-04 20:04:52 +020014311 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014312 switch (PyUnicode_CHECK_INTERNED(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014313 case SSTATE_NOT_INTERNED:
14314 /* XXX Shouldn't happen */
14315 break;
14316 case SSTATE_INTERNED_IMMORTAL:
14317 Py_REFCNT(s) += 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014318 immortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014319 break;
14320 case SSTATE_INTERNED_MORTAL:
14321 Py_REFCNT(s) += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014322 mortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014323 break;
14324 default:
14325 Py_FatalError("Inconsistent interned string state.");
14326 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014327 _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014328 }
14329 fprintf(stderr, "total size of all interned strings: "
14330 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
14331 "mortal/immortal\n", mortal_size, immortal_size);
14332 Py_DECREF(keys);
14333 PyDict_Clear(interned);
14334 Py_DECREF(interned);
14335 interned = NULL;
Walter Dörwald16807132007-05-25 13:52:07 +000014336}
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014337
14338
14339/********************* Unicode Iterator **************************/
14340
14341typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014342 PyObject_HEAD
14343 Py_ssize_t it_index;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014344 PyObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014345} unicodeiterobject;
14346
14347static void
14348unicodeiter_dealloc(unicodeiterobject *it)
14349{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014350 _PyObject_GC_UNTRACK(it);
14351 Py_XDECREF(it->it_seq);
14352 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014353}
14354
14355static int
14356unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
14357{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014358 Py_VISIT(it->it_seq);
14359 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014360}
14361
14362static PyObject *
14363unicodeiter_next(unicodeiterobject *it)
14364{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014365 PyObject *seq, *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014366
Benjamin Peterson14339b62009-01-31 16:36:08 +000014367 assert(it != NULL);
14368 seq = it->it_seq;
14369 if (seq == NULL)
14370 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020014371 assert(_PyUnicode_CHECK(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014372
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014373 if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
14374 int kind = PyUnicode_KIND(seq);
14375 void *data = PyUnicode_DATA(seq);
14376 Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
14377 item = PyUnicode_FromOrdinal(chr);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014378 if (item != NULL)
14379 ++it->it_index;
14380 return item;
14381 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014382
Benjamin Peterson14339b62009-01-31 16:36:08 +000014383 Py_DECREF(seq);
14384 it->it_seq = NULL;
14385 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014386}
14387
14388static PyObject *
14389unicodeiter_len(unicodeiterobject *it)
14390{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014391 Py_ssize_t len = 0;
14392 if (it->it_seq)
Victor Stinnerc4f281e2011-10-11 22:11:42 +020014393 len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014394 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014395}
14396
14397PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
14398
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000014399static PyObject *
14400unicodeiter_reduce(unicodeiterobject *it)
14401{
14402 if (it->it_seq != NULL) {
Antoine Pitroua7013882012-04-05 00:04:20 +020014403 return Py_BuildValue("N(O)n", _PyObject_GetBuiltin("iter"),
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000014404 it->it_seq, it->it_index);
14405 } else {
14406 PyObject *u = PyUnicode_FromUnicode(NULL, 0);
14407 if (u == NULL)
14408 return NULL;
Antoine Pitroua7013882012-04-05 00:04:20 +020014409 return Py_BuildValue("N(N)", _PyObject_GetBuiltin("iter"), u);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000014410 }
14411}
14412
14413PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
14414
14415static PyObject *
14416unicodeiter_setstate(unicodeiterobject *it, PyObject *state)
14417{
14418 Py_ssize_t index = PyLong_AsSsize_t(state);
14419 if (index == -1 && PyErr_Occurred())
14420 return NULL;
14421 if (index < 0)
14422 index = 0;
14423 it->it_index = index;
14424 Py_RETURN_NONE;
14425}
14426
14427PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
14428
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014429static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014430 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000014431 length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000014432 {"__reduce__", (PyCFunction)unicodeiter_reduce, METH_NOARGS,
14433 reduce_doc},
14434 {"__setstate__", (PyCFunction)unicodeiter_setstate, METH_O,
14435 setstate_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000014436 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014437};
14438
14439PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014440 PyVarObject_HEAD_INIT(&PyType_Type, 0)
14441 "str_iterator", /* tp_name */
14442 sizeof(unicodeiterobject), /* tp_basicsize */
14443 0, /* tp_itemsize */
14444 /* methods */
14445 (destructor)unicodeiter_dealloc, /* tp_dealloc */
14446 0, /* tp_print */
14447 0, /* tp_getattr */
14448 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000014449 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014450 0, /* tp_repr */
14451 0, /* tp_as_number */
14452 0, /* tp_as_sequence */
14453 0, /* tp_as_mapping */
14454 0, /* tp_hash */
14455 0, /* tp_call */
14456 0, /* tp_str */
14457 PyObject_GenericGetAttr, /* tp_getattro */
14458 0, /* tp_setattro */
14459 0, /* tp_as_buffer */
14460 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
14461 0, /* tp_doc */
14462 (traverseproc)unicodeiter_traverse, /* tp_traverse */
14463 0, /* tp_clear */
14464 0, /* tp_richcompare */
14465 0, /* tp_weaklistoffset */
14466 PyObject_SelfIter, /* tp_iter */
14467 (iternextfunc)unicodeiter_next, /* tp_iternext */
14468 unicodeiter_methods, /* tp_methods */
14469 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014470};
14471
14472static PyObject *
14473unicode_iter(PyObject *seq)
14474{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014475 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014476
Benjamin Peterson14339b62009-01-31 16:36:08 +000014477 if (!PyUnicode_Check(seq)) {
14478 PyErr_BadInternalCall();
14479 return NULL;
14480 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014481 if (PyUnicode_READY(seq) == -1)
14482 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014483 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
14484 if (it == NULL)
14485 return NULL;
14486 it->it_index = 0;
14487 Py_INCREF(seq);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014488 it->it_seq = seq;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014489 _PyObject_GC_TRACK(it);
14490 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014491}
14492
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010014493
14494size_t
14495Py_UNICODE_strlen(const Py_UNICODE *u)
14496{
14497 int res = 0;
14498 while(*u++)
14499 res++;
14500 return res;
14501}
14502
14503Py_UNICODE*
14504Py_UNICODE_strcpy(Py_UNICODE *s1, const Py_UNICODE *s2)
14505{
14506 Py_UNICODE *u = s1;
14507 while ((*u++ = *s2++));
14508 return s1;
14509}
14510
14511Py_UNICODE*
14512Py_UNICODE_strncpy(Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
14513{
14514 Py_UNICODE *u = s1;
14515 while ((*u++ = *s2++))
14516 if (n-- == 0)
14517 break;
14518 return s1;
14519}
14520
14521Py_UNICODE*
14522Py_UNICODE_strcat(Py_UNICODE *s1, const Py_UNICODE *s2)
14523{
14524 Py_UNICODE *u1 = s1;
14525 u1 += Py_UNICODE_strlen(u1);
14526 Py_UNICODE_strcpy(u1, s2);
14527 return s1;
14528}
14529
14530int
14531Py_UNICODE_strcmp(const Py_UNICODE *s1, const Py_UNICODE *s2)
14532{
14533 while (*s1 && *s2 && *s1 == *s2)
14534 s1++, s2++;
14535 if (*s1 && *s2)
14536 return (*s1 < *s2) ? -1 : +1;
14537 if (*s1)
14538 return 1;
14539 if (*s2)
14540 return -1;
14541 return 0;
14542}
14543
14544int
14545Py_UNICODE_strncmp(const Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
14546{
14547 register Py_UNICODE u1, u2;
14548 for (; n != 0; n--) {
14549 u1 = *s1;
14550 u2 = *s2;
14551 if (u1 != u2)
14552 return (u1 < u2) ? -1 : +1;
14553 if (u1 == '\0')
14554 return 0;
14555 s1++;
14556 s2++;
14557 }
14558 return 0;
14559}
14560
14561Py_UNICODE*
14562Py_UNICODE_strchr(const Py_UNICODE *s, Py_UNICODE c)
14563{
14564 const Py_UNICODE *p;
14565 for (p = s; *p; p++)
14566 if (*p == c)
14567 return (Py_UNICODE*)p;
14568 return NULL;
14569}
14570
14571Py_UNICODE*
14572Py_UNICODE_strrchr(const Py_UNICODE *s, Py_UNICODE c)
14573{
14574 const Py_UNICODE *p;
14575 p = s + Py_UNICODE_strlen(s);
14576 while (p != s) {
14577 p--;
14578 if (*p == c)
14579 return (Py_UNICODE*)p;
14580 }
14581 return NULL;
14582}
Victor Stinner331ea922010-08-10 16:37:20 +000014583
Victor Stinner71133ff2010-09-01 23:43:53 +000014584Py_UNICODE*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014585PyUnicode_AsUnicodeCopy(PyObject *unicode)
Victor Stinner71133ff2010-09-01 23:43:53 +000014586{
Victor Stinner577db2c2011-10-11 22:12:48 +020014587 Py_UNICODE *u, *copy;
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014588 Py_ssize_t len, size;
Victor Stinner71133ff2010-09-01 23:43:53 +000014589
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014590 if (!PyUnicode_Check(unicode)) {
14591 PyErr_BadArgument();
14592 return NULL;
14593 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014594 u = PyUnicode_AsUnicodeAndSize(unicode, &len);
Victor Stinner577db2c2011-10-11 22:12:48 +020014595 if (u == NULL)
14596 return NULL;
Victor Stinner71133ff2010-09-01 23:43:53 +000014597 /* Ensure we won't overflow the size. */
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014598 if (len > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
Victor Stinner71133ff2010-09-01 23:43:53 +000014599 PyErr_NoMemory();
14600 return NULL;
14601 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014602 size = len + 1; /* copy the null character */
Victor Stinner71133ff2010-09-01 23:43:53 +000014603 size *= sizeof(Py_UNICODE);
14604 copy = PyMem_Malloc(size);
14605 if (copy == NULL) {
14606 PyErr_NoMemory();
14607 return NULL;
14608 }
Victor Stinner577db2c2011-10-11 22:12:48 +020014609 memcpy(copy, u, size);
Victor Stinner71133ff2010-09-01 23:43:53 +000014610 return copy;
14611}
Martin v. Löwis5b222132007-06-10 09:51:05 +000014612
Georg Brandl66c221e2010-10-14 07:04:07 +000014613/* A _string module, to export formatter_parser and formatter_field_name_split
14614 to the string.Formatter class implemented in Python. */
14615
14616static PyMethodDef _string_methods[] = {
14617 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
14618 METH_O, PyDoc_STR("split the argument as a field name")},
14619 {"formatter_parser", (PyCFunction) formatter_parser,
14620 METH_O, PyDoc_STR("parse the argument as a format string")},
14621 {NULL, NULL}
14622};
14623
14624static struct PyModuleDef _string_module = {
14625 PyModuleDef_HEAD_INIT,
14626 "_string",
14627 PyDoc_STR("string helper module"),
14628 0,
14629 _string_methods,
14630 NULL,
14631 NULL,
14632 NULL,
14633 NULL
14634};
14635
14636PyMODINIT_FUNC
14637PyInit__string(void)
14638{
14639 return PyModule_Create(&_string_module);
14640}
14641
14642
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000014643#ifdef __cplusplus
14644}
14645#endif