blob: 09067e919c46dd4f4bb7d4e6042ac7a55d858c39 [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 Stinnerafffce42012-10-03 23:03:17 +0200643#ifdef Py_DEBUG
644/* Fill the data of an Unicode string with invalid characters to detect bugs
645 earlier.
646
647 _PyUnicode_CheckConsistency(str, 1) detects invalid characters, at least for
648 ASCII and UCS-4 strings. U+00FF is invalid in ASCII and U+FFFFFFFF is an
649 invalid character in Unicode 6.0. */
650static void
651unicode_fill_invalid(PyObject *unicode, Py_ssize_t old_length)
652{
653 int kind = PyUnicode_KIND(unicode);
654 Py_UCS1 *data = PyUnicode_1BYTE_DATA(unicode);
655 Py_ssize_t length = _PyUnicode_LENGTH(unicode);
656 if (length <= old_length)
657 return;
658 memset(data + old_length * kind, 0xff, (length - old_length) * kind);
659}
660#endif
661
Victor Stinnerfe226c02011-10-03 03:52:20 +0200662static PyObject*
663resize_compact(PyObject *unicode, Py_ssize_t length)
664{
665 Py_ssize_t char_size;
666 Py_ssize_t struct_size;
667 Py_ssize_t new_size;
668 int share_wstr;
Victor Stinner84def372011-12-11 20:04:56 +0100669 PyObject *new_unicode;
Victor Stinnerafffce42012-10-03 23:03:17 +0200670#ifdef Py_DEBUG
671 Py_ssize_t old_length = _PyUnicode_LENGTH(unicode);
672#endif
673
Victor Stinner79891572012-05-03 13:43:07 +0200674 assert(unicode_modifiable(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200675 assert(PyUnicode_IS_READY(unicode));
Victor Stinner488fa492011-12-12 00:01:39 +0100676 assert(PyUnicode_IS_COMPACT(unicode));
677
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200678 char_size = PyUnicode_KIND(unicode);
Victor Stinner488fa492011-12-12 00:01:39 +0100679 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerfe226c02011-10-03 03:52:20 +0200680 struct_size = sizeof(PyASCIIObject);
681 else
682 struct_size = sizeof(PyCompactUnicodeObject);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200683 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200684
Victor Stinnerfe226c02011-10-03 03:52:20 +0200685 if (length > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1)) {
686 PyErr_NoMemory();
687 return NULL;
688 }
689 new_size = (struct_size + (length + 1) * char_size);
690
Victor Stinner84def372011-12-11 20:04:56 +0100691 _Py_DEC_REFTOTAL;
692 _Py_ForgetReference(unicode);
693
694 new_unicode = (PyObject *)PyObject_REALLOC((char *)unicode, new_size);
695 if (new_unicode == NULL) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +0100696 _Py_NewReference(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200697 PyErr_NoMemory();
698 return NULL;
699 }
Victor Stinner84def372011-12-11 20:04:56 +0100700 unicode = new_unicode;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200701 _Py_NewReference(unicode);
Victor Stinner84def372011-12-11 20:04:56 +0100702
Victor Stinnerfe226c02011-10-03 03:52:20 +0200703 _PyUnicode_LENGTH(unicode) = length;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200704 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200705 _PyUnicode_WSTR(unicode) = PyUnicode_DATA(unicode);
Victor Stinner488fa492011-12-12 00:01:39 +0100706 if (!PyUnicode_IS_ASCII(unicode))
Victor Stinnerc379ead2011-10-03 12:52:27 +0200707 _PyUnicode_WSTR_LENGTH(unicode) = length;
708 }
Victor Stinnerafffce42012-10-03 23:03:17 +0200709#ifdef Py_DEBUG
710 unicode_fill_invalid(unicode, old_length);
711#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +0200712 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
713 length, 0);
Victor Stinner79891572012-05-03 13:43:07 +0200714 assert(_PyUnicode_CheckConsistency(unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200715 return unicode;
716}
717
Alexander Belopolsky40018472011-02-26 01:02:56 +0000718static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200719resize_inplace(PyObject *unicode, Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000720{
Victor Stinner95663112011-10-04 01:03:50 +0200721 wchar_t *wstr;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100722 Py_ssize_t new_size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200723 assert(!PyUnicode_IS_COMPACT(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200724 assert(Py_REFCNT(unicode) == 1);
Tim Petersced69f82003-09-16 20:30:58 +0000725
Victor Stinnerfe226c02011-10-03 03:52:20 +0200726 if (PyUnicode_IS_READY(unicode)) {
727 Py_ssize_t char_size;
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200728 int share_wstr, share_utf8;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200729 void *data;
Victor Stinnerafffce42012-10-03 23:03:17 +0200730#ifdef Py_DEBUG
731 Py_ssize_t old_length = _PyUnicode_LENGTH(unicode);
732#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +0200733
734 data = _PyUnicode_DATA_ANY(unicode);
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200735 char_size = PyUnicode_KIND(unicode);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200736 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
737 share_utf8 = _PyUnicode_SHARE_UTF8(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200738
739 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
740 PyErr_NoMemory();
741 return -1;
742 }
743 new_size = (length + 1) * char_size;
744
Victor Stinner7a9105a2011-12-12 00:13:42 +0100745 if (!share_utf8 && _PyUnicode_HAS_UTF8_MEMORY(unicode))
746 {
747 PyObject_DEL(_PyUnicode_UTF8(unicode));
748 _PyUnicode_UTF8(unicode) = NULL;
749 _PyUnicode_UTF8_LENGTH(unicode) = 0;
750 }
751
Victor Stinnerfe226c02011-10-03 03:52:20 +0200752 data = (PyObject *)PyObject_REALLOC(data, new_size);
753 if (data == NULL) {
754 PyErr_NoMemory();
755 return -1;
756 }
757 _PyUnicode_DATA_ANY(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200758 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200759 _PyUnicode_WSTR(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200760 _PyUnicode_WSTR_LENGTH(unicode) = length;
761 }
762 if (share_utf8) {
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200763 _PyUnicode_UTF8(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200764 _PyUnicode_UTF8_LENGTH(unicode) = length;
765 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200766 _PyUnicode_LENGTH(unicode) = length;
767 PyUnicode_WRITE(PyUnicode_KIND(unicode), data, length, 0);
Victor Stinnerafffce42012-10-03 23:03:17 +0200768#ifdef Py_DEBUG
769 unicode_fill_invalid(unicode, old_length);
770#endif
Victor Stinner95663112011-10-04 01:03:50 +0200771 if (share_wstr || _PyUnicode_WSTR(unicode) == NULL) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200772 assert(_PyUnicode_CheckConsistency(unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200773 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200774 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200775 }
Victor Stinner95663112011-10-04 01:03:50 +0200776 assert(_PyUnicode_WSTR(unicode) != NULL);
777
778 /* check for integer overflow */
779 if (length > PY_SSIZE_T_MAX / sizeof(wchar_t) - 1) {
780 PyErr_NoMemory();
781 return -1;
782 }
Victor Stinner7a9105a2011-12-12 00:13:42 +0100783 new_size = sizeof(wchar_t) * (length + 1);
Victor Stinner95663112011-10-04 01:03:50 +0200784 wstr = _PyUnicode_WSTR(unicode);
Victor Stinner7a9105a2011-12-12 00:13:42 +0100785 wstr = PyObject_REALLOC(wstr, new_size);
Victor Stinner95663112011-10-04 01:03:50 +0200786 if (!wstr) {
787 PyErr_NoMemory();
788 return -1;
789 }
790 _PyUnicode_WSTR(unicode) = wstr;
791 _PyUnicode_WSTR(unicode)[length] = 0;
792 _PyUnicode_WSTR_LENGTH(unicode) = length;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200793 assert(_PyUnicode_CheckConsistency(unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +0000794 return 0;
795}
796
Victor Stinnerfe226c02011-10-03 03:52:20 +0200797static PyObject*
798resize_copy(PyObject *unicode, Py_ssize_t length)
799{
800 Py_ssize_t copy_length;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100801 if (_PyUnicode_KIND(unicode) != PyUnicode_WCHAR_KIND) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200802 PyObject *copy;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100803
Benjamin Petersonbac79492012-01-14 13:34:47 -0500804 if (PyUnicode_READY(unicode) == -1)
Victor Stinner7a9105a2011-12-12 00:13:42 +0100805 return NULL;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200806
807 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
808 if (copy == NULL)
809 return NULL;
810
811 copy_length = Py_MIN(length, PyUnicode_GET_LENGTH(unicode));
Victor Stinnerd3f08822012-05-29 12:57:52 +0200812 _PyUnicode_FastCopyCharacters(copy, 0, unicode, 0, copy_length);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200813 return copy;
Victor Stinner8cfcbed2011-10-03 23:19:21 +0200814 }
815 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200816 PyObject *w;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100817
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200818 w = (PyObject*)_PyUnicode_New(length);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200819 if (w == NULL)
820 return NULL;
821 copy_length = _PyUnicode_WSTR_LENGTH(unicode);
822 copy_length = Py_MIN(copy_length, length);
823 Py_UNICODE_COPY(_PyUnicode_WSTR(w), _PyUnicode_WSTR(unicode),
824 copy_length);
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200825 return w;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200826 }
827}
828
Guido van Rossumd57fd912000-03-10 22:53:23 +0000829/* We allocate one more byte to make sure the string is
Martin v. Löwis47383402007-08-15 07:32:56 +0000830 Ux0000 terminated; some code (e.g. new_identifier)
831 relies on that.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000832
833 XXX This allocator could further be enhanced by assuring that the
Benjamin Peterson29060642009-01-31 22:14:21 +0000834 free list never reduces its size below 1.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000835
836*/
837
Alexander Belopolsky40018472011-02-26 01:02:56 +0000838static PyUnicodeObject *
839_PyUnicode_New(Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000840{
841 register PyUnicodeObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200842 size_t new_size;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000843
Thomas Wouters477c8d52006-05-27 19:21:47 +0000844 /* Optimization for empty strings */
Guido van Rossumd57fd912000-03-10 22:53:23 +0000845 if (length == 0 && unicode_empty != NULL) {
846 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +0200847 return (PyUnicodeObject*)unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000848 }
849
Neal Norwitz3ce5d922008-08-24 07:08:55 +0000850 /* Ensure we won't overflow the size. */
851 if (length > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
852 return (PyUnicodeObject *)PyErr_NoMemory();
853 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200854 if (length < 0) {
855 PyErr_SetString(PyExc_SystemError,
856 "Negative size passed to _PyUnicode_New");
857 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000858 }
859
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200860 unicode = PyObject_New(PyUnicodeObject, &PyUnicode_Type);
861 if (unicode == NULL)
862 return NULL;
863 new_size = sizeof(Py_UNICODE) * ((size_t)length + 1);
864 _PyUnicode_WSTR(unicode) = (Py_UNICODE*) PyObject_MALLOC(new_size);
865 if (!_PyUnicode_WSTR(unicode)) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +0100866 Py_DECREF(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +0000867 PyErr_NoMemory();
Victor Stinnerb0a82a62011-12-12 13:08:33 +0100868 return NULL;
Guido van Rossum3c1bb802000-04-27 20:13:50 +0000869 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200870
Jeremy Hyltond8082792003-09-16 19:41:39 +0000871 /* Initialize the first element to guard against cases where
Tim Petersced69f82003-09-16 20:30:58 +0000872 * the caller fails before initializing str -- unicode_resize()
873 * reads str[0], and the Keep-Alive optimization can keep memory
874 * allocated for str alive across a call to unicode_dealloc(unicode).
875 * We don't want unicode_resize to read uninitialized memory in
876 * that case.
877 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200878 _PyUnicode_WSTR(unicode)[0] = 0;
879 _PyUnicode_WSTR(unicode)[length] = 0;
880 _PyUnicode_WSTR_LENGTH(unicode) = length;
881 _PyUnicode_HASH(unicode) = -1;
882 _PyUnicode_STATE(unicode).interned = 0;
883 _PyUnicode_STATE(unicode).kind = 0;
884 _PyUnicode_STATE(unicode).compact = 0;
885 _PyUnicode_STATE(unicode).ready = 0;
886 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +0200887 _PyUnicode_DATA_ANY(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200888 _PyUnicode_LENGTH(unicode) = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200889 _PyUnicode_UTF8(unicode) = NULL;
890 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner7931d9a2011-11-04 00:22:48 +0100891 assert(_PyUnicode_CheckConsistency((PyObject *)unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +0000892 return unicode;
893}
894
Victor Stinnerf42dc442011-10-02 23:33:16 +0200895static const char*
896unicode_kind_name(PyObject *unicode)
897{
Victor Stinner42dfd712011-10-03 14:41:45 +0200898 /* don't check consistency: unicode_kind_name() is called from
899 _PyUnicode_Dump() */
Victor Stinnerf42dc442011-10-02 23:33:16 +0200900 if (!PyUnicode_IS_COMPACT(unicode))
901 {
902 if (!PyUnicode_IS_READY(unicode))
903 return "wstr";
Benjamin Petersonead6b532011-12-20 17:23:42 -0600904 switch (PyUnicode_KIND(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200905 {
906 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200907 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200908 return "legacy ascii";
909 else
910 return "legacy latin1";
911 case PyUnicode_2BYTE_KIND:
912 return "legacy UCS2";
913 case PyUnicode_4BYTE_KIND:
914 return "legacy UCS4";
915 default:
916 return "<legacy invalid kind>";
917 }
918 }
919 assert(PyUnicode_IS_READY(unicode));
Benjamin Petersonead6b532011-12-20 17:23:42 -0600920 switch (PyUnicode_KIND(unicode)) {
Victor Stinnerf42dc442011-10-02 23:33:16 +0200921 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200922 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200923 return "ascii";
924 else
Victor Stinnera3b334d2011-10-03 13:53:37 +0200925 return "latin1";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200926 case PyUnicode_2BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200927 return "UCS2";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200928 case PyUnicode_4BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200929 return "UCS4";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200930 default:
931 return "<invalid compact kind>";
932 }
933}
934
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200935#ifdef Py_DEBUG
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200936/* Functions wrapping macros for use in debugger */
937char *_PyUnicode_utf8(void *unicode){
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200938 return PyUnicode_UTF8(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200939}
940
941void *_PyUnicode_compact_data(void *unicode) {
942 return _PyUnicode_COMPACT_DATA(unicode);
943}
944void *_PyUnicode_data(void *unicode){
945 printf("obj %p\n", unicode);
946 printf("compact %d\n", PyUnicode_IS_COMPACT(unicode));
947 printf("compact ascii %d\n", PyUnicode_IS_COMPACT_ASCII(unicode));
948 printf("ascii op %p\n", ((void*)((PyASCIIObject*)(unicode) + 1)));
949 printf("compact op %p\n", ((void*)((PyCompactUnicodeObject*)(unicode) + 1)));
950 printf("compact data %p\n", _PyUnicode_COMPACT_DATA(unicode));
951 return PyUnicode_DATA(unicode);
952}
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200953
954void
955_PyUnicode_Dump(PyObject *op)
956{
957 PyASCIIObject *ascii = (PyASCIIObject *)op;
Victor Stinnera849a4b2011-10-03 12:12:11 +0200958 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
959 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
960 void *data;
Victor Stinner0d60e872011-10-23 19:47:19 +0200961
Victor Stinnera849a4b2011-10-03 12:12:11 +0200962 if (ascii->state.compact)
Victor Stinner0d60e872011-10-23 19:47:19 +0200963 {
964 if (ascii->state.ascii)
965 data = (ascii + 1);
966 else
967 data = (compact + 1);
968 }
Victor Stinnera849a4b2011-10-03 12:12:11 +0200969 else
970 data = unicode->data.any;
Victor Stinner0d60e872011-10-23 19:47:19 +0200971 printf("%s: len=%zu, ",unicode_kind_name(op), ascii->length);
972
Victor Stinnera849a4b2011-10-03 12:12:11 +0200973 if (ascii->wstr == data)
974 printf("shared ");
975 printf("wstr=%p", ascii->wstr);
Victor Stinner0d60e872011-10-23 19:47:19 +0200976
Victor Stinnera3b334d2011-10-03 13:53:37 +0200977 if (!(ascii->state.ascii == 1 && ascii->state.compact == 1)) {
Victor Stinnera849a4b2011-10-03 12:12:11 +0200978 printf(" (%zu), ", compact->wstr_length);
979 if (!ascii->state.compact && compact->utf8 == unicode->data.any)
980 printf("shared ");
981 printf("utf8=%p (%zu)", compact->utf8, compact->utf8_length);
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200982 }
Victor Stinnera849a4b2011-10-03 12:12:11 +0200983 printf(", data=%p\n", data);
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200984}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200985#endif
986
987PyObject *
988PyUnicode_New(Py_ssize_t size, Py_UCS4 maxchar)
989{
990 PyObject *obj;
991 PyCompactUnicodeObject *unicode;
992 void *data;
Victor Stinner8f825062012-04-27 13:55:39 +0200993 enum PyUnicode_Kind kind;
Victor Stinner9e9d6892011-10-04 01:02:02 +0200994 int is_sharing, is_ascii;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200995 Py_ssize_t char_size;
996 Py_ssize_t struct_size;
997
998 /* Optimization for empty strings */
999 if (size == 0 && unicode_empty != NULL) {
1000 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001001 return unicode_empty;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001002 }
1003
Victor Stinner9e9d6892011-10-04 01:02:02 +02001004 is_ascii = 0;
1005 is_sharing = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001006 struct_size = sizeof(PyCompactUnicodeObject);
1007 if (maxchar < 128) {
Victor Stinner8f825062012-04-27 13:55:39 +02001008 kind = PyUnicode_1BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001009 char_size = 1;
1010 is_ascii = 1;
1011 struct_size = sizeof(PyASCIIObject);
1012 }
1013 else if (maxchar < 256) {
Victor Stinner8f825062012-04-27 13:55:39 +02001014 kind = PyUnicode_1BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001015 char_size = 1;
1016 }
1017 else if (maxchar < 65536) {
Victor Stinner8f825062012-04-27 13:55:39 +02001018 kind = PyUnicode_2BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001019 char_size = 2;
1020 if (sizeof(wchar_t) == 2)
1021 is_sharing = 1;
1022 }
1023 else {
Victor Stinnerc9590ad2012-03-04 01:34:37 +01001024 if (maxchar > MAX_UNICODE) {
1025 PyErr_SetString(PyExc_SystemError,
1026 "invalid maximum character passed to PyUnicode_New");
1027 return NULL;
1028 }
Victor Stinner8f825062012-04-27 13:55:39 +02001029 kind = PyUnicode_4BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001030 char_size = 4;
1031 if (sizeof(wchar_t) == 4)
1032 is_sharing = 1;
1033 }
1034
1035 /* Ensure we won't overflow the size. */
1036 if (size < 0) {
1037 PyErr_SetString(PyExc_SystemError,
1038 "Negative size passed to PyUnicode_New");
1039 return NULL;
1040 }
1041 if (size > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1))
1042 return PyErr_NoMemory();
1043
1044 /* Duplicated allocation code from _PyObject_New() instead of a call to
1045 * PyObject_New() so we are able to allocate space for the object and
1046 * it's data buffer.
1047 */
1048 obj = (PyObject *) PyObject_MALLOC(struct_size + (size + 1) * char_size);
1049 if (obj == NULL)
1050 return PyErr_NoMemory();
1051 obj = PyObject_INIT(obj, &PyUnicode_Type);
1052 if (obj == NULL)
1053 return NULL;
1054
1055 unicode = (PyCompactUnicodeObject *)obj;
1056 if (is_ascii)
1057 data = ((PyASCIIObject*)obj) + 1;
1058 else
1059 data = unicode + 1;
1060 _PyUnicode_LENGTH(unicode) = size;
1061 _PyUnicode_HASH(unicode) = -1;
1062 _PyUnicode_STATE(unicode).interned = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001063 _PyUnicode_STATE(unicode).kind = kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001064 _PyUnicode_STATE(unicode).compact = 1;
1065 _PyUnicode_STATE(unicode).ready = 1;
1066 _PyUnicode_STATE(unicode).ascii = is_ascii;
1067 if (is_ascii) {
1068 ((char*)data)[size] = 0;
1069 _PyUnicode_WSTR(unicode) = NULL;
1070 }
Victor Stinner8f825062012-04-27 13:55:39 +02001071 else if (kind == PyUnicode_1BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001072 ((char*)data)[size] = 0;
1073 _PyUnicode_WSTR(unicode) = NULL;
1074 _PyUnicode_WSTR_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001075 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001076 unicode->utf8_length = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001077 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001078 else {
1079 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001080 unicode->utf8_length = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001081 if (kind == PyUnicode_2BYTE_KIND)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001082 ((Py_UCS2*)data)[size] = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001083 else /* kind == PyUnicode_4BYTE_KIND */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001084 ((Py_UCS4*)data)[size] = 0;
1085 if (is_sharing) {
1086 _PyUnicode_WSTR_LENGTH(unicode) = size;
1087 _PyUnicode_WSTR(unicode) = (wchar_t *)data;
1088 }
1089 else {
1090 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1091 _PyUnicode_WSTR(unicode) = NULL;
1092 }
1093 }
Victor Stinner8f825062012-04-27 13:55:39 +02001094#ifdef Py_DEBUG
Victor Stinnerafffce42012-10-03 23:03:17 +02001095 unicode_fill_invalid((PyObject*)unicode, 0);
Victor Stinner8f825062012-04-27 13:55:39 +02001096#endif
Victor Stinner7931d9a2011-11-04 00:22:48 +01001097 assert(_PyUnicode_CheckConsistency((PyObject*)unicode, 0));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001098 return obj;
1099}
1100
1101#if SIZEOF_WCHAR_T == 2
1102/* Helper function to convert a 16-bits wchar_t representation to UCS4, this
1103 will decode surrogate pairs, the other conversions are implemented as macros
Georg Brandl7597add2011-10-05 16:36:47 +02001104 for efficiency.
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001105
1106 This function assumes that unicode can hold one more code point than wstr
1107 characters for a terminating null character. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001108static void
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001109unicode_convert_wchar_to_ucs4(const wchar_t *begin, const wchar_t *end,
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001110 PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001111{
1112 const wchar_t *iter;
1113 Py_UCS4 *ucs4_out;
1114
Victor Stinner910337b2011-10-03 03:20:16 +02001115 assert(unicode != NULL);
1116 assert(_PyUnicode_CHECK(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001117 assert(_PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
1118 ucs4_out = PyUnicode_4BYTE_DATA(unicode);
1119
1120 for (iter = begin; iter < end; ) {
1121 assert(ucs4_out < (PyUnicode_4BYTE_DATA(unicode) +
1122 _PyUnicode_GET_LENGTH(unicode)));
Victor Stinner551ac952011-11-29 22:58:13 +01001123 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1124 && (iter+1) < end
1125 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001126 {
Victor Stinner551ac952011-11-29 22:58:13 +01001127 *ucs4_out++ = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001128 iter += 2;
1129 }
1130 else {
1131 *ucs4_out++ = *iter;
1132 iter++;
1133 }
1134 }
1135 assert(ucs4_out == (PyUnicode_4BYTE_DATA(unicode) +
1136 _PyUnicode_GET_LENGTH(unicode)));
1137
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001138}
1139#endif
1140
Victor Stinnercd9950f2011-10-02 00:34:53 +02001141static int
Victor Stinner488fa492011-12-12 00:01:39 +01001142unicode_check_modifiable(PyObject *unicode)
Victor Stinnercd9950f2011-10-02 00:34:53 +02001143{
Victor Stinner488fa492011-12-12 00:01:39 +01001144 if (!unicode_modifiable(unicode)) {
Victor Stinner01698042011-10-04 00:04:26 +02001145 PyErr_SetString(PyExc_SystemError,
Victor Stinner488fa492011-12-12 00:01:39 +01001146 "Cannot modify a string currently used");
Victor Stinnercd9950f2011-10-02 00:34:53 +02001147 return -1;
1148 }
Victor Stinnercd9950f2011-10-02 00:34:53 +02001149 return 0;
1150}
1151
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001152static int
1153_copy_characters(PyObject *to, Py_ssize_t to_start,
1154 PyObject *from, Py_ssize_t from_start,
1155 Py_ssize_t how_many, int check_maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001156{
Victor Stinnera0702ab2011-09-29 14:14:38 +02001157 unsigned int from_kind, to_kind;
1158 void *from_data, *to_data;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001159
Victor Stinneree4544c2012-05-09 22:24:08 +02001160 assert(0 <= how_many);
1161 assert(0 <= from_start);
1162 assert(0 <= to_start);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001163 assert(PyUnicode_Check(from));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001164 assert(PyUnicode_IS_READY(from));
Victor Stinneree4544c2012-05-09 22:24:08 +02001165 assert(from_start + how_many <= PyUnicode_GET_LENGTH(from));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001166
Victor Stinnerd3f08822012-05-29 12:57:52 +02001167 assert(PyUnicode_Check(to));
1168 assert(PyUnicode_IS_READY(to));
1169 assert(to_start + how_many <= PyUnicode_GET_LENGTH(to));
1170
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001171 if (how_many == 0)
1172 return 0;
1173
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001174 from_kind = PyUnicode_KIND(from);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001175 from_data = PyUnicode_DATA(from);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001176 to_kind = PyUnicode_KIND(to);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001177 to_data = PyUnicode_DATA(to);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001178
Victor Stinnerf1852262012-06-16 16:38:26 +02001179#ifdef Py_DEBUG
1180 if (!check_maxchar
1181 && PyUnicode_MAX_CHAR_VALUE(from) > PyUnicode_MAX_CHAR_VALUE(to))
1182 {
1183 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
1184 Py_UCS4 ch;
1185 Py_ssize_t i;
1186 for (i=0; i < how_many; i++) {
1187 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1188 assert(ch <= to_maxchar);
1189 }
1190 }
1191#endif
1192
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001193 if (from_kind == to_kind) {
Victor Stinnerf1852262012-06-16 16:38:26 +02001194 if (check_maxchar
1195 && !PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to))
1196 {
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001197 /* Writing Latin-1 characters into an ASCII string requires to
1198 check that all written characters are pure ASCII */
Victor Stinnerf1852262012-06-16 16:38:26 +02001199 Py_UCS4 max_char;
1200 max_char = ucs1lib_find_max_char(from_data,
1201 (Py_UCS1*)from_data + how_many);
1202 if (max_char >= 128)
1203 return -1;
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001204 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +02001205 Py_MEMCPY((char*)to_data + to_kind * to_start,
1206 (char*)from_data + from_kind * from_start,
1207 to_kind * how_many);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001208 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001209 else if (from_kind == PyUnicode_1BYTE_KIND
1210 && to_kind == PyUnicode_2BYTE_KIND)
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001211 {
1212 _PyUnicode_CONVERT_BYTES(
1213 Py_UCS1, Py_UCS2,
1214 PyUnicode_1BYTE_DATA(from) + from_start,
1215 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1216 PyUnicode_2BYTE_DATA(to) + to_start
1217 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001218 }
Victor Stinner157f83f2011-09-28 21:41:31 +02001219 else if (from_kind == PyUnicode_1BYTE_KIND
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001220 && to_kind == PyUnicode_4BYTE_KIND)
1221 {
1222 _PyUnicode_CONVERT_BYTES(
1223 Py_UCS1, Py_UCS4,
1224 PyUnicode_1BYTE_DATA(from) + from_start,
1225 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1226 PyUnicode_4BYTE_DATA(to) + to_start
1227 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001228 }
1229 else if (from_kind == PyUnicode_2BYTE_KIND
1230 && to_kind == PyUnicode_4BYTE_KIND)
1231 {
1232 _PyUnicode_CONVERT_BYTES(
1233 Py_UCS2, Py_UCS4,
1234 PyUnicode_2BYTE_DATA(from) + from_start,
1235 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1236 PyUnicode_4BYTE_DATA(to) + to_start
1237 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001238 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001239 else {
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001240 assert (PyUnicode_MAX_CHAR_VALUE(from) > PyUnicode_MAX_CHAR_VALUE(to));
1241
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001242 if (!check_maxchar) {
1243 if (from_kind == PyUnicode_2BYTE_KIND
1244 && to_kind == PyUnicode_1BYTE_KIND)
1245 {
1246 _PyUnicode_CONVERT_BYTES(
1247 Py_UCS2, Py_UCS1,
1248 PyUnicode_2BYTE_DATA(from) + from_start,
1249 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1250 PyUnicode_1BYTE_DATA(to) + to_start
1251 );
1252 }
1253 else if (from_kind == PyUnicode_4BYTE_KIND
1254 && to_kind == PyUnicode_1BYTE_KIND)
1255 {
1256 _PyUnicode_CONVERT_BYTES(
1257 Py_UCS4, Py_UCS1,
1258 PyUnicode_4BYTE_DATA(from) + from_start,
1259 PyUnicode_4BYTE_DATA(from) + from_start + how_many,
1260 PyUnicode_1BYTE_DATA(to) + to_start
1261 );
1262 }
1263 else if (from_kind == PyUnicode_4BYTE_KIND
1264 && to_kind == PyUnicode_2BYTE_KIND)
1265 {
1266 _PyUnicode_CONVERT_BYTES(
1267 Py_UCS4, Py_UCS2,
1268 PyUnicode_4BYTE_DATA(from) + from_start,
1269 PyUnicode_4BYTE_DATA(from) + from_start + how_many,
1270 PyUnicode_2BYTE_DATA(to) + to_start
1271 );
1272 }
1273 else {
1274 assert(0);
1275 return -1;
1276 }
1277 }
Victor Stinnerf1852262012-06-16 16:38:26 +02001278 else {
Victor Stinnera0702ab2011-09-29 14:14:38 +02001279 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001280 Py_UCS4 ch;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001281 Py_ssize_t i;
1282
Victor Stinnera0702ab2011-09-29 14:14:38 +02001283 for (i=0; i < how_many; i++) {
1284 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001285 if (ch > to_maxchar)
1286 return -1;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001287 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1288 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001289 }
1290 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001291 return 0;
1292}
1293
Victor Stinnerd3f08822012-05-29 12:57:52 +02001294void
1295_PyUnicode_FastCopyCharacters(
1296 PyObject *to, Py_ssize_t to_start,
1297 PyObject *from, Py_ssize_t from_start, Py_ssize_t how_many)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001298{
1299 (void)_copy_characters(to, to_start, from, from_start, how_many, 0);
1300}
1301
1302Py_ssize_t
1303PyUnicode_CopyCharacters(PyObject *to, Py_ssize_t to_start,
1304 PyObject *from, Py_ssize_t from_start,
1305 Py_ssize_t how_many)
1306{
1307 int err;
1308
1309 if (!PyUnicode_Check(from) || !PyUnicode_Check(to)) {
1310 PyErr_BadInternalCall();
1311 return -1;
1312 }
1313
Benjamin Petersonbac79492012-01-14 13:34:47 -05001314 if (PyUnicode_READY(from) == -1)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001315 return -1;
Benjamin Petersonbac79492012-01-14 13:34:47 -05001316 if (PyUnicode_READY(to) == -1)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001317 return -1;
1318
Victor Stinnerd3f08822012-05-29 12:57:52 +02001319 if (from_start < 0) {
1320 PyErr_SetString(PyExc_IndexError, "string index out of range");
1321 return -1;
1322 }
1323 if (to_start < 0) {
1324 PyErr_SetString(PyExc_IndexError, "string index out of range");
1325 return -1;
1326 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001327 how_many = Py_MIN(PyUnicode_GET_LENGTH(from), how_many);
1328 if (to_start + how_many > PyUnicode_GET_LENGTH(to)) {
1329 PyErr_Format(PyExc_SystemError,
1330 "Cannot write %zi characters at %zi "
1331 "in a string of %zi characters",
1332 how_many, to_start, PyUnicode_GET_LENGTH(to));
1333 return -1;
1334 }
1335
1336 if (how_many == 0)
1337 return 0;
1338
Victor Stinner488fa492011-12-12 00:01:39 +01001339 if (unicode_check_modifiable(to))
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001340 return -1;
1341
1342 err = _copy_characters(to, to_start, from, from_start, how_many, 1);
1343 if (err) {
1344 PyErr_Format(PyExc_SystemError,
1345 "Cannot copy %s characters "
1346 "into a string of %s characters",
1347 unicode_kind_name(from),
1348 unicode_kind_name(to));
1349 return -1;
1350 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001351 return how_many;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001352}
1353
Victor Stinner17222162011-09-28 22:15:37 +02001354/* Find the maximum code point and count the number of surrogate pairs so a
1355 correct string length can be computed before converting a string to UCS4.
1356 This function counts single surrogates as a character and not as a pair.
1357
1358 Return 0 on success, or -1 on error. */
1359static int
1360find_maxchar_surrogates(const wchar_t *begin, const wchar_t *end,
1361 Py_UCS4 *maxchar, Py_ssize_t *num_surrogates)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001362{
1363 const wchar_t *iter;
Victor Stinner8faf8212011-12-08 22:14:11 +01001364 Py_UCS4 ch;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001365
Victor Stinnerc53be962011-10-02 21:33:54 +02001366 assert(num_surrogates != NULL && maxchar != NULL);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001367 *num_surrogates = 0;
1368 *maxchar = 0;
1369
1370 for (iter = begin; iter < end; ) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001371#if SIZEOF_WCHAR_T == 2
Victor Stinnerca4f2072011-11-22 03:38:40 +01001372 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1373 && (iter+1) < end
1374 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001375 {
Victor Stinner8faf8212011-12-08 22:14:11 +01001376 ch = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001377 ++(*num_surrogates);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001378 iter += 2;
1379 }
1380 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001381#endif
Victor Stinner8faf8212011-12-08 22:14:11 +01001382 {
1383 ch = *iter;
1384 iter++;
1385 }
1386 if (ch > *maxchar) {
1387 *maxchar = ch;
1388 if (*maxchar > MAX_UNICODE) {
1389 PyErr_Format(PyExc_ValueError,
1390 "character U+%x is not in range [U+0000; U+10ffff]",
1391 ch);
1392 return -1;
1393 }
1394 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001395 }
1396 return 0;
1397}
1398
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001399int
1400_PyUnicode_Ready(PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001401{
1402 wchar_t *end;
1403 Py_UCS4 maxchar = 0;
1404 Py_ssize_t num_surrogates;
1405#if SIZEOF_WCHAR_T == 2
1406 Py_ssize_t length_wo_surrogates;
1407#endif
1408
Georg Brandl7597add2011-10-05 16:36:47 +02001409 /* _PyUnicode_Ready() is only intended for old-style API usage where
Victor Stinnerd8f65102011-09-29 19:43:17 +02001410 strings were created using _PyObject_New() and where no canonical
1411 representation (the str field) has been set yet aka strings
1412 which are not yet ready. */
Victor Stinner910337b2011-10-03 03:20:16 +02001413 assert(_PyUnicode_CHECK(unicode));
1414 assert(_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001415 assert(_PyUnicode_WSTR(unicode) != NULL);
Victor Stinnerc3c74152011-10-02 20:39:55 +02001416 assert(_PyUnicode_DATA_ANY(unicode) == NULL);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001417 assert(_PyUnicode_UTF8(unicode) == NULL);
Victor Stinnerd8f65102011-09-29 19:43:17 +02001418 /* Actually, it should neither be interned nor be anything else: */
1419 assert(_PyUnicode_STATE(unicode).interned == SSTATE_NOT_INTERNED);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001420
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001421 end = _PyUnicode_WSTR(unicode) + _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinner17222162011-09-28 22:15:37 +02001422 if (find_maxchar_surrogates(_PyUnicode_WSTR(unicode), end,
Victor Stinnerd8f65102011-09-29 19:43:17 +02001423 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001424 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001425
1426 if (maxchar < 256) {
Victor Stinnerc3c74152011-10-02 20:39:55 +02001427 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(_PyUnicode_WSTR_LENGTH(unicode) + 1);
1428 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001429 PyErr_NoMemory();
1430 return -1;
1431 }
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001432 _PyUnicode_CONVERT_BYTES(wchar_t, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001433 _PyUnicode_WSTR(unicode), end,
1434 PyUnicode_1BYTE_DATA(unicode));
1435 PyUnicode_1BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1436 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1437 _PyUnicode_STATE(unicode).kind = PyUnicode_1BYTE_KIND;
1438 if (maxchar < 128) {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001439 _PyUnicode_STATE(unicode).ascii = 1;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001440 _PyUnicode_UTF8(unicode) = _PyUnicode_DATA_ANY(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001441 _PyUnicode_UTF8_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001442 }
1443 else {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001444 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001445 _PyUnicode_UTF8(unicode) = NULL;
1446 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001447 }
1448 PyObject_FREE(_PyUnicode_WSTR(unicode));
1449 _PyUnicode_WSTR(unicode) = NULL;
1450 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1451 }
1452 /* In this case we might have to convert down from 4-byte native
1453 wchar_t to 2-byte unicode. */
1454 else if (maxchar < 65536) {
1455 assert(num_surrogates == 0 &&
1456 "FindMaxCharAndNumSurrogatePairs() messed up");
1457
Victor Stinner506f5922011-09-28 22:34:18 +02001458#if SIZEOF_WCHAR_T == 2
1459 /* We can share representations and are done. */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001460 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Victor Stinner506f5922011-09-28 22:34:18 +02001461 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1462 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1463 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001464 _PyUnicode_UTF8(unicode) = NULL;
1465 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001466#else
1467 /* sizeof(wchar_t) == 4 */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001468 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(
Victor Stinner506f5922011-09-28 22:34:18 +02001469 2 * (_PyUnicode_WSTR_LENGTH(unicode) + 1));
Victor Stinnerc3c74152011-10-02 20:39:55 +02001470 if (!_PyUnicode_DATA_ANY(unicode)) {
Victor Stinner506f5922011-09-28 22:34:18 +02001471 PyErr_NoMemory();
1472 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001473 }
Victor Stinner506f5922011-09-28 22:34:18 +02001474 _PyUnicode_CONVERT_BYTES(wchar_t, Py_UCS2,
1475 _PyUnicode_WSTR(unicode), end,
1476 PyUnicode_2BYTE_DATA(unicode));
1477 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1478 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1479 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001480 _PyUnicode_UTF8(unicode) = NULL;
1481 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001482 PyObject_FREE(_PyUnicode_WSTR(unicode));
1483 _PyUnicode_WSTR(unicode) = NULL;
1484 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1485#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001486 }
1487 /* maxchar exeeds 16 bit, wee need 4 bytes for unicode characters */
1488 else {
1489#if SIZEOF_WCHAR_T == 2
1490 /* in case the native representation is 2-bytes, we need to allocate a
1491 new normalized 4-byte version. */
1492 length_wo_surrogates = _PyUnicode_WSTR_LENGTH(unicode) - num_surrogates;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001493 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(4 * (length_wo_surrogates + 1));
1494 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001495 PyErr_NoMemory();
1496 return -1;
1497 }
1498 _PyUnicode_LENGTH(unicode) = length_wo_surrogates;
1499 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001500 _PyUnicode_UTF8(unicode) = NULL;
1501 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner126c5592011-10-03 04:17:10 +02001502 /* unicode_convert_wchar_to_ucs4() requires a ready string */
1503 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerc53be962011-10-02 21:33:54 +02001504 unicode_convert_wchar_to_ucs4(_PyUnicode_WSTR(unicode), end, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001505 PyObject_FREE(_PyUnicode_WSTR(unicode));
1506 _PyUnicode_WSTR(unicode) = NULL;
1507 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1508#else
1509 assert(num_surrogates == 0);
1510
Victor Stinnerc3c74152011-10-02 20:39:55 +02001511 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001512 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001513 _PyUnicode_UTF8(unicode) = NULL;
1514 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001515 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
1516#endif
1517 PyUnicode_4BYTE_DATA(unicode)[_PyUnicode_LENGTH(unicode)] = '\0';
1518 }
1519 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001520 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001521 return 0;
1522}
1523
Alexander Belopolsky40018472011-02-26 01:02:56 +00001524static void
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001525unicode_dealloc(register PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001526{
Walter Dörwald16807132007-05-25 13:52:07 +00001527 switch (PyUnicode_CHECK_INTERNED(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001528 case SSTATE_NOT_INTERNED:
1529 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001530
Benjamin Peterson29060642009-01-31 22:14:21 +00001531 case SSTATE_INTERNED_MORTAL:
1532 /* revive dead object temporarily for DelItem */
1533 Py_REFCNT(unicode) = 3;
Victor Stinner7931d9a2011-11-04 00:22:48 +01001534 if (PyDict_DelItem(interned, unicode) != 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00001535 Py_FatalError(
1536 "deletion of interned string failed");
1537 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001538
Benjamin Peterson29060642009-01-31 22:14:21 +00001539 case SSTATE_INTERNED_IMMORTAL:
1540 Py_FatalError("Immortal interned string died.");
Walter Dörwald16807132007-05-25 13:52:07 +00001541
Benjamin Peterson29060642009-01-31 22:14:21 +00001542 default:
1543 Py_FatalError("Inconsistent interned string state.");
Walter Dörwald16807132007-05-25 13:52:07 +00001544 }
1545
Victor Stinner03490912011-10-03 23:45:12 +02001546 if (_PyUnicode_HAS_WSTR_MEMORY(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001547 PyObject_DEL(_PyUnicode_WSTR(unicode));
Victor Stinner829c0ad2011-10-03 01:08:02 +02001548 if (_PyUnicode_HAS_UTF8_MEMORY(unicode))
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001549 PyObject_DEL(_PyUnicode_UTF8(unicode));
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001550 if (!PyUnicode_IS_COMPACT(unicode) && _PyUnicode_DATA_ANY(unicode))
1551 PyObject_DEL(_PyUnicode_DATA_ANY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001552
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001553 Py_TYPE(unicode)->tp_free(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001554}
1555
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001556#ifdef Py_DEBUG
1557static int
1558unicode_is_singleton(PyObject *unicode)
1559{
1560 PyASCIIObject *ascii = (PyASCIIObject *)unicode;
1561 if (unicode == unicode_empty)
1562 return 1;
1563 if (ascii->state.kind != PyUnicode_WCHAR_KIND && ascii->length == 1)
1564 {
1565 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, 0);
1566 if (ch < 256 && unicode_latin1[ch] == unicode)
1567 return 1;
1568 }
1569 return 0;
1570}
1571#endif
1572
Alexander Belopolsky40018472011-02-26 01:02:56 +00001573static int
Victor Stinner488fa492011-12-12 00:01:39 +01001574unicode_modifiable(PyObject *unicode)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001575{
Victor Stinner488fa492011-12-12 00:01:39 +01001576 assert(_PyUnicode_CHECK(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001577 if (Py_REFCNT(unicode) != 1)
1578 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001579 if (_PyUnicode_HASH(unicode) != -1)
1580 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001581 if (PyUnicode_CHECK_INTERNED(unicode))
1582 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001583 if (!PyUnicode_CheckExact(unicode))
1584 return 0;
Victor Stinner77bb47b2011-10-03 20:06:05 +02001585#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001586 /* singleton refcount is greater than 1 */
1587 assert(!unicode_is_singleton(unicode));
Victor Stinner77bb47b2011-10-03 20:06:05 +02001588#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +02001589 return 1;
1590}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001591
Victor Stinnerfe226c02011-10-03 03:52:20 +02001592static int
1593unicode_resize(PyObject **p_unicode, Py_ssize_t length)
1594{
1595 PyObject *unicode;
1596 Py_ssize_t old_length;
1597
1598 assert(p_unicode != NULL);
1599 unicode = *p_unicode;
1600
1601 assert(unicode != NULL);
1602 assert(PyUnicode_Check(unicode));
1603 assert(0 <= length);
1604
Victor Stinner910337b2011-10-03 03:20:16 +02001605 if (_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001606 old_length = PyUnicode_WSTR_LENGTH(unicode);
1607 else
1608 old_length = PyUnicode_GET_LENGTH(unicode);
1609 if (old_length == length)
1610 return 0;
1611
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001612 if (length == 0) {
1613 Py_DECREF(*p_unicode);
1614 *p_unicode = unicode_empty;
1615 Py_INCREF(*p_unicode);
1616 return 0;
1617 }
1618
Victor Stinner488fa492011-12-12 00:01:39 +01001619 if (!unicode_modifiable(unicode)) {
Victor Stinnerfe226c02011-10-03 03:52:20 +02001620 PyObject *copy = resize_copy(unicode, length);
1621 if (copy == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001622 return -1;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001623 Py_DECREF(*p_unicode);
1624 *p_unicode = copy;
Benjamin Peterson29060642009-01-31 22:14:21 +00001625 return 0;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001626 }
1627
Victor Stinnerfe226c02011-10-03 03:52:20 +02001628 if (PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001629 PyObject *new_unicode = resize_compact(unicode, length);
1630 if (new_unicode == NULL)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001631 return -1;
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001632 *p_unicode = new_unicode;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001633 return 0;
Benjamin Peterson4bfce8f2011-10-03 19:35:07 -04001634 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001635 return resize_inplace(unicode, length);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001636}
1637
Alexander Belopolsky40018472011-02-26 01:02:56 +00001638int
Victor Stinnerfe226c02011-10-03 03:52:20 +02001639PyUnicode_Resize(PyObject **p_unicode, Py_ssize_t length)
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001640{
Victor Stinnerfe226c02011-10-03 03:52:20 +02001641 PyObject *unicode;
1642 if (p_unicode == NULL) {
1643 PyErr_BadInternalCall();
1644 return -1;
1645 }
1646 unicode = *p_unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001647 if (unicode == NULL || !PyUnicode_Check(unicode) || length < 0)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001648 {
1649 PyErr_BadInternalCall();
1650 return -1;
1651 }
1652 return unicode_resize(p_unicode, length);
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001653}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001654
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001655static int
Victor Stinner1b487b42012-05-03 12:29:04 +02001656unicode_widen(PyObject **p_unicode, Py_ssize_t length,
1657 unsigned int maxchar)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001658{
1659 PyObject *result;
1660 assert(PyUnicode_IS_READY(*p_unicode));
Victor Stinner1b487b42012-05-03 12:29:04 +02001661 assert(length <= PyUnicode_GET_LENGTH(*p_unicode));
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001662 if (maxchar <= PyUnicode_MAX_CHAR_VALUE(*p_unicode))
1663 return 0;
1664 result = PyUnicode_New(PyUnicode_GET_LENGTH(*p_unicode),
1665 maxchar);
1666 if (result == NULL)
1667 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +02001668 _PyUnicode_FastCopyCharacters(result, 0, *p_unicode, 0, length);
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001669 Py_DECREF(*p_unicode);
1670 *p_unicode = result;
1671 return 0;
1672}
1673
1674static int
1675unicode_putchar(PyObject **p_unicode, Py_ssize_t *pos,
1676 Py_UCS4 ch)
1677{
Victor Stinner15e9ed22012-02-22 13:36:20 +01001678 assert(ch <= MAX_UNICODE);
Victor Stinner1b487b42012-05-03 12:29:04 +02001679 if (unicode_widen(p_unicode, *pos, ch) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001680 return -1;
1681 PyUnicode_WRITE(PyUnicode_KIND(*p_unicode),
1682 PyUnicode_DATA(*p_unicode),
1683 (*pos)++, ch);
1684 return 0;
1685}
1686
Victor Stinnerc5166102012-02-22 13:55:02 +01001687/* Copy a ASCII or latin1 char* string into a Python Unicode string.
Victor Stinnerc5166102012-02-22 13:55:02 +01001688
Victor Stinnerb429d3b2012-02-22 21:22:20 +01001689 WARNING: The function doesn't copy the terminating null character and
1690 doesn't check the maximum character (may write a latin1 character in an
1691 ASCII string). */
Victor Stinner184252a2012-06-16 02:57:41 +02001692static void
1693unicode_write_cstr(PyObject *unicode, Py_ssize_t index,
1694 const char *str, Py_ssize_t len)
Victor Stinnerc5166102012-02-22 13:55:02 +01001695{
1696 enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
1697 void *data = PyUnicode_DATA(unicode);
Victor Stinner184252a2012-06-16 02:57:41 +02001698 const char *end = str + len;
Victor Stinnerc5166102012-02-22 13:55:02 +01001699
1700 switch (kind) {
1701 case PyUnicode_1BYTE_KIND: {
Victor Stinnerc5166102012-02-22 13:55:02 +01001702 assert(index + len <= PyUnicode_GET_LENGTH(unicode));
Antoine Pitrouba6bafc2012-02-22 16:41:50 +01001703 memcpy((char *) data + index, str, len);
Victor Stinner184252a2012-06-16 02:57:41 +02001704 break;
Victor Stinnerc5166102012-02-22 13:55:02 +01001705 }
1706 case PyUnicode_2BYTE_KIND: {
1707 Py_UCS2 *start = (Py_UCS2 *)data + index;
1708 Py_UCS2 *ucs2 = start;
1709 assert(index <= PyUnicode_GET_LENGTH(unicode));
1710
Victor Stinner184252a2012-06-16 02:57:41 +02001711 for (; str < end; ++ucs2, ++str)
Victor Stinnerc5166102012-02-22 13:55:02 +01001712 *ucs2 = (Py_UCS2)*str;
1713
1714 assert((ucs2 - start) <= PyUnicode_GET_LENGTH(unicode));
Victor Stinner184252a2012-06-16 02:57:41 +02001715 break;
Victor Stinnerc5166102012-02-22 13:55:02 +01001716 }
1717 default: {
1718 Py_UCS4 *start = (Py_UCS4 *)data + index;
1719 Py_UCS4 *ucs4 = start;
1720 assert(kind == PyUnicode_4BYTE_KIND);
1721 assert(index <= PyUnicode_GET_LENGTH(unicode));
1722
Victor Stinner184252a2012-06-16 02:57:41 +02001723 for (; str < end; ++ucs4, ++str)
Victor Stinnerc5166102012-02-22 13:55:02 +01001724 *ucs4 = (Py_UCS4)*str;
1725
1726 assert((ucs4 - start) <= PyUnicode_GET_LENGTH(unicode));
Victor Stinnerc5166102012-02-22 13:55:02 +01001727 }
1728 }
1729}
1730
1731
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001732static PyObject*
1733get_latin1_char(unsigned char ch)
1734{
Victor Stinnera464fc12011-10-02 20:39:30 +02001735 PyObject *unicode = unicode_latin1[ch];
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001736 if (!unicode) {
Victor Stinnera464fc12011-10-02 20:39:30 +02001737 unicode = PyUnicode_New(1, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001738 if (!unicode)
1739 return NULL;
1740 PyUnicode_1BYTE_DATA(unicode)[0] = ch;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001741 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001742 unicode_latin1[ch] = unicode;
1743 }
1744 Py_INCREF(unicode);
Victor Stinnera464fc12011-10-02 20:39:30 +02001745 return unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001746}
1747
Alexander Belopolsky40018472011-02-26 01:02:56 +00001748PyObject *
1749PyUnicode_FromUnicode(const Py_UNICODE *u, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001750{
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001751 PyObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001752 Py_UCS4 maxchar = 0;
1753 Py_ssize_t num_surrogates;
1754
1755 if (u == NULL)
1756 return (PyObject*)_PyUnicode_New(size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001757
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001758 /* If the Unicode data is known at construction time, we can apply
1759 some optimizations which share commonly used objects. */
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001760
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001761 /* Optimization for empty strings */
1762 if (size == 0 && unicode_empty != NULL) {
1763 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001764 return unicode_empty;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001765 }
Tim Petersced69f82003-09-16 20:30:58 +00001766
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001767 /* Single character Unicode objects in the Latin-1 range are
1768 shared when using this constructor */
1769 if (size == 1 && *u < 256)
1770 return get_latin1_char((unsigned char)*u);
1771
1772 /* If not empty and not single character, copy the Unicode data
1773 into the new object */
Victor Stinnerd8f65102011-09-29 19:43:17 +02001774 if (find_maxchar_surrogates(u, u + size,
1775 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001776 return NULL;
1777
Victor Stinner8faf8212011-12-08 22:14:11 +01001778 unicode = PyUnicode_New(size - num_surrogates, maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001779 if (!unicode)
1780 return NULL;
1781
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001782 switch (PyUnicode_KIND(unicode)) {
1783 case PyUnicode_1BYTE_KIND:
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001784 _PyUnicode_CONVERT_BYTES(Py_UNICODE, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001785 u, u + size, PyUnicode_1BYTE_DATA(unicode));
1786 break;
1787 case PyUnicode_2BYTE_KIND:
1788#if Py_UNICODE_SIZE == 2
1789 Py_MEMCPY(PyUnicode_2BYTE_DATA(unicode), u, size * 2);
1790#else
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001791 _PyUnicode_CONVERT_BYTES(Py_UNICODE, Py_UCS2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001792 u, u + size, PyUnicode_2BYTE_DATA(unicode));
1793#endif
1794 break;
1795 case PyUnicode_4BYTE_KIND:
1796#if SIZEOF_WCHAR_T == 2
1797 /* This is the only case which has to process surrogates, thus
1798 a simple copy loop is not enough and we need a function. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001799 unicode_convert_wchar_to_ucs4(u, u + size, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001800#else
1801 assert(num_surrogates == 0);
1802 Py_MEMCPY(PyUnicode_4BYTE_DATA(unicode), u, size * 4);
1803#endif
1804 break;
1805 default:
1806 assert(0 && "Impossible state");
1807 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00001808
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001809 return unicode_result(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001810}
1811
Alexander Belopolsky40018472011-02-26 01:02:56 +00001812PyObject *
1813PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size)
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001814{
Benjamin Peterson14339b62009-01-31 16:36:08 +00001815 if (size < 0) {
1816 PyErr_SetString(PyExc_SystemError,
Benjamin Peterson29060642009-01-31 22:14:21 +00001817 "Negative size passed to PyUnicode_FromStringAndSize");
Benjamin Peterson14339b62009-01-31 16:36:08 +00001818 return NULL;
1819 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01001820 if (u != NULL)
1821 return PyUnicode_DecodeUTF8Stateful(u, size, NULL, NULL);
1822 else
1823 return (PyObject *)_PyUnicode_New(size);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001824}
1825
Alexander Belopolsky40018472011-02-26 01:02:56 +00001826PyObject *
1827PyUnicode_FromString(const char *u)
Walter Dörwaldd2034312007-05-18 16:29:38 +00001828{
1829 size_t size = strlen(u);
1830 if (size > PY_SSIZE_T_MAX) {
1831 PyErr_SetString(PyExc_OverflowError, "input too long");
1832 return NULL;
1833 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01001834 return PyUnicode_DecodeUTF8Stateful(u, (Py_ssize_t)size, NULL, NULL);
Walter Dörwaldd2034312007-05-18 16:29:38 +00001835}
1836
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001837PyObject *
1838_PyUnicode_FromId(_Py_Identifier *id)
1839{
1840 if (!id->object) {
Victor Stinnerd1cd99b2012-02-07 23:05:55 +01001841 id->object = PyUnicode_DecodeUTF8Stateful(id->string,
1842 strlen(id->string),
1843 NULL, NULL);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001844 if (!id->object)
1845 return NULL;
1846 PyUnicode_InternInPlace(&id->object);
1847 assert(!id->next);
1848 id->next = static_strings;
1849 static_strings = id;
1850 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001851 return id->object;
1852}
1853
1854void
1855_PyUnicode_ClearStaticStrings()
1856{
1857 _Py_Identifier *i;
1858 for (i = static_strings; i; i = i->next) {
1859 Py_DECREF(i->object);
1860 i->object = NULL;
1861 i->next = NULL;
1862 }
1863}
1864
Benjamin Peterson0df54292012-03-26 14:50:32 -04001865/* Internal function, doesn't check maximum character */
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001866
Victor Stinnerd3f08822012-05-29 12:57:52 +02001867PyObject*
1868_PyUnicode_FromASCII(const char *buffer, Py_ssize_t size)
Victor Stinner702c7342011-10-05 13:50:52 +02001869{
Victor Stinnerd3f08822012-05-29 12:57:52 +02001870 const unsigned char *s = (const unsigned char *)buffer;
Victor Stinner785938e2011-12-11 20:09:03 +01001871 PyObject *unicode;
Victor Stinnere6b2d442011-12-11 21:54:30 +01001872 if (size == 1) {
Victor Stinner0617b6e2011-10-05 23:26:01 +02001873#ifdef Py_DEBUG
Victor Stinnere6b2d442011-12-11 21:54:30 +01001874 assert(s[0] < 128);
Victor Stinner0617b6e2011-10-05 23:26:01 +02001875#endif
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001876 return get_latin1_char(s[0]);
Victor Stinnere6b2d442011-12-11 21:54:30 +01001877 }
Victor Stinner785938e2011-12-11 20:09:03 +01001878 unicode = PyUnicode_New(size, 127);
1879 if (!unicode)
Victor Stinner702c7342011-10-05 13:50:52 +02001880 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01001881 memcpy(PyUnicode_1BYTE_DATA(unicode), s, size);
1882 assert(_PyUnicode_CheckConsistency(unicode, 1));
1883 return unicode;
Victor Stinner702c7342011-10-05 13:50:52 +02001884}
1885
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001886static Py_UCS4
1887kind_maxchar_limit(unsigned int kind)
1888{
Benjamin Petersonead6b532011-12-20 17:23:42 -06001889 switch (kind) {
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001890 case PyUnicode_1BYTE_KIND:
1891 return 0x80;
1892 case PyUnicode_2BYTE_KIND:
1893 return 0x100;
1894 case PyUnicode_4BYTE_KIND:
1895 return 0x10000;
1896 default:
1897 assert(0 && "invalid kind");
Victor Stinner8faf8212011-12-08 22:14:11 +01001898 return MAX_UNICODE;
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001899 }
1900}
1901
Victor Stinnere6abb482012-05-02 01:15:40 +02001902Py_LOCAL_INLINE(Py_UCS4)
1903align_maxchar(Py_UCS4 maxchar)
1904{
1905 if (maxchar <= 127)
1906 return 127;
1907 else if (maxchar <= 255)
1908 return 255;
1909 else if (maxchar <= 65535)
1910 return 65535;
1911 else
1912 return MAX_UNICODE;
1913}
1914
Victor Stinner702c7342011-10-05 13:50:52 +02001915static PyObject*
Victor Stinnere57b1c02011-09-28 22:20:48 +02001916_PyUnicode_FromUCS1(const unsigned char* u, Py_ssize_t size)
Mark Dickinson081dfee2009-03-18 14:47:41 +00001917{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001918 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001919 unsigned char max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001920
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001921 if (size == 0) {
1922 Py_INCREF(unicode_empty);
1923 return unicode_empty;
1924 }
1925 assert(size > 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001926 if (size == 1)
1927 return get_latin1_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001928
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001929 max_char = ucs1lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001930 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001931 if (!res)
1932 return NULL;
1933 memcpy(PyUnicode_1BYTE_DATA(res), u, size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001934 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001935 return res;
Mark Dickinson081dfee2009-03-18 14:47:41 +00001936}
1937
Victor Stinnere57b1c02011-09-28 22:20:48 +02001938static PyObject*
1939_PyUnicode_FromUCS2(const Py_UCS2 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001940{
1941 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001942 Py_UCS2 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001943
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001944 if (size == 0) {
1945 Py_INCREF(unicode_empty);
1946 return unicode_empty;
1947 }
1948 assert(size > 0);
Victor Stinnerb6cd0142012-05-03 02:17:04 +02001949 if (size == 1) {
1950 Py_UCS4 ch = u[0];
1951 if (ch < 256)
1952 return get_latin1_char((unsigned char)ch);
1953
1954 res = PyUnicode_New(1, ch);
1955 if (res == NULL)
1956 return NULL;
1957 PyUnicode_WRITE(PyUnicode_KIND(res), PyUnicode_DATA(res), 0, ch);
1958 assert(_PyUnicode_CheckConsistency(res, 1));
1959 return res;
1960 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001961
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001962 max_char = ucs2lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001963 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001964 if (!res)
1965 return NULL;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001966 if (max_char >= 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001967 memcpy(PyUnicode_2BYTE_DATA(res), u, sizeof(Py_UCS2)*size);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001968 else {
1969 _PyUnicode_CONVERT_BYTES(
1970 Py_UCS2, Py_UCS1, u, u + size, PyUnicode_1BYTE_DATA(res));
1971 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001972 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001973 return res;
1974}
1975
Victor Stinnere57b1c02011-09-28 22:20:48 +02001976static PyObject*
1977_PyUnicode_FromUCS4(const Py_UCS4 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001978{
1979 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001980 Py_UCS4 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001981
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001982 if (size == 0) {
1983 Py_INCREF(unicode_empty);
1984 return unicode_empty;
1985 }
1986 assert(size > 0);
Victor Stinnerb6cd0142012-05-03 02:17:04 +02001987 if (size == 1) {
1988 Py_UCS4 ch = u[0];
1989 if (ch < 256)
1990 return get_latin1_char((unsigned char)ch);
1991
1992 res = PyUnicode_New(1, ch);
1993 if (res == NULL)
1994 return NULL;
1995 PyUnicode_WRITE(PyUnicode_KIND(res), PyUnicode_DATA(res), 0, ch);
1996 assert(_PyUnicode_CheckConsistency(res, 1));
1997 return res;
1998 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001999
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002000 max_char = ucs4lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002001 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002002 if (!res)
2003 return NULL;
Antoine Pitrou950468e2011-10-11 22:45:48 +02002004 if (max_char < 256)
2005 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, u, u + size,
2006 PyUnicode_1BYTE_DATA(res));
2007 else if (max_char < 0x10000)
2008 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, u, u + size,
2009 PyUnicode_2BYTE_DATA(res));
2010 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002011 memcpy(PyUnicode_4BYTE_DATA(res), u, sizeof(Py_UCS4)*size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002012 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002013 return res;
2014}
2015
2016PyObject*
2017PyUnicode_FromKindAndData(int kind, const void *buffer, Py_ssize_t size)
2018{
Victor Stinnercfed46e2011-11-22 01:29:14 +01002019 if (size < 0) {
2020 PyErr_SetString(PyExc_ValueError, "size must be positive");
2021 return NULL;
2022 }
Benjamin Petersonead6b532011-12-20 17:23:42 -06002023 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002024 case PyUnicode_1BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002025 return _PyUnicode_FromUCS1(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002026 case PyUnicode_2BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002027 return _PyUnicode_FromUCS2(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002028 case PyUnicode_4BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002029 return _PyUnicode_FromUCS4(buffer, size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002030 default:
Victor Stinnerb9275c12011-10-05 14:01:42 +02002031 PyErr_SetString(PyExc_SystemError, "invalid kind");
2032 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002033 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002034}
2035
Victor Stinnerece58de2012-04-23 23:36:38 +02002036Py_UCS4
2037_PyUnicode_FindMaxChar(PyObject *unicode, Py_ssize_t start, Py_ssize_t end)
2038{
2039 enum PyUnicode_Kind kind;
2040 void *startptr, *endptr;
2041
2042 assert(PyUnicode_IS_READY(unicode));
2043 assert(0 <= start);
2044 assert(end <= PyUnicode_GET_LENGTH(unicode));
2045 assert(start <= end);
2046
2047 if (start == 0 && end == PyUnicode_GET_LENGTH(unicode))
2048 return PyUnicode_MAX_CHAR_VALUE(unicode);
2049
2050 if (start == end)
2051 return 127;
2052
Victor Stinner94d558b2012-04-27 22:26:58 +02002053 if (PyUnicode_IS_ASCII(unicode))
2054 return 127;
2055
Victor Stinnerece58de2012-04-23 23:36:38 +02002056 kind = PyUnicode_KIND(unicode);
Benjamin Petersonf3b7d862012-04-23 18:07:01 -04002057 startptr = PyUnicode_DATA(unicode);
Benjamin Petersonb9f4c9d2012-04-23 21:45:40 -04002058 endptr = (char *)startptr + end * kind;
2059 startptr = (char *)startptr + start * kind;
Benjamin Peterson2844a7a2012-04-23 18:00:25 -04002060 switch(kind) {
2061 case PyUnicode_1BYTE_KIND:
2062 return ucs1lib_find_max_char(startptr, endptr);
2063 case PyUnicode_2BYTE_KIND:
2064 return ucs2lib_find_max_char(startptr, endptr);
2065 case PyUnicode_4BYTE_KIND:
2066 return ucs4lib_find_max_char(startptr, endptr);
Victor Stinnerece58de2012-04-23 23:36:38 +02002067 default:
Benjamin Peterson2844a7a2012-04-23 18:00:25 -04002068 assert(0);
2069 return 0;
Victor Stinnerece58de2012-04-23 23:36:38 +02002070 }
2071}
2072
Victor Stinner25a4b292011-10-06 12:31:55 +02002073/* Ensure that a string uses the most efficient storage, if it is not the
2074 case: create a new string with of the right kind. Write NULL into *p_unicode
2075 on error. */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02002076static void
Victor Stinner25a4b292011-10-06 12:31:55 +02002077unicode_adjust_maxchar(PyObject **p_unicode)
2078{
2079 PyObject *unicode, *copy;
2080 Py_UCS4 max_char;
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002081 Py_ssize_t len;
Victor Stinner25a4b292011-10-06 12:31:55 +02002082 unsigned int kind;
2083
2084 assert(p_unicode != NULL);
2085 unicode = *p_unicode;
2086 assert(PyUnicode_IS_READY(unicode));
2087 if (PyUnicode_IS_ASCII(unicode))
2088 return;
2089
2090 len = PyUnicode_GET_LENGTH(unicode);
2091 kind = PyUnicode_KIND(unicode);
2092 if (kind == PyUnicode_1BYTE_KIND) {
2093 const Py_UCS1 *u = PyUnicode_1BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002094 max_char = ucs1lib_find_max_char(u, u + len);
2095 if (max_char >= 128)
2096 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002097 }
2098 else if (kind == PyUnicode_2BYTE_KIND) {
2099 const Py_UCS2 *u = PyUnicode_2BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002100 max_char = ucs2lib_find_max_char(u, u + len);
2101 if (max_char >= 256)
2102 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002103 }
2104 else {
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002105 const Py_UCS4 *u = PyUnicode_4BYTE_DATA(unicode);
Victor Stinner25a4b292011-10-06 12:31:55 +02002106 assert(kind == PyUnicode_4BYTE_KIND);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002107 max_char = ucs4lib_find_max_char(u, u + len);
2108 if (max_char >= 0x10000)
2109 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002110 }
Victor Stinner25a4b292011-10-06 12:31:55 +02002111 copy = PyUnicode_New(len, max_char);
Victor Stinnerca439ee2012-06-16 03:17:34 +02002112 if (copy != NULL)
2113 _PyUnicode_FastCopyCharacters(copy, 0, unicode, 0, len);
Victor Stinner25a4b292011-10-06 12:31:55 +02002114 Py_DECREF(unicode);
2115 *p_unicode = copy;
2116}
2117
Victor Stinner034f6cf2011-09-30 02:26:44 +02002118PyObject*
Victor Stinnerbf6e5602011-12-12 01:53:47 +01002119_PyUnicode_Copy(PyObject *unicode)
Victor Stinner034f6cf2011-09-30 02:26:44 +02002120{
Victor Stinner87af4f22011-11-21 23:03:47 +01002121 Py_ssize_t length;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002122 PyObject *copy;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002123
Victor Stinner034f6cf2011-09-30 02:26:44 +02002124 if (!PyUnicode_Check(unicode)) {
2125 PyErr_BadInternalCall();
2126 return NULL;
2127 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05002128 if (PyUnicode_READY(unicode) == -1)
Victor Stinner034f6cf2011-09-30 02:26:44 +02002129 return NULL;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002130
Victor Stinner87af4f22011-11-21 23:03:47 +01002131 length = PyUnicode_GET_LENGTH(unicode);
2132 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002133 if (!copy)
2134 return NULL;
2135 assert(PyUnicode_KIND(copy) == PyUnicode_KIND(unicode));
2136
Victor Stinner87af4f22011-11-21 23:03:47 +01002137 Py_MEMCPY(PyUnicode_DATA(copy), PyUnicode_DATA(unicode),
2138 length * PyUnicode_KIND(unicode));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002139 assert(_PyUnicode_CheckConsistency(copy, 1));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002140 return copy;
Victor Stinner034f6cf2011-09-30 02:26:44 +02002141}
2142
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002143
Victor Stinnerbc603d12011-10-02 01:00:40 +02002144/* Widen Unicode objects to larger buffers. Don't write terminating null
2145 character. Return NULL on error. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002146
2147void*
2148_PyUnicode_AsKind(PyObject *s, unsigned int kind)
2149{
Victor Stinnerbc603d12011-10-02 01:00:40 +02002150 Py_ssize_t len;
2151 void *result;
2152 unsigned int skind;
2153
Benjamin Petersonbac79492012-01-14 13:34:47 -05002154 if (PyUnicode_READY(s) == -1)
Victor Stinnerbc603d12011-10-02 01:00:40 +02002155 return NULL;
2156
2157 len = PyUnicode_GET_LENGTH(s);
2158 skind = PyUnicode_KIND(s);
2159 if (skind >= kind) {
Victor Stinner01698042011-10-04 00:04:26 +02002160 PyErr_SetString(PyExc_SystemError, "invalid widening attempt");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002161 return NULL;
2162 }
Benjamin Petersonead6b532011-12-20 17:23:42 -06002163 switch (kind) {
Victor Stinnerbc603d12011-10-02 01:00:40 +02002164 case PyUnicode_2BYTE_KIND:
2165 result = PyMem_Malloc(len * sizeof(Py_UCS2));
2166 if (!result)
2167 return PyErr_NoMemory();
2168 assert(skind == PyUnicode_1BYTE_KIND);
2169 _PyUnicode_CONVERT_BYTES(
2170 Py_UCS1, Py_UCS2,
2171 PyUnicode_1BYTE_DATA(s),
2172 PyUnicode_1BYTE_DATA(s) + len,
2173 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002174 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002175 case PyUnicode_4BYTE_KIND:
2176 result = PyMem_Malloc(len * sizeof(Py_UCS4));
2177 if (!result)
2178 return PyErr_NoMemory();
2179 if (skind == PyUnicode_2BYTE_KIND) {
2180 _PyUnicode_CONVERT_BYTES(
2181 Py_UCS2, Py_UCS4,
2182 PyUnicode_2BYTE_DATA(s),
2183 PyUnicode_2BYTE_DATA(s) + len,
2184 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002185 }
Victor Stinnerbc603d12011-10-02 01:00:40 +02002186 else {
2187 assert(skind == PyUnicode_1BYTE_KIND);
2188 _PyUnicode_CONVERT_BYTES(
2189 Py_UCS1, Py_UCS4,
2190 PyUnicode_1BYTE_DATA(s),
2191 PyUnicode_1BYTE_DATA(s) + len,
2192 result);
2193 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002194 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002195 default:
2196 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002197 }
Victor Stinner01698042011-10-04 00:04:26 +02002198 PyErr_SetString(PyExc_SystemError, "invalid kind");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002199 return NULL;
2200}
2201
2202static Py_UCS4*
2203as_ucs4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2204 int copy_null)
2205{
2206 int kind;
2207 void *data;
2208 Py_ssize_t len, targetlen;
2209 if (PyUnicode_READY(string) == -1)
2210 return NULL;
2211 kind = PyUnicode_KIND(string);
2212 data = PyUnicode_DATA(string);
2213 len = PyUnicode_GET_LENGTH(string);
2214 targetlen = len;
2215 if (copy_null)
2216 targetlen++;
2217 if (!target) {
2218 if (PY_SSIZE_T_MAX / sizeof(Py_UCS4) < targetlen) {
2219 PyErr_NoMemory();
2220 return NULL;
2221 }
2222 target = PyMem_Malloc(targetlen * sizeof(Py_UCS4));
2223 if (!target) {
2224 PyErr_NoMemory();
2225 return NULL;
2226 }
2227 }
2228 else {
2229 if (targetsize < targetlen) {
2230 PyErr_Format(PyExc_SystemError,
2231 "string is longer than the buffer");
2232 if (copy_null && 0 < targetsize)
2233 target[0] = 0;
2234 return NULL;
2235 }
2236 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002237 if (kind == PyUnicode_1BYTE_KIND) {
2238 Py_UCS1 *start = (Py_UCS1 *) data;
2239 _PyUnicode_CONVERT_BYTES(Py_UCS1, Py_UCS4, start, start + len, target);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002240 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002241 else if (kind == PyUnicode_2BYTE_KIND) {
2242 Py_UCS2 *start = (Py_UCS2 *) data;
2243 _PyUnicode_CONVERT_BYTES(Py_UCS2, Py_UCS4, start, start + len, target);
2244 }
2245 else {
2246 assert(kind == PyUnicode_4BYTE_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002247 Py_MEMCPY(target, data, len * sizeof(Py_UCS4));
Antoine Pitrou950468e2011-10-11 22:45:48 +02002248 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002249 if (copy_null)
2250 target[len] = 0;
2251 return target;
2252}
2253
2254Py_UCS4*
2255PyUnicode_AsUCS4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2256 int copy_null)
2257{
Antoine Pitroude20b0b2011-11-10 21:47:38 +01002258 if (target == NULL || targetsize < 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002259 PyErr_BadInternalCall();
2260 return NULL;
2261 }
2262 return as_ucs4(string, target, targetsize, copy_null);
2263}
2264
2265Py_UCS4*
2266PyUnicode_AsUCS4Copy(PyObject *string)
2267{
2268 return as_ucs4(string, NULL, 0, 1);
2269}
2270
2271#ifdef HAVE_WCHAR_H
Mark Dickinson081dfee2009-03-18 14:47:41 +00002272
Alexander Belopolsky40018472011-02-26 01:02:56 +00002273PyObject *
2274PyUnicode_FromWideChar(register const wchar_t *w, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002275{
Guido van Rossumd57fd912000-03-10 22:53:23 +00002276 if (w == NULL) {
Victor Stinner382955f2011-12-11 21:44:00 +01002277 if (size == 0) {
2278 Py_INCREF(unicode_empty);
2279 return unicode_empty;
2280 }
Benjamin Peterson29060642009-01-31 22:14:21 +00002281 PyErr_BadInternalCall();
2282 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002283 }
2284
Martin v. Löwis790465f2008-04-05 20:41:37 +00002285 if (size == -1) {
2286 size = wcslen(w);
2287 }
2288
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002289 return PyUnicode_FromUnicode(w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002290}
2291
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002292#endif /* HAVE_WCHAR_H */
Mark Dickinson081dfee2009-03-18 14:47:41 +00002293
Walter Dörwald346737f2007-05-31 10:44:43 +00002294static void
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002295makefmt(char *fmt, int longflag, int longlongflag, int size_tflag,
2296 int zeropad, int width, int precision, char c)
Walter Dörwald346737f2007-05-31 10:44:43 +00002297{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002298 *fmt++ = '%';
2299 if (width) {
2300 if (zeropad)
2301 *fmt++ = '0';
2302 fmt += sprintf(fmt, "%d", width);
2303 }
2304 if (precision)
2305 fmt += sprintf(fmt, ".%d", precision);
2306 if (longflag)
2307 *fmt++ = 'l';
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002308 else if (longlongflag) {
2309 /* longlongflag should only ever be nonzero on machines with
2310 HAVE_LONG_LONG defined */
2311#ifdef HAVE_LONG_LONG
2312 char *f = PY_FORMAT_LONG_LONG;
2313 while (*f)
2314 *fmt++ = *f++;
2315#else
2316 /* we shouldn't ever get here */
2317 assert(0);
2318 *fmt++ = 'l';
2319#endif
2320 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002321 else if (size_tflag) {
2322 char *f = PY_FORMAT_SIZE_T;
2323 while (*f)
2324 *fmt++ = *f++;
2325 }
2326 *fmt++ = c;
2327 *fmt = '\0';
Walter Dörwald346737f2007-05-31 10:44:43 +00002328}
2329
Victor Stinner96865452011-03-01 23:44:09 +00002330/* helper for PyUnicode_FromFormatV() */
2331
2332static const char*
2333parse_format_flags(const char *f,
2334 int *p_width, int *p_precision,
2335 int *p_longflag, int *p_longlongflag, int *p_size_tflag)
2336{
2337 int width, precision, longflag, longlongflag, size_tflag;
2338
2339 /* parse the width.precision part, e.g. "%2.5s" => width=2, precision=5 */
2340 f++;
2341 width = 0;
2342 while (Py_ISDIGIT((unsigned)*f))
2343 width = (width*10) + *f++ - '0';
2344 precision = 0;
2345 if (*f == '.') {
2346 f++;
2347 while (Py_ISDIGIT((unsigned)*f))
2348 precision = (precision*10) + *f++ - '0';
2349 if (*f == '%') {
2350 /* "%.3%s" => f points to "3" */
2351 f--;
2352 }
2353 }
2354 if (*f == '\0') {
2355 /* bogus format "%.1" => go backward, f points to "1" */
2356 f--;
2357 }
2358 if (p_width != NULL)
2359 *p_width = width;
2360 if (p_precision != NULL)
2361 *p_precision = precision;
2362
2363 /* Handle %ld, %lu, %lld and %llu. */
2364 longflag = 0;
2365 longlongflag = 0;
Victor Stinnere7faec12011-03-02 00:01:53 +00002366 size_tflag = 0;
Victor Stinner96865452011-03-01 23:44:09 +00002367
2368 if (*f == 'l') {
Victor Stinner6d970f42011-03-02 00:04:25 +00002369 if (f[1] == 'd' || f[1] == 'u' || f[1] == 'i') {
Victor Stinner96865452011-03-01 23:44:09 +00002370 longflag = 1;
2371 ++f;
2372 }
2373#ifdef HAVE_LONG_LONG
2374 else if (f[1] == 'l' &&
Victor Stinner6d970f42011-03-02 00:04:25 +00002375 (f[2] == 'd' || f[2] == 'u' || f[2] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002376 longlongflag = 1;
2377 f += 2;
2378 }
2379#endif
2380 }
2381 /* handle the size_t flag. */
Victor Stinner6d970f42011-03-02 00:04:25 +00002382 else if (*f == 'z' && (f[1] == 'd' || f[1] == 'u' || f[1] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002383 size_tflag = 1;
2384 ++f;
2385 }
2386 if (p_longflag != NULL)
2387 *p_longflag = longflag;
2388 if (p_longlongflag != NULL)
2389 *p_longlongflag = longlongflag;
2390 if (p_size_tflag != NULL)
2391 *p_size_tflag = size_tflag;
2392 return f;
2393}
2394
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002395/* maximum number of characters required for output of %ld. 21 characters
2396 allows for 64-bit integers (in decimal) and an optional sign. */
2397#define MAX_LONG_CHARS 21
2398/* maximum number of characters required for output of %lld.
2399 We need at most ceil(log10(256)*SIZEOF_LONG_LONG) digits,
2400 plus 1 for the sign. 53/22 is an upper bound for log10(256). */
2401#define MAX_LONG_LONG_CHARS (2 + (SIZEOF_LONG_LONG*53-1) / 22)
2402
Walter Dörwaldd2034312007-05-18 16:29:38 +00002403PyObject *
2404PyUnicode_FromFormatV(const char *format, va_list vargs)
2405{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002406 va_list count;
2407 Py_ssize_t callcount = 0;
2408 PyObject **callresults = NULL;
2409 PyObject **callresult = NULL;
2410 Py_ssize_t n = 0;
2411 int width = 0;
2412 int precision = 0;
2413 int zeropad;
2414 const char* f;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002415 PyObject *string;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002416 /* used by sprintf */
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002417 char fmt[61]; /* should be enough for %0width.precisionlld */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002418 Py_UCS4 maxchar = 127; /* result is ASCII by default */
2419 Py_UCS4 argmaxchar;
2420 Py_ssize_t numbersize = 0;
2421 char *numberresults = NULL;
2422 char *numberresult = NULL;
2423 Py_ssize_t i;
2424 int kind;
2425 void *data;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002426
Victor Stinner4a2b7a12010-08-13 14:03:48 +00002427 Py_VA_COPY(count, vargs);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002428 /* step 1: count the number of %S/%R/%A/%s format specifications
2429 * (we call PyObject_Str()/PyObject_Repr()/PyObject_ASCII()/
2430 * PyUnicode_DecodeUTF8() for these objects once during step 3 and put the
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002431 * result in an array)
Georg Brandl7597add2011-10-05 16:36:47 +02002432 * also estimate a upper bound for all the number formats in the string,
2433 * numbers will be formatted in step 3 and be kept in a '\0'-separated
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002434 * buffer before putting everything together. */
Benjamin Peterson14339b62009-01-31 16:36:08 +00002435 for (f = format; *f; f++) {
2436 if (*f == '%') {
Victor Stinner96865452011-03-01 23:44:09 +00002437 int longlongflag;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002438 /* skip width or width.precision (eg. "1.2" of "%1.2f") */
2439 f = parse_format_flags(f, &width, NULL, NULL, &longlongflag, NULL);
2440 if (*f == 's' || *f=='S' || *f=='R' || *f=='A' || *f=='V')
2441 ++callcount;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002442
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002443 else if (*f == 'd' || *f=='u' || *f=='i' || *f=='x' || *f=='p') {
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002444#ifdef HAVE_LONG_LONG
2445 if (longlongflag) {
2446 if (width < MAX_LONG_LONG_CHARS)
2447 width = MAX_LONG_LONG_CHARS;
2448 }
2449 else
2450#endif
2451 /* MAX_LONG_CHARS is enough to hold a 64-bit integer,
2452 including sign. Decimal takes the most space. This
2453 isn't enough for octal. If a width is specified we
2454 need more (which we allocate later). */
2455 if (width < MAX_LONG_CHARS)
2456 width = MAX_LONG_CHARS;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002457
2458 /* account for the size + '\0' to separate numbers
2459 inside of the numberresults buffer */
2460 numbersize += (width + 1);
2461 }
2462 }
2463 else if ((unsigned char)*f > 127) {
2464 PyErr_Format(PyExc_ValueError,
2465 "PyUnicode_FromFormatV() expects an ASCII-encoded format "
2466 "string, got a non-ASCII byte: 0x%02x",
2467 (unsigned char)*f);
2468 return NULL;
2469 }
2470 }
2471 /* step 2: allocate memory for the results of
2472 * PyObject_Str()/PyObject_Repr()/PyUnicode_DecodeUTF8() calls */
2473 if (callcount) {
2474 callresults = PyObject_Malloc(sizeof(PyObject *) * callcount);
2475 if (!callresults) {
2476 PyErr_NoMemory();
2477 return NULL;
2478 }
2479 callresult = callresults;
2480 }
2481 /* step 2.5: allocate memory for the results of formating numbers */
2482 if (numbersize) {
2483 numberresults = PyObject_Malloc(numbersize);
2484 if (!numberresults) {
2485 PyErr_NoMemory();
2486 goto fail;
2487 }
2488 numberresult = numberresults;
2489 }
2490
2491 /* step 3: format numbers and figure out how large a buffer we need */
2492 for (f = format; *f; f++) {
2493 if (*f == '%') {
2494 const char* p;
2495 int longflag;
2496 int longlongflag;
2497 int size_tflag;
2498 int numprinted;
2499
2500 p = f;
2501 zeropad = (f[1] == '0');
2502 f = parse_format_flags(f, &width, &precision,
2503 &longflag, &longlongflag, &size_tflag);
2504 switch (*f) {
2505 case 'c':
2506 {
2507 Py_UCS4 ordinal = va_arg(count, int);
Victor Stinnere6abb482012-05-02 01:15:40 +02002508 maxchar = MAX_MAXCHAR(maxchar, ordinal);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002509 n++;
2510 break;
2511 }
2512 case '%':
2513 n++;
2514 break;
2515 case 'i':
2516 case 'd':
2517 makefmt(fmt, longflag, longlongflag, size_tflag, zeropad,
2518 width, precision, *f);
2519 if (longflag)
2520 numprinted = sprintf(numberresult, fmt,
2521 va_arg(count, long));
2522#ifdef HAVE_LONG_LONG
2523 else if (longlongflag)
2524 numprinted = sprintf(numberresult, fmt,
2525 va_arg(count, PY_LONG_LONG));
2526#endif
2527 else if (size_tflag)
2528 numprinted = sprintf(numberresult, fmt,
2529 va_arg(count, Py_ssize_t));
2530 else
2531 numprinted = sprintf(numberresult, fmt,
2532 va_arg(count, int));
2533 n += numprinted;
2534 /* advance by +1 to skip over the '\0' */
2535 numberresult += (numprinted + 1);
2536 assert(*(numberresult - 1) == '\0');
2537 assert(*(numberresult - 2) != '\0');
2538 assert(numprinted >= 0);
2539 assert(numberresult <= numberresults + numbersize);
2540 break;
2541 case 'u':
2542 makefmt(fmt, longflag, longlongflag, size_tflag, zeropad,
2543 width, precision, 'u');
2544 if (longflag)
2545 numprinted = sprintf(numberresult, fmt,
2546 va_arg(count, unsigned long));
2547#ifdef HAVE_LONG_LONG
2548 else if (longlongflag)
2549 numprinted = sprintf(numberresult, fmt,
2550 va_arg(count, unsigned PY_LONG_LONG));
2551#endif
2552 else if (size_tflag)
2553 numprinted = sprintf(numberresult, fmt,
2554 va_arg(count, size_t));
2555 else
2556 numprinted = sprintf(numberresult, fmt,
2557 va_arg(count, unsigned int));
2558 n += numprinted;
2559 numberresult += (numprinted + 1);
2560 assert(*(numberresult - 1) == '\0');
2561 assert(*(numberresult - 2) != '\0');
2562 assert(numprinted >= 0);
2563 assert(numberresult <= numberresults + numbersize);
2564 break;
2565 case 'x':
2566 makefmt(fmt, 0, 0, 0, zeropad, width, precision, 'x');
2567 numprinted = sprintf(numberresult, fmt, va_arg(count, int));
2568 n += numprinted;
2569 numberresult += (numprinted + 1);
2570 assert(*(numberresult - 1) == '\0');
2571 assert(*(numberresult - 2) != '\0');
2572 assert(numprinted >= 0);
2573 assert(numberresult <= numberresults + numbersize);
2574 break;
2575 case 'p':
2576 numprinted = sprintf(numberresult, "%p", va_arg(count, void*));
2577 /* %p is ill-defined: ensure leading 0x. */
2578 if (numberresult[1] == 'X')
2579 numberresult[1] = 'x';
2580 else if (numberresult[1] != 'x') {
2581 memmove(numberresult + 2, numberresult,
2582 strlen(numberresult) + 1);
2583 numberresult[0] = '0';
2584 numberresult[1] = 'x';
2585 numprinted += 2;
2586 }
2587 n += numprinted;
2588 numberresult += (numprinted + 1);
2589 assert(*(numberresult - 1) == '\0');
2590 assert(*(numberresult - 2) != '\0');
2591 assert(numprinted >= 0);
2592 assert(numberresult <= numberresults + numbersize);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002593 break;
2594 case 's':
2595 {
2596 /* UTF-8 */
Georg Brandl780b2a62009-05-05 09:19:59 +00002597 const char *s = va_arg(count, const char*);
Victor Stinnera1d12bb2011-12-11 21:53:09 +01002598 PyObject *str = PyUnicode_DecodeUTF8Stateful(s, strlen(s), "replace", NULL);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002599 if (!str)
2600 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002601 /* since PyUnicode_DecodeUTF8 returns already flexible
2602 unicode objects, there is no need to call ready on them */
2603 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str);
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(str);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002606 /* Remember the str and switch to the next slot */
2607 *callresult++ = str;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002608 break;
2609 }
2610 case 'U':
2611 {
2612 PyObject *obj = va_arg(count, PyObject *);
Victor Stinner910337b2011-10-03 03:20:16 +02002613 assert(obj && _PyUnicode_CHECK(obj));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002614 if (PyUnicode_READY(obj) == -1)
2615 goto fail;
2616 argmaxchar = PyUnicode_MAX_CHAR_VALUE(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(obj);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002619 break;
2620 }
2621 case 'V':
2622 {
2623 PyObject *obj = va_arg(count, PyObject *);
2624 const char *str = va_arg(count, const char *);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002625 PyObject *str_obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002626 assert(obj || str);
Victor Stinner910337b2011-10-03 03:20:16 +02002627 assert(!obj || _PyUnicode_CHECK(obj));
Victor Stinner2512a8b2011-03-01 22:46:52 +00002628 if (obj) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002629 if (PyUnicode_READY(obj) == -1)
2630 goto fail;
2631 argmaxchar = PyUnicode_MAX_CHAR_VALUE(obj);
Victor Stinnere6abb482012-05-02 01:15:40 +02002632 maxchar = MAX_MAXCHAR(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002633 n += PyUnicode_GET_LENGTH(obj);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002634 *callresult++ = NULL;
2635 }
2636 else {
Victor Stinnera1d12bb2011-12-11 21:53:09 +01002637 str_obj = PyUnicode_DecodeUTF8Stateful(str, strlen(str), "replace", NULL);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002638 if (!str_obj)
2639 goto fail;
Benjamin Petersonbac79492012-01-14 13:34:47 -05002640 if (PyUnicode_READY(str_obj) == -1) {
Victor Stinnere1335c72011-10-04 20:53:03 +02002641 Py_DECREF(str_obj);
2642 goto fail;
2643 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002644 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str_obj);
Victor Stinnere6abb482012-05-02 01:15:40 +02002645 maxchar = MAX_MAXCHAR(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002646 n += PyUnicode_GET_LENGTH(str_obj);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002647 *callresult++ = str_obj;
2648 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002649 break;
2650 }
2651 case 'S':
2652 {
2653 PyObject *obj = va_arg(count, PyObject *);
2654 PyObject *str;
2655 assert(obj);
2656 str = PyObject_Str(obj);
Benjamin Petersonc8d8b882012-01-14 13:37:31 -05002657 if (!str)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002658 goto fail;
Benjamin Petersonc8d8b882012-01-14 13:37:31 -05002659 if (PyUnicode_READY(str) == -1) {
2660 Py_DECREF(str);
2661 goto fail;
2662 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002663 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str);
Victor Stinnere6abb482012-05-02 01:15:40 +02002664 maxchar = MAX_MAXCHAR(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002665 n += PyUnicode_GET_LENGTH(str);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002666 /* Remember the str and switch to the next slot */
2667 *callresult++ = str;
2668 break;
2669 }
2670 case 'R':
2671 {
2672 PyObject *obj = va_arg(count, PyObject *);
2673 PyObject *repr;
2674 assert(obj);
2675 repr = PyObject_Repr(obj);
Benjamin Petersonc8d8b882012-01-14 13:37:31 -05002676 if (!repr)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002677 goto fail;
Benjamin Petersonc8d8b882012-01-14 13:37:31 -05002678 if (PyUnicode_READY(repr) == -1) {
2679 Py_DECREF(repr);
2680 goto fail;
2681 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002682 argmaxchar = PyUnicode_MAX_CHAR_VALUE(repr);
Victor Stinnere6abb482012-05-02 01:15:40 +02002683 maxchar = MAX_MAXCHAR(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002684 n += PyUnicode_GET_LENGTH(repr);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002685 /* Remember the repr and switch to the next slot */
2686 *callresult++ = repr;
2687 break;
2688 }
2689 case 'A':
2690 {
2691 PyObject *obj = va_arg(count, PyObject *);
2692 PyObject *ascii;
2693 assert(obj);
2694 ascii = PyObject_ASCII(obj);
Benjamin Petersonc8d8b882012-01-14 13:37:31 -05002695 if (!ascii)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002696 goto fail;
Benjamin Petersonc8d8b882012-01-14 13:37:31 -05002697 if (PyUnicode_READY(ascii) == -1) {
2698 Py_DECREF(ascii);
2699 goto fail;
2700 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002701 argmaxchar = PyUnicode_MAX_CHAR_VALUE(ascii);
Victor Stinnere6abb482012-05-02 01:15:40 +02002702 maxchar = MAX_MAXCHAR(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002703 n += PyUnicode_GET_LENGTH(ascii);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002704 /* Remember the repr and switch to the next slot */
2705 *callresult++ = ascii;
2706 break;
2707 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002708 default:
2709 /* if we stumble upon an unknown
2710 formatting code, copy the rest of
2711 the format string to the output
2712 string. (we cannot just skip the
2713 code, since there's no way to know
2714 what's in the argument list) */
2715 n += strlen(p);
2716 goto expand;
2717 }
2718 } else
2719 n++;
2720 }
Benjamin Peterson29060642009-01-31 22:14:21 +00002721 expand:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002722 /* step 4: fill the buffer */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002723 /* Since we've analyzed how much space we need,
Benjamin Peterson14339b62009-01-31 16:36:08 +00002724 we don't have to resize the string.
2725 There can be no errors beyond this point. */
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002726 string = PyUnicode_New(n, maxchar);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002727 if (!string)
2728 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002729 kind = PyUnicode_KIND(string);
2730 data = PyUnicode_DATA(string);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002731 callresult = callresults;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002732 numberresult = numberresults;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002733
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002734 for (i = 0, f = format; *f; f++) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00002735 if (*f == '%') {
Victor Stinner96865452011-03-01 23:44:09 +00002736 const char* p;
Victor Stinner96865452011-03-01 23:44:09 +00002737
2738 p = f;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002739 f = parse_format_flags(f, NULL, NULL, NULL, NULL, NULL);
2740 /* checking for == because the last argument could be a empty
2741 string, which causes i to point to end, the assert at the end of
2742 the loop */
2743 assert(i <= PyUnicode_GET_LENGTH(string));
Walter Dörwaldd2034312007-05-18 16:29:38 +00002744
Benjamin Peterson14339b62009-01-31 16:36:08 +00002745 switch (*f) {
2746 case 'c':
Victor Stinner5ed8b2c2011-02-21 21:13:44 +00002747 {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002748 const int ordinal = va_arg(vargs, int);
2749 PyUnicode_WRITE(kind, data, i++, ordinal);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002750 break;
Victor Stinner5ed8b2c2011-02-21 21:13:44 +00002751 }
Victor Stinner6d970f42011-03-02 00:04:25 +00002752 case 'i':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002753 case 'd':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002754 case 'u':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002755 case 'x':
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002756 case 'p':
Victor Stinnerc5166102012-02-22 13:55:02 +01002757 {
Victor Stinner184252a2012-06-16 02:57:41 +02002758 Py_ssize_t len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002759 /* unused, since we already have the result */
2760 if (*f == 'p')
2761 (void) va_arg(vargs, void *);
2762 else
2763 (void) va_arg(vargs, int);
2764 /* extract the result from numberresults and append. */
Victor Stinner184252a2012-06-16 02:57:41 +02002765 len = strlen(numberresult);
2766 unicode_write_cstr(string, i, numberresult, len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002767 /* skip over the separating '\0' */
Victor Stinner184252a2012-06-16 02:57:41 +02002768 i += len;
2769 numberresult += len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002770 assert(*numberresult == '\0');
2771 numberresult++;
2772 assert(numberresult <= numberresults + numbersize);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002773 break;
Victor Stinnerc5166102012-02-22 13:55:02 +01002774 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002775 case 's':
2776 {
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002777 /* unused, since we already have the result */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002778 Py_ssize_t size;
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002779 (void) va_arg(vargs, char *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002780 size = PyUnicode_GET_LENGTH(*callresult);
2781 assert(PyUnicode_KIND(*callresult) <= PyUnicode_KIND(string));
Victor Stinnerd3f08822012-05-29 12:57:52 +02002782 _PyUnicode_FastCopyCharacters(string, i, *callresult, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002783 i += size;
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002784 /* We're done with the unicode()/repr() => forget it */
2785 Py_DECREF(*callresult);
2786 /* switch to next unicode()/repr() result */
2787 ++callresult;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002788 break;
2789 }
2790 case 'U':
2791 {
2792 PyObject *obj = va_arg(vargs, PyObject *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002793 Py_ssize_t size;
2794 assert(PyUnicode_KIND(obj) <= PyUnicode_KIND(string));
2795 size = PyUnicode_GET_LENGTH(obj);
Victor Stinnerd3f08822012-05-29 12:57:52 +02002796 _PyUnicode_FastCopyCharacters(string, i, obj, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002797 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002798 break;
2799 }
2800 case 'V':
2801 {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002802 Py_ssize_t size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002803 PyObject *obj = va_arg(vargs, PyObject *);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002804 va_arg(vargs, const char *);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002805 if (obj) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002806 size = PyUnicode_GET_LENGTH(obj);
2807 assert(PyUnicode_KIND(obj) <= PyUnicode_KIND(string));
Victor Stinnerd3f08822012-05-29 12:57:52 +02002808 _PyUnicode_FastCopyCharacters(string, i, obj, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002809 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002810 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002811 size = PyUnicode_GET_LENGTH(*callresult);
2812 assert(PyUnicode_KIND(*callresult) <=
2813 PyUnicode_KIND(string));
Victor Stinnerd3f08822012-05-29 12:57:52 +02002814 _PyUnicode_FastCopyCharacters(string, i, *callresult, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002815 i += size;
Victor Stinner2512a8b2011-03-01 22:46:52 +00002816 Py_DECREF(*callresult);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002817 }
Victor Stinner2512a8b2011-03-01 22:46:52 +00002818 ++callresult;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002819 break;
2820 }
2821 case 'S':
2822 case 'R':
Victor Stinner9a909002010-10-18 20:59:24 +00002823 case 'A':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002824 {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002825 Py_ssize_t size = PyUnicode_GET_LENGTH(*callresult);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002826 /* unused, since we already have the result */
2827 (void) va_arg(vargs, PyObject *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002828 assert(PyUnicode_KIND(*callresult) <= PyUnicode_KIND(string));
Victor Stinnerd3f08822012-05-29 12:57:52 +02002829 _PyUnicode_FastCopyCharacters(string, i, *callresult, 0, size);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002830 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002831 /* We're done with the unicode()/repr() => forget it */
2832 Py_DECREF(*callresult);
2833 /* switch to next unicode()/repr() result */
2834 ++callresult;
2835 break;
2836 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002837 case '%':
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002838 PyUnicode_WRITE(kind, data, i++, '%');
Benjamin Peterson14339b62009-01-31 16:36:08 +00002839 break;
2840 default:
Victor Stinner184252a2012-06-16 02:57:41 +02002841 {
2842 Py_ssize_t len = strlen(p);
2843 unicode_write_cstr(string, i, p, len);
2844 i += len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002845 assert(i == PyUnicode_GET_LENGTH(string));
Benjamin Peterson14339b62009-01-31 16:36:08 +00002846 goto end;
2847 }
Victor Stinner184252a2012-06-16 02:57:41 +02002848 }
Victor Stinner1205f272010-09-11 00:54:47 +00002849 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002850 else {
2851 assert(i < PyUnicode_GET_LENGTH(string));
2852 PyUnicode_WRITE(kind, data, i++, *f);
2853 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002854 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002855 assert(i == PyUnicode_GET_LENGTH(string));
Walter Dörwaldd2034312007-05-18 16:29:38 +00002856
Benjamin Peterson29060642009-01-31 22:14:21 +00002857 end:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002858 if (callresults)
2859 PyObject_Free(callresults);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002860 if (numberresults)
2861 PyObject_Free(numberresults);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002862 return unicode_result(string);
Benjamin Peterson29060642009-01-31 22:14:21 +00002863 fail:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002864 if (callresults) {
2865 PyObject **callresult2 = callresults;
2866 while (callresult2 < callresult) {
Victor Stinner2512a8b2011-03-01 22:46:52 +00002867 Py_XDECREF(*callresult2);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002868 ++callresult2;
2869 }
2870 PyObject_Free(callresults);
2871 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002872 if (numberresults)
2873 PyObject_Free(numberresults);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002874 return NULL;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002875}
2876
Walter Dörwaldd2034312007-05-18 16:29:38 +00002877PyObject *
2878PyUnicode_FromFormat(const char *format, ...)
2879{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002880 PyObject* ret;
2881 va_list vargs;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002882
2883#ifdef HAVE_STDARG_PROTOTYPES
Benjamin Peterson14339b62009-01-31 16:36:08 +00002884 va_start(vargs, format);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002885#else
Benjamin Peterson14339b62009-01-31 16:36:08 +00002886 va_start(vargs);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002887#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00002888 ret = PyUnicode_FromFormatV(format, vargs);
2889 va_end(vargs);
2890 return ret;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002891}
2892
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002893#ifdef HAVE_WCHAR_H
2894
Victor Stinner5593d8a2010-10-02 11:11:27 +00002895/* Helper function for PyUnicode_AsWideChar() and PyUnicode_AsWideCharString():
2896 convert a Unicode object to a wide character string.
2897
Victor Stinnerd88d9832011-09-06 02:00:05 +02002898 - If w is NULL: return the number of wide characters (including the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002899 character) required to convert the unicode object. Ignore size argument.
2900
Victor Stinnerd88d9832011-09-06 02:00:05 +02002901 - Otherwise: return the number of wide characters (excluding the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002902 character) written into w. Write at most size wide characters (including
Victor Stinnerd88d9832011-09-06 02:00:05 +02002903 the null character). */
Victor Stinner5593d8a2010-10-02 11:11:27 +00002904static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002905unicode_aswidechar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002906 wchar_t *w,
2907 Py_ssize_t size)
2908{
Victor Stinner5593d8a2010-10-02 11:11:27 +00002909 Py_ssize_t res;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002910 const wchar_t *wstr;
2911
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002912 wstr = PyUnicode_AsUnicodeAndSize(unicode, &res);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002913 if (wstr == NULL)
2914 return -1;
2915
Victor Stinner5593d8a2010-10-02 11:11:27 +00002916 if (w != NULL) {
Victor Stinner5593d8a2010-10-02 11:11:27 +00002917 if (size > res)
2918 size = res + 1;
2919 else
2920 res = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002921 Py_MEMCPY(w, wstr, size * sizeof(wchar_t));
Victor Stinner5593d8a2010-10-02 11:11:27 +00002922 return res;
2923 }
2924 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002925 return res + 1;
Victor Stinner137c34c2010-09-29 10:25:54 +00002926}
2927
2928Py_ssize_t
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002929PyUnicode_AsWideChar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002930 wchar_t *w,
2931 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002932{
2933 if (unicode == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002934 PyErr_BadInternalCall();
2935 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002936 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002937 return unicode_aswidechar(unicode, w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002938}
2939
Victor Stinner137c34c2010-09-29 10:25:54 +00002940wchar_t*
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00002941PyUnicode_AsWideCharString(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002942 Py_ssize_t *size)
2943{
2944 wchar_t* buffer;
2945 Py_ssize_t buflen;
2946
2947 if (unicode == NULL) {
2948 PyErr_BadInternalCall();
2949 return NULL;
2950 }
2951
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002952 buflen = unicode_aswidechar(unicode, NULL, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002953 if (buflen == -1)
2954 return NULL;
Victor Stinner5593d8a2010-10-02 11:11:27 +00002955 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < buflen) {
Victor Stinner137c34c2010-09-29 10:25:54 +00002956 PyErr_NoMemory();
2957 return NULL;
2958 }
2959
Victor Stinner137c34c2010-09-29 10:25:54 +00002960 buffer = PyMem_MALLOC(buflen * sizeof(wchar_t));
2961 if (buffer == NULL) {
2962 PyErr_NoMemory();
2963 return NULL;
2964 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002965 buflen = unicode_aswidechar(unicode, buffer, buflen);
Stefan Krah8528c312012-08-19 21:52:43 +02002966 if (buflen == -1) {
2967 PyMem_FREE(buffer);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002968 return NULL;
Stefan Krah8528c312012-08-19 21:52:43 +02002969 }
Victor Stinner5593d8a2010-10-02 11:11:27 +00002970 if (size != NULL)
2971 *size = buflen;
Victor Stinner137c34c2010-09-29 10:25:54 +00002972 return buffer;
2973}
2974
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002975#endif /* HAVE_WCHAR_H */
Guido van Rossumd57fd912000-03-10 22:53:23 +00002976
Alexander Belopolsky40018472011-02-26 01:02:56 +00002977PyObject *
2978PyUnicode_FromOrdinal(int ordinal)
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002979{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002980 PyObject *v;
Victor Stinner8faf8212011-12-08 22:14:11 +01002981 if (ordinal < 0 || ordinal > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002982 PyErr_SetString(PyExc_ValueError,
2983 "chr() arg not in range(0x110000)");
2984 return NULL;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002985 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00002986
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002987 if (ordinal < 256)
2988 return get_latin1_char(ordinal);
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002989
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002990 v = PyUnicode_New(1, ordinal);
2991 if (v == NULL)
2992 return NULL;
2993 PyUnicode_WRITE(PyUnicode_KIND(v), PyUnicode_DATA(v), 0, ordinal);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002994 assert(_PyUnicode_CheckConsistency(v, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002995 return v;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002996}
2997
Alexander Belopolsky40018472011-02-26 01:02:56 +00002998PyObject *
2999PyUnicode_FromObject(register PyObject *obj)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003000{
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003001 /* XXX Perhaps we should make this API an alias of
Benjamin Peterson29060642009-01-31 22:14:21 +00003002 PyObject_Str() instead ?! */
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003003 if (PyUnicode_CheckExact(obj)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -05003004 if (PyUnicode_READY(obj) == -1)
Victor Stinnerd3a83d52011-10-01 03:09:33 +02003005 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +00003006 Py_INCREF(obj);
3007 return obj;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003008 }
3009 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003010 /* For a Unicode subtype that's not a Unicode object,
3011 return a true Unicode object with the same data. */
Victor Stinnerbf6e5602011-12-12 01:53:47 +01003012 return _PyUnicode_Copy(obj);
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003013 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00003014 PyErr_Format(PyExc_TypeError,
3015 "Can't convert '%.100s' object to str implicitly",
Christian Heimes90aa7642007-12-19 02:45:37 +00003016 Py_TYPE(obj)->tp_name);
Guido van Rossum98297ee2007-11-06 21:34:58 +00003017 return NULL;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003018}
3019
Alexander Belopolsky40018472011-02-26 01:02:56 +00003020PyObject *
3021PyUnicode_FromEncodedObject(register PyObject *obj,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003022 const char *encoding,
3023 const char *errors)
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003024{
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003025 Py_buffer buffer;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003026 PyObject *v;
Tim Petersced69f82003-09-16 20:30:58 +00003027
Guido van Rossumd57fd912000-03-10 22:53:23 +00003028 if (obj == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003029 PyErr_BadInternalCall();
3030 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003031 }
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003032
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003033 /* Decoding bytes objects is the most common case and should be fast */
3034 if (PyBytes_Check(obj)) {
3035 if (PyBytes_GET_SIZE(obj) == 0) {
3036 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02003037 v = unicode_empty;
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003038 }
3039 else {
3040 v = PyUnicode_Decode(
3041 PyBytes_AS_STRING(obj), PyBytes_GET_SIZE(obj),
3042 encoding, errors);
3043 }
3044 return v;
3045 }
3046
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003047 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003048 PyErr_SetString(PyExc_TypeError,
3049 "decoding str is not supported");
3050 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +00003051 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003052
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003053 /* Retrieve a bytes buffer view through the PEP 3118 buffer interface */
3054 if (PyObject_GetBuffer(obj, &buffer, PyBUF_SIMPLE) < 0) {
3055 PyErr_Format(PyExc_TypeError,
3056 "coercing to str: need bytes, bytearray "
3057 "or buffer-like object, %.80s found",
3058 Py_TYPE(obj)->tp_name);
3059 return NULL;
Marc-André Lemburg6871f6a2001-09-20 12:53:16 +00003060 }
Tim Petersced69f82003-09-16 20:30:58 +00003061
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003062 if (buffer.len == 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003063 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02003064 v = unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003065 }
Tim Petersced69f82003-09-16 20:30:58 +00003066 else
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003067 v = PyUnicode_Decode((char*) buffer.buf, buffer.len, encoding, errors);
Marc-André Lemburgad7c98e2001-01-17 17:09:53 +00003068
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003069 PyBuffer_Release(&buffer);
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003070 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003071}
3072
Victor Stinner600d3be2010-06-10 12:00:55 +00003073/* Convert encoding to lower case and replace '_' with '-' in order to
Victor Stinner37296e82010-06-10 13:36:23 +00003074 catch e.g. UTF_8. Return 0 on error (encoding is longer than lower_len-1),
3075 1 on success. */
3076static int
3077normalize_encoding(const char *encoding,
3078 char *lower,
3079 size_t lower_len)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003080{
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003081 const char *e;
Victor Stinner600d3be2010-06-10 12:00:55 +00003082 char *l;
3083 char *l_end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003084
Benjamin Peterson7a6debe2011-10-15 09:25:28 -04003085 if (encoding == NULL) {
3086 strcpy(lower, "utf-8");
3087 return 1;
3088 }
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003089 e = encoding;
3090 l = lower;
Victor Stinner600d3be2010-06-10 12:00:55 +00003091 l_end = &lower[lower_len - 1];
Victor Stinner37296e82010-06-10 13:36:23 +00003092 while (*e) {
3093 if (l == l_end)
3094 return 0;
David Malcolm96960882010-11-05 17:23:41 +00003095 if (Py_ISUPPER(*e)) {
3096 *l++ = Py_TOLOWER(*e++);
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003097 }
3098 else if (*e == '_') {
3099 *l++ = '-';
3100 e++;
3101 }
3102 else {
3103 *l++ = *e++;
3104 }
3105 }
3106 *l = '\0';
Victor Stinner37296e82010-06-10 13:36:23 +00003107 return 1;
Victor Stinner600d3be2010-06-10 12:00:55 +00003108}
3109
Alexander Belopolsky40018472011-02-26 01:02:56 +00003110PyObject *
3111PyUnicode_Decode(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003112 Py_ssize_t size,
3113 const char *encoding,
3114 const char *errors)
Victor Stinner600d3be2010-06-10 12:00:55 +00003115{
3116 PyObject *buffer = NULL, *unicode;
3117 Py_buffer info;
3118 char lower[11]; /* Enough for any encoding shortcut */
3119
Fred Drakee4315f52000-05-09 19:53:39 +00003120 /* Shortcuts for common default encodings */
Victor Stinner37296e82010-06-10 13:36:23 +00003121 if (normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003122 if ((strcmp(lower, "utf-8") == 0) ||
3123 (strcmp(lower, "utf8") == 0))
Victor Stinnera1d12bb2011-12-11 21:53:09 +01003124 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
Victor Stinner37296e82010-06-10 13:36:23 +00003125 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003126 (strcmp(lower, "latin1") == 0) ||
Victor Stinner37296e82010-06-10 13:36:23 +00003127 (strcmp(lower, "iso-8859-1") == 0))
3128 return PyUnicode_DecodeLatin1(s, size, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02003129#ifdef HAVE_MBCS
Victor Stinner37296e82010-06-10 13:36:23 +00003130 else if (strcmp(lower, "mbcs") == 0)
3131 return PyUnicode_DecodeMBCS(s, size, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003132#endif
Victor Stinner37296e82010-06-10 13:36:23 +00003133 else if (strcmp(lower, "ascii") == 0)
3134 return PyUnicode_DecodeASCII(s, size, errors);
3135 else if (strcmp(lower, "utf-16") == 0)
3136 return PyUnicode_DecodeUTF16(s, size, errors, 0);
3137 else if (strcmp(lower, "utf-32") == 0)
3138 return PyUnicode_DecodeUTF32(s, size, errors, 0);
3139 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003140
3141 /* Decode via the codec registry */
Guido van Rossumbe801ac2007-10-08 03:32:34 +00003142 buffer = NULL;
Antoine Pitrouc3b39242009-01-03 16:59:18 +00003143 if (PyBuffer_FillInfo(&info, NULL, (void *)s, size, 1, PyBUF_FULL_RO) < 0)
Guido van Rossumbe801ac2007-10-08 03:32:34 +00003144 goto onError;
Antoine Pitrouee58fa42008-08-19 18:22:14 +00003145 buffer = PyMemoryView_FromBuffer(&info);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003146 if (buffer == NULL)
3147 goto onError;
3148 unicode = PyCodec_Decode(buffer, encoding, errors);
3149 if (unicode == NULL)
3150 goto onError;
3151 if (!PyUnicode_Check(unicode)) {
3152 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00003153 "decoder did not return a str object (type=%.400s)",
Christian Heimes90aa7642007-12-19 02:45:37 +00003154 Py_TYPE(unicode)->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003155 Py_DECREF(unicode);
3156 goto onError;
3157 }
3158 Py_DECREF(buffer);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003159 return unicode_result(unicode);
Tim Petersced69f82003-09-16 20:30:58 +00003160
Benjamin Peterson29060642009-01-31 22:14:21 +00003161 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003162 Py_XDECREF(buffer);
3163 return NULL;
3164}
3165
Alexander Belopolsky40018472011-02-26 01:02:56 +00003166PyObject *
3167PyUnicode_AsDecodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003168 const char *encoding,
3169 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003170{
3171 PyObject *v;
3172
3173 if (!PyUnicode_Check(unicode)) {
3174 PyErr_BadArgument();
3175 goto onError;
3176 }
3177
3178 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003179 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003180
3181 /* Decode via the codec registry */
3182 v = PyCodec_Decode(unicode, encoding, errors);
3183 if (v == NULL)
3184 goto onError;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003185 return unicode_result(v);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003186
Benjamin Peterson29060642009-01-31 22:14:21 +00003187 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003188 return NULL;
3189}
3190
Alexander Belopolsky40018472011-02-26 01:02:56 +00003191PyObject *
3192PyUnicode_AsDecodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003193 const char *encoding,
3194 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003195{
3196 PyObject *v;
3197
3198 if (!PyUnicode_Check(unicode)) {
3199 PyErr_BadArgument();
3200 goto onError;
3201 }
3202
3203 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003204 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003205
3206 /* Decode via the codec registry */
3207 v = PyCodec_Decode(unicode, encoding, errors);
3208 if (v == NULL)
3209 goto onError;
3210 if (!PyUnicode_Check(v)) {
3211 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00003212 "decoder did not return a str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003213 Py_TYPE(v)->tp_name);
3214 Py_DECREF(v);
3215 goto onError;
3216 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003217 return unicode_result(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003218
Benjamin Peterson29060642009-01-31 22:14:21 +00003219 onError:
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003220 return NULL;
3221}
3222
Alexander Belopolsky40018472011-02-26 01:02:56 +00003223PyObject *
3224PyUnicode_Encode(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003225 Py_ssize_t size,
3226 const char *encoding,
3227 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003228{
3229 PyObject *v, *unicode;
Tim Petersced69f82003-09-16 20:30:58 +00003230
Guido van Rossumd57fd912000-03-10 22:53:23 +00003231 unicode = PyUnicode_FromUnicode(s, size);
3232 if (unicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003233 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003234 v = PyUnicode_AsEncodedString(unicode, encoding, errors);
3235 Py_DECREF(unicode);
3236 return v;
3237}
3238
Alexander Belopolsky40018472011-02-26 01:02:56 +00003239PyObject *
3240PyUnicode_AsEncodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003241 const char *encoding,
3242 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003243{
3244 PyObject *v;
3245
3246 if (!PyUnicode_Check(unicode)) {
3247 PyErr_BadArgument();
3248 goto onError;
3249 }
3250
3251 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003252 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003253
3254 /* Encode via the codec registry */
3255 v = PyCodec_Encode(unicode, encoding, errors);
3256 if (v == NULL)
3257 goto onError;
3258 return v;
3259
Benjamin Peterson29060642009-01-31 22:14:21 +00003260 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003261 return NULL;
3262}
3263
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003264static size_t
3265wcstombs_errorpos(const wchar_t *wstr)
3266{
3267 size_t len;
3268#if SIZEOF_WCHAR_T == 2
3269 wchar_t buf[3];
3270#else
3271 wchar_t buf[2];
3272#endif
3273 char outbuf[MB_LEN_MAX];
3274 const wchar_t *start, *previous;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003275
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003276#if SIZEOF_WCHAR_T == 2
3277 buf[2] = 0;
3278#else
3279 buf[1] = 0;
3280#endif
3281 start = wstr;
3282 while (*wstr != L'\0')
3283 {
3284 previous = wstr;
3285#if SIZEOF_WCHAR_T == 2
3286 if (Py_UNICODE_IS_HIGH_SURROGATE(wstr[0])
3287 && Py_UNICODE_IS_LOW_SURROGATE(wstr[1]))
3288 {
3289 buf[0] = wstr[0];
3290 buf[1] = wstr[1];
3291 wstr += 2;
3292 }
3293 else {
3294 buf[0] = *wstr;
3295 buf[1] = 0;
3296 wstr++;
3297 }
3298#else
3299 buf[0] = *wstr;
3300 wstr++;
3301#endif
3302 len = wcstombs(outbuf, buf, sizeof(outbuf));
Victor Stinner2f197072011-12-17 07:08:30 +01003303 if (len == (size_t)-1)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003304 return previous - start;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003305 }
3306
3307 /* failed to find the unencodable character */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003308 return 0;
3309}
3310
Victor Stinner1b579672011-12-17 05:47:23 +01003311static int
3312locale_error_handler(const char *errors, int *surrogateescape)
3313{
3314 if (errors == NULL) {
3315 *surrogateescape = 0;
3316 return 0;
3317 }
3318
3319 if (strcmp(errors, "strict") == 0) {
3320 *surrogateescape = 0;
3321 return 0;
3322 }
3323 if (strcmp(errors, "surrogateescape") == 0) {
3324 *surrogateescape = 1;
3325 return 0;
3326 }
3327 PyErr_Format(PyExc_ValueError,
3328 "only 'strict' and 'surrogateescape' error handlers "
3329 "are supported, not '%s'",
3330 errors);
3331 return -1;
3332}
3333
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003334PyObject *
Victor Stinner1b579672011-12-17 05:47:23 +01003335PyUnicode_EncodeLocale(PyObject *unicode, const char *errors)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003336{
3337 Py_ssize_t wlen, wlen2;
3338 wchar_t *wstr;
3339 PyObject *bytes = NULL;
3340 char *errmsg;
Victor Stinner1f33f2b2011-12-17 04:45:09 +01003341 PyObject *reason;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003342 PyObject *exc;
3343 size_t error_pos;
Victor Stinner1b579672011-12-17 05:47:23 +01003344 int surrogateescape;
3345
3346 if (locale_error_handler(errors, &surrogateescape) < 0)
3347 return NULL;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003348
3349 wstr = PyUnicode_AsWideCharString(unicode, &wlen);
3350 if (wstr == NULL)
3351 return NULL;
3352
3353 wlen2 = wcslen(wstr);
3354 if (wlen2 != wlen) {
3355 PyMem_Free(wstr);
3356 PyErr_SetString(PyExc_TypeError, "embedded null character");
3357 return NULL;
3358 }
3359
3360 if (surrogateescape) {
3361 /* locale encoding with surrogateescape */
3362 char *str;
3363
3364 str = _Py_wchar2char(wstr, &error_pos);
3365 if (str == NULL) {
3366 if (error_pos == (size_t)-1) {
3367 PyErr_NoMemory();
3368 PyMem_Free(wstr);
3369 return NULL;
3370 }
3371 else {
3372 goto encode_error;
3373 }
3374 }
3375 PyMem_Free(wstr);
3376
3377 bytes = PyBytes_FromString(str);
3378 PyMem_Free(str);
3379 }
3380 else {
3381 size_t len, len2;
3382
3383 len = wcstombs(NULL, wstr, 0);
3384 if (len == (size_t)-1) {
Victor Stinner2f197072011-12-17 07:08:30 +01003385 error_pos = (size_t)-1;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003386 goto encode_error;
3387 }
3388
3389 bytes = PyBytes_FromStringAndSize(NULL, len);
3390 if (bytes == NULL) {
3391 PyMem_Free(wstr);
3392 return NULL;
3393 }
3394
3395 len2 = wcstombs(PyBytes_AS_STRING(bytes), wstr, len+1);
3396 if (len2 == (size_t)-1 || len2 > len) {
Victor Stinner2f197072011-12-17 07:08:30 +01003397 error_pos = (size_t)-1;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003398 goto encode_error;
3399 }
3400 PyMem_Free(wstr);
3401 }
3402 return bytes;
3403
3404encode_error:
3405 errmsg = strerror(errno);
3406 assert(errmsg != NULL);
Victor Stinner2f197072011-12-17 07:08:30 +01003407
3408 if (error_pos == (size_t)-1)
3409 error_pos = wcstombs_errorpos(wstr);
3410
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003411 PyMem_Free(wstr);
3412 Py_XDECREF(bytes);
3413
Victor Stinner2f197072011-12-17 07:08:30 +01003414 if (errmsg != NULL) {
3415 size_t errlen;
3416 wstr = _Py_char2wchar(errmsg, &errlen);
3417 if (wstr != NULL) {
3418 reason = PyUnicode_FromWideChar(wstr, errlen);
3419 PyMem_Free(wstr);
3420 } else
3421 errmsg = NULL;
3422 }
3423 if (errmsg == NULL)
Victor Stinner1f33f2b2011-12-17 04:45:09 +01003424 reason = PyUnicode_FromString(
3425 "wcstombs() encountered an unencodable "
3426 "wide character");
3427 if (reason == NULL)
3428 return NULL;
3429
3430 exc = PyObject_CallFunction(PyExc_UnicodeEncodeError, "sOnnO",
3431 "locale", unicode,
3432 (Py_ssize_t)error_pos,
3433 (Py_ssize_t)(error_pos+1),
3434 reason);
3435 Py_DECREF(reason);
3436 if (exc != NULL) {
3437 PyCodec_StrictErrors(exc);
3438 Py_XDECREF(exc);
3439 }
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003440 return NULL;
3441}
3442
Victor Stinnerad158722010-10-27 00:25:46 +00003443PyObject *
3444PyUnicode_EncodeFSDefault(PyObject *unicode)
Victor Stinnerae6265f2010-05-15 16:27:27 +00003445{
Victor Stinner99b95382011-07-04 14:23:54 +02003446#ifdef HAVE_MBCS
Victor Stinnerac931b12011-11-20 18:27:03 +01003447 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003448#elif defined(__APPLE__)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003449 return _PyUnicode_AsUTF8String(unicode, "surrogateescape");
Victor Stinnerad158722010-10-27 00:25:46 +00003450#else
Victor Stinner793b5312011-04-27 00:24:21 +02003451 PyInterpreterState *interp = PyThreadState_GET()->interp;
3452 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3453 cannot use it to encode and decode filenames before it is loaded. Load
3454 the Python codec requires to encode at least its own filename. Use the C
3455 version of the locale codec until the codec registry is initialized and
3456 the Python codec is loaded.
3457
3458 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3459 cannot only rely on it: check also interp->fscodec_initialized for
3460 subinterpreters. */
3461 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Victor Stinnerae6265f2010-05-15 16:27:27 +00003462 return PyUnicode_AsEncodedString(unicode,
3463 Py_FileSystemDefaultEncoding,
3464 "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00003465 }
3466 else {
Victor Stinner1b579672011-12-17 05:47:23 +01003467 return PyUnicode_EncodeLocale(unicode, "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00003468 }
Victor Stinnerad158722010-10-27 00:25:46 +00003469#endif
Victor Stinnerae6265f2010-05-15 16:27:27 +00003470}
3471
Alexander Belopolsky40018472011-02-26 01:02:56 +00003472PyObject *
3473PyUnicode_AsEncodedString(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003474 const char *encoding,
3475 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003476{
3477 PyObject *v;
Victor Stinner600d3be2010-06-10 12:00:55 +00003478 char lower[11]; /* Enough for any encoding shortcut */
Tim Petersced69f82003-09-16 20:30:58 +00003479
Guido van Rossumd57fd912000-03-10 22:53:23 +00003480 if (!PyUnicode_Check(unicode)) {
3481 PyErr_BadArgument();
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003482 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003483 }
Fred Drakee4315f52000-05-09 19:53:39 +00003484
Fred Drakee4315f52000-05-09 19:53:39 +00003485 /* Shortcuts for common default encodings */
Victor Stinner37296e82010-06-10 13:36:23 +00003486 if (normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003487 if ((strcmp(lower, "utf-8") == 0) ||
3488 (strcmp(lower, "utf8") == 0))
Victor Stinnera5c68c32011-03-02 01:03:14 +00003489 {
Victor Stinner2f283c22011-03-02 01:21:46 +00003490 if (errors == NULL || strcmp(errors, "strict") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003491 return _PyUnicode_AsUTF8String(unicode, NULL);
Victor Stinner2f283c22011-03-02 01:21:46 +00003492 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003493 return _PyUnicode_AsUTF8String(unicode, errors);
Victor Stinnera5c68c32011-03-02 01:03:14 +00003494 }
Victor Stinner37296e82010-06-10 13:36:23 +00003495 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003496 (strcmp(lower, "latin1") == 0) ||
Victor Stinner37296e82010-06-10 13:36:23 +00003497 (strcmp(lower, "iso-8859-1") == 0))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003498 return _PyUnicode_AsLatin1String(unicode, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02003499#ifdef HAVE_MBCS
Victor Stinnerac931b12011-11-20 18:27:03 +01003500 else if (strcmp(lower, "mbcs") == 0)
3501 return PyUnicode_EncodeCodePage(CP_ACP, unicode, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003502#endif
Victor Stinner37296e82010-06-10 13:36:23 +00003503 else if (strcmp(lower, "ascii") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003504 return _PyUnicode_AsASCIIString(unicode, errors);
Victor Stinner37296e82010-06-10 13:36:23 +00003505 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003506
3507 /* Encode via the codec registry */
3508 v = PyCodec_Encode(unicode, encoding, errors);
3509 if (v == NULL)
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003510 return NULL;
3511
3512 /* The normal path */
3513 if (PyBytes_Check(v))
3514 return v;
3515
3516 /* If the codec returns a buffer, raise a warning and convert to bytes */
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003517 if (PyByteArray_Check(v)) {
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003518 int error;
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003519 PyObject *b;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003520
3521 error = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
3522 "encoder %s returned bytearray instead of bytes",
3523 encoding);
3524 if (error) {
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003525 Py_DECREF(v);
3526 return NULL;
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003527 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003528
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003529 b = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(v), Py_SIZE(v));
3530 Py_DECREF(v);
3531 return b;
3532 }
3533
3534 PyErr_Format(PyExc_TypeError,
3535 "encoder did not return a bytes object (type=%.400s)",
3536 Py_TYPE(v)->tp_name);
3537 Py_DECREF(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003538 return NULL;
3539}
3540
Alexander Belopolsky40018472011-02-26 01:02:56 +00003541PyObject *
3542PyUnicode_AsEncodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003543 const char *encoding,
3544 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003545{
3546 PyObject *v;
3547
3548 if (!PyUnicode_Check(unicode)) {
3549 PyErr_BadArgument();
3550 goto onError;
3551 }
3552
3553 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003554 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003555
3556 /* Encode via the codec registry */
3557 v = PyCodec_Encode(unicode, encoding, errors);
3558 if (v == NULL)
3559 goto onError;
3560 if (!PyUnicode_Check(v)) {
3561 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00003562 "encoder did not return an str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003563 Py_TYPE(v)->tp_name);
3564 Py_DECREF(v);
3565 goto onError;
3566 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003567 return v;
Tim Petersced69f82003-09-16 20:30:58 +00003568
Benjamin Peterson29060642009-01-31 22:14:21 +00003569 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003570 return NULL;
3571}
3572
Victor Stinner2f197072011-12-17 07:08:30 +01003573static size_t
3574mbstowcs_errorpos(const char *str, size_t len)
3575{
3576#ifdef HAVE_MBRTOWC
3577 const char *start = str;
3578 mbstate_t mbs;
3579 size_t converted;
3580 wchar_t ch;
3581
3582 memset(&mbs, 0, sizeof mbs);
3583 while (len)
3584 {
3585 converted = mbrtowc(&ch, (char*)str, len, &mbs);
3586 if (converted == 0)
3587 /* Reached end of string */
3588 break;
3589 if (converted == (size_t)-1 || converted == (size_t)-2) {
3590 /* Conversion error or incomplete character */
3591 return str - start;
3592 }
3593 else {
3594 str += converted;
3595 len -= converted;
3596 }
3597 }
3598 /* failed to find the undecodable byte sequence */
3599 return 0;
3600#endif
3601 return 0;
3602}
3603
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003604PyObject*
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003605PyUnicode_DecodeLocaleAndSize(const char *str, Py_ssize_t len,
Victor Stinner1b579672011-12-17 05:47:23 +01003606 const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003607{
3608 wchar_t smallbuf[256];
3609 size_t smallbuf_len = Py_ARRAY_LENGTH(smallbuf);
3610 wchar_t *wstr;
3611 size_t wlen, wlen2;
3612 PyObject *unicode;
Victor Stinner1b579672011-12-17 05:47:23 +01003613 int surrogateescape;
Victor Stinner2f197072011-12-17 07:08:30 +01003614 size_t error_pos;
3615 char *errmsg;
3616 PyObject *reason, *exc;
Victor Stinner1b579672011-12-17 05:47:23 +01003617
3618 if (locale_error_handler(errors, &surrogateescape) < 0)
3619 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003620
3621 if (str[len] != '\0' || len != strlen(str)) {
3622 PyErr_SetString(PyExc_TypeError, "embedded null character");
3623 return NULL;
3624 }
3625
3626 if (surrogateescape)
3627 {
3628 wstr = _Py_char2wchar(str, &wlen);
3629 if (wstr == NULL) {
3630 if (wlen == (size_t)-1)
3631 PyErr_NoMemory();
3632 else
3633 PyErr_SetFromErrno(PyExc_OSError);
3634 return NULL;
3635 }
3636
3637 unicode = PyUnicode_FromWideChar(wstr, wlen);
3638 PyMem_Free(wstr);
3639 }
3640 else {
3641#ifndef HAVE_BROKEN_MBSTOWCS
3642 wlen = mbstowcs(NULL, str, 0);
3643#else
3644 wlen = len;
3645#endif
Victor Stinner2f197072011-12-17 07:08:30 +01003646 if (wlen == (size_t)-1)
3647 goto decode_error;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003648 if (wlen+1 <= smallbuf_len) {
3649 wstr = smallbuf;
3650 }
3651 else {
3652 if (wlen > PY_SSIZE_T_MAX / sizeof(wchar_t) - 1)
3653 return PyErr_NoMemory();
3654
3655 wstr = PyMem_Malloc((wlen+1) * sizeof(wchar_t));
3656 if (!wstr)
3657 return PyErr_NoMemory();
3658 }
3659
3660 /* This shouldn't fail now */
3661 wlen2 = mbstowcs(wstr, str, wlen+1);
3662 if (wlen2 == (size_t)-1) {
3663 if (wstr != smallbuf)
3664 PyMem_Free(wstr);
Victor Stinner2f197072011-12-17 07:08:30 +01003665 goto decode_error;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003666 }
3667#ifdef HAVE_BROKEN_MBSTOWCS
3668 assert(wlen2 == wlen);
3669#endif
3670 unicode = PyUnicode_FromWideChar(wstr, wlen2);
3671 if (wstr != smallbuf)
3672 PyMem_Free(wstr);
3673 }
3674 return unicode;
Victor Stinner2f197072011-12-17 07:08:30 +01003675
3676decode_error:
3677 errmsg = strerror(errno);
3678 assert(errmsg != NULL);
3679
3680 error_pos = mbstowcs_errorpos(str, len);
3681 if (errmsg != NULL) {
3682 size_t errlen;
3683 wstr = _Py_char2wchar(errmsg, &errlen);
3684 if (wstr != NULL) {
3685 reason = PyUnicode_FromWideChar(wstr, errlen);
3686 PyMem_Free(wstr);
3687 } else
3688 errmsg = NULL;
3689 }
3690 if (errmsg == NULL)
3691 reason = PyUnicode_FromString(
3692 "mbstowcs() encountered an invalid multibyte sequence");
3693 if (reason == NULL)
3694 return NULL;
3695
3696 exc = PyObject_CallFunction(PyExc_UnicodeDecodeError, "sy#nnO",
3697 "locale", str, len,
3698 (Py_ssize_t)error_pos,
3699 (Py_ssize_t)(error_pos+1),
3700 reason);
3701 Py_DECREF(reason);
3702 if (exc != NULL) {
3703 PyCodec_StrictErrors(exc);
3704 Py_XDECREF(exc);
3705 }
3706 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003707}
3708
3709PyObject*
Victor Stinner1b579672011-12-17 05:47:23 +01003710PyUnicode_DecodeLocale(const char *str, const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003711{
3712 Py_ssize_t size = (Py_ssize_t)strlen(str);
Victor Stinner1b579672011-12-17 05:47:23 +01003713 return PyUnicode_DecodeLocaleAndSize(str, size, errors);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003714}
3715
3716
3717PyObject*
Christian Heimes5894ba72007-11-04 11:43:14 +00003718PyUnicode_DecodeFSDefault(const char *s) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003719 Py_ssize_t size = (Py_ssize_t)strlen(s);
Christian Heimes5894ba72007-11-04 11:43:14 +00003720 return PyUnicode_DecodeFSDefaultAndSize(s, size);
3721}
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003722
Christian Heimes5894ba72007-11-04 11:43:14 +00003723PyObject*
3724PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
3725{
Victor Stinner99b95382011-07-04 14:23:54 +02003726#ifdef HAVE_MBCS
Victor Stinnerad158722010-10-27 00:25:46 +00003727 return PyUnicode_DecodeMBCS(s, size, NULL);
3728#elif defined(__APPLE__)
Victor Stinnera1d12bb2011-12-11 21:53:09 +01003729 return PyUnicode_DecodeUTF8Stateful(s, size, "surrogateescape", NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003730#else
Victor Stinner793b5312011-04-27 00:24:21 +02003731 PyInterpreterState *interp = PyThreadState_GET()->interp;
3732 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3733 cannot use it to encode and decode filenames before it is loaded. Load
3734 the Python codec requires to encode at least its own filename. Use the C
3735 version of the locale codec until the codec registry is initialized and
3736 the Python codec is loaded.
3737
3738 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3739 cannot only rely on it: check also interp->fscodec_initialized for
3740 subinterpreters. */
3741 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003742 return PyUnicode_Decode(s, size,
3743 Py_FileSystemDefaultEncoding,
Victor Stinnerb9a20ad2010-04-30 16:37:52 +00003744 "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003745 }
3746 else {
Victor Stinner1b579672011-12-17 05:47:23 +01003747 return PyUnicode_DecodeLocaleAndSize(s, size, "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003748 }
Victor Stinnerad158722010-10-27 00:25:46 +00003749#endif
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003750}
3751
Martin v. Löwis011e8422009-05-05 04:43:17 +00003752
3753int
Antoine Pitrou13348842012-01-29 18:36:34 +01003754_PyUnicode_HasNULChars(PyObject* s)
3755{
3756 static PyObject *nul = NULL;
3757
3758 if (nul == NULL)
3759 nul = PyUnicode_FromStringAndSize("\0", 1);
3760 if (nul == NULL)
3761 return -1;
3762 return PyUnicode_Contains(s, nul);
3763}
3764
3765
3766int
Martin v. Löwis011e8422009-05-05 04:43:17 +00003767PyUnicode_FSConverter(PyObject* arg, void* addr)
3768{
3769 PyObject *output = NULL;
3770 Py_ssize_t size;
3771 void *data;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003772 if (arg == NULL) {
3773 Py_DECREF(*(PyObject**)addr);
3774 return 1;
3775 }
Victor Stinnerdcb24032010-04-22 12:08:36 +00003776 if (PyBytes_Check(arg)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00003777 output = arg;
3778 Py_INCREF(output);
3779 }
3780 else {
3781 arg = PyUnicode_FromObject(arg);
3782 if (!arg)
3783 return 0;
Victor Stinnerae6265f2010-05-15 16:27:27 +00003784 output = PyUnicode_EncodeFSDefault(arg);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003785 Py_DECREF(arg);
3786 if (!output)
3787 return 0;
3788 if (!PyBytes_Check(output)) {
3789 Py_DECREF(output);
3790 PyErr_SetString(PyExc_TypeError, "encoder failed to return bytes");
3791 return 0;
3792 }
3793 }
Victor Stinner0ea2a462010-04-30 00:22:08 +00003794 size = PyBytes_GET_SIZE(output);
3795 data = PyBytes_AS_STRING(output);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003796 if (size != strlen(data)) {
Benjamin Peterson7a6b44a2011-08-18 13:51:47 -05003797 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
Martin v. Löwis011e8422009-05-05 04:43:17 +00003798 Py_DECREF(output);
3799 return 0;
3800 }
3801 *(PyObject**)addr = output;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003802 return Py_CLEANUP_SUPPORTED;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003803}
3804
3805
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003806int
3807PyUnicode_FSDecoder(PyObject* arg, void* addr)
3808{
3809 PyObject *output = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003810 if (arg == NULL) {
3811 Py_DECREF(*(PyObject**)addr);
3812 return 1;
3813 }
3814 if (PyUnicode_Check(arg)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -05003815 if (PyUnicode_READY(arg) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003816 return 0;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003817 output = arg;
3818 Py_INCREF(output);
3819 }
3820 else {
3821 arg = PyBytes_FromObject(arg);
3822 if (!arg)
3823 return 0;
3824 output = PyUnicode_DecodeFSDefaultAndSize(PyBytes_AS_STRING(arg),
3825 PyBytes_GET_SIZE(arg));
3826 Py_DECREF(arg);
3827 if (!output)
3828 return 0;
3829 if (!PyUnicode_Check(output)) {
3830 Py_DECREF(output);
3831 PyErr_SetString(PyExc_TypeError, "decoder failed to return unicode");
3832 return 0;
3833 }
3834 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05003835 if (PyUnicode_READY(output) == -1) {
Victor Stinner065836e2011-10-27 01:56:33 +02003836 Py_DECREF(output);
3837 return 0;
3838 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003839 if (findchar(PyUnicode_DATA(output), PyUnicode_KIND(output),
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02003840 PyUnicode_GET_LENGTH(output), 0, 1) >= 0) {
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003841 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
3842 Py_DECREF(output);
3843 return 0;
3844 }
3845 *(PyObject**)addr = output;
3846 return Py_CLEANUP_SUPPORTED;
3847}
3848
3849
Martin v. Löwis5b222132007-06-10 09:51:05 +00003850char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003851PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *psize)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003852{
Christian Heimesf3863112007-11-22 07:46:41 +00003853 PyObject *bytes;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003854
Neal Norwitze0a0a6e2007-08-25 01:04:21 +00003855 if (!PyUnicode_Check(unicode)) {
3856 PyErr_BadArgument();
3857 return NULL;
3858 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003859 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003860 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003861
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003862 if (PyUnicode_UTF8(unicode) == NULL) {
3863 assert(!PyUnicode_IS_COMPACT_ASCII(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003864 bytes = _PyUnicode_AsUTF8String(unicode, "strict");
3865 if (bytes == NULL)
3866 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003867 _PyUnicode_UTF8(unicode) = PyObject_MALLOC(PyBytes_GET_SIZE(bytes) + 1);
3868 if (_PyUnicode_UTF8(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003869 Py_DECREF(bytes);
3870 return NULL;
3871 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003872 _PyUnicode_UTF8_LENGTH(unicode) = PyBytes_GET_SIZE(bytes);
3873 Py_MEMCPY(_PyUnicode_UTF8(unicode),
3874 PyBytes_AS_STRING(bytes),
3875 _PyUnicode_UTF8_LENGTH(unicode) + 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003876 Py_DECREF(bytes);
3877 }
3878
3879 if (psize)
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003880 *psize = PyUnicode_UTF8_LENGTH(unicode);
3881 return PyUnicode_UTF8(unicode);
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003882}
3883
3884char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003885PyUnicode_AsUTF8(PyObject *unicode)
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003886{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003887 return PyUnicode_AsUTF8AndSize(unicode, NULL);
3888}
3889
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003890Py_UNICODE *
3891PyUnicode_AsUnicodeAndSize(PyObject *unicode, Py_ssize_t *size)
3892{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003893 const unsigned char *one_byte;
3894#if SIZEOF_WCHAR_T == 4
3895 const Py_UCS2 *two_bytes;
3896#else
3897 const Py_UCS4 *four_bytes;
3898 const Py_UCS4 *ucs4_end;
3899 Py_ssize_t num_surrogates;
3900#endif
3901 wchar_t *w;
3902 wchar_t *wchar_end;
3903
3904 if (!PyUnicode_Check(unicode)) {
3905 PyErr_BadArgument();
3906 return NULL;
3907 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003908 if (_PyUnicode_WSTR(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003909 /* Non-ASCII compact unicode object */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003910 assert(_PyUnicode_KIND(unicode) != 0);
3911 assert(PyUnicode_IS_READY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003912
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003913 if (PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003914#if SIZEOF_WCHAR_T == 2
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003915 four_bytes = PyUnicode_4BYTE_DATA(unicode);
3916 ucs4_end = four_bytes + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003917 num_surrogates = 0;
3918
3919 for (; four_bytes < ucs4_end; ++four_bytes) {
3920 if (*four_bytes > 0xFFFF)
3921 ++num_surrogates;
3922 }
3923
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003924 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(
3925 sizeof(wchar_t) * (_PyUnicode_LENGTH(unicode) + 1 + num_surrogates));
3926 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003927 PyErr_NoMemory();
3928 return NULL;
3929 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003930 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode) + num_surrogates;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003931
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003932 w = _PyUnicode_WSTR(unicode);
3933 wchar_end = w + _PyUnicode_WSTR_LENGTH(unicode);
3934 four_bytes = PyUnicode_4BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003935 for (; four_bytes < ucs4_end; ++four_bytes, ++w) {
3936 if (*four_bytes > 0xFFFF) {
Victor Stinner8faf8212011-12-08 22:14:11 +01003937 assert(*four_bytes <= MAX_UNICODE);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003938 /* encode surrogate pair in this case */
Victor Stinner551ac952011-11-29 22:58:13 +01003939 *w++ = Py_UNICODE_HIGH_SURROGATE(*four_bytes);
3940 *w = Py_UNICODE_LOW_SURROGATE(*four_bytes);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003941 }
3942 else
3943 *w = *four_bytes;
3944
3945 if (w > wchar_end) {
3946 assert(0 && "Miscalculated string end");
3947 }
3948 }
3949 *w = 0;
3950#else
3951 /* sizeof(wchar_t) == 4 */
3952 Py_FatalError("Impossible unicode object state, wstr and str "
3953 "should share memory already.");
3954 return NULL;
3955#endif
3956 }
3957 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003958 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(sizeof(wchar_t) *
3959 (_PyUnicode_LENGTH(unicode) + 1));
3960 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003961 PyErr_NoMemory();
3962 return NULL;
3963 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003964 if (!PyUnicode_IS_COMPACT_ASCII(unicode))
3965 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode);
3966 w = _PyUnicode_WSTR(unicode);
3967 wchar_end = w + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003968
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003969 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND) {
3970 one_byte = PyUnicode_1BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003971 for (; w < wchar_end; ++one_byte, ++w)
3972 *w = *one_byte;
3973 /* null-terminate the wstr */
3974 *w = 0;
3975 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003976 else if (PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003977#if SIZEOF_WCHAR_T == 4
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003978 two_bytes = PyUnicode_2BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003979 for (; w < wchar_end; ++two_bytes, ++w)
3980 *w = *two_bytes;
3981 /* null-terminate the wstr */
3982 *w = 0;
3983#else
3984 /* sizeof(wchar_t) == 2 */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003985 PyObject_FREE(_PyUnicode_WSTR(unicode));
3986 _PyUnicode_WSTR(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003987 Py_FatalError("Impossible unicode object state, wstr "
3988 "and str should share memory already.");
3989 return NULL;
3990#endif
3991 }
3992 else {
3993 assert(0 && "This should never happen.");
3994 }
3995 }
3996 }
3997 if (size != NULL)
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003998 *size = PyUnicode_WSTR_LENGTH(unicode);
3999 return _PyUnicode_WSTR(unicode);
Martin v. Löwis5b222132007-06-10 09:51:05 +00004000}
4001
Alexander Belopolsky40018472011-02-26 01:02:56 +00004002Py_UNICODE *
4003PyUnicode_AsUnicode(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004004{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004005 return PyUnicode_AsUnicodeAndSize(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004006}
4007
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004008
Alexander Belopolsky40018472011-02-26 01:02:56 +00004009Py_ssize_t
4010PyUnicode_GetSize(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004011{
4012 if (!PyUnicode_Check(unicode)) {
4013 PyErr_BadArgument();
4014 goto onError;
4015 }
4016 return PyUnicode_GET_SIZE(unicode);
4017
Benjamin Peterson29060642009-01-31 22:14:21 +00004018 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00004019 return -1;
4020}
4021
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004022Py_ssize_t
4023PyUnicode_GetLength(PyObject *unicode)
4024{
Victor Stinner07621332012-06-16 04:53:46 +02004025 if (!PyUnicode_Check(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004026 PyErr_BadArgument();
4027 return -1;
4028 }
Victor Stinner07621332012-06-16 04:53:46 +02004029 if (PyUnicode_READY(unicode) == -1)
4030 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004031 return PyUnicode_GET_LENGTH(unicode);
4032}
4033
4034Py_UCS4
4035PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
4036{
Victor Stinner2fe5ced2011-10-02 00:25:40 +02004037 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
4038 PyErr_BadArgument();
4039 return (Py_UCS4)-1;
4040 }
Victor Stinnerc4b49542011-12-11 22:44:26 +01004041 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinner2fe5ced2011-10-02 00:25:40 +02004042 PyErr_SetString(PyExc_IndexError, "string index out of range");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004043 return (Py_UCS4)-1;
4044 }
4045 return PyUnicode_READ_CHAR(unicode, index);
4046}
4047
4048int
4049PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 ch)
4050{
4051 if (!PyUnicode_Check(unicode) || !PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02004052 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004053 return -1;
4054 }
Victor Stinner488fa492011-12-12 00:01:39 +01004055 assert(PyUnicode_IS_READY(unicode));
Victor Stinnerc4b49542011-12-11 22:44:26 +01004056 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02004057 PyErr_SetString(PyExc_IndexError, "string index out of range");
4058 return -1;
4059 }
Victor Stinner488fa492011-12-12 00:01:39 +01004060 if (unicode_check_modifiable(unicode))
Victor Stinnercd9950f2011-10-02 00:34:53 +02004061 return -1;
Victor Stinnerc9590ad2012-03-04 01:34:37 +01004062 if (ch > PyUnicode_MAX_CHAR_VALUE(unicode)) {
4063 PyErr_SetString(PyExc_ValueError, "character out of range");
4064 return -1;
4065 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004066 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
4067 index, ch);
4068 return 0;
4069}
4070
Alexander Belopolsky40018472011-02-26 01:02:56 +00004071const char *
4072PyUnicode_GetDefaultEncoding(void)
Fred Drakee4315f52000-05-09 19:53:39 +00004073{
Victor Stinner42cb4622010-09-01 19:39:01 +00004074 return "utf-8";
Fred Drakee4315f52000-05-09 19:53:39 +00004075}
4076
Victor Stinner554f3f02010-06-16 23:33:54 +00004077/* create or adjust a UnicodeDecodeError */
4078static void
4079make_decode_exception(PyObject **exceptionObject,
4080 const char *encoding,
4081 const char *input, Py_ssize_t length,
4082 Py_ssize_t startpos, Py_ssize_t endpos,
4083 const char *reason)
4084{
4085 if (*exceptionObject == NULL) {
4086 *exceptionObject = PyUnicodeDecodeError_Create(
4087 encoding, input, length, startpos, endpos, reason);
4088 }
4089 else {
4090 if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
4091 goto onError;
4092 if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
4093 goto onError;
4094 if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
4095 goto onError;
4096 }
4097 return;
4098
4099onError:
4100 Py_DECREF(*exceptionObject);
4101 *exceptionObject = NULL;
4102}
4103
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004104/* error handling callback helper:
4105 build arguments, call the callback and check the arguments,
Fred Drakedb390c12005-10-28 14:39:47 +00004106 if no exception occurred, copy the replacement to the output
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004107 and adjust various state variables.
4108 return 0 on success, -1 on error
4109*/
4110
Alexander Belopolsky40018472011-02-26 01:02:56 +00004111static int
4112unicode_decode_call_errorhandler(const char *errors, PyObject **errorHandler,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004113 const char *encoding, const char *reason,
4114 const char **input, const char **inend, Py_ssize_t *startinpos,
4115 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004116 PyObject **output, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004117{
Benjamin Peterson142957c2008-07-04 19:55:29 +00004118 static char *argparse = "O!n;decoding error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004119
4120 PyObject *restuple = NULL;
4121 PyObject *repunicode = NULL;
Victor Stinner596a6c42011-11-09 00:02:18 +01004122 Py_ssize_t outsize;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004123 Py_ssize_t insize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004124 Py_ssize_t requiredsize;
4125 Py_ssize_t newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004126 PyObject *inputobj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004127 int res = -1;
4128
Victor Stinner596a6c42011-11-09 00:02:18 +01004129 if (_PyUnicode_KIND(*output) != PyUnicode_WCHAR_KIND)
4130 outsize = PyUnicode_GET_LENGTH(*output);
4131 else
4132 outsize = _PyUnicode_WSTR_LENGTH(*output);
4133
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004134 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004135 *errorHandler = PyCodec_LookupError(errors);
4136 if (*errorHandler == NULL)
4137 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004138 }
4139
Victor Stinner554f3f02010-06-16 23:33:54 +00004140 make_decode_exception(exceptionObject,
4141 encoding,
4142 *input, *inend - *input,
4143 *startinpos, *endinpos,
4144 reason);
4145 if (*exceptionObject == NULL)
4146 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004147
4148 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
4149 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004150 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004151 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00004152 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00004153 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004154 }
4155 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00004156 goto onError;
Benjamin Petersonbac79492012-01-14 13:34:47 -05004157 if (PyUnicode_READY(repunicode) == -1)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004158 goto onError;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004159
4160 /* Copy back the bytes variables, which might have been modified by the
4161 callback */
4162 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4163 if (!inputobj)
4164 goto onError;
Christian Heimes72b710a2008-05-26 13:28:38 +00004165 if (!PyBytes_Check(inputobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004166 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
Walter Dörwalde78178e2007-07-30 13:31:40 +00004167 }
Christian Heimes72b710a2008-05-26 13:28:38 +00004168 *input = PyBytes_AS_STRING(inputobj);
4169 insize = PyBytes_GET_SIZE(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004170 *inend = *input + insize;
Walter Dörwald36f938f2007-08-10 10:11:43 +00004171 /* we can DECREF safely, as the exception has another reference,
4172 so the object won't go away. */
4173 Py_DECREF(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004174
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004175 if (newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004176 newpos = insize+newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004177 if (newpos<0 || newpos>insize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004178 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
4179 goto onError;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004180 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004181
Victor Stinner596a6c42011-11-09 00:02:18 +01004182 if (_PyUnicode_KIND(*output) != PyUnicode_WCHAR_KIND) {
4183 /* need more space? (at least enough for what we
4184 have+the replacement+the rest of the string (starting
4185 at the new input position), so we won't have to check space
4186 when there are no errors in the rest of the string) */
4187 Py_ssize_t replen = PyUnicode_GET_LENGTH(repunicode);
4188 requiredsize = *outpos + replen + insize-newpos;
4189 if (requiredsize > outsize) {
4190 if (requiredsize<2*outsize)
4191 requiredsize = 2*outsize;
4192 if (unicode_resize(output, requiredsize) < 0)
4193 goto onError;
4194 }
Victor Stinner1b487b42012-05-03 12:29:04 +02004195 if (unicode_widen(output, *outpos,
4196 PyUnicode_MAX_CHAR_VALUE(repunicode)) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004197 goto onError;
Victor Stinnerd3f08822012-05-29 12:57:52 +02004198 _PyUnicode_FastCopyCharacters(*output, *outpos, repunicode, 0, replen);
Victor Stinner596a6c42011-11-09 00:02:18 +01004199 *outpos += replen;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004200 }
Victor Stinner596a6c42011-11-09 00:02:18 +01004201 else {
4202 wchar_t *repwstr;
4203 Py_ssize_t repwlen;
4204 repwstr = PyUnicode_AsUnicodeAndSize(repunicode, &repwlen);
4205 if (repwstr == NULL)
4206 goto onError;
4207 /* need more space? (at least enough for what we
4208 have+the replacement+the rest of the string (starting
4209 at the new input position), so we won't have to check space
4210 when there are no errors in the rest of the string) */
4211 requiredsize = *outpos + repwlen + insize-newpos;
4212 if (requiredsize > outsize) {
4213 if (requiredsize < 2*outsize)
4214 requiredsize = 2*outsize;
4215 if (unicode_resize(output, requiredsize) < 0)
4216 goto onError;
4217 }
4218 wcsncpy(_PyUnicode_WSTR(*output) + *outpos, repwstr, repwlen);
4219 *outpos += repwlen;
4220 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004221 *endinpos = newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004222 *inptr = *input + newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004223
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004224 /* we made it! */
4225 res = 0;
4226
Benjamin Peterson29060642009-01-31 22:14:21 +00004227 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004228 Py_XDECREF(restuple);
4229 return res;
4230}
4231
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004232/* --- UTF-7 Codec -------------------------------------------------------- */
4233
Antoine Pitrou244651a2009-05-04 18:56:13 +00004234/* See RFC2152 for details. We encode conservatively and decode liberally. */
4235
4236/* Three simple macros defining base-64. */
4237
4238/* Is c a base-64 character? */
4239
4240#define IS_BASE64(c) \
4241 (((c) >= 'A' && (c) <= 'Z') || \
4242 ((c) >= 'a' && (c) <= 'z') || \
4243 ((c) >= '0' && (c) <= '9') || \
4244 (c) == '+' || (c) == '/')
4245
4246/* given that c is a base-64 character, what is its base-64 value? */
4247
4248#define FROM_BASE64(c) \
4249 (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' : \
4250 ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 : \
4251 ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 : \
4252 (c) == '+' ? 62 : 63)
4253
4254/* What is the base-64 character of the bottom 6 bits of n? */
4255
4256#define TO_BASE64(n) \
4257 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
4258
4259/* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
4260 * decoded as itself. We are permissive on decoding; the only ASCII
4261 * byte not decoding to itself is the + which begins a base64
4262 * string. */
4263
4264#define DECODE_DIRECT(c) \
4265 ((c) <= 127 && (c) != '+')
4266
4267/* The UTF-7 encoder treats ASCII characters differently according to
4268 * whether they are Set D, Set O, Whitespace, or special (i.e. none of
4269 * the above). See RFC2152. This array identifies these different
4270 * sets:
4271 * 0 : "Set D"
4272 * alphanumeric and '(),-./:?
4273 * 1 : "Set O"
4274 * !"#$%&*;<=>@[]^_`{|}
4275 * 2 : "whitespace"
4276 * ht nl cr sp
4277 * 3 : special (must be base64 encoded)
4278 * everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
4279 */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004280
Tim Petersced69f82003-09-16 20:30:58 +00004281static
Antoine Pitrou244651a2009-05-04 18:56:13 +00004282char utf7_category[128] = {
4283/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
4284 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
4285/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
4286 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
4287/* sp ! " # $ % & ' ( ) * + , - . / */
4288 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
4289/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
4290 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
4291/* @ A B C D E F G H I J K L M N O */
4292 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4293/* P Q R S T U V W X Y Z [ \ ] ^ _ */
4294 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
4295/* ` a b c d e f g h i j k l m n o */
4296 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4297/* p q r s t u v w x y z { | } ~ del */
4298 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004299};
4300
Antoine Pitrou244651a2009-05-04 18:56:13 +00004301/* ENCODE_DIRECT: this character should be encoded as itself. The
4302 * answer depends on whether we are encoding set O as itself, and also
4303 * on whether we are encoding whitespace as itself. RFC2152 makes it
4304 * clear that the answers to these questions vary between
4305 * applications, so this code needs to be flexible. */
Marc-André Lemburge115ec82005-10-19 22:33:31 +00004306
Antoine Pitrou244651a2009-05-04 18:56:13 +00004307#define ENCODE_DIRECT(c, directO, directWS) \
4308 ((c) < 128 && (c) > 0 && \
4309 ((utf7_category[(c)] == 0) || \
4310 (directWS && (utf7_category[(c)] == 2)) || \
4311 (directO && (utf7_category[(c)] == 1))))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004312
Alexander Belopolsky40018472011-02-26 01:02:56 +00004313PyObject *
4314PyUnicode_DecodeUTF7(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004315 Py_ssize_t size,
4316 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004317{
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004318 return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
4319}
4320
Antoine Pitrou244651a2009-05-04 18:56:13 +00004321/* The decoder. The only state we preserve is our read position,
4322 * i.e. how many characters we have consumed. So if we end in the
4323 * middle of a shift sequence we have to back off the read position
4324 * and the output to the beginning of the sequence, otherwise we lose
4325 * all the shift state (seen bits, number of bits seen, high
4326 * surrogate). */
4327
Alexander Belopolsky40018472011-02-26 01:02:56 +00004328PyObject *
4329PyUnicode_DecodeUTF7Stateful(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004330 Py_ssize_t size,
4331 const char *errors,
4332 Py_ssize_t *consumed)
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004333{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004334 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004335 Py_ssize_t startinpos;
4336 Py_ssize_t endinpos;
4337 Py_ssize_t outpos;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004338 const char *e;
Victor Stinner7931d9a2011-11-04 00:22:48 +01004339 PyObject *unicode;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004340 const char *errmsg = "";
4341 int inShift = 0;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004342 Py_ssize_t shiftOutStart;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004343 unsigned int base64bits = 0;
4344 unsigned long base64buffer = 0;
Victor Stinner24729f32011-11-10 20:31:37 +01004345 Py_UCS4 surrogate = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004346 PyObject *errorHandler = NULL;
4347 PyObject *exc = NULL;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004348
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004349 /* Start off assuming it's all ASCII. Widen later as necessary. */
4350 unicode = PyUnicode_New(size, 127);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004351 if (!unicode)
4352 return NULL;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004353 if (size == 0) {
4354 if (consumed)
4355 *consumed = 0;
Victor Stinner7931d9a2011-11-04 00:22:48 +01004356 return unicode;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004357 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004358
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004359 shiftOutStart = outpos = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004360 e = s + size;
4361
4362 while (s < e) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004363 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00004364 restart:
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00004365 ch = (unsigned char) *s;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004366
Antoine Pitrou244651a2009-05-04 18:56:13 +00004367 if (inShift) { /* in a base-64 section */
4368 if (IS_BASE64(ch)) { /* consume a base-64 character */
4369 base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
4370 base64bits += 6;
4371 s++;
4372 if (base64bits >= 16) {
4373 /* we have enough bits for a UTF-16 value */
Victor Stinner24729f32011-11-10 20:31:37 +01004374 Py_UCS4 outCh = (Py_UCS4)(base64buffer >> (base64bits-16));
Antoine Pitrou244651a2009-05-04 18:56:13 +00004375 base64bits -= 16;
4376 base64buffer &= (1 << base64bits) - 1; /* clear high bits */
4377 if (surrogate) {
4378 /* expecting a second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004379 if (Py_UNICODE_IS_LOW_SURROGATE(outCh)) {
4380 Py_UCS4 ch2 = Py_UNICODE_JOIN_SURROGATES(surrogate, outCh);
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004381 if (unicode_putchar(&unicode, &outpos, ch2) < 0)
4382 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004383 surrogate = 0;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01004384 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004385 }
4386 else {
Antoine Pitrou78edf752011-11-15 01:44:16 +01004387 if (unicode_putchar(&unicode, &outpos, surrogate) < 0)
4388 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004389 surrogate = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004390 }
4391 }
Victor Stinner551ac952011-11-29 22:58:13 +01004392 if (Py_UNICODE_IS_HIGH_SURROGATE(outCh)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004393 /* first surrogate */
4394 surrogate = outCh;
4395 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004396 else {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004397 if (unicode_putchar(&unicode, &outpos, outCh) < 0)
4398 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004399 }
4400 }
4401 }
4402 else { /* now leaving a base-64 section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004403 inShift = 0;
4404 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004405 if (surrogate) {
Antoine Pitrou78edf752011-11-15 01:44:16 +01004406 if (unicode_putchar(&unicode, &outpos, surrogate) < 0)
4407 goto onError;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01004408 surrogate = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004409 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004410 if (base64bits > 0) { /* left-over bits */
4411 if (base64bits >= 6) {
4412 /* We've seen at least one base-64 character */
4413 errmsg = "partial character in shift sequence";
4414 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004415 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004416 else {
4417 /* Some bits remain; they should be zero */
4418 if (base64buffer != 0) {
4419 errmsg = "non-zero padding bits in shift sequence";
4420 goto utf7Error;
4421 }
4422 }
4423 }
4424 if (ch != '-') {
4425 /* '-' is absorbed; other terminating
4426 characters are preserved */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004427 if (unicode_putchar(&unicode, &outpos, ch) < 0)
4428 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004429 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004430 }
4431 }
4432 else if ( ch == '+' ) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004433 startinpos = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004434 s++; /* consume '+' */
4435 if (s < e && *s == '-') { /* '+-' encodes '+' */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004436 s++;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004437 if (unicode_putchar(&unicode, &outpos, '+') < 0)
4438 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004439 }
4440 else { /* begin base64-encoded section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004441 inShift = 1;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004442 shiftOutStart = outpos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004443 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004444 }
4445 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004446 else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004447 if (unicode_putchar(&unicode, &outpos, ch) < 0)
4448 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004449 s++;
4450 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004451 else {
4452 startinpos = s-starts;
4453 s++;
4454 errmsg = "unexpected special character";
4455 goto utf7Error;
4456 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004457 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004458utf7Error:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004459 endinpos = s-starts;
4460 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00004461 errors, &errorHandler,
4462 "utf7", errmsg,
4463 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004464 &unicode, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00004465 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004466 }
4467
Antoine Pitrou244651a2009-05-04 18:56:13 +00004468 /* end of string */
4469
4470 if (inShift && !consumed) { /* in shift sequence, no more to follow */
4471 /* if we're in an inconsistent state, that's an error */
4472 if (surrogate ||
4473 (base64bits >= 6) ||
4474 (base64bits > 0 && base64buffer != 0)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004475 endinpos = size;
4476 if (unicode_decode_call_errorhandler(
4477 errors, &errorHandler,
4478 "utf7", "unterminated shift sequence",
4479 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004480 &unicode, &outpos))
Antoine Pitrou244651a2009-05-04 18:56:13 +00004481 goto onError;
4482 if (s < e)
4483 goto restart;
4484 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004485 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004486
4487 /* return state */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004488 if (consumed) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004489 if (inShift) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004490 outpos = shiftOutStart; /* back off output */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004491 *consumed = startinpos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004492 }
4493 else {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004494 *consumed = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004495 }
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004496 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004497
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004498 if (unicode_resize(&unicode, outpos) < 0)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004499 goto onError;
4500
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004501 Py_XDECREF(errorHandler);
4502 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01004503 return unicode_result(unicode);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004504
Benjamin Peterson29060642009-01-31 22:14:21 +00004505 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004506 Py_XDECREF(errorHandler);
4507 Py_XDECREF(exc);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004508 Py_DECREF(unicode);
4509 return NULL;
4510}
4511
4512
Alexander Belopolsky40018472011-02-26 01:02:56 +00004513PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004514_PyUnicode_EncodeUTF7(PyObject *str,
4515 int base64SetO,
4516 int base64WhiteSpace,
4517 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004518{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004519 int kind;
4520 void *data;
4521 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004522 PyObject *v;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004523 Py_ssize_t allocated;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004524 int inShift = 0;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004525 Py_ssize_t i;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004526 unsigned int base64bits = 0;
4527 unsigned long base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004528 char * out;
4529 char * start;
4530
Benjamin Petersonbac79492012-01-14 13:34:47 -05004531 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004532 return NULL;
4533 kind = PyUnicode_KIND(str);
4534 data = PyUnicode_DATA(str);
4535 len = PyUnicode_GET_LENGTH(str);
4536
4537 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004538 return PyBytes_FromStringAndSize(NULL, 0);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004539
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004540 /* It might be possible to tighten this worst case */
4541 allocated = 8 * len;
4542 if (allocated / 8 != len)
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004543 return PyErr_NoMemory();
4544
Antoine Pitrou244651a2009-05-04 18:56:13 +00004545 v = PyBytes_FromStringAndSize(NULL, allocated);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004546 if (v == NULL)
4547 return NULL;
4548
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004549 start = out = PyBytes_AS_STRING(v);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004550 for (i = 0; i < len; ++i) {
Victor Stinner0e368262011-11-10 20:12:49 +01004551 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004552
Antoine Pitrou244651a2009-05-04 18:56:13 +00004553 if (inShift) {
4554 if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4555 /* shifting out */
4556 if (base64bits) { /* output remaining bits */
4557 *out++ = TO_BASE64(base64buffer << (6-base64bits));
4558 base64buffer = 0;
4559 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004560 }
4561 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004562 /* Characters not in the BASE64 set implicitly unshift the sequence
4563 so no '-' is required, except if the character is itself a '-' */
4564 if (IS_BASE64(ch) || ch == '-') {
4565 *out++ = '-';
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004566 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004567 *out++ = (char) ch;
4568 }
4569 else {
4570 goto encode_char;
Tim Petersced69f82003-09-16 20:30:58 +00004571 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004572 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004573 else { /* not in a shift sequence */
4574 if (ch == '+') {
4575 *out++ = '+';
4576 *out++ = '-';
4577 }
4578 else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4579 *out++ = (char) ch;
4580 }
4581 else {
4582 *out++ = '+';
4583 inShift = 1;
4584 goto encode_char;
4585 }
4586 }
4587 continue;
4588encode_char:
Antoine Pitrou244651a2009-05-04 18:56:13 +00004589 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01004590 assert(ch <= MAX_UNICODE);
Victor Stinner0d3721d2011-11-22 03:27:53 +01004591
Antoine Pitrou244651a2009-05-04 18:56:13 +00004592 /* code first surrogate */
4593 base64bits += 16;
4594 base64buffer = (base64buffer << 16) | 0xd800 | ((ch-0x10000) >> 10);
4595 while (base64bits >= 6) {
4596 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4597 base64bits -= 6;
4598 }
4599 /* prepare second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004600 ch = Py_UNICODE_LOW_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004601 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004602 base64bits += 16;
4603 base64buffer = (base64buffer << 16) | ch;
4604 while (base64bits >= 6) {
4605 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4606 base64bits -= 6;
4607 }
Hye-Shik Chang1bc09b72004-01-03 19:35:43 +00004608 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004609 if (base64bits)
4610 *out++= TO_BASE64(base64buffer << (6-base64bits) );
4611 if (inShift)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004612 *out++ = '-';
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004613 if (_PyBytes_Resize(&v, out - start) < 0)
4614 return NULL;
4615 return v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004616}
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004617PyObject *
4618PyUnicode_EncodeUTF7(const Py_UNICODE *s,
4619 Py_ssize_t size,
4620 int base64SetO,
4621 int base64WhiteSpace,
4622 const char *errors)
4623{
4624 PyObject *result;
4625 PyObject *tmp = PyUnicode_FromUnicode(s, size);
4626 if (tmp == NULL)
4627 return NULL;
Victor Stinner0e368262011-11-10 20:12:49 +01004628 result = _PyUnicode_EncodeUTF7(tmp, base64SetO,
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004629 base64WhiteSpace, errors);
4630 Py_DECREF(tmp);
4631 return result;
4632}
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004633
Antoine Pitrou244651a2009-05-04 18:56:13 +00004634#undef IS_BASE64
4635#undef FROM_BASE64
4636#undef TO_BASE64
4637#undef DECODE_DIRECT
4638#undef ENCODE_DIRECT
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004639
Guido van Rossumd57fd912000-03-10 22:53:23 +00004640/* --- UTF-8 Codec -------------------------------------------------------- */
4641
Alexander Belopolsky40018472011-02-26 01:02:56 +00004642PyObject *
4643PyUnicode_DecodeUTF8(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004644 Py_ssize_t size,
4645 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004646{
Walter Dörwald69652032004-09-07 20:24:22 +00004647 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
4648}
4649
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004650#include "stringlib/asciilib.h"
4651#include "stringlib/codecs.h"
4652#include "stringlib/undef.h"
4653
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004654#include "stringlib/ucs1lib.h"
4655#include "stringlib/codecs.h"
4656#include "stringlib/undef.h"
4657
4658#include "stringlib/ucs2lib.h"
4659#include "stringlib/codecs.h"
4660#include "stringlib/undef.h"
4661
4662#include "stringlib/ucs4lib.h"
4663#include "stringlib/codecs.h"
4664#include "stringlib/undef.h"
4665
Antoine Pitrouab868312009-01-10 15:40:25 +00004666/* Mask to quickly check whether a C 'long' contains a
4667 non-ASCII, UTF8-encoded char. */
4668#if (SIZEOF_LONG == 8)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004669# define ASCII_CHAR_MASK 0x8080808080808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004670#elif (SIZEOF_LONG == 4)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004671# define ASCII_CHAR_MASK 0x80808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004672#else
4673# error C 'long' size should be either 4 or 8!
4674#endif
4675
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004676static Py_ssize_t
4677ascii_decode(const char *start, const char *end, Py_UCS1 *dest)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004678{
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004679 const char *p = start;
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004680 const char *aligned_end = (const char *) _Py_ALIGN_DOWN(end, SIZEOF_LONG);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004681
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004682#if SIZEOF_LONG <= SIZEOF_VOID_P
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004683 assert(_Py_IS_ALIGNED(dest, SIZEOF_LONG));
4684 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004685 /* Fast path, see in STRINGLIB(utf8_decode) for
4686 an explanation. */
4687 /* Help register allocation */
4688 register const char *_p = p;
4689 register Py_UCS1 * q = dest;
4690 while (_p < aligned_end) {
4691 unsigned long value = *(const unsigned long *) _p;
4692 if (value & ASCII_CHAR_MASK)
Benjamin Peterson29060642009-01-31 22:14:21 +00004693 break;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004694 *((unsigned long *)q) = value;
4695 _p += SIZEOF_LONG;
4696 q += SIZEOF_LONG;
Benjamin Peterson14339b62009-01-31 16:36:08 +00004697 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004698 p = _p;
4699 while (p < end) {
4700 if ((unsigned char)*p & 0x80)
4701 break;
4702 *q++ = *p++;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004703 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004704 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004705 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004706#endif
4707 while (p < end) {
4708 /* Fast path, see in STRINGLIB(utf8_decode) in stringlib/codecs.h
4709 for an explanation. */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004710 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004711 /* Help register allocation */
4712 register const char *_p = p;
4713 while (_p < aligned_end) {
4714 unsigned long value = *(unsigned long *) _p;
4715 if (value & ASCII_CHAR_MASK)
4716 break;
4717 _p += SIZEOF_LONG;
4718 }
4719 p = _p;
4720 if (_p == end)
4721 break;
4722 }
4723 if ((unsigned char)*p & 0x80)
4724 break;
4725 ++p;
4726 }
4727 memcpy(dest, start, p - start);
4728 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004729}
Antoine Pitrouab868312009-01-10 15:40:25 +00004730
Victor Stinner785938e2011-12-11 20:09:03 +01004731PyObject *
4732PyUnicode_DecodeUTF8Stateful(const char *s,
4733 Py_ssize_t size,
4734 const char *errors,
4735 Py_ssize_t *consumed)
4736{
Victor Stinner785938e2011-12-11 20:09:03 +01004737 PyObject *unicode;
Victor Stinner785938e2011-12-11 20:09:03 +01004738 const char *starts = s;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004739 const char *end = s + size;
4740 Py_ssize_t outpos;
4741
4742 Py_ssize_t startinpos;
4743 Py_ssize_t endinpos;
4744 const char *errmsg = "";
4745 PyObject *errorHandler = NULL;
4746 PyObject *exc = NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01004747
4748 if (size == 0) {
4749 if (consumed)
4750 *consumed = 0;
Victor Stinner382955f2011-12-11 21:44:00 +01004751 Py_INCREF(unicode_empty);
4752 return unicode_empty;
Victor Stinner785938e2011-12-11 20:09:03 +01004753 }
4754
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004755 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
4756 if (size == 1 && (unsigned char)s[0] < 128) {
Victor Stinner785938e2011-12-11 20:09:03 +01004757 if (consumed)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004758 *consumed = 1;
4759 return get_latin1_char((unsigned char)s[0]);
Victor Stinner785938e2011-12-11 20:09:03 +01004760 }
4761
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004762 unicode = PyUnicode_New(size, 127);
Victor Stinner785938e2011-12-11 20:09:03 +01004763 if (!unicode)
4764 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01004765
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004766 outpos = ascii_decode(s, end, PyUnicode_1BYTE_DATA(unicode));
4767 s += outpos;
4768 while (s < end) {
4769 Py_UCS4 ch;
4770 int kind = PyUnicode_KIND(unicode);
4771 if (kind == PyUnicode_1BYTE_KIND) {
4772 if (PyUnicode_IS_ASCII(unicode))
4773 ch = asciilib_utf8_decode(&s, end,
4774 PyUnicode_1BYTE_DATA(unicode), &outpos);
4775 else
4776 ch = ucs1lib_utf8_decode(&s, end,
4777 PyUnicode_1BYTE_DATA(unicode), &outpos);
4778 } else if (kind == PyUnicode_2BYTE_KIND) {
4779 ch = ucs2lib_utf8_decode(&s, end,
4780 PyUnicode_2BYTE_DATA(unicode), &outpos);
4781 } else {
4782 assert(kind == PyUnicode_4BYTE_KIND);
4783 ch = ucs4lib_utf8_decode(&s, end,
4784 PyUnicode_4BYTE_DATA(unicode), &outpos);
4785 }
4786
4787 switch (ch) {
4788 case 0:
4789 if (s == end || consumed)
4790 goto End;
4791 errmsg = "unexpected end of data";
4792 startinpos = s - starts;
4793 endinpos = startinpos + 1;
4794 while (endinpos < size && (starts[endinpos] & 0xC0) == 0x80)
4795 endinpos++;
4796 break;
4797 case 1:
4798 errmsg = "invalid start byte";
4799 startinpos = s - starts;
4800 endinpos = startinpos + 1;
4801 break;
4802 case 2:
4803 errmsg = "invalid continuation byte";
4804 startinpos = s - starts;
4805 endinpos = startinpos + 1;
4806 while (endinpos < size && (starts[endinpos] & 0xC0) == 0x80)
4807 endinpos++;
4808 break;
4809 default:
4810 if (unicode_putchar(&unicode, &outpos, ch) < 0)
4811 goto onError;
4812 continue;
4813 }
4814
4815 if (unicode_decode_call_errorhandler(
4816 errors, &errorHandler,
4817 "utf-8", errmsg,
4818 &starts, &end, &startinpos, &endinpos, &exc, &s,
4819 &unicode, &outpos))
4820 goto onError;
Victor Stinner785938e2011-12-11 20:09:03 +01004821 }
4822
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004823End:
4824 if (unicode_resize(&unicode, outpos) < 0)
4825 goto onError;
4826
4827 if (consumed)
4828 *consumed = s - starts;
4829
4830 Py_XDECREF(errorHandler);
4831 Py_XDECREF(exc);
4832 assert(_PyUnicode_CheckConsistency(unicode, 1));
4833 return unicode;
4834
4835onError:
4836 Py_XDECREF(errorHandler);
4837 Py_XDECREF(exc);
4838 Py_XDECREF(unicode);
4839 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01004840}
4841
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004842#ifdef __APPLE__
4843
4844/* Simplified UTF-8 decoder using surrogateescape error handler,
4845 used to decode the command line arguments on Mac OS X. */
4846
4847wchar_t*
4848_Py_DecodeUTF8_surrogateescape(const char *s, Py_ssize_t size)
4849{
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004850 const char *e;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004851 wchar_t *unicode;
4852 Py_ssize_t outpos;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004853
4854 /* Note: size will always be longer than the resulting Unicode
4855 character count */
4856 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < (size + 1)) {
4857 PyErr_NoMemory();
4858 return NULL;
4859 }
4860 unicode = PyMem_Malloc((size + 1) * sizeof(wchar_t));
4861 if (!unicode)
4862 return NULL;
4863
4864 /* Unpack UTF-8 encoded data */
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004865 e = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004866 outpos = 0;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004867 while (s < e) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004868 Py_UCS4 ch;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004869#if SIZEOF_WCHAR_T == 4
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004870 ch = ucs4lib_utf8_decode(&s, e, (Py_UCS4 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004871#else
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004872 ch = ucs2lib_utf8_decode(&s, e, (Py_UCS2 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004873#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004874 if (ch > 0xFF) {
4875#if SIZEOF_WCHAR_T == 4
4876 assert(0);
4877#else
4878 assert(Py_UNICODE_IS_SURROGATE(ch));
4879 /* compute and append the two surrogates: */
4880 unicode[outpos++] = (wchar_t)Py_UNICODE_HIGH_SURROGATE(ch);
4881 unicode[outpos++] = (wchar_t)Py_UNICODE_LOW_SURROGATE(ch);
4882#endif
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004883 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004884 else {
4885 if (!ch && s == e)
4886 break;
4887 /* surrogateescape */
4888 unicode[outpos++] = 0xDC00 + (unsigned char)*s++;
4889 }
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004890 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004891 unicode[outpos] = L'\0';
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004892 return unicode;
4893}
4894
4895#endif /* __APPLE__ */
Antoine Pitrouab868312009-01-10 15:40:25 +00004896
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004897/* Primary internal function which creates utf8 encoded bytes objects.
4898
4899 Allocation strategy: if the string is short, convert into a stack buffer
Tim Peters602f7402002-04-27 18:03:26 +00004900 and allocate exactly as much space needed at the end. Else allocate the
4901 maximum possible needed (4 result bytes per Unicode character), and return
4902 the excess memory at the end.
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004903*/
Tim Peters7e3d9612002-04-21 03:26:37 +00004904PyObject *
Victor Stinner7931d9a2011-11-04 00:22:48 +01004905_PyUnicode_AsUTF8String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004906{
Victor Stinner6099a032011-12-18 14:22:26 +01004907 enum PyUnicode_Kind kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004908 void *data;
4909 Py_ssize_t size;
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00004910
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004911 if (!PyUnicode_Check(unicode)) {
4912 PyErr_BadArgument();
4913 return NULL;
4914 }
4915
4916 if (PyUnicode_READY(unicode) == -1)
4917 return NULL;
4918
Victor Stinnere90fe6a2011-10-01 16:48:13 +02004919 if (PyUnicode_UTF8(unicode))
4920 return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode),
4921 PyUnicode_UTF8_LENGTH(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004922
4923 kind = PyUnicode_KIND(unicode);
4924 data = PyUnicode_DATA(unicode);
4925 size = PyUnicode_GET_LENGTH(unicode);
4926
Benjamin Petersonead6b532011-12-20 17:23:42 -06004927 switch (kind) {
Victor Stinner6099a032011-12-18 14:22:26 +01004928 default:
4929 assert(0);
4930 case PyUnicode_1BYTE_KIND:
4931 /* the string cannot be ASCII, or PyUnicode_UTF8() would be set */
4932 assert(!PyUnicode_IS_ASCII(unicode));
4933 return ucs1lib_utf8_encoder(unicode, data, size, errors);
4934 case PyUnicode_2BYTE_KIND:
4935 return ucs2lib_utf8_encoder(unicode, data, size, errors);
4936 case PyUnicode_4BYTE_KIND:
4937 return ucs4lib_utf8_encoder(unicode, data, size, errors);
Tim Peters602f7402002-04-27 18:03:26 +00004938 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004939}
4940
Alexander Belopolsky40018472011-02-26 01:02:56 +00004941PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004942PyUnicode_EncodeUTF8(const Py_UNICODE *s,
4943 Py_ssize_t size,
4944 const char *errors)
4945{
4946 PyObject *v, *unicode;
4947
4948 unicode = PyUnicode_FromUnicode(s, size);
4949 if (unicode == NULL)
4950 return NULL;
4951 v = _PyUnicode_AsUTF8String(unicode, errors);
4952 Py_DECREF(unicode);
4953 return v;
4954}
4955
4956PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00004957PyUnicode_AsUTF8String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004958{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004959 return _PyUnicode_AsUTF8String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004960}
4961
Walter Dörwald41980ca2007-08-16 21:55:45 +00004962/* --- UTF-32 Codec ------------------------------------------------------- */
4963
4964PyObject *
4965PyUnicode_DecodeUTF32(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004966 Py_ssize_t size,
4967 const char *errors,
4968 int *byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004969{
4970 return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
4971}
4972
4973PyObject *
4974PyUnicode_DecodeUTF32Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004975 Py_ssize_t size,
4976 const char *errors,
4977 int *byteorder,
4978 Py_ssize_t *consumed)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004979{
4980 const char *starts = s;
4981 Py_ssize_t startinpos;
4982 Py_ssize_t endinpos;
4983 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01004984 PyObject *unicode;
Mark Dickinson7db923c2010-06-12 09:10:14 +00004985 const unsigned char *q, *e;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004986 int bo = 0; /* assume native ordering by default */
4987 const char *errmsg = "";
Walter Dörwald41980ca2007-08-16 21:55:45 +00004988 /* Offsets from q for retrieving bytes in the right order. */
4989#ifdef BYTEORDER_IS_LITTLE_ENDIAN
4990 int iorder[] = {0, 1, 2, 3};
4991#else
4992 int iorder[] = {3, 2, 1, 0};
4993#endif
4994 PyObject *errorHandler = NULL;
4995 PyObject *exc = NULL;
Victor Stinner313a1202010-06-11 23:56:51 +00004996
Walter Dörwald41980ca2007-08-16 21:55:45 +00004997 q = (unsigned char *)s;
4998 e = q + size;
4999
5000 if (byteorder)
5001 bo = *byteorder;
5002
5003 /* Check for BOM marks (U+FEFF) in the input and adjust current
5004 byte order setting accordingly. In native mode, the leading BOM
5005 mark is skipped, in all other modes, it is copied to the output
5006 stream as-is (giving a ZWNBSP character). */
5007 if (bo == 0) {
5008 if (size >= 4) {
5009 const Py_UCS4 bom = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
Benjamin Peterson29060642009-01-31 22:14:21 +00005010 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00005011#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Benjamin Peterson29060642009-01-31 22:14:21 +00005012 if (bom == 0x0000FEFF) {
5013 q += 4;
5014 bo = -1;
5015 }
5016 else if (bom == 0xFFFE0000) {
5017 q += 4;
5018 bo = 1;
5019 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00005020#else
Benjamin Peterson29060642009-01-31 22:14:21 +00005021 if (bom == 0x0000FEFF) {
5022 q += 4;
5023 bo = 1;
5024 }
5025 else if (bom == 0xFFFE0000) {
5026 q += 4;
5027 bo = -1;
5028 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00005029#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00005030 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00005031 }
5032
5033 if (bo == -1) {
5034 /* force LE */
5035 iorder[0] = 0;
5036 iorder[1] = 1;
5037 iorder[2] = 2;
5038 iorder[3] = 3;
5039 }
5040 else if (bo == 1) {
5041 /* force BE */
5042 iorder[0] = 3;
5043 iorder[1] = 2;
5044 iorder[2] = 1;
5045 iorder[3] = 0;
5046 }
5047
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005048 /* This might be one to much, because of a BOM */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005049 unicode = PyUnicode_New((size+3)/4, 127);
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005050 if (!unicode)
5051 return NULL;
5052 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01005053 return unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005054 outpos = 0;
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005055
Walter Dörwald41980ca2007-08-16 21:55:45 +00005056 while (q < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005057 Py_UCS4 ch;
5058 /* remaining bytes at the end? (size should be divisible by 4) */
5059 if (e-q<4) {
5060 if (consumed)
5061 break;
5062 errmsg = "truncated data";
5063 startinpos = ((const char *)q)-starts;
5064 endinpos = ((const char *)e)-starts;
5065 goto utf32Error;
5066 /* The remaining input chars are ignored if the callback
5067 chooses to skip the input */
5068 }
5069 ch = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
5070 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00005071
Benjamin Peterson29060642009-01-31 22:14:21 +00005072 if (ch >= 0x110000)
5073 {
5074 errmsg = "codepoint not in range(0x110000)";
5075 startinpos = ((const char *)q)-starts;
5076 endinpos = startinpos+4;
5077 goto utf32Error;
5078 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005079 if (unicode_putchar(&unicode, &outpos, ch) < 0)
5080 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005081 q += 4;
5082 continue;
5083 utf32Error:
Benjamin Peterson29060642009-01-31 22:14:21 +00005084 if (unicode_decode_call_errorhandler(
5085 errors, &errorHandler,
5086 "utf32", errmsg,
5087 &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005088 &unicode, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00005089 goto onError;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005090 }
5091
5092 if (byteorder)
5093 *byteorder = bo;
5094
5095 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005096 *consumed = (const char *)q-starts;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005097
5098 /* Adjust length */
Victor Stinner16e6a802011-12-12 13:24:15 +01005099 if (unicode_resize(&unicode, outpos) < 0)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005100 goto onError;
5101
5102 Py_XDECREF(errorHandler);
5103 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01005104 return unicode_result(unicode);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005105
Benjamin Peterson29060642009-01-31 22:14:21 +00005106 onError:
Walter Dörwald41980ca2007-08-16 21:55:45 +00005107 Py_DECREF(unicode);
5108 Py_XDECREF(errorHandler);
5109 Py_XDECREF(exc);
5110 return NULL;
5111}
5112
5113PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005114_PyUnicode_EncodeUTF32(PyObject *str,
5115 const char *errors,
5116 int byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005117{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005118 int kind;
5119 void *data;
5120 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005121 PyObject *v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005122 unsigned char *p;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005123 Py_ssize_t nsize, bytesize, i;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005124 /* Offsets from p for storing byte pairs in the right order. */
5125#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5126 int iorder[] = {0, 1, 2, 3};
5127#else
5128 int iorder[] = {3, 2, 1, 0};
5129#endif
5130
Benjamin Peterson29060642009-01-31 22:14:21 +00005131#define STORECHAR(CH) \
5132 do { \
5133 p[iorder[3]] = ((CH) >> 24) & 0xff; \
5134 p[iorder[2]] = ((CH) >> 16) & 0xff; \
5135 p[iorder[1]] = ((CH) >> 8) & 0xff; \
5136 p[iorder[0]] = (CH) & 0xff; \
5137 p += 4; \
Walter Dörwald41980ca2007-08-16 21:55:45 +00005138 } while(0)
5139
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005140 if (!PyUnicode_Check(str)) {
5141 PyErr_BadArgument();
5142 return NULL;
5143 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005144 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005145 return NULL;
5146 kind = PyUnicode_KIND(str);
5147 data = PyUnicode_DATA(str);
5148 len = PyUnicode_GET_LENGTH(str);
5149
5150 nsize = len + (byteorder == 0);
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005151 bytesize = nsize * 4;
5152 if (bytesize / 4 != nsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005153 return PyErr_NoMemory();
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005154 v = PyBytes_FromStringAndSize(NULL, bytesize);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005155 if (v == NULL)
5156 return NULL;
5157
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005158 p = (unsigned char *)PyBytes_AS_STRING(v);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005159 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005160 STORECHAR(0xFEFF);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005161 if (len == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005162 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005163
5164 if (byteorder == -1) {
5165 /* force LE */
5166 iorder[0] = 0;
5167 iorder[1] = 1;
5168 iorder[2] = 2;
5169 iorder[3] = 3;
5170 }
5171 else if (byteorder == 1) {
5172 /* force BE */
5173 iorder[0] = 3;
5174 iorder[1] = 2;
5175 iorder[2] = 1;
5176 iorder[3] = 0;
5177 }
5178
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005179 for (i = 0; i < len; i++)
5180 STORECHAR(PyUnicode_READ(kind, data, i));
Guido van Rossum98297ee2007-11-06 21:34:58 +00005181
5182 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005183 return v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005184#undef STORECHAR
5185}
5186
Alexander Belopolsky40018472011-02-26 01:02:56 +00005187PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005188PyUnicode_EncodeUTF32(const Py_UNICODE *s,
5189 Py_ssize_t size,
5190 const char *errors,
5191 int byteorder)
5192{
5193 PyObject *result;
5194 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5195 if (tmp == NULL)
5196 return NULL;
5197 result = _PyUnicode_EncodeUTF32(tmp, errors, byteorder);
5198 Py_DECREF(tmp);
5199 return result;
5200}
5201
5202PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005203PyUnicode_AsUTF32String(PyObject *unicode)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005204{
Victor Stinnerb960b342011-11-20 19:12:52 +01005205 return _PyUnicode_EncodeUTF32(unicode, NULL, 0);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005206}
5207
Guido van Rossumd57fd912000-03-10 22:53:23 +00005208/* --- UTF-16 Codec ------------------------------------------------------- */
5209
Tim Peters772747b2001-08-09 22:21:55 +00005210PyObject *
5211PyUnicode_DecodeUTF16(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005212 Py_ssize_t size,
5213 const char *errors,
5214 int *byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005215{
Walter Dörwald69652032004-09-07 20:24:22 +00005216 return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
5217}
5218
5219PyObject *
5220PyUnicode_DecodeUTF16Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005221 Py_ssize_t size,
5222 const char *errors,
5223 int *byteorder,
5224 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00005225{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005226 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005227 Py_ssize_t startinpos;
5228 Py_ssize_t endinpos;
5229 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01005230 PyObject *unicode;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005231 const unsigned char *q, *e;
Tim Peters772747b2001-08-09 22:21:55 +00005232 int bo = 0; /* assume native ordering by default */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005233 int native_ordering;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00005234 const char *errmsg = "";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005235 PyObject *errorHandler = NULL;
5236 PyObject *exc = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005237
Tim Peters772747b2001-08-09 22:21:55 +00005238 q = (unsigned char *)s;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005239 e = q + size;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005240
5241 if (byteorder)
Tim Peters772747b2001-08-09 22:21:55 +00005242 bo = *byteorder;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005243
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005244 /* Check for BOM marks (U+FEFF) in the input and adjust current
5245 byte order setting accordingly. In native mode, the leading BOM
5246 mark is skipped, in all other modes, it is copied to the output
5247 stream as-is (giving a ZWNBSP character). */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005248 if (bo == 0 && size >= 2) {
5249 const Py_UCS4 bom = (q[1] << 8) | q[0];
5250 if (bom == 0xFEFF) {
5251 q += 2;
5252 bo = -1;
Benjamin Peterson29060642009-01-31 22:14:21 +00005253 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005254 else if (bom == 0xFFFE) {
5255 q += 2;
5256 bo = 1;
5257 }
5258 if (byteorder)
5259 *byteorder = bo;
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005260 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005261
Antoine Pitrou63065d72012-05-15 23:48:04 +02005262 if (q == e) {
5263 if (consumed)
5264 *consumed = size;
5265 Py_INCREF(unicode_empty);
5266 return unicode_empty;
Tim Peters772747b2001-08-09 22:21:55 +00005267 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005268
Antoine Pitrouab868312009-01-10 15:40:25 +00005269#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Antoine Pitrou63065d72012-05-15 23:48:04 +02005270 native_ordering = bo <= 0;
Antoine Pitrouab868312009-01-10 15:40:25 +00005271#else
Antoine Pitrou63065d72012-05-15 23:48:04 +02005272 native_ordering = bo >= 0;
Antoine Pitrouab868312009-01-10 15:40:25 +00005273#endif
Tim Peters772747b2001-08-09 22:21:55 +00005274
Antoine Pitrou63065d72012-05-15 23:48:04 +02005275 /* Note: size will always be longer than the resulting Unicode
5276 character count */
5277 unicode = PyUnicode_New((e - q + 1) / 2, 127);
5278 if (!unicode)
5279 return NULL;
5280
5281 outpos = 0;
5282 while (1) {
5283 Py_UCS4 ch = 0;
5284 if (e - q >= 2) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005285 int kind = PyUnicode_KIND(unicode);
Antoine Pitrou63065d72012-05-15 23:48:04 +02005286 if (kind == PyUnicode_1BYTE_KIND) {
5287 if (PyUnicode_IS_ASCII(unicode))
5288 ch = asciilib_utf16_decode(&q, e,
5289 PyUnicode_1BYTE_DATA(unicode), &outpos,
5290 native_ordering);
5291 else
5292 ch = ucs1lib_utf16_decode(&q, e,
5293 PyUnicode_1BYTE_DATA(unicode), &outpos,
5294 native_ordering);
5295 } else if (kind == PyUnicode_2BYTE_KIND) {
5296 ch = ucs2lib_utf16_decode(&q, e,
5297 PyUnicode_2BYTE_DATA(unicode), &outpos,
5298 native_ordering);
5299 } else {
5300 assert(kind == PyUnicode_4BYTE_KIND);
5301 ch = ucs4lib_utf16_decode(&q, e,
5302 PyUnicode_4BYTE_DATA(unicode), &outpos,
5303 native_ordering);
Antoine Pitrouab868312009-01-10 15:40:25 +00005304 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005305 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005306
Antoine Pitrou63065d72012-05-15 23:48:04 +02005307 switch (ch)
5308 {
5309 case 0:
5310 /* remaining byte at the end? (size should be even) */
5311 if (q == e || consumed)
5312 goto End;
5313 errmsg = "truncated data";
5314 startinpos = ((const char *)q) - starts;
5315 endinpos = ((const char *)e) - starts;
5316 break;
5317 /* The remaining input chars are ignored if the callback
5318 chooses to skip the input */
5319 case 1:
5320 errmsg = "unexpected end of data";
5321 startinpos = ((const char *)q) - 2 - starts;
5322 endinpos = ((const char *)e) - starts;
5323 break;
5324 case 2:
5325 errmsg = "illegal encoding";
5326 startinpos = ((const char *)q) - 2 - starts;
5327 endinpos = startinpos + 2;
5328 break;
5329 case 3:
5330 errmsg = "illegal UTF-16 surrogate";
5331 startinpos = ((const char *)q) - 4 - starts;
5332 endinpos = startinpos + 2;
5333 break;
5334 default:
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005335 if (unicode_putchar(&unicode, &outpos, ch) < 0)
5336 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005337 continue;
5338 }
5339
Benjamin Peterson29060642009-01-31 22:14:21 +00005340 if (unicode_decode_call_errorhandler(
Antoine Pitrouab868312009-01-10 15:40:25 +00005341 errors,
5342 &errorHandler,
5343 "utf16", errmsg,
5344 &starts,
5345 (const char **)&e,
5346 &startinpos,
5347 &endinpos,
5348 &exc,
5349 (const char **)&q,
5350 &unicode,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005351 &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00005352 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005353 }
5354
Antoine Pitrou63065d72012-05-15 23:48:04 +02005355End:
Walter Dörwald69652032004-09-07 20:24:22 +00005356 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005357 *consumed = (const char *)q-starts;
Walter Dörwald69652032004-09-07 20:24:22 +00005358
Guido van Rossumd57fd912000-03-10 22:53:23 +00005359 /* Adjust length */
Victor Stinner16e6a802011-12-12 13:24:15 +01005360 if (unicode_resize(&unicode, outpos) < 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005361 goto onError;
5362
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005363 Py_XDECREF(errorHandler);
5364 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01005365 return unicode_result(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005366
Benjamin Peterson29060642009-01-31 22:14:21 +00005367 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00005368 Py_DECREF(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005369 Py_XDECREF(errorHandler);
5370 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005371 return NULL;
5372}
5373
Tim Peters772747b2001-08-09 22:21:55 +00005374PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005375_PyUnicode_EncodeUTF16(PyObject *str,
5376 const char *errors,
5377 int byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005378{
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005379 enum PyUnicode_Kind kind;
5380 const void *data;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005381 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005382 PyObject *v;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005383 unsigned short *out;
5384 Py_ssize_t bytesize;
5385 Py_ssize_t pairs;
5386#ifdef WORDS_BIGENDIAN
5387 int native_ordering = byteorder >= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005388#else
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005389 int native_ordering = byteorder <= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005390#endif
5391
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005392 if (!PyUnicode_Check(str)) {
5393 PyErr_BadArgument();
5394 return NULL;
5395 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005396 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005397 return NULL;
5398 kind = PyUnicode_KIND(str);
5399 data = PyUnicode_DATA(str);
5400 len = PyUnicode_GET_LENGTH(str);
Victor Stinner0e368262011-11-10 20:12:49 +01005401
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005402 pairs = 0;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005403 if (kind == PyUnicode_4BYTE_KIND) {
5404 const Py_UCS4 *in = (const Py_UCS4 *)data;
5405 const Py_UCS4 *end = in + len;
5406 while (in < end)
5407 if (*in++ >= 0x10000)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005408 pairs++;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005409 }
5410 if (len > PY_SSIZE_T_MAX / 2 - pairs - (byteorder == 0))
Benjamin Peterson29060642009-01-31 22:14:21 +00005411 return PyErr_NoMemory();
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005412 bytesize = (len + pairs + (byteorder == 0)) * 2;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005413 v = PyBytes_FromStringAndSize(NULL, bytesize);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005414 if (v == NULL)
5415 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005416
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005417 /* output buffer is 2-bytes aligned */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02005418 assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 2));
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005419 out = (unsigned short *)PyBytes_AS_STRING(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005420 if (byteorder == 0)
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005421 *out++ = 0xFEFF;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005422 if (len == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005423 goto done;
Tim Peters772747b2001-08-09 22:21:55 +00005424
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005425 switch (kind) {
5426 case PyUnicode_1BYTE_KIND: {
5427 ucs1lib_utf16_encode(out, (const Py_UCS1 *)data, len, native_ordering);
5428 break;
Tim Peters772747b2001-08-09 22:21:55 +00005429 }
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005430 case PyUnicode_2BYTE_KIND: {
5431 ucs2lib_utf16_encode(out, (const Py_UCS2 *)data, len, native_ordering);
5432 break;
Tim Peters772747b2001-08-09 22:21:55 +00005433 }
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005434 case PyUnicode_4BYTE_KIND: {
5435 ucs4lib_utf16_encode(out, (const Py_UCS4 *)data, len, native_ordering);
5436 break;
5437 }
5438 default:
5439 assert(0);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005440 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005441
5442 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005443 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005444}
5445
Alexander Belopolsky40018472011-02-26 01:02:56 +00005446PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005447PyUnicode_EncodeUTF16(const Py_UNICODE *s,
5448 Py_ssize_t size,
5449 const char *errors,
5450 int byteorder)
5451{
5452 PyObject *result;
5453 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5454 if (tmp == NULL)
5455 return NULL;
5456 result = _PyUnicode_EncodeUTF16(tmp, errors, byteorder);
5457 Py_DECREF(tmp);
5458 return result;
5459}
5460
5461PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005462PyUnicode_AsUTF16String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005463{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005464 return _PyUnicode_EncodeUTF16(unicode, NULL, 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005465}
5466
5467/* --- Unicode Escape Codec ----------------------------------------------- */
5468
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005469/* Helper function for PyUnicode_DecodeUnicodeEscape, determines
5470 if all the escapes in the string make it still a valid ASCII string.
5471 Returns -1 if any escapes were found which cause the string to
5472 pop out of ASCII range. Otherwise returns the length of the
5473 required buffer to hold the string.
5474 */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02005475static Py_ssize_t
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005476length_of_escaped_ascii_string(const char *s, Py_ssize_t size)
5477{
5478 const unsigned char *p = (const unsigned char *)s;
5479 const unsigned char *end = p + size;
5480 Py_ssize_t length = 0;
5481
5482 if (size < 0)
5483 return -1;
5484
5485 for (; p < end; ++p) {
5486 if (*p > 127) {
5487 /* Non-ASCII */
5488 return -1;
5489 }
5490 else if (*p != '\\') {
5491 /* Normal character */
5492 ++length;
5493 }
5494 else {
5495 /* Backslash-escape, check next char */
5496 ++p;
5497 /* Escape sequence reaches till end of string or
5498 non-ASCII follow-up. */
5499 if (p >= end || *p > 127)
5500 return -1;
5501 switch (*p) {
5502 case '\n':
5503 /* backslash + \n result in zero characters */
5504 break;
5505 case '\\': case '\'': case '\"':
5506 case 'b': case 'f': case 't':
5507 case 'n': case 'r': case 'v': case 'a':
5508 ++length;
5509 break;
5510 case '0': case '1': case '2': case '3':
5511 case '4': case '5': case '6': case '7':
5512 case 'x': case 'u': case 'U': case 'N':
5513 /* these do not guarantee ASCII characters */
5514 return -1;
5515 default:
5516 /* count the backslash + the other character */
5517 length += 2;
5518 }
5519 }
5520 }
5521 return length;
5522}
5523
Fredrik Lundh06d12682001-01-24 07:59:11 +00005524static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
Marc-André Lemburg0f774e32000-06-28 16:43:35 +00005525
Alexander Belopolsky40018472011-02-26 01:02:56 +00005526PyObject *
5527PyUnicode_DecodeUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005528 Py_ssize_t size,
Victor Stinnerc17f5402011-09-29 00:16:58 +02005529 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005530{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005531 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005532 Py_ssize_t startinpos;
5533 Py_ssize_t endinpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005534 int j;
Victor Stinner7931d9a2011-11-04 00:22:48 +01005535 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005536 const char *end;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005537 char* message;
5538 Py_UCS4 chr = 0xffffffff; /* in case 'getcode' messes up */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005539 PyObject *errorHandler = NULL;
5540 PyObject *exc = NULL;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005541 Py_ssize_t len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005542 Py_ssize_t i;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005543
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005544 len = length_of_escaped_ascii_string(s, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005545
5546 /* After length_of_escaped_ascii_string() there are two alternatives,
5547 either the string is pure ASCII with named escapes like \n, etc.
5548 and we determined it's exact size (common case)
5549 or it contains \x, \u, ... escape sequences. then we create a
5550 legacy wchar string and resize it at the end of this function. */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005551 if (len >= 0) {
5552 v = PyUnicode_New(len, 127);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005553 if (!v)
5554 goto onError;
5555 assert(PyUnicode_KIND(v) == PyUnicode_1BYTE_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005556 }
5557 else {
5558 /* Escaped strings will always be longer than the resulting
5559 Unicode string, so we start with size here and then reduce the
5560 length after conversion to the true value.
5561 (but if the error callback returns a long replacement string
5562 we'll have to allocate more space) */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005563 v = PyUnicode_New(size, 127);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005564 if (!v)
5565 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005566 len = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005567 }
5568
Guido van Rossumd57fd912000-03-10 22:53:23 +00005569 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01005570 return v;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005571 i = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005572 end = s + size;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005573
Guido van Rossumd57fd912000-03-10 22:53:23 +00005574 while (s < end) {
5575 unsigned char c;
Victor Stinner24729f32011-11-10 20:31:37 +01005576 Py_UCS4 x;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005577 int digits;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005578
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005579 /* The only case in which i == ascii_length is a backslash
5580 followed by a newline. */
5581 assert(i <= len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005582
Guido van Rossumd57fd912000-03-10 22:53:23 +00005583 /* Non-escape characters are interpreted as Unicode ordinals */
5584 if (*s != '\\') {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005585 if (unicode_putchar(&v, &i, (unsigned char) *s++) < 0)
5586 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005587 continue;
5588 }
5589
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005590 startinpos = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005591 /* \ - Escapes */
5592 s++;
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005593 c = *s++;
5594 if (s > end)
5595 c = '\0'; /* Invalid after \ */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005596
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005597 /* The only case in which i == ascii_length is a backslash
5598 followed by a newline. */
5599 assert(i < len || (i == len && c == '\n'));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005600
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005601 switch (c) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005602
Benjamin Peterson29060642009-01-31 22:14:21 +00005603 /* \x escapes */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005604#define WRITECHAR(ch) \
5605 do { \
5606 if (unicode_putchar(&v, &i, ch) < 0) \
5607 goto onError; \
5608 }while(0)
5609
Guido van Rossumd57fd912000-03-10 22:53:23 +00005610 case '\n': break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005611 case '\\': WRITECHAR('\\'); break;
5612 case '\'': WRITECHAR('\''); break;
5613 case '\"': WRITECHAR('\"'); break;
5614 case 'b': WRITECHAR('\b'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005615 /* FF */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005616 case 'f': WRITECHAR('\014'); break;
5617 case 't': WRITECHAR('\t'); break;
5618 case 'n': WRITECHAR('\n'); break;
5619 case 'r': WRITECHAR('\r'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005620 /* VT */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005621 case 'v': WRITECHAR('\013'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005622 /* BEL, not classic C */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005623 case 'a': WRITECHAR('\007'); break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005624
Benjamin Peterson29060642009-01-31 22:14:21 +00005625 /* \OOO (octal) escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005626 case '0': case '1': case '2': case '3':
5627 case '4': case '5': case '6': case '7':
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005628 x = s[-1] - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005629 if (s < end && '0' <= *s && *s <= '7') {
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005630 x = (x<<3) + *s++ - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005631 if (s < end && '0' <= *s && *s <= '7')
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005632 x = (x<<3) + *s++ - '0';
Guido van Rossumd57fd912000-03-10 22:53:23 +00005633 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005634 WRITECHAR(x);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005635 break;
5636
Benjamin Peterson29060642009-01-31 22:14:21 +00005637 /* hex escapes */
5638 /* \xXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005639 case 'x':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005640 digits = 2;
5641 message = "truncated \\xXX escape";
5642 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005643
Benjamin Peterson29060642009-01-31 22:14:21 +00005644 /* \uXXXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005645 case 'u':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005646 digits = 4;
5647 message = "truncated \\uXXXX escape";
5648 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005649
Benjamin Peterson29060642009-01-31 22:14:21 +00005650 /* \UXXXXXXXX */
Fredrik Lundhdf846752000-09-03 11:29:49 +00005651 case 'U':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005652 digits = 8;
5653 message = "truncated \\UXXXXXXXX escape";
5654 hexescape:
5655 chr = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005656 if (s+digits>end) {
5657 endinpos = size;
5658 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005659 errors, &errorHandler,
5660 "unicodeescape", "end of string in escape sequence",
5661 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005662 &v, &i))
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005663 goto onError;
5664 goto nextByte;
5665 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005666 for (j = 0; j < digits; ++j) {
5667 c = (unsigned char) s[j];
David Malcolm96960882010-11-05 17:23:41 +00005668 if (!Py_ISXDIGIT(c)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005669 endinpos = (s+j+1)-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005670 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005671 errors, &errorHandler,
5672 "unicodeescape", message,
5673 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005674 &v, &i))
Fredrik Lundhdf846752000-09-03 11:29:49 +00005675 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005676 len = PyUnicode_GET_LENGTH(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005677 goto nextByte;
Fredrik Lundhdf846752000-09-03 11:29:49 +00005678 }
5679 chr = (chr<<4) & ~0xF;
5680 if (c >= '0' && c <= '9')
5681 chr += c - '0';
5682 else if (c >= 'a' && c <= 'f')
5683 chr += 10 + c - 'a';
5684 else
5685 chr += 10 + c - 'A';
5686 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005687 s += j;
Jeremy Hylton504de6b2003-10-06 05:08:26 +00005688 if (chr == 0xffffffff && PyErr_Occurred())
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005689 /* _decoding_error will have already written into the
5690 target buffer. */
5691 break;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005692 store:
Fredrik Lundhdf846752000-09-03 11:29:49 +00005693 /* when we get here, chr is a 32-bit unicode character */
Victor Stinner8faf8212011-12-08 22:14:11 +01005694 if (chr <= MAX_UNICODE) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005695 WRITECHAR(chr);
Fredrik Lundhdf846752000-09-03 11:29:49 +00005696 } else {
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", "illegal Unicode character",
5701 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005702 &v, &i))
Fredrik Lundhdf846752000-09-03 11:29:49 +00005703 goto onError;
5704 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00005705 break;
5706
Benjamin Peterson29060642009-01-31 22:14:21 +00005707 /* \N{name} */
Fredrik Lundhccc74732001-02-18 22:13:49 +00005708 case 'N':
5709 message = "malformed \\N character escape";
5710 if (ucnhash_CAPI == NULL) {
5711 /* load the unicode data module */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005712 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
5713 PyUnicodeData_CAPSULE_NAME, 1);
Fredrik Lundhccc74732001-02-18 22:13:49 +00005714 if (ucnhash_CAPI == NULL)
5715 goto ucnhashError;
5716 }
5717 if (*s == '{') {
5718 const char *start = s+1;
5719 /* look for the closing brace */
5720 while (*s != '}' && s < end)
5721 s++;
5722 if (s > start && s < end && *s == '}') {
5723 /* found a name. look it up in the unicode database */
5724 message = "unknown Unicode character name";
5725 s++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005726 if (ucnhash_CAPI->getcode(NULL, start, (int)(s-start-1),
Ezio Melotti931b8aa2011-10-21 21:57:36 +03005727 &chr, 0))
Fredrik Lundhccc74732001-02-18 22:13:49 +00005728 goto store;
5729 }
5730 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005731 endinpos = s-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005732 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005733 errors, &errorHandler,
5734 "unicodeescape", message,
5735 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005736 &v, &i))
Fredrik Lundhccc74732001-02-18 22:13:49 +00005737 goto onError;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005738 break;
5739
5740 default:
Walter Dörwald8c077222002-03-25 11:16:18 +00005741 if (s > end) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005742 message = "\\ at end of string";
5743 s--;
5744 endinpos = s-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005745 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005746 errors, &errorHandler,
5747 "unicodeescape", message,
5748 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005749 &v, &i))
Walter Dörwald8c077222002-03-25 11:16:18 +00005750 goto onError;
5751 }
5752 else {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005753 WRITECHAR('\\');
5754 WRITECHAR(s[-1]);
Walter Dörwald8c077222002-03-25 11:16:18 +00005755 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00005756 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005757 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005758 nextByte:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005759 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005760 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005761#undef WRITECHAR
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005762
Victor Stinner16e6a802011-12-12 13:24:15 +01005763 if (unicode_resize(&v, i) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005764 goto onError;
Walter Dörwaldd4ade082003-08-15 15:00:26 +00005765 Py_XDECREF(errorHandler);
5766 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01005767 return unicode_result(v);
Walter Dörwald8c077222002-03-25 11:16:18 +00005768
Benjamin Peterson29060642009-01-31 22:14:21 +00005769 ucnhashError:
Fredrik Lundh06d12682001-01-24 07:59:11 +00005770 PyErr_SetString(
5771 PyExc_UnicodeError,
5772 "\\N escapes not supported (can't load unicodedata module)"
5773 );
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00005774 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005775 Py_XDECREF(errorHandler);
5776 Py_XDECREF(exc);
Fredrik Lundhf6056062001-01-20 11:15:25 +00005777 return NULL;
5778
Benjamin Peterson29060642009-01-31 22:14:21 +00005779 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00005780 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005781 Py_XDECREF(errorHandler);
5782 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005783 return NULL;
5784}
5785
5786/* Return a Unicode-Escape string version of the Unicode object.
5787
5788 If quotes is true, the string is enclosed in u"" or u'' quotes as
5789 appropriate.
5790
5791*/
5792
Alexander Belopolsky40018472011-02-26 01:02:56 +00005793PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005794PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005795{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005796 Py_ssize_t i, len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005797 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005798 char *p;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005799 int kind;
5800 void *data;
5801 Py_ssize_t expandsize = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005802
Thomas Wouters89f507f2006-12-13 04:49:30 +00005803 /* Initial allocation is based on the longest-possible unichr
5804 escape.
5805
5806 In wide (UTF-32) builds '\U00xxxxxx' is 10 chars per source
5807 unichr, so in this case it's the longest unichr escape. In
5808 narrow (UTF-16) builds this is five chars per source unichr
5809 since there are two unichrs in the surrogate pair, so in narrow
5810 (UTF-16) builds it's not the longest unichr escape.
5811
5812 In wide or narrow builds '\uxxxx' is 6 chars per source unichr,
5813 so in the narrow (UTF-16) build case it's the longest unichr
5814 escape.
5815 */
5816
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005817 if (!PyUnicode_Check(unicode)) {
5818 PyErr_BadArgument();
5819 return NULL;
5820 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005821 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005822 return NULL;
5823 len = PyUnicode_GET_LENGTH(unicode);
5824 kind = PyUnicode_KIND(unicode);
5825 data = PyUnicode_DATA(unicode);
Benjamin Petersonead6b532011-12-20 17:23:42 -06005826 switch (kind) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005827 case PyUnicode_1BYTE_KIND: expandsize = 4; break;
5828 case PyUnicode_2BYTE_KIND: expandsize = 6; break;
5829 case PyUnicode_4BYTE_KIND: expandsize = 10; break;
5830 }
5831
5832 if (len == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005833 return PyBytes_FromStringAndSize(NULL, 0);
5834
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005835 if (len > (PY_SSIZE_T_MAX - 2 - 1) / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005836 return PyErr_NoMemory();
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005837
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005838 repr = PyBytes_FromStringAndSize(NULL,
Benjamin Peterson29060642009-01-31 22:14:21 +00005839 2
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005840 + expandsize*len
Benjamin Peterson29060642009-01-31 22:14:21 +00005841 + 1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005842 if (repr == NULL)
5843 return NULL;
5844
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005845 p = PyBytes_AS_STRING(repr);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005846
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005847 for (i = 0; i < len; i++) {
Victor Stinner3326cb62011-11-10 20:15:25 +01005848 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005849
Walter Dörwald79e913e2007-05-12 11:08:06 +00005850 /* Escape backslashes */
5851 if (ch == '\\') {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005852 *p++ = '\\';
5853 *p++ = (char) ch;
Walter Dörwald79e913e2007-05-12 11:08:06 +00005854 continue;
Tim Petersced69f82003-09-16 20:30:58 +00005855 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005856
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005857 /* Map 21-bit characters to '\U00xxxxxx' */
5858 else if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01005859 assert(ch <= MAX_UNICODE);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005860 *p++ = '\\';
5861 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005862 *p++ = Py_hexdigits[(ch >> 28) & 0x0000000F];
5863 *p++ = Py_hexdigits[(ch >> 24) & 0x0000000F];
5864 *p++ = Py_hexdigits[(ch >> 20) & 0x0000000F];
5865 *p++ = Py_hexdigits[(ch >> 16) & 0x0000000F];
5866 *p++ = Py_hexdigits[(ch >> 12) & 0x0000000F];
5867 *p++ = Py_hexdigits[(ch >> 8) & 0x0000000F];
5868 *p++ = Py_hexdigits[(ch >> 4) & 0x0000000F];
5869 *p++ = Py_hexdigits[ch & 0x0000000F];
Benjamin Peterson29060642009-01-31 22:14:21 +00005870 continue;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005871 }
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005872
Guido van Rossumd57fd912000-03-10 22:53:23 +00005873 /* Map 16-bit characters to '\uxxxx' */
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005874 if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005875 *p++ = '\\';
5876 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005877 *p++ = Py_hexdigits[(ch >> 12) & 0x000F];
5878 *p++ = Py_hexdigits[(ch >> 8) & 0x000F];
5879 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
5880 *p++ = Py_hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00005881 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005882
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005883 /* Map special whitespace to '\t', \n', '\r' */
5884 else if (ch == '\t') {
5885 *p++ = '\\';
5886 *p++ = 't';
5887 }
5888 else if (ch == '\n') {
5889 *p++ = '\\';
5890 *p++ = 'n';
5891 }
5892 else if (ch == '\r') {
5893 *p++ = '\\';
5894 *p++ = 'r';
5895 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005896
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005897 /* Map non-printable US ASCII to '\xhh' */
Marc-André Lemburg11326de2001-11-28 12:56:20 +00005898 else if (ch < ' ' || ch >= 0x7F) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005899 *p++ = '\\';
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005900 *p++ = 'x';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005901 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
5902 *p++ = Py_hexdigits[ch & 0x000F];
Tim Petersced69f82003-09-16 20:30:58 +00005903 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005904
Guido van Rossumd57fd912000-03-10 22:53:23 +00005905 /* Copy everything else as-is */
5906 else
5907 *p++ = (char) ch;
5908 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005909
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005910 assert(p - PyBytes_AS_STRING(repr) > 0);
5911 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0)
5912 return NULL;
5913 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005914}
5915
Alexander Belopolsky40018472011-02-26 01:02:56 +00005916PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005917PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
5918 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005919{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005920 PyObject *result;
5921 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5922 if (tmp == NULL)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005923 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005924 result = PyUnicode_AsUnicodeEscapeString(tmp);
5925 Py_DECREF(tmp);
5926 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005927}
5928
5929/* --- Raw Unicode Escape Codec ------------------------------------------- */
5930
Alexander Belopolsky40018472011-02-26 01:02:56 +00005931PyObject *
5932PyUnicode_DecodeRawUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005933 Py_ssize_t size,
5934 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005935{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005936 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005937 Py_ssize_t startinpos;
5938 Py_ssize_t endinpos;
5939 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01005940 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005941 const char *end;
5942 const char *bs;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005943 PyObject *errorHandler = NULL;
5944 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00005945
Guido van Rossumd57fd912000-03-10 22:53:23 +00005946 /* Escaped strings will always be longer than the resulting
5947 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005948 length after conversion to the true value. (But decoding error
5949 handler might have to resize the string) */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005950 v = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005951 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005952 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005953 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01005954 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005955 outpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005956 end = s + size;
5957 while (s < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005958 unsigned char c;
5959 Py_UCS4 x;
5960 int i;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00005961 int count;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005962
Benjamin Peterson29060642009-01-31 22:14:21 +00005963 /* Non-escape characters are interpreted as Unicode ordinals */
5964 if (*s != '\\') {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005965 if (unicode_putchar(&v, &outpos, (unsigned char)*s++) < 0)
5966 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005967 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00005968 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005969 startinpos = s-starts;
5970
5971 /* \u-escapes are only interpreted iff the number of leading
5972 backslashes if odd */
5973 bs = s;
5974 for (;s < end;) {
5975 if (*s != '\\')
5976 break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005977 if (unicode_putchar(&v, &outpos, (unsigned char)*s++) < 0)
5978 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005979 }
5980 if (((s - bs) & 1) == 0 ||
5981 s >= end ||
5982 (*s != 'u' && *s != 'U')) {
5983 continue;
5984 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005985 outpos--;
Benjamin Peterson29060642009-01-31 22:14:21 +00005986 count = *s=='u' ? 4 : 8;
5987 s++;
5988
5989 /* \uXXXX with 4 hex digits, \Uxxxxxxxx with 8 */
Benjamin Peterson29060642009-01-31 22:14:21 +00005990 for (x = 0, i = 0; i < count; ++i, ++s) {
5991 c = (unsigned char)*s;
David Malcolm96960882010-11-05 17:23:41 +00005992 if (!Py_ISXDIGIT(c)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005993 endinpos = s-starts;
5994 if (unicode_decode_call_errorhandler(
5995 errors, &errorHandler,
5996 "rawunicodeescape", "truncated \\uXXXX",
5997 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005998 &v, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00005999 goto onError;
6000 goto nextByte;
6001 }
6002 x = (x<<4) & ~0xF;
6003 if (c >= '0' && c <= '9')
6004 x += c - '0';
6005 else if (c >= 'a' && c <= 'f')
6006 x += 10 + c - 'a';
6007 else
6008 x += 10 + c - 'A';
6009 }
Victor Stinner8faf8212011-12-08 22:14:11 +01006010 if (x <= MAX_UNICODE) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006011 if (unicode_putchar(&v, &outpos, x) < 0)
6012 goto onError;
Christian Heimesfe337bf2008-03-23 21:54:12 +00006013 } else {
6014 endinpos = s-starts;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006015 if (unicode_decode_call_errorhandler(
6016 errors, &errorHandler,
6017 "rawunicodeescape", "\\Uxxxxxxxx out of range",
Benjamin Peterson29060642009-01-31 22:14:21 +00006018 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006019 &v, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00006020 goto onError;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006021 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006022 nextByte:
6023 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006024 }
Victor Stinner16e6a802011-12-12 13:24:15 +01006025 if (unicode_resize(&v, outpos) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006026 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006027 Py_XDECREF(errorHandler);
6028 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006029 return unicode_result(v);
Tim Petersced69f82003-09-16 20:30:58 +00006030
Benjamin Peterson29060642009-01-31 22:14:21 +00006031 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00006032 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006033 Py_XDECREF(errorHandler);
6034 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006035 return NULL;
6036}
6037
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006038
Alexander Belopolsky40018472011-02-26 01:02:56 +00006039PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006040PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006041{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006042 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006043 char *p;
6044 char *q;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006045 Py_ssize_t expandsize, pos;
6046 int kind;
6047 void *data;
6048 Py_ssize_t len;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006049
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006050 if (!PyUnicode_Check(unicode)) {
6051 PyErr_BadArgument();
6052 return NULL;
6053 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05006054 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006055 return NULL;
6056 kind = PyUnicode_KIND(unicode);
6057 data = PyUnicode_DATA(unicode);
6058 len = PyUnicode_GET_LENGTH(unicode);
Benjamin Peterson1518e872011-11-23 10:44:52 -06006059 /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6
6060 bytes, and 1 byte characters 4. */
6061 expandsize = kind * 2 + 2;
Victor Stinner0e368262011-11-10 20:12:49 +01006062
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006063 if (len > PY_SSIZE_T_MAX / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00006064 return PyErr_NoMemory();
Benjamin Peterson14339b62009-01-31 16:36:08 +00006065
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006066 repr = PyBytes_FromStringAndSize(NULL, expandsize * len);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006067 if (repr == NULL)
6068 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006069 if (len == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006070 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006071
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006072 p = q = PyBytes_AS_STRING(repr);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006073 for (pos = 0; pos < len; pos++) {
6074 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Benjamin Peterson29060642009-01-31 22:14:21 +00006075 /* Map 32-bit characters to '\Uxxxxxxxx' */
6076 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01006077 assert(ch <= MAX_UNICODE);
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006078 *p++ = '\\';
6079 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006080 *p++ = Py_hexdigits[(ch >> 28) & 0xf];
6081 *p++ = Py_hexdigits[(ch >> 24) & 0xf];
6082 *p++ = Py_hexdigits[(ch >> 20) & 0xf];
6083 *p++ = Py_hexdigits[(ch >> 16) & 0xf];
6084 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6085 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6086 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6087 *p++ = Py_hexdigits[ch & 15];
Tim Petersced69f82003-09-16 20:30:58 +00006088 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006089 /* Map 16-bit characters to '\uxxxx' */
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006090 else if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006091 *p++ = '\\';
6092 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006093 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6094 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6095 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6096 *p++ = Py_hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006097 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006098 /* Copy everything else as-is */
6099 else
Guido van Rossumd57fd912000-03-10 22:53:23 +00006100 *p++ = (char) ch;
6101 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00006102
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006103 assert(p > q);
6104 if (_PyBytes_Resize(&repr, p - q) < 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006105 return NULL;
6106 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006107}
6108
Alexander Belopolsky40018472011-02-26 01:02:56 +00006109PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006110PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
6111 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006112{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006113 PyObject *result;
6114 PyObject *tmp = PyUnicode_FromUnicode(s, size);
6115 if (tmp == NULL)
Walter Dörwald711005d2007-05-12 12:03:26 +00006116 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006117 result = PyUnicode_AsRawUnicodeEscapeString(tmp);
6118 Py_DECREF(tmp);
6119 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006120}
6121
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006122/* --- Unicode Internal Codec ------------------------------------------- */
6123
Alexander Belopolsky40018472011-02-26 01:02:56 +00006124PyObject *
6125_PyUnicode_DecodeUnicodeInternal(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006126 Py_ssize_t size,
6127 const char *errors)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006128{
6129 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006130 Py_ssize_t startinpos;
6131 Py_ssize_t endinpos;
6132 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01006133 PyObject *v;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006134 const char *end;
6135 const char *reason;
6136 PyObject *errorHandler = NULL;
6137 PyObject *exc = NULL;
6138
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006139 if (PyErr_WarnEx(PyExc_DeprecationWarning,
Ezio Melotti11060a42011-11-16 09:39:10 +02006140 "unicode_internal codec has been deprecated",
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006141 1))
6142 return NULL;
6143
Thomas Wouters89f507f2006-12-13 04:49:30 +00006144 /* XXX overflow detection missing */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006145 v = PyUnicode_New((size+Py_UNICODE_SIZE-1)/ Py_UNICODE_SIZE, 127);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006146 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006147 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006148 if (PyUnicode_GET_LENGTH(v) == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01006149 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006150 outpos = 0;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006151 end = s + size;
6152
6153 while (s < end) {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006154 Py_UNICODE uch;
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006155 Py_UCS4 ch;
6156 /* We copy the raw representation one byte at a time because the
6157 pointer may be unaligned (see test_codeccallbacks). */
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006158 ((char *) &uch)[0] = s[0];
6159 ((char *) &uch)[1] = s[1];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006160#ifdef Py_UNICODE_WIDE
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006161 ((char *) &uch)[2] = s[2];
6162 ((char *) &uch)[3] = s[3];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006163#endif
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006164 ch = uch;
6165
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006166 /* We have to sanity check the raw data, otherwise doom looms for
6167 some malformed UCS-4 data. */
6168 if (
Benjamin Peterson29060642009-01-31 22:14:21 +00006169#ifdef Py_UNICODE_WIDE
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006170 ch > 0x10ffff ||
Benjamin Peterson29060642009-01-31 22:14:21 +00006171#endif
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006172 end-s < Py_UNICODE_SIZE
6173 )
Benjamin Peterson29060642009-01-31 22:14:21 +00006174 {
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006175 startinpos = s - starts;
6176 if (end-s < Py_UNICODE_SIZE) {
6177 endinpos = end-starts;
6178 reason = "truncated input";
6179 }
6180 else {
6181 endinpos = s - starts + Py_UNICODE_SIZE;
6182 reason = "illegal code point (> 0x10FFFF)";
6183 }
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006184 if (unicode_decode_call_errorhandler(
6185 errors, &errorHandler,
6186 "unicode_internal", reason,
Walter Dörwalde78178e2007-07-30 13:31:40 +00006187 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006188 &v, &outpos))
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006189 goto onError;
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006190 continue;
6191 }
6192
6193 s += Py_UNICODE_SIZE;
6194#ifndef Py_UNICODE_WIDE
Victor Stinner551ac952011-11-29 22:58:13 +01006195 if (Py_UNICODE_IS_HIGH_SURROGATE(ch) && s < end)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006196 {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006197 Py_UNICODE uch2;
6198 ((char *) &uch2)[0] = s[0];
6199 ((char *) &uch2)[1] = s[1];
Victor Stinner551ac952011-11-29 22:58:13 +01006200 if (Py_UNICODE_IS_LOW_SURROGATE(uch2))
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006201 {
Victor Stinner551ac952011-11-29 22:58:13 +01006202 ch = Py_UNICODE_JOIN_SURROGATES(uch, uch2);
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006203 s += Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006204 }
6205 }
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006206#endif
6207
6208 if (unicode_putchar(&v, &outpos, ch) < 0)
6209 goto onError;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006210 }
6211
Victor Stinner16e6a802011-12-12 13:24:15 +01006212 if (unicode_resize(&v, outpos) < 0)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006213 goto onError;
6214 Py_XDECREF(errorHandler);
6215 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006216 return unicode_result(v);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006217
Benjamin Peterson29060642009-01-31 22:14:21 +00006218 onError:
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006219 Py_XDECREF(v);
6220 Py_XDECREF(errorHandler);
6221 Py_XDECREF(exc);
6222 return NULL;
6223}
6224
Guido van Rossumd57fd912000-03-10 22:53:23 +00006225/* --- Latin-1 Codec ------------------------------------------------------ */
6226
Alexander Belopolsky40018472011-02-26 01:02:56 +00006227PyObject *
6228PyUnicode_DecodeLatin1(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006229 Py_ssize_t size,
6230 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006231{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006232 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Victor Stinnere57b1c02011-09-28 22:20:48 +02006233 return _PyUnicode_FromUCS1((unsigned char*)s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006234}
6235
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006236/* create or adjust a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006237static void
6238make_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006239 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006240 PyObject *unicode,
6241 Py_ssize_t startpos, Py_ssize_t endpos,
6242 const char *reason)
6243{
6244 if (*exceptionObject == NULL) {
6245 *exceptionObject = PyObject_CallFunction(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006246 PyExc_UnicodeEncodeError, "sOnns",
Martin v. Löwis9e816682011-11-02 12:45:42 +01006247 encoding, unicode, startpos, endpos, reason);
6248 }
6249 else {
6250 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
6251 goto onError;
6252 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
6253 goto onError;
6254 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
6255 goto onError;
6256 return;
6257 onError:
6258 Py_DECREF(*exceptionObject);
6259 *exceptionObject = NULL;
6260 }
6261}
6262
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006263/* raises a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006264static void
6265raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006266 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006267 PyObject *unicode,
6268 Py_ssize_t startpos, Py_ssize_t endpos,
6269 const char *reason)
6270{
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006271 make_encode_exception(exceptionObject,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006272 encoding, unicode, startpos, endpos, reason);
6273 if (*exceptionObject != NULL)
6274 PyCodec_StrictErrors(*exceptionObject);
6275}
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006276
6277/* error handling callback helper:
6278 build arguments, call the callback and check the arguments,
6279 put the result into newpos and return the replacement string, which
6280 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006281static PyObject *
6282unicode_encode_call_errorhandler(const char *errors,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006283 PyObject **errorHandler,
6284 const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006285 PyObject *unicode, PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006286 Py_ssize_t startpos, Py_ssize_t endpos,
6287 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006288{
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006289 static char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006290 Py_ssize_t len;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006291 PyObject *restuple;
6292 PyObject *resunicode;
6293
6294 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006295 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006296 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006297 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006298 }
6299
Benjamin Petersonbac79492012-01-14 13:34:47 -05006300 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006301 return NULL;
6302 len = PyUnicode_GET_LENGTH(unicode);
6303
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006304 make_encode_exception(exceptionObject,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006305 encoding, unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006306 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006307 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006308
6309 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00006310 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006311 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006312 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006313 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006314 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00006315 Py_DECREF(restuple);
6316 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006317 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006318 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00006319 &resunicode, newpos)) {
6320 Py_DECREF(restuple);
6321 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006322 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006323 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
6324 PyErr_SetString(PyExc_TypeError, &argparse[3]);
6325 Py_DECREF(restuple);
6326 return NULL;
6327 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006328 if (*newpos<0)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006329 *newpos = len + *newpos;
6330 if (*newpos<0 || *newpos>len) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006331 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
6332 Py_DECREF(restuple);
6333 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00006334 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006335 Py_INCREF(resunicode);
6336 Py_DECREF(restuple);
6337 return resunicode;
6338}
6339
Alexander Belopolsky40018472011-02-26 01:02:56 +00006340static PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006341unicode_encode_ucs1(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006342 const char *errors,
Victor Stinnerfcd96532011-11-04 00:28:50 +01006343 unsigned int limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006344{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006345 /* input state */
6346 Py_ssize_t pos=0, size;
6347 int kind;
6348 void *data;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006349 /* output object */
6350 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006351 /* pointer into the output */
6352 char *str;
6353 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00006354 Py_ssize_t ressize;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006355 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
6356 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006357 PyObject *errorHandler = NULL;
6358 PyObject *exc = NULL;
6359 /* the following variable is used for caching string comparisons
6360 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
6361 int known_errorHandler = -1;
6362
Benjamin Petersonbac79492012-01-14 13:34:47 -05006363 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006364 return NULL;
6365 size = PyUnicode_GET_LENGTH(unicode);
6366 kind = PyUnicode_KIND(unicode);
6367 data = PyUnicode_DATA(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006368 /* allocate enough for a simple encoding without
6369 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00006370 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00006371 return PyBytes_FromStringAndSize(NULL, 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006372 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006373 if (res == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00006374 return NULL;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006375 str = PyBytes_AS_STRING(res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006376 ressize = size;
6377
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006378 while (pos < size) {
6379 Py_UCS4 c = PyUnicode_READ(kind, data, pos);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006380
Benjamin Peterson29060642009-01-31 22:14:21 +00006381 /* can we encode this? */
6382 if (c<limit) {
6383 /* no overflow check, because we know that the space is enough */
6384 *str++ = (char)c;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006385 ++pos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006386 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006387 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006388 Py_ssize_t requiredsize;
6389 PyObject *repunicode;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006390 Py_ssize_t repsize, newpos, respos, i;
Benjamin Peterson29060642009-01-31 22:14:21 +00006391 /* startpos for collecting unencodable chars */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006392 Py_ssize_t collstart = pos;
6393 Py_ssize_t collend = pos;
Benjamin Peterson29060642009-01-31 22:14:21 +00006394 /* find all unecodable characters */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006395 while ((collend < size) && (PyUnicode_READ(kind, data, collend)>=limit))
Benjamin Peterson29060642009-01-31 22:14:21 +00006396 ++collend;
6397 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
6398 if (known_errorHandler==-1) {
6399 if ((errors==NULL) || (!strcmp(errors, "strict")))
6400 known_errorHandler = 1;
6401 else if (!strcmp(errors, "replace"))
6402 known_errorHandler = 2;
6403 else if (!strcmp(errors, "ignore"))
6404 known_errorHandler = 3;
6405 else if (!strcmp(errors, "xmlcharrefreplace"))
6406 known_errorHandler = 4;
6407 else
6408 known_errorHandler = 0;
6409 }
6410 switch (known_errorHandler) {
6411 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006412 raise_encode_exception(&exc, encoding, unicode, collstart, collend, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006413 goto onError;
6414 case 2: /* replace */
6415 while (collstart++<collend)
6416 *str++ = '?'; /* fall through */
6417 case 3: /* ignore */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006418 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006419 break;
6420 case 4: /* xmlcharrefreplace */
6421 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006422 /* determine replacement size */
6423 for (i = collstart, repsize = 0; i < collend; ++i) {
6424 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
6425 if (ch < 10)
Benjamin Peterson29060642009-01-31 22:14:21 +00006426 repsize += 2+1+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006427 else if (ch < 100)
Benjamin Peterson29060642009-01-31 22:14:21 +00006428 repsize += 2+2+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006429 else if (ch < 1000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006430 repsize += 2+3+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006431 else if (ch < 10000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006432 repsize += 2+4+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006433 else if (ch < 100000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006434 repsize += 2+5+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006435 else if (ch < 1000000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006436 repsize += 2+6+1;
Victor Stinner0d3721d2011-11-22 03:27:53 +01006437 else {
Victor Stinner8faf8212011-12-08 22:14:11 +01006438 assert(ch <= MAX_UNICODE);
Benjamin Peterson29060642009-01-31 22:14:21 +00006439 repsize += 2+7+1;
Victor Stinner0d3721d2011-11-22 03:27:53 +01006440 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006441 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006442 requiredsize = respos+repsize+(size-collend);
Benjamin Peterson29060642009-01-31 22:14:21 +00006443 if (requiredsize > ressize) {
6444 if (requiredsize<2*ressize)
6445 requiredsize = 2*ressize;
6446 if (_PyBytes_Resize(&res, requiredsize))
6447 goto onError;
6448 str = PyBytes_AS_STRING(res) + respos;
6449 ressize = requiredsize;
6450 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006451 /* generate replacement */
6452 for (i = collstart; i < collend; ++i) {
6453 str += sprintf(str, "&#%d;", PyUnicode_READ(kind, data, i));
Benjamin Peterson29060642009-01-31 22:14:21 +00006454 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006455 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006456 break;
6457 default:
6458 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006459 encoding, reason, unicode, &exc,
6460 collstart, collend, &newpos);
6461 if (repunicode == NULL || (PyUnicode_Check(repunicode) &&
Benjamin Petersonbac79492012-01-14 13:34:47 -05006462 PyUnicode_READY(repunicode) == -1))
Benjamin Peterson29060642009-01-31 22:14:21 +00006463 goto onError;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006464 if (PyBytes_Check(repunicode)) {
6465 /* Directly copy bytes result to output. */
6466 repsize = PyBytes_Size(repunicode);
6467 if (repsize > 1) {
6468 /* Make room for all additional bytes. */
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006469 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006470 if (_PyBytes_Resize(&res, ressize+repsize-1)) {
6471 Py_DECREF(repunicode);
6472 goto onError;
6473 }
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006474 str = PyBytes_AS_STRING(res) + respos;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006475 ressize += repsize-1;
6476 }
6477 memcpy(str, PyBytes_AsString(repunicode), repsize);
6478 str += repsize;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006479 pos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006480 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006481 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006482 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006483 /* need more space? (at least enough for what we
6484 have+the replacement+the rest of the string, so
6485 we won't have to check space for encodable characters) */
6486 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006487 repsize = PyUnicode_GET_LENGTH(repunicode);
6488 requiredsize = respos+repsize+(size-collend);
Benjamin Peterson29060642009-01-31 22:14:21 +00006489 if (requiredsize > ressize) {
6490 if (requiredsize<2*ressize)
6491 requiredsize = 2*ressize;
6492 if (_PyBytes_Resize(&res, requiredsize)) {
6493 Py_DECREF(repunicode);
6494 goto onError;
6495 }
6496 str = PyBytes_AS_STRING(res) + respos;
6497 ressize = requiredsize;
6498 }
6499 /* check if there is anything unencodable in the replacement
6500 and copy it to the output */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006501 for (i = 0; repsize-->0; ++i, ++str) {
6502 c = PyUnicode_READ_CHAR(repunicode, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00006503 if (c >= limit) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006504 raise_encode_exception(&exc, encoding, unicode,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006505 pos, pos+1, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006506 Py_DECREF(repunicode);
6507 goto onError;
6508 }
6509 *str = (char)c;
6510 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006511 pos = newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006512 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006513 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00006514 }
6515 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006516 /* Resize if we allocated to much */
6517 size = str - PyBytes_AS_STRING(res);
6518 if (size < ressize) { /* If this falls res will be NULL */
Alexandre Vassalottibad1b922008-12-27 09:49:09 +00006519 assert(size >= 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006520 if (_PyBytes_Resize(&res, size) < 0)
6521 goto onError;
6522 }
6523
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006524 Py_XDECREF(errorHandler);
6525 Py_XDECREF(exc);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006526 return res;
6527
6528 onError:
6529 Py_XDECREF(res);
6530 Py_XDECREF(errorHandler);
6531 Py_XDECREF(exc);
6532 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006533}
6534
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006535/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006536PyObject *
6537PyUnicode_EncodeLatin1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006538 Py_ssize_t size,
6539 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006540{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006541 PyObject *result;
6542 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6543 if (unicode == NULL)
6544 return NULL;
6545 result = unicode_encode_ucs1(unicode, errors, 256);
6546 Py_DECREF(unicode);
6547 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006548}
6549
Alexander Belopolsky40018472011-02-26 01:02:56 +00006550PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006551_PyUnicode_AsLatin1String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006552{
6553 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006554 PyErr_BadArgument();
6555 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006556 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006557 if (PyUnicode_READY(unicode) == -1)
6558 return NULL;
6559 /* Fast path: if it is a one-byte string, construct
6560 bytes object directly. */
6561 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND)
6562 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6563 PyUnicode_GET_LENGTH(unicode));
6564 /* Non-Latin-1 characters present. Defer to above function to
6565 raise the exception. */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006566 return unicode_encode_ucs1(unicode, errors, 256);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006567}
6568
6569PyObject*
6570PyUnicode_AsLatin1String(PyObject *unicode)
6571{
6572 return _PyUnicode_AsLatin1String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006573}
6574
6575/* --- 7-bit ASCII Codec -------------------------------------------------- */
6576
Alexander Belopolsky40018472011-02-26 01:02:56 +00006577PyObject *
6578PyUnicode_DecodeASCII(const char *s,
6579 Py_ssize_t size,
6580 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006581{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006582 const char *starts = s;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006583 PyObject *unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006584 int kind;
6585 void *data;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006586 Py_ssize_t startinpos;
6587 Py_ssize_t endinpos;
6588 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006589 const char *e;
6590 PyObject *errorHandler = NULL;
6591 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006592
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006593 if (size == 0) {
6594 Py_INCREF(unicode_empty);
6595 return unicode_empty;
6596 }
6597
Guido van Rossumd57fd912000-03-10 22:53:23 +00006598 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Victor Stinner702c7342011-10-05 13:50:52 +02006599 if (size == 1 && (unsigned char)s[0] < 128)
6600 return get_latin1_char((unsigned char)s[0]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006601
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006602 unicode = PyUnicode_New(size, 127);
6603 if (unicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006604 goto onError;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006605
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006606 e = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006607 data = PyUnicode_1BYTE_DATA(unicode);
6608 outpos = ascii_decode(s, e, (Py_UCS1 *)data);
6609 if (outpos == size)
6610 return unicode;
6611
6612 s += outpos;
6613 kind = PyUnicode_1BYTE_KIND;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006614 while (s < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006615 register unsigned char c = (unsigned char)*s;
6616 if (c < 128) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006617 PyUnicode_WRITE(kind, data, outpos++, c);
Benjamin Peterson29060642009-01-31 22:14:21 +00006618 ++s;
6619 }
6620 else {
6621 startinpos = s-starts;
6622 endinpos = startinpos + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00006623 if (unicode_decode_call_errorhandler(
6624 errors, &errorHandler,
6625 "ascii", "ordinal not in range(128)",
6626 &starts, &e, &startinpos, &endinpos, &exc, &s,
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006627 &unicode, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00006628 goto onError;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006629 kind = PyUnicode_KIND(unicode);
6630 data = PyUnicode_DATA(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00006631 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006632 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006633 if (unicode_resize(&unicode, outpos) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006634 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006635 Py_XDECREF(errorHandler);
6636 Py_XDECREF(exc);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006637 assert(_PyUnicode_CheckConsistency(unicode, 1));
6638 return unicode;
Tim Petersced69f82003-09-16 20:30:58 +00006639
Benjamin Peterson29060642009-01-31 22:14:21 +00006640 onError:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006641 Py_XDECREF(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006642 Py_XDECREF(errorHandler);
6643 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006644 return NULL;
6645}
6646
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006647/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006648PyObject *
6649PyUnicode_EncodeASCII(const Py_UNICODE *p,
6650 Py_ssize_t size,
6651 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006652{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006653 PyObject *result;
6654 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6655 if (unicode == NULL)
6656 return NULL;
6657 result = unicode_encode_ucs1(unicode, errors, 128);
6658 Py_DECREF(unicode);
6659 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006660}
6661
Alexander Belopolsky40018472011-02-26 01:02:56 +00006662PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006663_PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006664{
6665 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006666 PyErr_BadArgument();
6667 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006668 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006669 if (PyUnicode_READY(unicode) == -1)
6670 return NULL;
6671 /* Fast path: if it is an ASCII-only string, construct bytes object
6672 directly. Else defer to above function to raise the exception. */
6673 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
6674 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6675 PyUnicode_GET_LENGTH(unicode));
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006676 return unicode_encode_ucs1(unicode, errors, 128);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006677}
6678
6679PyObject *
6680PyUnicode_AsASCIIString(PyObject *unicode)
6681{
6682 return _PyUnicode_AsASCIIString(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006683}
6684
Victor Stinner99b95382011-07-04 14:23:54 +02006685#ifdef HAVE_MBCS
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006686
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006687/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006688
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00006689#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006690#define NEED_RETRY
6691#endif
6692
Victor Stinner3a50e702011-10-18 21:21:00 +02006693#ifndef WC_ERR_INVALID_CHARS
6694# define WC_ERR_INVALID_CHARS 0x0080
6695#endif
6696
6697static char*
6698code_page_name(UINT code_page, PyObject **obj)
6699{
6700 *obj = NULL;
6701 if (code_page == CP_ACP)
6702 return "mbcs";
6703 if (code_page == CP_UTF7)
6704 return "CP_UTF7";
6705 if (code_page == CP_UTF8)
6706 return "CP_UTF8";
6707
6708 *obj = PyBytes_FromFormat("cp%u", code_page);
6709 if (*obj == NULL)
6710 return NULL;
6711 return PyBytes_AS_STRING(*obj);
6712}
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006713
Alexander Belopolsky40018472011-02-26 01:02:56 +00006714static int
Victor Stinner3a50e702011-10-18 21:21:00 +02006715is_dbcs_lead_byte(UINT code_page, const char *s, int offset)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006716{
6717 const char *curr = s + offset;
Victor Stinner3a50e702011-10-18 21:21:00 +02006718 const char *prev;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006719
Victor Stinner3a50e702011-10-18 21:21:00 +02006720 if (!IsDBCSLeadByteEx(code_page, *curr))
6721 return 0;
6722
6723 prev = CharPrevExA(code_page, s, curr, 0);
6724 if (prev == curr)
6725 return 1;
6726 /* FIXME: This code is limited to "true" double-byte encodings,
6727 as it assumes an incomplete character consists of a single
6728 byte. */
6729 if (curr - prev == 2)
6730 return 1;
6731 if (!IsDBCSLeadByteEx(code_page, *prev))
6732 return 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006733 return 0;
6734}
6735
Victor Stinner3a50e702011-10-18 21:21:00 +02006736static DWORD
6737decode_code_page_flags(UINT code_page)
6738{
6739 if (code_page == CP_UTF7) {
6740 /* The CP_UTF7 decoder only supports flags=0 */
6741 return 0;
6742 }
6743 else
6744 return MB_ERR_INVALID_CHARS;
6745}
6746
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006747/*
Victor Stinner3a50e702011-10-18 21:21:00 +02006748 * Decode a byte string from a Windows code page into unicode object in strict
6749 * mode.
6750 *
6751 * Returns consumed size if succeed, returns -2 on decode error, or raise a
6752 * WindowsError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006753 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006754static int
Victor Stinner3a50e702011-10-18 21:21:00 +02006755decode_code_page_strict(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01006756 PyObject **v,
Victor Stinner3a50e702011-10-18 21:21:00 +02006757 const char *in,
6758 int insize)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006759{
Victor Stinner3a50e702011-10-18 21:21:00 +02006760 const DWORD flags = decode_code_page_flags(code_page);
Victor Stinner24729f32011-11-10 20:31:37 +01006761 wchar_t *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02006762 DWORD outsize;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006763
6764 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02006765 assert(insize > 0);
6766 outsize = MultiByteToWideChar(code_page, flags, in, insize, NULL, 0);
6767 if (outsize <= 0)
6768 goto error;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006769
6770 if (*v == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006771 /* Create unicode object */
Victor Stinnerab595942011-12-17 04:59:06 +01006772 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01006773 *v = (PyObject*)_PyUnicode_New(outsize);
Benjamin Peterson29060642009-01-31 22:14:21 +00006774 if (*v == NULL)
6775 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02006776 out = PyUnicode_AS_UNICODE(*v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006777 }
6778 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006779 /* Extend unicode object */
Victor Stinner3a50e702011-10-18 21:21:00 +02006780 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
Victor Stinner16e6a802011-12-12 13:24:15 +01006781 if (unicode_resize(v, n + outsize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006782 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02006783 out = PyUnicode_AS_UNICODE(*v) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006784 }
6785
6786 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02006787 outsize = MultiByteToWideChar(code_page, flags, in, insize, out, outsize);
6788 if (outsize <= 0)
6789 goto error;
6790 return insize;
Victor Stinner554f3f02010-06-16 23:33:54 +00006791
Victor Stinner3a50e702011-10-18 21:21:00 +02006792error:
6793 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
6794 return -2;
6795 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00006796 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006797}
6798
Victor Stinner3a50e702011-10-18 21:21:00 +02006799/*
6800 * Decode a byte string from a code page into unicode object with an error
6801 * handler.
6802 *
6803 * Returns consumed size if succeed, or raise a WindowsError or
6804 * UnicodeDecodeError exception and returns -1 on error.
6805 */
6806static int
6807decode_code_page_errors(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01006808 PyObject **v,
6809 const char *in, const int size,
Victor Stinner3a50e702011-10-18 21:21:00 +02006810 const char *errors)
6811{
6812 const char *startin = in;
6813 const char *endin = in + size;
6814 const DWORD flags = decode_code_page_flags(code_page);
6815 /* Ideally, we should get reason from FormatMessage. This is the Windows
6816 2000 English version of the message. */
6817 const char *reason = "No mapping for the Unicode character exists "
6818 "in the target code page.";
6819 /* each step cannot decode more than 1 character, but a character can be
6820 represented as a surrogate pair */
6821 wchar_t buffer[2], *startout, *out;
6822 int insize, outsize;
6823 PyObject *errorHandler = NULL;
6824 PyObject *exc = NULL;
6825 PyObject *encoding_obj = NULL;
6826 char *encoding;
6827 DWORD err;
6828 int ret = -1;
6829
6830 assert(size > 0);
6831
6832 encoding = code_page_name(code_page, &encoding_obj);
6833 if (encoding == NULL)
6834 return -1;
6835
6836 if (errors == NULL || strcmp(errors, "strict") == 0) {
6837 /* The last error was ERROR_NO_UNICODE_TRANSLATION, then we raise a
6838 UnicodeDecodeError. */
6839 make_decode_exception(&exc, encoding, in, size, 0, 0, reason);
6840 if (exc != NULL) {
6841 PyCodec_StrictErrors(exc);
6842 Py_CLEAR(exc);
6843 }
6844 goto error;
6845 }
6846
6847 if (*v == NULL) {
6848 /* Create unicode object */
6849 if (size > PY_SSIZE_T_MAX / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
6850 PyErr_NoMemory();
6851 goto error;
6852 }
Victor Stinnerab595942011-12-17 04:59:06 +01006853 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01006854 *v = (PyObject*)_PyUnicode_New(size * Py_ARRAY_LENGTH(buffer));
Victor Stinner3a50e702011-10-18 21:21:00 +02006855 if (*v == NULL)
6856 goto error;
6857 startout = PyUnicode_AS_UNICODE(*v);
6858 }
6859 else {
6860 /* Extend unicode object */
6861 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
6862 if (size > (PY_SSIZE_T_MAX - n) / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
6863 PyErr_NoMemory();
6864 goto error;
6865 }
Victor Stinner16e6a802011-12-12 13:24:15 +01006866 if (unicode_resize(v, n + size * Py_ARRAY_LENGTH(buffer)) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02006867 goto error;
6868 startout = PyUnicode_AS_UNICODE(*v) + n;
6869 }
6870
6871 /* Decode the byte string character per character */
6872 out = startout;
6873 while (in < endin)
6874 {
6875 /* Decode a character */
6876 insize = 1;
6877 do
6878 {
6879 outsize = MultiByteToWideChar(code_page, flags,
6880 in, insize,
6881 buffer, Py_ARRAY_LENGTH(buffer));
6882 if (outsize > 0)
6883 break;
6884 err = GetLastError();
6885 if (err != ERROR_NO_UNICODE_TRANSLATION
6886 && err != ERROR_INSUFFICIENT_BUFFER)
6887 {
6888 PyErr_SetFromWindowsErr(0);
6889 goto error;
6890 }
6891 insize++;
6892 }
6893 /* 4=maximum length of a UTF-8 sequence */
6894 while (insize <= 4 && (in + insize) <= endin);
6895
6896 if (outsize <= 0) {
6897 Py_ssize_t startinpos, endinpos, outpos;
6898
6899 startinpos = in - startin;
6900 endinpos = startinpos + 1;
6901 outpos = out - PyUnicode_AS_UNICODE(*v);
6902 if (unicode_decode_call_errorhandler(
6903 errors, &errorHandler,
6904 encoding, reason,
6905 &startin, &endin, &startinpos, &endinpos, &exc, &in,
Victor Stinner596a6c42011-11-09 00:02:18 +01006906 v, &outpos))
Victor Stinner3a50e702011-10-18 21:21:00 +02006907 {
6908 goto error;
6909 }
Victor Stinner596a6c42011-11-09 00:02:18 +01006910 out = PyUnicode_AS_UNICODE(*v) + outpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02006911 }
6912 else {
6913 in += insize;
6914 memcpy(out, buffer, outsize * sizeof(wchar_t));
6915 out += outsize;
6916 }
6917 }
6918
6919 /* write a NUL character at the end */
6920 *out = 0;
6921
6922 /* Extend unicode object */
6923 outsize = out - startout;
6924 assert(outsize <= PyUnicode_WSTR_LENGTH(*v));
Victor Stinner16e6a802011-12-12 13:24:15 +01006925 if (unicode_resize(v, outsize) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02006926 goto error;
Victor Stinner76a31a62011-11-04 00:05:13 +01006927 ret = size;
Victor Stinner3a50e702011-10-18 21:21:00 +02006928
6929error:
6930 Py_XDECREF(encoding_obj);
6931 Py_XDECREF(errorHandler);
6932 Py_XDECREF(exc);
6933 return ret;
6934}
6935
Victor Stinner3a50e702011-10-18 21:21:00 +02006936static PyObject *
6937decode_code_page_stateful(int code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01006938 const char *s, Py_ssize_t size,
6939 const char *errors, Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006940{
Victor Stinner76a31a62011-11-04 00:05:13 +01006941 PyObject *v = NULL;
6942 int chunk_size, final, converted, done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006943
Victor Stinner3a50e702011-10-18 21:21:00 +02006944 if (code_page < 0) {
6945 PyErr_SetString(PyExc_ValueError, "invalid code page number");
6946 return NULL;
6947 }
6948
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006949 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00006950 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006951
Victor Stinner76a31a62011-11-04 00:05:13 +01006952 do
6953 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006954#ifdef NEED_RETRY
Victor Stinner76a31a62011-11-04 00:05:13 +01006955 if (size > INT_MAX) {
6956 chunk_size = INT_MAX;
6957 final = 0;
6958 done = 0;
6959 }
6960 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006961#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01006962 {
6963 chunk_size = (int)size;
6964 final = (consumed == NULL);
6965 done = 1;
6966 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006967
Victor Stinner76a31a62011-11-04 00:05:13 +01006968 /* Skip trailing lead-byte unless 'final' is set */
6969 if (!final && is_dbcs_lead_byte(code_page, s, chunk_size - 1))
6970 --chunk_size;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006971
Victor Stinner76a31a62011-11-04 00:05:13 +01006972 if (chunk_size == 0 && done) {
6973 if (v != NULL)
6974 break;
6975 Py_INCREF(unicode_empty);
6976 return unicode_empty;
6977 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006978
Victor Stinner76a31a62011-11-04 00:05:13 +01006979
6980 converted = decode_code_page_strict(code_page, &v,
6981 s, chunk_size);
6982 if (converted == -2)
6983 converted = decode_code_page_errors(code_page, &v,
6984 s, chunk_size,
6985 errors);
6986 assert(converted != 0);
6987
6988 if (converted < 0) {
6989 Py_XDECREF(v);
6990 return NULL;
6991 }
6992
6993 if (consumed)
6994 *consumed += converted;
6995
6996 s += converted;
6997 size -= converted;
6998 } while (!done);
Victor Stinner3a50e702011-10-18 21:21:00 +02006999
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01007000 return unicode_result(v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007001}
7002
Alexander Belopolsky40018472011-02-26 01:02:56 +00007003PyObject *
Victor Stinner3a50e702011-10-18 21:21:00 +02007004PyUnicode_DecodeCodePageStateful(int code_page,
7005 const char *s,
7006 Py_ssize_t size,
7007 const char *errors,
7008 Py_ssize_t *consumed)
7009{
7010 return decode_code_page_stateful(code_page, s, size, errors, consumed);
7011}
7012
7013PyObject *
7014PyUnicode_DecodeMBCSStateful(const char *s,
7015 Py_ssize_t size,
7016 const char *errors,
7017 Py_ssize_t *consumed)
7018{
7019 return decode_code_page_stateful(CP_ACP, s, size, errors, consumed);
7020}
7021
7022PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00007023PyUnicode_DecodeMBCS(const char *s,
7024 Py_ssize_t size,
7025 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007026{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007027 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
7028}
7029
Victor Stinner3a50e702011-10-18 21:21:00 +02007030static DWORD
7031encode_code_page_flags(UINT code_page, const char *errors)
7032{
7033 if (code_page == CP_UTF8) {
7034 if (winver.dwMajorVersion >= 6)
7035 /* CP_UTF8 supports WC_ERR_INVALID_CHARS on Windows Vista
7036 and later */
7037 return WC_ERR_INVALID_CHARS;
7038 else
7039 /* CP_UTF8 only supports flags=0 on Windows older than Vista */
7040 return 0;
7041 }
7042 else if (code_page == CP_UTF7) {
7043 /* CP_UTF7 only supports flags=0 */
7044 return 0;
7045 }
7046 else {
7047 if (errors != NULL && strcmp(errors, "replace") == 0)
7048 return 0;
7049 else
7050 return WC_NO_BEST_FIT_CHARS;
7051 }
7052}
7053
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007054/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007055 * Encode a Unicode string to a Windows code page into a byte string in strict
7056 * mode.
7057 *
7058 * Returns consumed characters if succeed, returns -2 on encode error, or raise
7059 * a WindowsError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007060 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007061static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007062encode_code_page_strict(UINT code_page, PyObject **outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007063 PyObject *unicode, Py_ssize_t offset, int len,
Victor Stinner3a50e702011-10-18 21:21:00 +02007064 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007065{
Victor Stinner554f3f02010-06-16 23:33:54 +00007066 BOOL usedDefaultChar = FALSE;
Victor Stinner3a50e702011-10-18 21:21:00 +02007067 BOOL *pusedDefaultChar = &usedDefaultChar;
7068 int outsize;
Victor Stinner554f3f02010-06-16 23:33:54 +00007069 PyObject *exc = NULL;
Victor Stinner24729f32011-11-10 20:31:37 +01007070 wchar_t *p;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007071 Py_ssize_t size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007072 const DWORD flags = encode_code_page_flags(code_page, NULL);
7073 char *out;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007074 /* Create a substring so that we can get the UTF-16 representation
7075 of just the slice under consideration. */
7076 PyObject *substring;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007077
Martin v. Löwis3d325192011-11-04 18:23:06 +01007078 assert(len > 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007079
Victor Stinner3a50e702011-10-18 21:21:00 +02007080 if (code_page != CP_UTF8 && code_page != CP_UTF7)
Victor Stinner554f3f02010-06-16 23:33:54 +00007081 pusedDefaultChar = &usedDefaultChar;
Victor Stinner3a50e702011-10-18 21:21:00 +02007082 else
Victor Stinner554f3f02010-06-16 23:33:54 +00007083 pusedDefaultChar = NULL;
Victor Stinner554f3f02010-06-16 23:33:54 +00007084
Victor Stinner2fc507f2011-11-04 20:06:39 +01007085 substring = PyUnicode_Substring(unicode, offset, offset+len);
7086 if (substring == NULL)
7087 return -1;
7088 p = PyUnicode_AsUnicodeAndSize(substring, &size);
7089 if (p == NULL) {
7090 Py_DECREF(substring);
7091 return -1;
7092 }
Martin v. Löwis3d325192011-11-04 18:23:06 +01007093
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007094 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007095 outsize = WideCharToMultiByte(code_page, flags,
7096 p, size,
7097 NULL, 0,
7098 NULL, pusedDefaultChar);
7099 if (outsize <= 0)
7100 goto error;
7101 /* If we used a default char, then we failed! */
Victor Stinner2fc507f2011-11-04 20:06:39 +01007102 if (pusedDefaultChar && *pusedDefaultChar) {
7103 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007104 return -2;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007105 }
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007106
Victor Stinner3a50e702011-10-18 21:21:00 +02007107 if (*outbytes == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007108 /* Create string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007109 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007110 if (*outbytes == NULL) {
7111 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007112 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007113 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007114 out = PyBytes_AS_STRING(*outbytes);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007115 }
7116 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007117 /* Extend string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007118 const Py_ssize_t n = PyBytes_Size(*outbytes);
7119 if (outsize > PY_SSIZE_T_MAX - n) {
7120 PyErr_NoMemory();
Victor Stinner2fc507f2011-11-04 20:06:39 +01007121 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007122 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007123 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007124 if (_PyBytes_Resize(outbytes, n + outsize) < 0) {
7125 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007126 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007127 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007128 out = PyBytes_AS_STRING(*outbytes) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007129 }
7130
7131 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007132 outsize = WideCharToMultiByte(code_page, flags,
7133 p, size,
7134 out, outsize,
7135 NULL, pusedDefaultChar);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007136 Py_CLEAR(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007137 if (outsize <= 0)
7138 goto error;
7139 if (pusedDefaultChar && *pusedDefaultChar)
7140 return -2;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007141 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00007142
Victor Stinner3a50e702011-10-18 21:21:00 +02007143error:
Victor Stinner2fc507f2011-11-04 20:06:39 +01007144 Py_XDECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007145 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7146 return -2;
7147 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007148 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007149}
7150
Victor Stinner3a50e702011-10-18 21:21:00 +02007151/*
7152 * Encode a Unicode string to a Windows code page into a byte string using a
7153 * error handler.
7154 *
7155 * Returns consumed characters if succeed, or raise a WindowsError and returns
7156 * -1 on other error.
7157 */
7158static int
7159encode_code_page_errors(UINT code_page, PyObject **outbytes,
Victor Stinner7581cef2011-11-03 22:32:33 +01007160 PyObject *unicode, Py_ssize_t unicode_offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007161 Py_ssize_t insize, const char* errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007162{
Victor Stinner3a50e702011-10-18 21:21:00 +02007163 const DWORD flags = encode_code_page_flags(code_page, errors);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007164 Py_ssize_t pos = unicode_offset;
7165 Py_ssize_t endin = unicode_offset + insize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007166 /* Ideally, we should get reason from FormatMessage. This is the Windows
7167 2000 English version of the message. */
7168 const char *reason = "invalid character";
7169 /* 4=maximum length of a UTF-8 sequence */
7170 char buffer[4];
7171 BOOL usedDefaultChar = FALSE, *pusedDefaultChar;
7172 Py_ssize_t outsize;
7173 char *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007174 PyObject *errorHandler = NULL;
7175 PyObject *exc = NULL;
7176 PyObject *encoding_obj = NULL;
7177 char *encoding;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007178 Py_ssize_t newpos, newoutsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007179 PyObject *rep;
7180 int ret = -1;
7181
7182 assert(insize > 0);
7183
7184 encoding = code_page_name(code_page, &encoding_obj);
7185 if (encoding == NULL)
7186 return -1;
7187
7188 if (errors == NULL || strcmp(errors, "strict") == 0) {
7189 /* The last error was ERROR_NO_UNICODE_TRANSLATION,
7190 then we raise a UnicodeEncodeError. */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007191 make_encode_exception(&exc, encoding, unicode, 0, 0, reason);
Victor Stinner3a50e702011-10-18 21:21:00 +02007192 if (exc != NULL) {
7193 PyCodec_StrictErrors(exc);
7194 Py_DECREF(exc);
7195 }
7196 Py_XDECREF(encoding_obj);
7197 return -1;
7198 }
7199
7200 if (code_page != CP_UTF8 && code_page != CP_UTF7)
7201 pusedDefaultChar = &usedDefaultChar;
7202 else
7203 pusedDefaultChar = NULL;
7204
7205 if (Py_ARRAY_LENGTH(buffer) > PY_SSIZE_T_MAX / insize) {
7206 PyErr_NoMemory();
7207 goto error;
7208 }
7209 outsize = insize * Py_ARRAY_LENGTH(buffer);
7210
7211 if (*outbytes == NULL) {
7212 /* Create string object */
7213 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
7214 if (*outbytes == NULL)
7215 goto error;
7216 out = PyBytes_AS_STRING(*outbytes);
7217 }
7218 else {
7219 /* Extend string object */
7220 Py_ssize_t n = PyBytes_Size(*outbytes);
7221 if (n > PY_SSIZE_T_MAX - outsize) {
7222 PyErr_NoMemory();
7223 goto error;
7224 }
7225 if (_PyBytes_Resize(outbytes, n + outsize) < 0)
7226 goto error;
7227 out = PyBytes_AS_STRING(*outbytes) + n;
7228 }
7229
7230 /* Encode the string character per character */
Martin v. Löwis3d325192011-11-04 18:23:06 +01007231 while (pos < endin)
Victor Stinner3a50e702011-10-18 21:21:00 +02007232 {
Victor Stinner2fc507f2011-11-04 20:06:39 +01007233 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, pos);
7234 wchar_t chars[2];
7235 int charsize;
7236 if (ch < 0x10000) {
7237 chars[0] = (wchar_t)ch;
7238 charsize = 1;
7239 }
7240 else {
7241 ch -= 0x10000;
7242 chars[0] = 0xd800 + (ch >> 10);
7243 chars[1] = 0xdc00 + (ch & 0x3ff);
7244 charsize = 2;
7245 }
7246
Victor Stinner3a50e702011-10-18 21:21:00 +02007247 outsize = WideCharToMultiByte(code_page, flags,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007248 chars, charsize,
Victor Stinner3a50e702011-10-18 21:21:00 +02007249 buffer, Py_ARRAY_LENGTH(buffer),
7250 NULL, pusedDefaultChar);
7251 if (outsize > 0) {
7252 if (pusedDefaultChar == NULL || !(*pusedDefaultChar))
7253 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007254 pos++;
Victor Stinner3a50e702011-10-18 21:21:00 +02007255 memcpy(out, buffer, outsize);
7256 out += outsize;
7257 continue;
7258 }
7259 }
7260 else if (GetLastError() != ERROR_NO_UNICODE_TRANSLATION) {
7261 PyErr_SetFromWindowsErr(0);
7262 goto error;
7263 }
7264
Victor Stinner3a50e702011-10-18 21:21:00 +02007265 rep = unicode_encode_call_errorhandler(
7266 errors, &errorHandler, encoding, reason,
Victor Stinner7581cef2011-11-03 22:32:33 +01007267 unicode, &exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007268 pos, pos + 1, &newpos);
Victor Stinner3a50e702011-10-18 21:21:00 +02007269 if (rep == NULL)
7270 goto error;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007271 pos = newpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007272
7273 if (PyBytes_Check(rep)) {
7274 outsize = PyBytes_GET_SIZE(rep);
7275 if (outsize != 1) {
7276 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7277 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7278 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7279 Py_DECREF(rep);
7280 goto error;
7281 }
7282 out = PyBytes_AS_STRING(*outbytes) + offset;
7283 }
7284 memcpy(out, PyBytes_AS_STRING(rep), outsize);
7285 out += outsize;
7286 }
7287 else {
7288 Py_ssize_t i;
7289 enum PyUnicode_Kind kind;
7290 void *data;
7291
Benjamin Petersonbac79492012-01-14 13:34:47 -05007292 if (PyUnicode_READY(rep) == -1) {
Victor Stinner3a50e702011-10-18 21:21:00 +02007293 Py_DECREF(rep);
7294 goto error;
7295 }
7296
7297 outsize = PyUnicode_GET_LENGTH(rep);
7298 if (outsize != 1) {
7299 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7300 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7301 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7302 Py_DECREF(rep);
7303 goto error;
7304 }
7305 out = PyBytes_AS_STRING(*outbytes) + offset;
7306 }
7307 kind = PyUnicode_KIND(rep);
7308 data = PyUnicode_DATA(rep);
7309 for (i=0; i < outsize; i++) {
7310 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7311 if (ch > 127) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007312 raise_encode_exception(&exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007313 encoding, unicode,
7314 pos, pos + 1,
Victor Stinner3a50e702011-10-18 21:21:00 +02007315 "unable to encode error handler result to ASCII");
7316 Py_DECREF(rep);
7317 goto error;
7318 }
7319 *out = (unsigned char)ch;
7320 out++;
7321 }
7322 }
7323 Py_DECREF(rep);
7324 }
7325 /* write a NUL byte */
7326 *out = 0;
7327 outsize = out - PyBytes_AS_STRING(*outbytes);
7328 assert(outsize <= PyBytes_GET_SIZE(*outbytes));
7329 if (_PyBytes_Resize(outbytes, outsize) < 0)
7330 goto error;
7331 ret = 0;
7332
7333error:
7334 Py_XDECREF(encoding_obj);
7335 Py_XDECREF(errorHandler);
7336 Py_XDECREF(exc);
7337 return ret;
7338}
7339
Victor Stinner3a50e702011-10-18 21:21:00 +02007340static PyObject *
7341encode_code_page(int code_page,
Victor Stinner7581cef2011-11-03 22:32:33 +01007342 PyObject *unicode,
Victor Stinner3a50e702011-10-18 21:21:00 +02007343 const char *errors)
7344{
Martin v. Löwis3d325192011-11-04 18:23:06 +01007345 Py_ssize_t len;
Victor Stinner3a50e702011-10-18 21:21:00 +02007346 PyObject *outbytes = NULL;
Victor Stinner7581cef2011-11-03 22:32:33 +01007347 Py_ssize_t offset;
Victor Stinner76a31a62011-11-04 00:05:13 +01007348 int chunk_len, ret, done;
Victor Stinner7581cef2011-11-03 22:32:33 +01007349
Benjamin Petersonbac79492012-01-14 13:34:47 -05007350 if (PyUnicode_READY(unicode) == -1)
Victor Stinner2fc507f2011-11-04 20:06:39 +01007351 return NULL;
7352 len = PyUnicode_GET_LENGTH(unicode);
Guido van Rossum03e29f12000-05-04 15:52:20 +00007353
Victor Stinner3a50e702011-10-18 21:21:00 +02007354 if (code_page < 0) {
7355 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7356 return NULL;
7357 }
7358
Martin v. Löwis3d325192011-11-04 18:23:06 +01007359 if (len == 0)
Victor Stinner76a31a62011-11-04 00:05:13 +01007360 return PyBytes_FromStringAndSize(NULL, 0);
7361
Victor Stinner7581cef2011-11-03 22:32:33 +01007362 offset = 0;
7363 do
7364 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007365#ifdef NEED_RETRY
Victor Stinner2fc507f2011-11-04 20:06:39 +01007366 /* UTF-16 encoding may double the size, so use only INT_MAX/2
Martin v. Löwis3d325192011-11-04 18:23:06 +01007367 chunks. */
7368 if (len > INT_MAX/2) {
7369 chunk_len = INT_MAX/2;
Victor Stinner76a31a62011-11-04 00:05:13 +01007370 done = 0;
7371 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007372 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007373#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007374 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007375 chunk_len = (int)len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007376 done = 1;
7377 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007378
Victor Stinner76a31a62011-11-04 00:05:13 +01007379 ret = encode_code_page_strict(code_page, &outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007380 unicode, offset, chunk_len,
Victor Stinner76a31a62011-11-04 00:05:13 +01007381 errors);
7382 if (ret == -2)
7383 ret = encode_code_page_errors(code_page, &outbytes,
7384 unicode, offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007385 chunk_len, errors);
Victor Stinner7581cef2011-11-03 22:32:33 +01007386 if (ret < 0) {
7387 Py_XDECREF(outbytes);
7388 return NULL;
7389 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007390
Victor Stinner7581cef2011-11-03 22:32:33 +01007391 offset += chunk_len;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007392 len -= chunk_len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007393 } while (!done);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007394
Victor Stinner3a50e702011-10-18 21:21:00 +02007395 return outbytes;
7396}
7397
7398PyObject *
7399PyUnicode_EncodeMBCS(const Py_UNICODE *p,
7400 Py_ssize_t size,
7401 const char *errors)
7402{
Victor Stinner7581cef2011-11-03 22:32:33 +01007403 PyObject *unicode, *res;
7404 unicode = PyUnicode_FromUnicode(p, size);
7405 if (unicode == NULL)
7406 return NULL;
7407 res = encode_code_page(CP_ACP, unicode, errors);
7408 Py_DECREF(unicode);
7409 return res;
Victor Stinner3a50e702011-10-18 21:21:00 +02007410}
7411
7412PyObject *
7413PyUnicode_EncodeCodePage(int code_page,
7414 PyObject *unicode,
7415 const char *errors)
7416{
Victor Stinner7581cef2011-11-03 22:32:33 +01007417 return encode_code_page(code_page, unicode, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007418}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007419
Alexander Belopolsky40018472011-02-26 01:02:56 +00007420PyObject *
7421PyUnicode_AsMBCSString(PyObject *unicode)
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007422{
7423 if (!PyUnicode_Check(unicode)) {
7424 PyErr_BadArgument();
7425 return NULL;
7426 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007427 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007428}
7429
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007430#undef NEED_RETRY
7431
Victor Stinner99b95382011-07-04 14:23:54 +02007432#endif /* HAVE_MBCS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007433
Guido van Rossumd57fd912000-03-10 22:53:23 +00007434/* --- Character Mapping Codec -------------------------------------------- */
7435
Alexander Belopolsky40018472011-02-26 01:02:56 +00007436PyObject *
7437PyUnicode_DecodeCharmap(const char *s,
7438 Py_ssize_t size,
7439 PyObject *mapping,
7440 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007441{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007442 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007443 Py_ssize_t startinpos;
7444 Py_ssize_t endinpos;
7445 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007446 const char *e;
Victor Stinner7931d9a2011-11-04 00:22:48 +01007447 PyObject *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007448 Py_ssize_t extrachars = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007449 PyObject *errorHandler = NULL;
7450 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00007451
Guido van Rossumd57fd912000-03-10 22:53:23 +00007452 /* Default to Latin-1 */
7453 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007454 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007455
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007456 v = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007457 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007458 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007459 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01007460 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007461 outpos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007462 e = s + size;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007463 if (PyUnicode_CheckExact(mapping)) {
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007464 Py_ssize_t maplen;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007465 enum PyUnicode_Kind mapkind;
7466 void *mapdata;
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007467 Py_UCS4 x;
7468
Benjamin Petersonbac79492012-01-14 13:34:47 -05007469 if (PyUnicode_READY(mapping) == -1)
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007470 return NULL;
7471
7472 maplen = PyUnicode_GET_LENGTH(mapping);
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007473 mapdata = PyUnicode_DATA(mapping);
7474 mapkind = PyUnicode_KIND(mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00007475 while (s < e) {
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007476 unsigned char ch;
7477 if (mapkind == PyUnicode_2BYTE_KIND && maplen >= 256) {
7478 enum PyUnicode_Kind outkind = PyUnicode_KIND(v);
7479 if (outkind == PyUnicode_1BYTE_KIND) {
7480 void *outdata = PyUnicode_DATA(v);
7481 Py_UCS4 maxchar = PyUnicode_MAX_CHAR_VALUE(v);
7482 while (s < e) {
7483 unsigned char ch = *s;
7484 x = PyUnicode_READ(PyUnicode_2BYTE_KIND, mapdata, ch);
7485 if (x > maxchar)
7486 goto Error;
7487 PyUnicode_WRITE(PyUnicode_1BYTE_KIND, outdata, outpos++, x);
7488 ++s;
7489 }
7490 break;
7491 }
7492 else if (outkind == PyUnicode_2BYTE_KIND) {
7493 void *outdata = PyUnicode_DATA(v);
7494 while (s < e) {
7495 unsigned char ch = *s;
7496 x = PyUnicode_READ(PyUnicode_2BYTE_KIND, mapdata, ch);
7497 if (x == 0xFFFE)
7498 goto Error;
7499 PyUnicode_WRITE(PyUnicode_2BYTE_KIND, outdata, outpos++, x);
7500 ++s;
7501 }
7502 break;
7503 }
7504 }
7505 ch = *s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007506
Benjamin Peterson29060642009-01-31 22:14:21 +00007507 if (ch < maplen)
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007508 x = PyUnicode_READ(mapkind, mapdata, ch);
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007509 else
7510 x = 0xfffe; /* invalid value */
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007511Error:
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007512 if (x == 0xfffe)
7513 {
Benjamin Peterson29060642009-01-31 22:14:21 +00007514 /* undefined mapping */
Benjamin Peterson29060642009-01-31 22:14:21 +00007515 startinpos = s-starts;
7516 endinpos = startinpos+1;
7517 if (unicode_decode_call_errorhandler(
7518 errors, &errorHandler,
7519 "charmap", "character maps to <undefined>",
7520 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007521 &v, &outpos)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007522 goto onError;
7523 }
7524 continue;
7525 }
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007526
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007527 if (unicode_putchar(&v, &outpos, x) < 0)
7528 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00007529 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007530 }
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007531 }
7532 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007533 while (s < e) {
7534 unsigned char ch = *s;
7535 PyObject *w, *x;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007536
Benjamin Peterson29060642009-01-31 22:14:21 +00007537 /* Get mapping (char ordinal -> integer, Unicode char or None) */
7538 w = PyLong_FromLong((long)ch);
7539 if (w == NULL)
7540 goto onError;
7541 x = PyObject_GetItem(mapping, w);
7542 Py_DECREF(w);
7543 if (x == NULL) {
7544 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7545 /* No mapping found means: mapping is undefined. */
7546 PyErr_Clear();
7547 x = Py_None;
7548 Py_INCREF(x);
7549 } else
7550 goto onError;
7551 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007552
Benjamin Peterson29060642009-01-31 22:14:21 +00007553 /* Apply mapping */
7554 if (PyLong_Check(x)) {
7555 long value = PyLong_AS_LONG(x);
Antoine Pitroua1f76552012-09-23 20:00:04 +02007556 if (value < 0 || value > MAX_UNICODE) {
7557 PyErr_Format(PyExc_TypeError,
7558 "character mapping must be in range(0x%lx)",
7559 (unsigned long)MAX_UNICODE + 1);
Benjamin Peterson29060642009-01-31 22:14:21 +00007560 Py_DECREF(x);
7561 goto onError;
7562 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007563 if (unicode_putchar(&v, &outpos, value) < 0)
7564 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00007565 }
7566 else if (x == Py_None) {
7567 /* undefined mapping */
Benjamin Peterson29060642009-01-31 22:14:21 +00007568 startinpos = s-starts;
7569 endinpos = startinpos+1;
7570 if (unicode_decode_call_errorhandler(
7571 errors, &errorHandler,
7572 "charmap", "character maps to <undefined>",
7573 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007574 &v, &outpos)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007575 Py_DECREF(x);
7576 goto onError;
7577 }
7578 Py_DECREF(x);
7579 continue;
7580 }
7581 else if (PyUnicode_Check(x)) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007582 Py_ssize_t targetsize;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007583
Benjamin Petersonbac79492012-01-14 13:34:47 -05007584 if (PyUnicode_READY(x) == -1)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007585 goto onError;
7586 targetsize = PyUnicode_GET_LENGTH(x);
7587
7588 if (targetsize == 1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007589 /* 1-1 mapping */
Victor Stinner62aa4d02011-11-09 00:03:45 +01007590 if (unicode_putchar(&v, &outpos,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007591 PyUnicode_READ_CHAR(x, 0)) < 0)
7592 goto onError;
7593 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007594 else if (targetsize > 1) {
7595 /* 1-n mapping */
7596 if (targetsize > extrachars) {
7597 /* resize first */
Benjamin Peterson29060642009-01-31 22:14:21 +00007598 Py_ssize_t needed = (targetsize - extrachars) + \
7599 (targetsize << 2);
7600 extrachars += needed;
7601 /* XXX overflow detection missing */
Victor Stinner16e6a802011-12-12 13:24:15 +01007602 if (unicode_resize(&v,
7603 PyUnicode_GET_LENGTH(v) + needed) < 0)
7604 {
Benjamin Peterson29060642009-01-31 22:14:21 +00007605 Py_DECREF(x);
7606 goto onError;
7607 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007608 }
Victor Stinner1b487b42012-05-03 12:29:04 +02007609 if (unicode_widen(&v, outpos, PyUnicode_MAX_CHAR_VALUE(x)) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007610 goto onError;
7611 PyUnicode_CopyCharacters(v, outpos, x, 0, targetsize);
7612 outpos += targetsize;
Benjamin Peterson29060642009-01-31 22:14:21 +00007613 extrachars -= targetsize;
7614 }
7615 /* 1-0 mapping: skip the character */
7616 }
7617 else {
7618 /* wrong return value */
7619 PyErr_SetString(PyExc_TypeError,
7620 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00007621 Py_DECREF(x);
7622 goto onError;
7623 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007624 Py_DECREF(x);
7625 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007626 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00007627 }
Victor Stinner16e6a802011-12-12 13:24:15 +01007628 if (unicode_resize(&v, outpos) < 0)
Antoine Pitroua8f63c02011-11-08 18:37:16 +01007629 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007630 Py_XDECREF(errorHandler);
7631 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01007632 return unicode_result(v);
Tim Petersced69f82003-09-16 20:30:58 +00007633
Benjamin Peterson29060642009-01-31 22:14:21 +00007634 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007635 Py_XDECREF(errorHandler);
7636 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007637 Py_XDECREF(v);
7638 return NULL;
7639}
7640
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007641/* Charmap encoding: the lookup table */
7642
Alexander Belopolsky40018472011-02-26 01:02:56 +00007643struct encoding_map {
Benjamin Peterson29060642009-01-31 22:14:21 +00007644 PyObject_HEAD
7645 unsigned char level1[32];
7646 int count2, count3;
7647 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007648};
7649
7650static PyObject*
7651encoding_map_size(PyObject *obj, PyObject* args)
7652{
7653 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007654 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00007655 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007656}
7657
7658static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007659 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00007660 PyDoc_STR("Return the size (in bytes) of this object") },
7661 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007662};
7663
7664static void
7665encoding_map_dealloc(PyObject* o)
7666{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007667 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007668}
7669
7670static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007671 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007672 "EncodingMap", /*tp_name*/
7673 sizeof(struct encoding_map), /*tp_basicsize*/
7674 0, /*tp_itemsize*/
7675 /* methods */
7676 encoding_map_dealloc, /*tp_dealloc*/
7677 0, /*tp_print*/
7678 0, /*tp_getattr*/
7679 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00007680 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00007681 0, /*tp_repr*/
7682 0, /*tp_as_number*/
7683 0, /*tp_as_sequence*/
7684 0, /*tp_as_mapping*/
7685 0, /*tp_hash*/
7686 0, /*tp_call*/
7687 0, /*tp_str*/
7688 0, /*tp_getattro*/
7689 0, /*tp_setattro*/
7690 0, /*tp_as_buffer*/
7691 Py_TPFLAGS_DEFAULT, /*tp_flags*/
7692 0, /*tp_doc*/
7693 0, /*tp_traverse*/
7694 0, /*tp_clear*/
7695 0, /*tp_richcompare*/
7696 0, /*tp_weaklistoffset*/
7697 0, /*tp_iter*/
7698 0, /*tp_iternext*/
7699 encoding_map_methods, /*tp_methods*/
7700 0, /*tp_members*/
7701 0, /*tp_getset*/
7702 0, /*tp_base*/
7703 0, /*tp_dict*/
7704 0, /*tp_descr_get*/
7705 0, /*tp_descr_set*/
7706 0, /*tp_dictoffset*/
7707 0, /*tp_init*/
7708 0, /*tp_alloc*/
7709 0, /*tp_new*/
7710 0, /*tp_free*/
7711 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007712};
7713
7714PyObject*
7715PyUnicode_BuildEncodingMap(PyObject* string)
7716{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007717 PyObject *result;
7718 struct encoding_map *mresult;
7719 int i;
7720 int need_dict = 0;
7721 unsigned char level1[32];
7722 unsigned char level2[512];
7723 unsigned char *mlevel1, *mlevel2, *mlevel3;
7724 int count2 = 0, count3 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007725 int kind;
7726 void *data;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007727 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007728 Py_UCS4 ch;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007729
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007730 if (!PyUnicode_Check(string) || !PyUnicode_GET_LENGTH(string)) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007731 PyErr_BadArgument();
7732 return NULL;
7733 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007734 kind = PyUnicode_KIND(string);
7735 data = PyUnicode_DATA(string);
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007736 length = PyUnicode_GET_LENGTH(string);
7737 length = Py_MIN(length, 256);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007738 memset(level1, 0xFF, sizeof level1);
7739 memset(level2, 0xFF, sizeof level2);
7740
7741 /* If there isn't a one-to-one mapping of NULL to \0,
7742 or if there are non-BMP characters, we need to use
7743 a mapping dictionary. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007744 if (PyUnicode_READ(kind, data, 0) != 0)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007745 need_dict = 1;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007746 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007747 int l1, l2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007748 ch = PyUnicode_READ(kind, data, i);
7749 if (ch == 0 || ch > 0xFFFF) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007750 need_dict = 1;
7751 break;
7752 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007753 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007754 /* unmapped character */
7755 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007756 l1 = ch >> 11;
7757 l2 = ch >> 7;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007758 if (level1[l1] == 0xFF)
7759 level1[l1] = count2++;
7760 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00007761 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007762 }
7763
7764 if (count2 >= 0xFF || count3 >= 0xFF)
7765 need_dict = 1;
7766
7767 if (need_dict) {
7768 PyObject *result = PyDict_New();
7769 PyObject *key, *value;
7770 if (!result)
7771 return NULL;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007772 for (i = 0; i < length; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007773 key = PyLong_FromLong(PyUnicode_READ(kind, data, i));
Christian Heimes217cfd12007-12-02 14:31:20 +00007774 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007775 if (!key || !value)
7776 goto failed1;
7777 if (PyDict_SetItem(result, key, value) == -1)
7778 goto failed1;
7779 Py_DECREF(key);
7780 Py_DECREF(value);
7781 }
7782 return result;
7783 failed1:
7784 Py_XDECREF(key);
7785 Py_XDECREF(value);
7786 Py_DECREF(result);
7787 return NULL;
7788 }
7789
7790 /* Create a three-level trie */
7791 result = PyObject_MALLOC(sizeof(struct encoding_map) +
7792 16*count2 + 128*count3 - 1);
7793 if (!result)
7794 return PyErr_NoMemory();
7795 PyObject_Init(result, &EncodingMapType);
7796 mresult = (struct encoding_map*)result;
7797 mresult->count2 = count2;
7798 mresult->count3 = count3;
7799 mlevel1 = mresult->level1;
7800 mlevel2 = mresult->level23;
7801 mlevel3 = mresult->level23 + 16*count2;
7802 memcpy(mlevel1, level1, 32);
7803 memset(mlevel2, 0xFF, 16*count2);
7804 memset(mlevel3, 0, 128*count3);
7805 count3 = 0;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007806 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007807 int o1, o2, o3, i2, i3;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007808 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7809 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007810 /* unmapped character */
7811 continue;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007812 o1 = ch>>11;
7813 o2 = (ch>>7) & 0xF;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007814 i2 = 16*mlevel1[o1] + o2;
7815 if (mlevel2[i2] == 0xFF)
7816 mlevel2[i2] = count3++;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007817 o3 = ch & 0x7F;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007818 i3 = 128*mlevel2[i2] + o3;
7819 mlevel3[i3] = i;
7820 }
7821 return result;
7822}
7823
7824static int
Victor Stinner22168992011-11-20 17:09:18 +01007825encoding_map_lookup(Py_UCS4 c, PyObject *mapping)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007826{
7827 struct encoding_map *map = (struct encoding_map*)mapping;
7828 int l1 = c>>11;
7829 int l2 = (c>>7) & 0xF;
7830 int l3 = c & 0x7F;
7831 int i;
7832
Victor Stinner22168992011-11-20 17:09:18 +01007833 if (c > 0xFFFF)
Benjamin Peterson29060642009-01-31 22:14:21 +00007834 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007835 if (c == 0)
7836 return 0;
7837 /* level 1*/
7838 i = map->level1[l1];
7839 if (i == 0xFF) {
7840 return -1;
7841 }
7842 /* level 2*/
7843 i = map->level23[16*i+l2];
7844 if (i == 0xFF) {
7845 return -1;
7846 }
7847 /* level 3 */
7848 i = map->level23[16*map->count2 + 128*i + l3];
7849 if (i == 0) {
7850 return -1;
7851 }
7852 return i;
7853}
7854
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007855/* Lookup the character ch in the mapping. If the character
7856 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00007857 error occurred). */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007858static PyObject *
Victor Stinner22168992011-11-20 17:09:18 +01007859charmapencode_lookup(Py_UCS4 c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007860{
Christian Heimes217cfd12007-12-02 14:31:20 +00007861 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007862 PyObject *x;
7863
7864 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007865 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007866 x = PyObject_GetItem(mapping, w);
7867 Py_DECREF(w);
7868 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007869 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7870 /* No mapping found means: mapping is undefined. */
7871 PyErr_Clear();
7872 x = Py_None;
7873 Py_INCREF(x);
7874 return x;
7875 } else
7876 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007877 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00007878 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00007879 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00007880 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007881 long value = PyLong_AS_LONG(x);
7882 if (value < 0 || value > 255) {
7883 PyErr_SetString(PyExc_TypeError,
7884 "character mapping must be in range(256)");
7885 Py_DECREF(x);
7886 return NULL;
7887 }
7888 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007889 }
Christian Heimes72b710a2008-05-26 13:28:38 +00007890 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00007891 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007892 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007893 /* wrong return value */
7894 PyErr_Format(PyExc_TypeError,
7895 "character mapping must return integer, bytes or None, not %.400s",
7896 x->ob_type->tp_name);
7897 Py_DECREF(x);
7898 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007899 }
7900}
7901
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007902static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00007903charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007904{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007905 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
7906 /* exponentially overallocate to minimize reallocations */
7907 if (requiredsize < 2*outsize)
7908 requiredsize = 2*outsize;
7909 if (_PyBytes_Resize(outobj, requiredsize))
7910 return -1;
7911 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007912}
7913
Benjamin Peterson14339b62009-01-31 16:36:08 +00007914typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00007915 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Alexander Belopolsky40018472011-02-26 01:02:56 +00007916} charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007917/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00007918 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007919 space is available. Return a new reference to the object that
7920 was put in the output buffer, or Py_None, if the mapping was undefined
7921 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00007922 reallocation error occurred. The caller must decref the result */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007923static charmapencode_result
Victor Stinner22168992011-11-20 17:09:18 +01007924charmapencode_output(Py_UCS4 c, PyObject *mapping,
Alexander Belopolsky40018472011-02-26 01:02:56 +00007925 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007926{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007927 PyObject *rep;
7928 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00007929 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007930
Christian Heimes90aa7642007-12-19 02:45:37 +00007931 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007932 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00007933 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007934 if (res == -1)
7935 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00007936 if (outsize<requiredsize)
7937 if (charmapencode_resize(outobj, outpos, requiredsize))
7938 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00007939 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00007940 outstart[(*outpos)++] = (char)res;
7941 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007942 }
7943
7944 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007945 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007946 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007947 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007948 Py_DECREF(rep);
7949 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007950 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007951 if (PyLong_Check(rep)) {
7952 Py_ssize_t requiredsize = *outpos+1;
7953 if (outsize<requiredsize)
7954 if (charmapencode_resize(outobj, outpos, requiredsize)) {
7955 Py_DECREF(rep);
7956 return enc_EXCEPTION;
7957 }
Christian Heimes72b710a2008-05-26 13:28:38 +00007958 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00007959 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00007960 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007961 else {
7962 const char *repchars = PyBytes_AS_STRING(rep);
7963 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
7964 Py_ssize_t requiredsize = *outpos+repsize;
7965 if (outsize<requiredsize)
7966 if (charmapencode_resize(outobj, outpos, requiredsize)) {
7967 Py_DECREF(rep);
7968 return enc_EXCEPTION;
7969 }
Christian Heimes72b710a2008-05-26 13:28:38 +00007970 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00007971 memcpy(outstart + *outpos, repchars, repsize);
7972 *outpos += repsize;
7973 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007974 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007975 Py_DECREF(rep);
7976 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007977}
7978
7979/* handle an error in PyUnicode_EncodeCharmap
7980 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007981static int
7982charmap_encoding_error(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007983 PyObject *unicode, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007984 PyObject **exceptionObject,
Walter Dörwalde5402fb2003-08-14 20:25:29 +00007985 int *known_errorHandler, PyObject **errorHandler, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00007986 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007987{
7988 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007989 Py_ssize_t size, repsize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007990 Py_ssize_t newpos;
Victor Stinnerae4f7c82011-11-20 18:28:55 +01007991 enum PyUnicode_Kind kind;
7992 void *data;
7993 Py_ssize_t index;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007994 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00007995 Py_ssize_t collstartpos = *inpos;
7996 Py_ssize_t collendpos = *inpos+1;
7997 Py_ssize_t collpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007998 char *encoding = "charmap";
7999 char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008000 charmapencode_result x;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008001 Py_UCS4 ch;
Brian Curtin2787ea42011-11-02 15:09:37 -05008002 int val;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008003
Benjamin Petersonbac79492012-01-14 13:34:47 -05008004 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008005 return -1;
8006 size = PyUnicode_GET_LENGTH(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008007 /* find all unencodable characters */
8008 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008009 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00008010 if (Py_TYPE(mapping) == &EncodingMapType) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008011 ch = PyUnicode_READ_CHAR(unicode, collendpos);
Brian Curtin2787ea42011-11-02 15:09:37 -05008012 val = encoding_map_lookup(ch, mapping);
8013 if (val != -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008014 break;
8015 ++collendpos;
8016 continue;
8017 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008018
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008019 ch = PyUnicode_READ_CHAR(unicode, collendpos);
8020 rep = charmapencode_lookup(ch, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008021 if (rep==NULL)
8022 return -1;
8023 else if (rep!=Py_None) {
8024 Py_DECREF(rep);
8025 break;
8026 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008027 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00008028 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008029 }
8030 /* cache callback name lookup
8031 * (if not done yet, i.e. it's the first error) */
8032 if (*known_errorHandler==-1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008033 if ((errors==NULL) || (!strcmp(errors, "strict")))
8034 *known_errorHandler = 1;
8035 else if (!strcmp(errors, "replace"))
8036 *known_errorHandler = 2;
8037 else if (!strcmp(errors, "ignore"))
8038 *known_errorHandler = 3;
8039 else if (!strcmp(errors, "xmlcharrefreplace"))
8040 *known_errorHandler = 4;
8041 else
8042 *known_errorHandler = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008043 }
8044 switch (*known_errorHandler) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008045 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008046 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008047 return -1;
8048 case 2: /* replace */
8049 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008050 x = charmapencode_output('?', mapping, res, respos);
8051 if (x==enc_EXCEPTION) {
8052 return -1;
8053 }
8054 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008055 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008056 return -1;
8057 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008058 }
8059 /* fall through */
8060 case 3: /* ignore */
8061 *inpos = collendpos;
8062 break;
8063 case 4: /* xmlcharrefreplace */
8064 /* generate replacement (temporarily (mis)uses p) */
8065 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008066 char buffer[2+29+1+1];
8067 char *cp;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008068 sprintf(buffer, "&#%d;", (int)PyUnicode_READ_CHAR(unicode, collpos));
Benjamin Peterson29060642009-01-31 22:14:21 +00008069 for (cp = buffer; *cp; ++cp) {
8070 x = charmapencode_output(*cp, mapping, res, respos);
8071 if (x==enc_EXCEPTION)
8072 return -1;
8073 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008074 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008075 return -1;
8076 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008077 }
8078 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008079 *inpos = collendpos;
8080 break;
8081 default:
8082 repunicode = unicode_encode_call_errorhandler(errors, errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008083 encoding, reason, unicode, exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00008084 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008085 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008086 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00008087 if (PyBytes_Check(repunicode)) {
8088 /* Directly copy bytes result to output. */
8089 Py_ssize_t outsize = PyBytes_Size(*res);
8090 Py_ssize_t requiredsize;
8091 repsize = PyBytes_Size(repunicode);
8092 requiredsize = *respos + repsize;
8093 if (requiredsize > outsize)
8094 /* Make room for all additional bytes. */
8095 if (charmapencode_resize(res, respos, requiredsize)) {
8096 Py_DECREF(repunicode);
8097 return -1;
8098 }
8099 memcpy(PyBytes_AsString(*res) + *respos,
8100 PyBytes_AsString(repunicode), repsize);
8101 *respos += repsize;
8102 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008103 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00008104 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008105 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008106 /* generate replacement */
Benjamin Petersonbac79492012-01-14 13:34:47 -05008107 if (PyUnicode_READY(repunicode) == -1) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008108 Py_DECREF(repunicode);
8109 return -1;
8110 }
Victor Stinner9e30aa52011-11-21 02:49:52 +01008111 repsize = PyUnicode_GET_LENGTH(repunicode);
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008112 data = PyUnicode_DATA(repunicode);
8113 kind = PyUnicode_KIND(repunicode);
8114 for (index = 0; index < repsize; index++) {
8115 Py_UCS4 repch = PyUnicode_READ(kind, data, index);
8116 x = charmapencode_output(repch, mapping, res, respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008117 if (x==enc_EXCEPTION) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008118 Py_DECREF(repunicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00008119 return -1;
8120 }
8121 else if (x==enc_FAILED) {
8122 Py_DECREF(repunicode);
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008123 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008124 return -1;
8125 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008126 }
8127 *inpos = newpos;
8128 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008129 }
8130 return 0;
8131}
8132
Alexander Belopolsky40018472011-02-26 01:02:56 +00008133PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008134_PyUnicode_EncodeCharmap(PyObject *unicode,
8135 PyObject *mapping,
8136 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008137{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008138 /* output object */
8139 PyObject *res = NULL;
8140 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008141 Py_ssize_t inpos = 0;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008142 Py_ssize_t size;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008143 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008144 Py_ssize_t respos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008145 PyObject *errorHandler = NULL;
8146 PyObject *exc = NULL;
8147 /* the following variable is used for caching string comparisons
8148 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8149 * 3=ignore, 4=xmlcharrefreplace */
8150 int known_errorHandler = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008151
Benjamin Petersonbac79492012-01-14 13:34:47 -05008152 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008153 return NULL;
8154 size = PyUnicode_GET_LENGTH(unicode);
8155
Guido van Rossumd57fd912000-03-10 22:53:23 +00008156 /* Default to Latin-1 */
8157 if (mapping == NULL)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008158 return unicode_encode_ucs1(unicode, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008159
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008160 /* allocate enough for a simple encoding without
8161 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00008162 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008163 if (res == NULL)
8164 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00008165 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008166 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008167
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008168 while (inpos<size) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008169 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, inpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008170 /* try to encode it */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008171 charmapencode_result x = charmapencode_output(ch, mapping, &res, &respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008172 if (x==enc_EXCEPTION) /* error */
8173 goto onError;
8174 if (x==enc_FAILED) { /* unencodable character */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008175 if (charmap_encoding_error(unicode, &inpos, mapping,
Benjamin Peterson29060642009-01-31 22:14:21 +00008176 &exc,
8177 &known_errorHandler, &errorHandler, errors,
8178 &res, &respos)) {
8179 goto onError;
8180 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008181 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008182 else
8183 /* done with this character => adjust input position */
8184 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008185 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008186
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008187 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00008188 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00008189 if (_PyBytes_Resize(&res, respos) < 0)
8190 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00008191
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008192 Py_XDECREF(exc);
8193 Py_XDECREF(errorHandler);
8194 return res;
8195
Benjamin Peterson29060642009-01-31 22:14:21 +00008196 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008197 Py_XDECREF(res);
8198 Py_XDECREF(exc);
8199 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008200 return NULL;
8201}
8202
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008203/* Deprecated */
8204PyObject *
8205PyUnicode_EncodeCharmap(const Py_UNICODE *p,
8206 Py_ssize_t size,
8207 PyObject *mapping,
8208 const char *errors)
8209{
8210 PyObject *result;
8211 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8212 if (unicode == NULL)
8213 return NULL;
8214 result = _PyUnicode_EncodeCharmap(unicode, mapping, errors);
8215 Py_DECREF(unicode);
Victor Stinnerfc026c92011-11-04 00:24:51 +01008216 return result;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008217}
8218
Alexander Belopolsky40018472011-02-26 01:02:56 +00008219PyObject *
8220PyUnicode_AsCharmapString(PyObject *unicode,
8221 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008222{
8223 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008224 PyErr_BadArgument();
8225 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008226 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008227 return _PyUnicode_EncodeCharmap(unicode, mapping, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008228}
8229
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008230/* create or adjust a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008231static void
8232make_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008233 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008234 Py_ssize_t startpos, Py_ssize_t endpos,
8235 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008236{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008237 if (*exceptionObject == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008238 *exceptionObject = _PyUnicodeTranslateError_Create(
8239 unicode, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008240 }
8241 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008242 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
8243 goto onError;
8244 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
8245 goto onError;
8246 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
8247 goto onError;
8248 return;
8249 onError:
8250 Py_DECREF(*exceptionObject);
8251 *exceptionObject = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008252 }
8253}
8254
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008255/* raises a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008256static void
8257raise_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008258 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008259 Py_ssize_t startpos, Py_ssize_t endpos,
8260 const char *reason)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008261{
8262 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008263 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008264 if (*exceptionObject != NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008265 PyCodec_StrictErrors(*exceptionObject);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008266}
8267
8268/* error handling callback helper:
8269 build arguments, call the callback and check the arguments,
8270 put the result into newpos and return the replacement string, which
8271 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008272static PyObject *
8273unicode_translate_call_errorhandler(const char *errors,
8274 PyObject **errorHandler,
8275 const char *reason,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008276 PyObject *unicode, PyObject **exceptionObject,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008277 Py_ssize_t startpos, Py_ssize_t endpos,
8278 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008279{
Benjamin Peterson142957c2008-07-04 19:55:29 +00008280 static char *argparse = "O!n;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008281
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008282 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008283 PyObject *restuple;
8284 PyObject *resunicode;
8285
8286 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008287 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008288 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008289 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008290 }
8291
8292 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008293 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008294 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008295 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008296
8297 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00008298 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008299 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008300 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008301 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00008302 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00008303 Py_DECREF(restuple);
8304 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008305 }
8306 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type,
Benjamin Peterson29060642009-01-31 22:14:21 +00008307 &resunicode, &i_newpos)) {
8308 Py_DECREF(restuple);
8309 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008310 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00008311 if (i_newpos<0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008312 *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008313 else
8314 *newpos = i_newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008315 if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008316 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
8317 Py_DECREF(restuple);
8318 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00008319 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008320 Py_INCREF(resunicode);
8321 Py_DECREF(restuple);
8322 return resunicode;
8323}
8324
8325/* Lookup the character ch in the mapping and put the result in result,
8326 which must be decrefed by the caller.
8327 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008328static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008329charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008330{
Christian Heimes217cfd12007-12-02 14:31:20 +00008331 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008332 PyObject *x;
8333
8334 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008335 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008336 x = PyObject_GetItem(mapping, w);
8337 Py_DECREF(w);
8338 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008339 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8340 /* No mapping found means: use 1:1 mapping. */
8341 PyErr_Clear();
8342 *result = NULL;
8343 return 0;
8344 } else
8345 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008346 }
8347 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008348 *result = x;
8349 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008350 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008351 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008352 long value = PyLong_AS_LONG(x);
8353 long max = PyUnicode_GetMax();
8354 if (value < 0 || value > max) {
8355 PyErr_Format(PyExc_TypeError,
Guido van Rossum5a2f7e602007-10-24 21:13:09 +00008356 "character mapping must be in range(0x%x)", max+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00008357 Py_DECREF(x);
8358 return -1;
8359 }
8360 *result = x;
8361 return 0;
8362 }
8363 else if (PyUnicode_Check(x)) {
8364 *result = x;
8365 return 0;
8366 }
8367 else {
8368 /* wrong return value */
8369 PyErr_SetString(PyExc_TypeError,
8370 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00008371 Py_DECREF(x);
8372 return -1;
8373 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008374}
8375/* ensure that *outobj is at least requiredsize characters long,
Benjamin Peterson29060642009-01-31 22:14:21 +00008376 if not reallocate and adjust various state variables.
8377 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008378static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008379charmaptranslate_makespace(Py_UCS4 **outobj, Py_ssize_t *psize,
Benjamin Peterson29060642009-01-31 22:14:21 +00008380 Py_ssize_t requiredsize)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008381{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008382 Py_ssize_t oldsize = *psize;
Kristjan Valur Jonsson85634d72012-05-31 09:37:31 +00008383 Py_UCS4 *new_outobj;
Walter Dörwald4894c302003-10-24 14:25:28 +00008384 if (requiredsize > oldsize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008385 /* exponentially overallocate to minimize reallocations */
8386 if (requiredsize < 2 * oldsize)
8387 requiredsize = 2 * oldsize;
Kristjan Valur Jonsson85634d72012-05-31 09:37:31 +00008388 new_outobj = PyMem_Realloc(*outobj, requiredsize * sizeof(Py_UCS4));
8389 if (new_outobj == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008390 return -1;
Kristjan Valur Jonsson85634d72012-05-31 09:37:31 +00008391 *outobj = new_outobj;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008392 *psize = requiredsize;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008393 }
8394 return 0;
8395}
8396/* lookup the character, put the result in the output string and adjust
8397 various state variables. Return a new reference to the object that
8398 was put in the output buffer in *result, or Py_None, if the mapping was
8399 undefined (in which case no character was written).
8400 The called must decref result.
8401 Return 0 on success, -1 on error. */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008402static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008403charmaptranslate_output(PyObject *input, Py_ssize_t ipos,
8404 PyObject *mapping, Py_UCS4 **output,
8405 Py_ssize_t *osize, Py_ssize_t *opos,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008406 PyObject **res)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008407{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008408 Py_UCS4 curinp = PyUnicode_READ_CHAR(input, ipos);
8409 if (charmaptranslate_lookup(curinp, mapping, res))
Benjamin Peterson29060642009-01-31 22:14:21 +00008410 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008411 if (*res==NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008412 /* not found => default to 1:1 mapping */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008413 (*output)[(*opos)++] = curinp;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008414 }
8415 else if (*res==Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008416 ;
Christian Heimes217cfd12007-12-02 14:31:20 +00008417 else if (PyLong_Check(*res)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008418 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008419 (*output)[(*opos)++] = (Py_UCS4)PyLong_AS_LONG(*res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008420 }
8421 else if (PyUnicode_Check(*res)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008422 Py_ssize_t repsize;
8423 if (PyUnicode_READY(*res) == -1)
8424 return -1;
8425 repsize = PyUnicode_GET_LENGTH(*res);
Benjamin Peterson29060642009-01-31 22:14:21 +00008426 if (repsize==1) {
8427 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008428 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +00008429 }
8430 else if (repsize!=0) {
8431 /* more than one character */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008432 Py_ssize_t requiredsize = *opos +
8433 (PyUnicode_GET_LENGTH(input) - ipos) +
Benjamin Peterson29060642009-01-31 22:14:21 +00008434 repsize - 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008435 Py_ssize_t i;
8436 if (charmaptranslate_makespace(output, osize, requiredsize))
Benjamin Peterson29060642009-01-31 22:14:21 +00008437 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008438 for(i = 0; i < repsize; i++)
8439 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00008440 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008441 }
8442 else
Benjamin Peterson29060642009-01-31 22:14:21 +00008443 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008444 return 0;
8445}
8446
Alexander Belopolsky40018472011-02-26 01:02:56 +00008447PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008448_PyUnicode_TranslateCharmap(PyObject *input,
8449 PyObject *mapping,
8450 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008451{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008452 /* input object */
8453 char *idata;
8454 Py_ssize_t size, i;
8455 int kind;
8456 /* output buffer */
8457 Py_UCS4 *output = NULL;
8458 Py_ssize_t osize;
8459 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008460 /* current output position */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008461 Py_ssize_t opos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008462 char *reason = "character maps to <undefined>";
8463 PyObject *errorHandler = NULL;
8464 PyObject *exc = NULL;
8465 /* the following variable is used for caching string comparisons
8466 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8467 * 3=ignore, 4=xmlcharrefreplace */
8468 int known_errorHandler = -1;
8469
Guido van Rossumd57fd912000-03-10 22:53:23 +00008470 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008471 PyErr_BadArgument();
8472 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008473 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008474
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008475 if (PyUnicode_READY(input) == -1)
8476 return NULL;
8477 idata = (char*)PyUnicode_DATA(input);
8478 kind = PyUnicode_KIND(input);
8479 size = PyUnicode_GET_LENGTH(input);
8480 i = 0;
8481
8482 if (size == 0) {
8483 Py_INCREF(input);
8484 return input;
8485 }
8486
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008487 /* allocate enough for a simple 1:1 translation without
8488 replacements, if we need more, we'll resize */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008489 osize = size;
8490 output = PyMem_Malloc(osize * sizeof(Py_UCS4));
8491 opos = 0;
8492 if (output == NULL) {
8493 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00008494 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008495 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008496
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008497 while (i<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008498 /* try to encode it */
8499 PyObject *x = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008500 if (charmaptranslate_output(input, i, mapping,
8501 &output, &osize, &opos, &x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008502 Py_XDECREF(x);
8503 goto onError;
8504 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008505 Py_XDECREF(x);
Benjamin Peterson29060642009-01-31 22:14:21 +00008506 if (x!=Py_None) /* it worked => adjust input pointer */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008507 ++i;
Benjamin Peterson29060642009-01-31 22:14:21 +00008508 else { /* untranslatable character */
8509 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
8510 Py_ssize_t repsize;
8511 Py_ssize_t newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008512 Py_ssize_t uni2;
Benjamin Peterson29060642009-01-31 22:14:21 +00008513 /* startpos for collecting untranslatable chars */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008514 Py_ssize_t collstart = i;
8515 Py_ssize_t collend = i+1;
8516 Py_ssize_t coll;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008517
Benjamin Peterson29060642009-01-31 22:14:21 +00008518 /* find all untranslatable characters */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008519 while (collend < size) {
8520 if (charmaptranslate_lookup(PyUnicode_READ(kind,idata, collend), mapping, &x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008521 goto onError;
8522 Py_XDECREF(x);
8523 if (x!=Py_None)
8524 break;
8525 ++collend;
8526 }
8527 /* cache callback name lookup
8528 * (if not done yet, i.e. it's the first error) */
8529 if (known_errorHandler==-1) {
8530 if ((errors==NULL) || (!strcmp(errors, "strict")))
8531 known_errorHandler = 1;
8532 else if (!strcmp(errors, "replace"))
8533 known_errorHandler = 2;
8534 else if (!strcmp(errors, "ignore"))
8535 known_errorHandler = 3;
8536 else if (!strcmp(errors, "xmlcharrefreplace"))
8537 known_errorHandler = 4;
8538 else
8539 known_errorHandler = 0;
8540 }
8541 switch (known_errorHandler) {
8542 case 1: /* strict */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008543 raise_translate_exception(&exc, input, collstart,
8544 collend, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008545 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00008546 case 2: /* replace */
8547 /* No need to check for space, this is a 1:1 replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008548 for (coll = collstart; coll<collend; coll++)
8549 output[opos++] = '?';
Benjamin Peterson29060642009-01-31 22:14:21 +00008550 /* fall through */
8551 case 3: /* ignore */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008552 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008553 break;
8554 case 4: /* xmlcharrefreplace */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008555 /* generate replacement (temporarily (mis)uses i) */
8556 for (i = collstart; i < collend; ++i) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008557 char buffer[2+29+1+1];
8558 char *cp;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008559 sprintf(buffer, "&#%d;", PyUnicode_READ(kind, idata, i));
8560 if (charmaptranslate_makespace(&output, &osize,
8561 opos+strlen(buffer)+(size-collend)))
Benjamin Peterson29060642009-01-31 22:14:21 +00008562 goto onError;
8563 for (cp = buffer; *cp; ++cp)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008564 output[opos++] = *cp;
Benjamin Peterson29060642009-01-31 22:14:21 +00008565 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008566 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008567 break;
8568 default:
8569 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008570 reason, input, &exc,
8571 collstart, collend, &newpos);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008572 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008573 goto onError;
Benjamin Peterson9ca3ffa2012-01-01 16:04:29 -06008574 if (PyUnicode_READY(repunicode) == -1) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008575 Py_DECREF(repunicode);
8576 goto onError;
8577 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008578 /* generate replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008579 repsize = PyUnicode_GET_LENGTH(repunicode);
8580 if (charmaptranslate_makespace(&output, &osize,
8581 opos+repsize+(size-collend))) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008582 Py_DECREF(repunicode);
8583 goto onError;
8584 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008585 for (uni2 = 0; repsize-->0; ++uni2)
8586 output[opos++] = PyUnicode_READ_CHAR(repunicode, uni2);
8587 i = newpos;
Benjamin Peterson29060642009-01-31 22:14:21 +00008588 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008589 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008590 }
8591 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008592 res = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND, output, opos);
8593 if (!res)
8594 goto onError;
8595 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008596 Py_XDECREF(exc);
8597 Py_XDECREF(errorHandler);
8598 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008599
Benjamin Peterson29060642009-01-31 22:14:21 +00008600 onError:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008601 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008602 Py_XDECREF(exc);
8603 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008604 return NULL;
8605}
8606
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008607/* Deprecated. Use PyUnicode_Translate instead. */
8608PyObject *
8609PyUnicode_TranslateCharmap(const Py_UNICODE *p,
8610 Py_ssize_t size,
8611 PyObject *mapping,
8612 const char *errors)
8613{
Christian Heimes5f520f42012-09-11 14:03:25 +02008614 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008615 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8616 if (!unicode)
8617 return NULL;
Christian Heimes5f520f42012-09-11 14:03:25 +02008618 result = _PyUnicode_TranslateCharmap(unicode, mapping, errors);
8619 Py_DECREF(unicode);
8620 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008621}
8622
Alexander Belopolsky40018472011-02-26 01:02:56 +00008623PyObject *
8624PyUnicode_Translate(PyObject *str,
8625 PyObject *mapping,
8626 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008627{
8628 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +00008629
Guido van Rossumd57fd912000-03-10 22:53:23 +00008630 str = PyUnicode_FromObject(str);
8631 if (str == NULL)
Christian Heimes5f520f42012-09-11 14:03:25 +02008632 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008633 result = _PyUnicode_TranslateCharmap(str, mapping, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008634 Py_DECREF(str);
8635 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008636}
Tim Petersced69f82003-09-16 20:30:58 +00008637
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008638static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02008639fix_decimal_and_space_to_ascii(PyObject *self)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008640{
8641 /* No need to call PyUnicode_READY(self) because this function is only
8642 called as a callback from fixup() which does it already. */
8643 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
8644 const int kind = PyUnicode_KIND(self);
8645 void *data = PyUnicode_DATA(self);
Victor Stinnere6abb482012-05-02 01:15:40 +02008646 Py_UCS4 maxchar = 127, ch, fixed;
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008647 int modified = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008648 Py_ssize_t i;
8649
8650 for (i = 0; i < len; ++i) {
8651 ch = PyUnicode_READ(kind, data, i);
8652 fixed = 0;
8653 if (ch > 127) {
8654 if (Py_UNICODE_ISSPACE(ch))
8655 fixed = ' ';
8656 else {
8657 const int decimal = Py_UNICODE_TODECIMAL(ch);
8658 if (decimal >= 0)
8659 fixed = '0' + decimal;
8660 }
8661 if (fixed != 0) {
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008662 modified = 1;
Victor Stinnere6abb482012-05-02 01:15:40 +02008663 maxchar = MAX_MAXCHAR(maxchar, fixed);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008664 PyUnicode_WRITE(kind, data, i, fixed);
8665 }
Victor Stinnere6abb482012-05-02 01:15:40 +02008666 else
8667 maxchar = MAX_MAXCHAR(maxchar, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008668 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008669 }
8670
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008671 return (modified) ? maxchar : 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008672}
8673
8674PyObject *
8675_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
8676{
8677 if (!PyUnicode_Check(unicode)) {
8678 PyErr_BadInternalCall();
8679 return NULL;
8680 }
8681 if (PyUnicode_READY(unicode) == -1)
8682 return NULL;
8683 if (PyUnicode_MAX_CHAR_VALUE(unicode) <= 127) {
8684 /* If the string is already ASCII, just return the same string */
8685 Py_INCREF(unicode);
8686 return unicode;
8687 }
Victor Stinner9310abb2011-10-05 00:59:23 +02008688 return fixup(unicode, fix_decimal_and_space_to_ascii);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008689}
8690
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008691PyObject *
8692PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
8693 Py_ssize_t length)
8694{
Victor Stinnerf0124502011-11-21 23:12:56 +01008695 PyObject *decimal;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008696 Py_ssize_t i;
Victor Stinnerf0124502011-11-21 23:12:56 +01008697 Py_UCS4 maxchar;
8698 enum PyUnicode_Kind kind;
8699 void *data;
8700
Victor Stinner99d7ad02012-02-22 13:37:39 +01008701 maxchar = 127;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008702 for (i = 0; i < length; i++) {
Victor Stinnerf0124502011-11-21 23:12:56 +01008703 Py_UNICODE ch = s[i];
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008704 if (ch > 127) {
8705 int decimal = Py_UNICODE_TODECIMAL(ch);
8706 if (decimal >= 0)
Victor Stinnerf0124502011-11-21 23:12:56 +01008707 ch = '0' + decimal;
Victor Stinnere6abb482012-05-02 01:15:40 +02008708 maxchar = MAX_MAXCHAR(maxchar, ch);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008709 }
8710 }
Victor Stinnerf0124502011-11-21 23:12:56 +01008711
8712 /* Copy to a new string */
8713 decimal = PyUnicode_New(length, maxchar);
8714 if (decimal == NULL)
8715 return decimal;
8716 kind = PyUnicode_KIND(decimal);
8717 data = PyUnicode_DATA(decimal);
8718 /* Iterate over code points */
8719 for (i = 0; i < length; i++) {
8720 Py_UNICODE ch = s[i];
8721 if (ch > 127) {
8722 int decimal = Py_UNICODE_TODECIMAL(ch);
8723 if (decimal >= 0)
8724 ch = '0' + decimal;
8725 }
8726 PyUnicode_WRITE(kind, data, i, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008727 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008728 return unicode_result(decimal);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008729}
Guido van Rossum9e896b32000-04-05 20:11:21 +00008730/* --- Decimal Encoder ---------------------------------------------------- */
8731
Alexander Belopolsky40018472011-02-26 01:02:56 +00008732int
8733PyUnicode_EncodeDecimal(Py_UNICODE *s,
8734 Py_ssize_t length,
8735 char *output,
8736 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00008737{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008738 PyObject *unicode;
Victor Stinner6345be92011-11-25 20:09:01 +01008739 Py_ssize_t i;
Victor Stinner42bf7752011-11-21 22:52:58 +01008740 enum PyUnicode_Kind kind;
8741 void *data;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008742
8743 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008744 PyErr_BadArgument();
8745 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008746 }
8747
Victor Stinner42bf7752011-11-21 22:52:58 +01008748 unicode = PyUnicode_FromUnicode(s, length);
8749 if (unicode == NULL)
8750 return -1;
8751
Benjamin Petersonbac79492012-01-14 13:34:47 -05008752 if (PyUnicode_READY(unicode) == -1) {
Victor Stinner6345be92011-11-25 20:09:01 +01008753 Py_DECREF(unicode);
8754 return -1;
8755 }
Victor Stinner42bf7752011-11-21 22:52:58 +01008756 kind = PyUnicode_KIND(unicode);
8757 data = PyUnicode_DATA(unicode);
8758
Victor Stinnerb84d7232011-11-22 01:50:07 +01008759 for (i=0; i < length; ) {
Victor Stinner6345be92011-11-25 20:09:01 +01008760 PyObject *exc;
8761 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00008762 int decimal;
Victor Stinner6345be92011-11-25 20:09:01 +01008763 Py_ssize_t startpos;
8764
8765 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +00008766
Benjamin Peterson29060642009-01-31 22:14:21 +00008767 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008768 *output++ = ' ';
Victor Stinnerb84d7232011-11-22 01:50:07 +01008769 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00008770 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008771 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008772 decimal = Py_UNICODE_TODECIMAL(ch);
8773 if (decimal >= 0) {
8774 *output++ = '0' + decimal;
Victor Stinnerb84d7232011-11-22 01:50:07 +01008775 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00008776 continue;
8777 }
8778 if (0 < ch && ch < 256) {
8779 *output++ = (char)ch;
Victor Stinnerb84d7232011-11-22 01:50:07 +01008780 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00008781 continue;
8782 }
Victor Stinner6345be92011-11-25 20:09:01 +01008783
Victor Stinner42bf7752011-11-21 22:52:58 +01008784 startpos = i;
Victor Stinner6345be92011-11-25 20:09:01 +01008785 exc = NULL;
8786 raise_encode_exception(&exc, "decimal", unicode,
8787 startpos, startpos+1,
8788 "invalid decimal Unicode string");
8789 Py_XDECREF(exc);
8790 Py_DECREF(unicode);
8791 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008792 }
8793 /* 0-terminate the output string */
8794 *output++ = '\0';
Victor Stinner42bf7752011-11-21 22:52:58 +01008795 Py_DECREF(unicode);
Guido van Rossum9e896b32000-04-05 20:11:21 +00008796 return 0;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008797}
8798
Guido van Rossumd57fd912000-03-10 22:53:23 +00008799/* --- Helpers ------------------------------------------------------------ */
8800
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008801static Py_ssize_t
Victor Stinner794d5672011-10-10 03:21:36 +02008802any_find_slice(int direction, PyObject* s1, PyObject* s2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008803 Py_ssize_t start,
8804 Py_ssize_t end)
8805{
8806 int kind1, kind2, kind;
8807 void *buf1, *buf2;
8808 Py_ssize_t len1, len2, result;
8809
8810 kind1 = PyUnicode_KIND(s1);
8811 kind2 = PyUnicode_KIND(s2);
8812 kind = kind1 > kind2 ? kind1 : kind2;
8813 buf1 = PyUnicode_DATA(s1);
8814 buf2 = PyUnicode_DATA(s2);
8815 if (kind1 != kind)
8816 buf1 = _PyUnicode_AsKind(s1, kind);
8817 if (!buf1)
8818 return -2;
8819 if (kind2 != kind)
8820 buf2 = _PyUnicode_AsKind(s2, kind);
8821 if (!buf2) {
8822 if (kind1 != kind) PyMem_Free(buf1);
8823 return -2;
8824 }
8825 len1 = PyUnicode_GET_LENGTH(s1);
8826 len2 = PyUnicode_GET_LENGTH(s2);
8827
Victor Stinner794d5672011-10-10 03:21:36 +02008828 if (direction > 0) {
Benjamin Petersonead6b532011-12-20 17:23:42 -06008829 switch (kind) {
Victor Stinner794d5672011-10-10 03:21:36 +02008830 case PyUnicode_1BYTE_KIND:
8831 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
8832 result = asciilib_find_slice(buf1, len1, buf2, len2, start, end);
8833 else
8834 result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end);
8835 break;
8836 case PyUnicode_2BYTE_KIND:
8837 result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end);
8838 break;
8839 case PyUnicode_4BYTE_KIND:
8840 result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end);
8841 break;
8842 default:
8843 assert(0); result = -2;
8844 }
8845 }
8846 else {
Benjamin Petersonead6b532011-12-20 17:23:42 -06008847 switch (kind) {
Victor Stinner794d5672011-10-10 03:21:36 +02008848 case PyUnicode_1BYTE_KIND:
8849 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
8850 result = asciilib_rfind_slice(buf1, len1, buf2, len2, start, end);
8851 else
8852 result = ucs1lib_rfind_slice(buf1, len1, buf2, len2, start, end);
8853 break;
8854 case PyUnicode_2BYTE_KIND:
8855 result = ucs2lib_rfind_slice(buf1, len1, buf2, len2, start, end);
8856 break;
8857 case PyUnicode_4BYTE_KIND:
8858 result = ucs4lib_rfind_slice(buf1, len1, buf2, len2, start, end);
8859 break;
8860 default:
8861 assert(0); result = -2;
8862 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008863 }
8864
8865 if (kind1 != kind)
8866 PyMem_Free(buf1);
8867 if (kind2 != kind)
8868 PyMem_Free(buf2);
8869
8870 return result;
8871}
8872
8873Py_ssize_t
Victor Stinner41a863c2012-02-24 00:37:51 +01008874_PyUnicode_InsertThousandsGrouping(
8875 PyObject *unicode, Py_ssize_t index,
8876 Py_ssize_t n_buffer,
8877 void *digits, Py_ssize_t n_digits,
8878 Py_ssize_t min_width,
8879 const char *grouping, PyObject *thousands_sep,
8880 Py_UCS4 *maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008881{
Victor Stinner41a863c2012-02-24 00:37:51 +01008882 unsigned int kind, thousands_sep_kind;
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008883 char *data, *thousands_sep_data;
Victor Stinner41a863c2012-02-24 00:37:51 +01008884 Py_ssize_t thousands_sep_len;
8885 Py_ssize_t len;
8886
8887 if (unicode != NULL) {
8888 kind = PyUnicode_KIND(unicode);
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008889 data = (char *) PyUnicode_DATA(unicode) + index * kind;
Victor Stinner41a863c2012-02-24 00:37:51 +01008890 }
8891 else {
8892 kind = PyUnicode_1BYTE_KIND;
8893 data = NULL;
8894 }
8895 thousands_sep_kind = PyUnicode_KIND(thousands_sep);
8896 thousands_sep_data = PyUnicode_DATA(thousands_sep);
8897 thousands_sep_len = PyUnicode_GET_LENGTH(thousands_sep);
8898 if (unicode != NULL && thousands_sep_kind != kind) {
Victor Stinner90f50d42012-02-24 01:44:47 +01008899 if (thousands_sep_kind < kind) {
8900 thousands_sep_data = _PyUnicode_AsKind(thousands_sep, kind);
8901 if (!thousands_sep_data)
8902 return -1;
8903 }
8904 else {
8905 data = _PyUnicode_AsKind(unicode, thousands_sep_kind);
8906 if (!data)
8907 return -1;
8908 }
Victor Stinner41a863c2012-02-24 00:37:51 +01008909 }
8910
Benjamin Petersonead6b532011-12-20 17:23:42 -06008911 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008912 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02008913 if (unicode != NULL && PyUnicode_IS_ASCII(unicode))
Victor Stinner41a863c2012-02-24 00:37:51 +01008914 len = asciilib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008915 (Py_UCS1 *) data, n_buffer, (Py_UCS1 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01008916 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008917 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinnerc3cec782011-10-05 21:24:08 +02008918 else
Victor Stinner41a863c2012-02-24 00:37:51 +01008919 len = ucs1lib_InsertThousandsGrouping(
Victor Stinnerc3cec782011-10-05 21:24:08 +02008920 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01008921 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008922 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01008923 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008924 case PyUnicode_2BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01008925 len = ucs2lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008926 (Py_UCS2 *) data, n_buffer, (Py_UCS2 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01008927 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008928 (Py_UCS2 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01008929 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008930 case PyUnicode_4BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01008931 len = ucs4lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008932 (Py_UCS4 *) data, n_buffer, (Py_UCS4 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01008933 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008934 (Py_UCS4 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01008935 break;
8936 default:
8937 assert(0);
8938 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008939 }
Victor Stinner90f50d42012-02-24 01:44:47 +01008940 if (unicode != NULL && thousands_sep_kind != kind) {
8941 if (thousands_sep_kind < kind)
8942 PyMem_Free(thousands_sep_data);
8943 else
8944 PyMem_Free(data);
8945 }
Victor Stinner41a863c2012-02-24 00:37:51 +01008946 if (unicode == NULL) {
8947 *maxchar = 127;
8948 if (len != n_digits) {
Victor Stinnere6abb482012-05-02 01:15:40 +02008949 *maxchar = MAX_MAXCHAR(*maxchar,
8950 PyUnicode_MAX_CHAR_VALUE(thousands_sep));
Victor Stinner41a863c2012-02-24 00:37:51 +01008951 }
8952 }
8953 return len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008954}
8955
8956
Thomas Wouters477c8d52006-05-27 19:21:47 +00008957/* helper macro to fixup start/end slice values */
Antoine Pitrouf2c54842010-01-13 08:07:53 +00008958#define ADJUST_INDICES(start, end, len) \
8959 if (end > len) \
8960 end = len; \
8961 else if (end < 0) { \
8962 end += len; \
8963 if (end < 0) \
8964 end = 0; \
8965 } \
8966 if (start < 0) { \
8967 start += len; \
8968 if (start < 0) \
8969 start = 0; \
8970 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00008971
Alexander Belopolsky40018472011-02-26 01:02:56 +00008972Py_ssize_t
8973PyUnicode_Count(PyObject *str,
8974 PyObject *substr,
8975 Py_ssize_t start,
8976 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008977{
Martin v. Löwis18e16552006-02-15 17:27:45 +00008978 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02008979 PyObject* str_obj;
8980 PyObject* sub_obj;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008981 int kind1, kind2, kind;
8982 void *buf1 = NULL, *buf2 = NULL;
8983 Py_ssize_t len1, len2;
Tim Petersced69f82003-09-16 20:30:58 +00008984
Victor Stinner9db1a8b2011-10-23 20:04:37 +02008985 str_obj = PyUnicode_FromObject(str);
Benjamin Peterson22a29702012-01-02 09:00:30 -06008986 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +00008987 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02008988 sub_obj = PyUnicode_FromObject(substr);
Benjamin Peterson22a29702012-01-02 09:00:30 -06008989 if (!sub_obj) {
8990 Py_DECREF(str_obj);
8991 return -1;
8992 }
Benjamin Peterson4c13a4a2012-01-02 09:07:38 -06008993 if (PyUnicode_READY(sub_obj) == -1 || PyUnicode_READY(str_obj) == -1) {
Benjamin Peterson5e458f52012-01-02 10:12:13 -06008994 Py_DECREF(sub_obj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008995 Py_DECREF(str_obj);
8996 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008997 }
Tim Petersced69f82003-09-16 20:30:58 +00008998
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008999 kind1 = PyUnicode_KIND(str_obj);
9000 kind2 = PyUnicode_KIND(sub_obj);
Antoine Pitroue45c0c52012-05-12 15:49:07 +02009001 kind = kind1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009002 buf1 = PyUnicode_DATA(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009003 buf2 = PyUnicode_DATA(sub_obj);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -05009004 if (kind2 != kind) {
Antoine Pitrou758153b2012-05-12 15:51:51 +02009005 if (kind2 > kind) {
9006 Py_DECREF(sub_obj);
9007 Py_DECREF(str_obj);
Antoine Pitroue45c0c52012-05-12 15:49:07 +02009008 return 0;
Antoine Pitrou758153b2012-05-12 15:51:51 +02009009 }
Victor Stinner7931d9a2011-11-04 00:22:48 +01009010 buf2 = _PyUnicode_AsKind(sub_obj, kind);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -05009011 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009012 if (!buf2)
9013 goto onError;
9014 len1 = PyUnicode_GET_LENGTH(str_obj);
9015 len2 = PyUnicode_GET_LENGTH(sub_obj);
9016
9017 ADJUST_INDICES(start, end, len1);
Benjamin Petersonead6b532011-12-20 17:23:42 -06009018 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009019 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009020 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sub_obj))
9021 result = asciilib_count(
9022 ((Py_UCS1*)buf1) + start, end - start,
9023 buf2, len2, PY_SSIZE_T_MAX
9024 );
9025 else
9026 result = ucs1lib_count(
9027 ((Py_UCS1*)buf1) + start, end - start,
9028 buf2, len2, PY_SSIZE_T_MAX
9029 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009030 break;
9031 case PyUnicode_2BYTE_KIND:
9032 result = ucs2lib_count(
9033 ((Py_UCS2*)buf1) + start, end - start,
9034 buf2, len2, PY_SSIZE_T_MAX
9035 );
9036 break;
9037 case PyUnicode_4BYTE_KIND:
9038 result = ucs4lib_count(
9039 ((Py_UCS4*)buf1) + start, end - start,
9040 buf2, len2, PY_SSIZE_T_MAX
9041 );
9042 break;
9043 default:
9044 assert(0); result = 0;
9045 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009046
9047 Py_DECREF(sub_obj);
9048 Py_DECREF(str_obj);
9049
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009050 if (kind2 != kind)
9051 PyMem_Free(buf2);
9052
Guido van Rossumd57fd912000-03-10 22:53:23 +00009053 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009054 onError:
9055 Py_DECREF(sub_obj);
9056 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009057 if (kind2 != kind && buf2)
9058 PyMem_Free(buf2);
9059 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009060}
9061
Alexander Belopolsky40018472011-02-26 01:02:56 +00009062Py_ssize_t
9063PyUnicode_Find(PyObject *str,
9064 PyObject *sub,
9065 Py_ssize_t start,
9066 Py_ssize_t end,
9067 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009068{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009069 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009070
Guido van Rossumd57fd912000-03-10 22:53:23 +00009071 str = PyUnicode_FromObject(str);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009072 if (!str)
Benjamin Peterson29060642009-01-31 22:14:21 +00009073 return -2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009074 sub = PyUnicode_FromObject(sub);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009075 if (!sub) {
9076 Py_DECREF(str);
9077 return -2;
9078 }
9079 if (PyUnicode_READY(sub) == -1 || PyUnicode_READY(str) == -1) {
9080 Py_DECREF(sub);
Benjamin Peterson29060642009-01-31 22:14:21 +00009081 Py_DECREF(str);
9082 return -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009083 }
Tim Petersced69f82003-09-16 20:30:58 +00009084
Victor Stinner794d5672011-10-10 03:21:36 +02009085 result = any_find_slice(direction,
9086 str, sub, start, end
9087 );
Thomas Wouters477c8d52006-05-27 19:21:47 +00009088
Guido van Rossumd57fd912000-03-10 22:53:23 +00009089 Py_DECREF(str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009090 Py_DECREF(sub);
9091
Guido van Rossumd57fd912000-03-10 22:53:23 +00009092 return result;
9093}
9094
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009095Py_ssize_t
9096PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
9097 Py_ssize_t start, Py_ssize_t end,
9098 int direction)
9099{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009100 int kind;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009101 Py_ssize_t result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009102 if (PyUnicode_READY(str) == -1)
9103 return -2;
Victor Stinner267aa242011-10-02 01:08:37 +02009104 if (start < 0 || end < 0) {
9105 PyErr_SetString(PyExc_IndexError, "string index out of range");
9106 return -2;
9107 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009108 if (end > PyUnicode_GET_LENGTH(str))
9109 end = PyUnicode_GET_LENGTH(str);
9110 kind = PyUnicode_KIND(str);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009111 result = findchar(PyUnicode_1BYTE_DATA(str) + kind*start,
9112 kind, end-start, ch, direction);
9113 if (result == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009114 return -1;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009115 else
9116 return start + result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009117}
9118
Alexander Belopolsky40018472011-02-26 01:02:56 +00009119static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009120tailmatch(PyObject *self,
9121 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009122 Py_ssize_t start,
9123 Py_ssize_t end,
9124 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009125{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009126 int kind_self;
9127 int kind_sub;
9128 void *data_self;
9129 void *data_sub;
9130 Py_ssize_t offset;
9131 Py_ssize_t i;
9132 Py_ssize_t end_sub;
9133
9134 if (PyUnicode_READY(self) == -1 ||
9135 PyUnicode_READY(substring) == -1)
9136 return 0;
9137
9138 if (PyUnicode_GET_LENGTH(substring) == 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009139 return 1;
9140
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009141 ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
9142 end -= PyUnicode_GET_LENGTH(substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009143 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00009144 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009145
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009146 kind_self = PyUnicode_KIND(self);
9147 data_self = PyUnicode_DATA(self);
9148 kind_sub = PyUnicode_KIND(substring);
9149 data_sub = PyUnicode_DATA(substring);
9150 end_sub = PyUnicode_GET_LENGTH(substring) - 1;
9151
9152 if (direction > 0)
9153 offset = end;
9154 else
9155 offset = start;
9156
9157 if (PyUnicode_READ(kind_self, data_self, offset) ==
9158 PyUnicode_READ(kind_sub, data_sub, 0) &&
9159 PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
9160 PyUnicode_READ(kind_sub, data_sub, end_sub)) {
9161 /* If both are of the same kind, memcmp is sufficient */
9162 if (kind_self == kind_sub) {
9163 return ! memcmp((char *)data_self +
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009164 (offset * PyUnicode_KIND(substring)),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009165 data_sub,
9166 PyUnicode_GET_LENGTH(substring) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009167 PyUnicode_KIND(substring));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009168 }
9169 /* otherwise we have to compare each character by first accesing it */
9170 else {
9171 /* We do not need to compare 0 and len(substring)-1 because
9172 the if statement above ensured already that they are equal
9173 when we end up here. */
Antoine Pitrou057119b2012-09-02 17:56:33 +02009174 /* TODO: honor direction and do a forward or backwards search */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009175 for (i = 1; i < end_sub; ++i) {
9176 if (PyUnicode_READ(kind_self, data_self, offset + i) !=
9177 PyUnicode_READ(kind_sub, data_sub, i))
9178 return 0;
9179 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009180 return 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009181 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009182 }
9183
9184 return 0;
9185}
9186
Alexander Belopolsky40018472011-02-26 01:02:56 +00009187Py_ssize_t
9188PyUnicode_Tailmatch(PyObject *str,
9189 PyObject *substr,
9190 Py_ssize_t start,
9191 Py_ssize_t end,
9192 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009193{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009194 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009195
Guido van Rossumd57fd912000-03-10 22:53:23 +00009196 str = PyUnicode_FromObject(str);
9197 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009198 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009199 substr = PyUnicode_FromObject(substr);
9200 if (substr == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009201 Py_DECREF(str);
9202 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009203 }
Tim Petersced69f82003-09-16 20:30:58 +00009204
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009205 result = tailmatch(str, substr,
Benjamin Peterson29060642009-01-31 22:14:21 +00009206 start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009207 Py_DECREF(str);
9208 Py_DECREF(substr);
9209 return result;
9210}
9211
Guido van Rossumd57fd912000-03-10 22:53:23 +00009212/* Apply fixfct filter to the Unicode object self and return a
9213 reference to the modified object */
9214
Alexander Belopolsky40018472011-02-26 01:02:56 +00009215static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009216fixup(PyObject *self,
9217 Py_UCS4 (*fixfct)(PyObject *s))
Guido van Rossumd57fd912000-03-10 22:53:23 +00009218{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009219 PyObject *u;
9220 Py_UCS4 maxchar_old, maxchar_new = 0;
Victor Stinnereaab6042011-12-11 22:22:39 +01009221 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009222
Victor Stinnerbf6e5602011-12-12 01:53:47 +01009223 u = _PyUnicode_Copy(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009224 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009225 return NULL;
Victor Stinner87af4f22011-11-21 23:03:47 +01009226 maxchar_old = PyUnicode_MAX_CHAR_VALUE(u);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009227
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009228 /* fix functions return the new maximum character in a string,
9229 if the kind of the resulting unicode object does not change,
9230 everything is fine. Otherwise we need to change the string kind
9231 and re-run the fix function. */
Victor Stinner9310abb2011-10-05 00:59:23 +02009232 maxchar_new = fixfct(u);
Victor Stinnereaab6042011-12-11 22:22:39 +01009233
9234 if (maxchar_new == 0) {
9235 /* no changes */;
9236 if (PyUnicode_CheckExact(self)) {
9237 Py_DECREF(u);
9238 Py_INCREF(self);
9239 return self;
9240 }
9241 else
9242 return u;
9243 }
9244
Victor Stinnere6abb482012-05-02 01:15:40 +02009245 maxchar_new = align_maxchar(maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009246
Victor Stinnereaab6042011-12-11 22:22:39 +01009247 if (maxchar_new == maxchar_old)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009248 return u;
Victor Stinnereaab6042011-12-11 22:22:39 +01009249
9250 /* In case the maximum character changed, we need to
9251 convert the string to the new category. */
9252 v = PyUnicode_New(PyUnicode_GET_LENGTH(self), maxchar_new);
9253 if (v == NULL) {
9254 Py_DECREF(u);
9255 return NULL;
9256 }
9257 if (maxchar_new > maxchar_old) {
9258 /* If the maxchar increased so that the kind changed, not all
9259 characters are representable anymore and we need to fix the
9260 string again. This only happens in very few cases. */
Victor Stinnerd3f08822012-05-29 12:57:52 +02009261 _PyUnicode_FastCopyCharacters(v, 0,
9262 self, 0, PyUnicode_GET_LENGTH(self));
Victor Stinnereaab6042011-12-11 22:22:39 +01009263 maxchar_old = fixfct(v);
9264 assert(maxchar_old > 0 && maxchar_old <= maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009265 }
9266 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02009267 _PyUnicode_FastCopyCharacters(v, 0,
9268 u, 0, PyUnicode_GET_LENGTH(self));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009269 }
Victor Stinnereaab6042011-12-11 22:22:39 +01009270 Py_DECREF(u);
9271 assert(_PyUnicode_CheckConsistency(v, 1));
9272 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009273}
9274
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009275static PyObject *
9276ascii_upper_or_lower(PyObject *self, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009277{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009278 Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9279 char *resdata, *data = PyUnicode_DATA(self);
9280 PyObject *res;
Tim Petersced69f82003-09-16 20:30:58 +00009281
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009282 res = PyUnicode_New(len, 127);
9283 if (res == NULL)
9284 return NULL;
9285 resdata = PyUnicode_DATA(res);
9286 if (lower)
9287 _Py_bytes_lower(resdata, data, len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009288 else
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009289 _Py_bytes_upper(resdata, data, len);
9290 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009291}
9292
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009293static Py_UCS4
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009294handle_capital_sigma(int kind, void *data, Py_ssize_t length, Py_ssize_t i)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009295{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009296 Py_ssize_t j;
9297 int final_sigma;
9298 Py_UCS4 c;
9299 /* U+03A3 is in the Final_Sigma context when, it is found like this:
Tim Petersced69f82003-09-16 20:30:58 +00009300
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009301 \p{cased}\p{case-ignorable}*U+03A3!(\p{case-ignorable}*\p{cased})
9302
9303 where ! is a negation and \p{xxx} is a character with property xxx.
9304 */
9305 for (j = i - 1; j >= 0; j--) {
9306 c = PyUnicode_READ(kind, data, j);
9307 if (!_PyUnicode_IsCaseIgnorable(c))
9308 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009309 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009310 final_sigma = j >= 0 && _PyUnicode_IsCased(c);
9311 if (final_sigma) {
9312 for (j = i + 1; j < length; j++) {
9313 c = PyUnicode_READ(kind, data, j);
9314 if (!_PyUnicode_IsCaseIgnorable(c))
9315 break;
9316 }
9317 final_sigma = j == length || !_PyUnicode_IsCased(c);
9318 }
9319 return (final_sigma) ? 0x3C2 : 0x3C3;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009320}
9321
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009322static int
9323lower_ucs4(int kind, void *data, Py_ssize_t length, Py_ssize_t i,
9324 Py_UCS4 c, Py_UCS4 *mapped)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009325{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009326 /* Obscure special case. */
9327 if (c == 0x3A3) {
9328 mapped[0] = handle_capital_sigma(kind, data, length, i);
9329 return 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009330 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009331 return _PyUnicode_ToLowerFull(c, mapped);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009332}
9333
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009334static Py_ssize_t
9335do_capitalize(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009336{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009337 Py_ssize_t i, k = 0;
9338 int n_res, j;
9339 Py_UCS4 c, mapped[3];
Tim Petersced69f82003-09-16 20:30:58 +00009340
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009341 c = PyUnicode_READ(kind, data, 0);
9342 n_res = _PyUnicode_ToUpperFull(c, mapped);
9343 for (j = 0; j < n_res; j++) {
Victor Stinnere6abb482012-05-02 01:15:40 +02009344 *maxchar = MAX_MAXCHAR(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009345 res[k++] = mapped[j];
Guido van Rossumd57fd912000-03-10 22:53:23 +00009346 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009347 for (i = 1; i < length; i++) {
9348 c = PyUnicode_READ(kind, data, i);
9349 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9350 for (j = 0; j < n_res; j++) {
Victor Stinnere6abb482012-05-02 01:15:40 +02009351 *maxchar = MAX_MAXCHAR(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009352 res[k++] = mapped[j];
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009353 }
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009354 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009355 return k;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009356}
9357
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009358static Py_ssize_t
9359do_swapcase(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar) {
9360 Py_ssize_t i, k = 0;
9361
9362 for (i = 0; i < length; i++) {
9363 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9364 int n_res, j;
9365 if (Py_UNICODE_ISUPPER(c)) {
9366 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9367 }
9368 else if (Py_UNICODE_ISLOWER(c)) {
9369 n_res = _PyUnicode_ToUpperFull(c, mapped);
9370 }
9371 else {
9372 n_res = 1;
9373 mapped[0] = c;
9374 }
9375 for (j = 0; j < n_res; j++) {
Victor Stinnere6abb482012-05-02 01:15:40 +02009376 *maxchar = MAX_MAXCHAR(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009377 res[k++] = mapped[j];
9378 }
9379 }
9380 return k;
9381}
9382
9383static Py_ssize_t
9384do_upper_or_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res,
9385 Py_UCS4 *maxchar, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009386{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009387 Py_ssize_t i, k = 0;
9388
9389 for (i = 0; i < length; i++) {
9390 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9391 int n_res, j;
9392 if (lower)
9393 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9394 else
9395 n_res = _PyUnicode_ToUpperFull(c, mapped);
9396 for (j = 0; j < n_res; j++) {
Victor Stinnere6abb482012-05-02 01:15:40 +02009397 *maxchar = MAX_MAXCHAR(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009398 res[k++] = mapped[j];
9399 }
9400 }
9401 return k;
9402}
9403
9404static Py_ssize_t
9405do_upper(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9406{
9407 return do_upper_or_lower(kind, data, length, res, maxchar, 0);
9408}
9409
9410static Py_ssize_t
9411do_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9412{
9413 return do_upper_or_lower(kind, data, length, res, maxchar, 1);
9414}
9415
Benjamin Petersone51757f2012-01-12 21:10:29 -05009416static Py_ssize_t
Benjamin Petersond5890c82012-01-14 13:23:30 -05009417do_casefold(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9418{
9419 Py_ssize_t i, k = 0;
9420
9421 for (i = 0; i < length; i++) {
9422 Py_UCS4 c = PyUnicode_READ(kind, data, i);
9423 Py_UCS4 mapped[3];
9424 int j, n_res = _PyUnicode_ToFoldedFull(c, mapped);
9425 for (j = 0; j < n_res; j++) {
Victor Stinnere6abb482012-05-02 01:15:40 +02009426 *maxchar = MAX_MAXCHAR(*maxchar, mapped[j]);
Benjamin Petersond5890c82012-01-14 13:23:30 -05009427 res[k++] = mapped[j];
9428 }
9429 }
9430 return k;
9431}
9432
9433static Py_ssize_t
Benjamin Petersone51757f2012-01-12 21:10:29 -05009434do_title(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9435{
9436 Py_ssize_t i, k = 0;
9437 int previous_is_cased;
9438
9439 previous_is_cased = 0;
9440 for (i = 0; i < length; i++) {
9441 const Py_UCS4 c = PyUnicode_READ(kind, data, i);
9442 Py_UCS4 mapped[3];
9443 int n_res, j;
9444
9445 if (previous_is_cased)
9446 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9447 else
9448 n_res = _PyUnicode_ToTitleFull(c, mapped);
9449
9450 for (j = 0; j < n_res; j++) {
Victor Stinnere6abb482012-05-02 01:15:40 +02009451 *maxchar = MAX_MAXCHAR(*maxchar, mapped[j]);
Benjamin Petersone51757f2012-01-12 21:10:29 -05009452 res[k++] = mapped[j];
9453 }
9454
9455 previous_is_cased = _PyUnicode_IsCased(c);
9456 }
9457 return k;
9458}
9459
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009460static PyObject *
9461case_operation(PyObject *self,
9462 Py_ssize_t (*perform)(int, void *, Py_ssize_t, Py_UCS4 *, Py_UCS4 *))
9463{
9464 PyObject *res = NULL;
9465 Py_ssize_t length, newlength = 0;
9466 int kind, outkind;
9467 void *data, *outdata;
9468 Py_UCS4 maxchar = 0, *tmp, *tmpend;
9469
Benjamin Petersoneea48462012-01-16 14:28:50 -05009470 assert(PyUnicode_IS_READY(self));
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009471
9472 kind = PyUnicode_KIND(self);
9473 data = PyUnicode_DATA(self);
9474 length = PyUnicode_GET_LENGTH(self);
9475 tmp = PyMem_MALLOC(sizeof(Py_UCS4) * 3 * length);
9476 if (tmp == NULL)
9477 return PyErr_NoMemory();
9478 newlength = perform(kind, data, length, tmp, &maxchar);
9479 res = PyUnicode_New(newlength, maxchar);
9480 if (res == NULL)
9481 goto leave;
9482 tmpend = tmp + newlength;
9483 outdata = PyUnicode_DATA(res);
9484 outkind = PyUnicode_KIND(res);
9485 switch (outkind) {
9486 case PyUnicode_1BYTE_KIND:
9487 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, tmp, tmpend, outdata);
9488 break;
9489 case PyUnicode_2BYTE_KIND:
9490 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, tmp, tmpend, outdata);
9491 break;
9492 case PyUnicode_4BYTE_KIND:
9493 memcpy(outdata, tmp, sizeof(Py_UCS4) * newlength);
9494 break;
9495 default:
9496 assert(0);
9497 break;
9498 }
9499 leave:
9500 PyMem_FREE(tmp);
9501 return res;
9502}
9503
Tim Peters8ce9f162004-08-27 01:49:32 +00009504PyObject *
9505PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009506{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009507 PyObject *sep = NULL;
Victor Stinnerdd077322011-10-07 17:02:31 +02009508 Py_ssize_t seplen;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009509 PyObject *res = NULL; /* the result */
Tim Peters05eba1f2004-08-27 21:32:02 +00009510 PyObject *fseq; /* PySequence_Fast(seq) */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009511 Py_ssize_t seqlen; /* len(fseq) -- number of items in sequence */
9512 PyObject **items;
Tim Peters8ce9f162004-08-27 01:49:32 +00009513 PyObject *item;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009514 Py_ssize_t sz, i, res_offset;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009515 Py_UCS4 maxchar;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009516 Py_UCS4 item_maxchar;
Victor Stinnerdd077322011-10-07 17:02:31 +02009517 int use_memcpy;
9518 unsigned char *res_data = NULL, *sep_data = NULL;
9519 PyObject *last_obj;
9520 unsigned int kind = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009521
Tim Peters05eba1f2004-08-27 21:32:02 +00009522 fseq = PySequence_Fast(seq, "");
9523 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009524 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00009525 }
9526
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009527 /* NOTE: the following code can't call back into Python code,
9528 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00009529 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009530
Tim Peters05eba1f2004-08-27 21:32:02 +00009531 seqlen = PySequence_Fast_GET_SIZE(fseq);
9532 /* If empty sequence, return u"". */
9533 if (seqlen == 0) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009534 Py_DECREF(fseq);
9535 Py_INCREF(unicode_empty);
9536 res = unicode_empty;
9537 return res;
Tim Peters05eba1f2004-08-27 21:32:02 +00009538 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009539
Tim Peters05eba1f2004-08-27 21:32:02 +00009540 /* If singleton sequence with an exact Unicode, return that. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009541 last_obj = NULL;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009542 items = PySequence_Fast_ITEMS(fseq);
Victor Stinneracf47b82011-10-06 12:32:37 +02009543 if (seqlen == 1) {
9544 if (PyUnicode_CheckExact(items[0])) {
9545 res = items[0];
9546 Py_INCREF(res);
9547 Py_DECREF(fseq);
9548 return res;
9549 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009550 seplen = 0;
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009551 maxchar = 0;
Tim Peters8ce9f162004-08-27 01:49:32 +00009552 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009553 else {
Victor Stinneracf47b82011-10-06 12:32:37 +02009554 /* Set up sep and seplen */
9555 if (separator == NULL) {
9556 /* fall back to a blank space separator */
9557 sep = PyUnicode_FromOrdinal(' ');
9558 if (!sep)
9559 goto onError;
Victor Stinnerdd077322011-10-07 17:02:31 +02009560 seplen = 1;
Victor Stinneracf47b82011-10-06 12:32:37 +02009561 maxchar = 32;
Tim Peters05eba1f2004-08-27 21:32:02 +00009562 }
Victor Stinneracf47b82011-10-06 12:32:37 +02009563 else {
9564 if (!PyUnicode_Check(separator)) {
9565 PyErr_Format(PyExc_TypeError,
9566 "separator: expected str instance,"
9567 " %.80s found",
9568 Py_TYPE(separator)->tp_name);
9569 goto onError;
9570 }
9571 if (PyUnicode_READY(separator))
9572 goto onError;
9573 sep = separator;
9574 seplen = PyUnicode_GET_LENGTH(separator);
9575 maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
9576 /* inc refcount to keep this code path symmetric with the
9577 above case of a blank separator */
9578 Py_INCREF(sep);
9579 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009580 last_obj = sep;
Tim Peters05eba1f2004-08-27 21:32:02 +00009581 }
9582
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009583 /* There are at least two things to join, or else we have a subclass
9584 * of str in the sequence.
9585 * Do a pre-pass to figure out the total amount of space we'll
9586 * need (sz), and see whether all argument are strings.
9587 */
9588 sz = 0;
Victor Stinnerdd077322011-10-07 17:02:31 +02009589#ifdef Py_DEBUG
9590 use_memcpy = 0;
9591#else
9592 use_memcpy = 1;
9593#endif
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009594 for (i = 0; i < seqlen; i++) {
9595 const Py_ssize_t old_sz = sz;
9596 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009597 if (!PyUnicode_Check(item)) {
9598 PyErr_Format(PyExc_TypeError,
9599 "sequence item %zd: expected str instance,"
9600 " %.80s found",
9601 i, Py_TYPE(item)->tp_name);
9602 goto onError;
9603 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009604 if (PyUnicode_READY(item) == -1)
9605 goto onError;
9606 sz += PyUnicode_GET_LENGTH(item);
9607 item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
Victor Stinnere6abb482012-05-02 01:15:40 +02009608 maxchar = MAX_MAXCHAR(maxchar, item_maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009609 if (i != 0)
9610 sz += seplen;
9611 if (sz < old_sz || sz > PY_SSIZE_T_MAX) {
9612 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009613 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009614 goto onError;
9615 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009616 if (use_memcpy && last_obj != NULL) {
9617 if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
9618 use_memcpy = 0;
9619 }
9620 last_obj = item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009621 }
Tim Petersced69f82003-09-16 20:30:58 +00009622
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009623 res = PyUnicode_New(sz, maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009624 if (res == NULL)
9625 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +00009626
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009627 /* Catenate everything. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009628#ifdef Py_DEBUG
9629 use_memcpy = 0;
9630#else
9631 if (use_memcpy) {
9632 res_data = PyUnicode_1BYTE_DATA(res);
9633 kind = PyUnicode_KIND(res);
9634 if (seplen != 0)
9635 sep_data = PyUnicode_1BYTE_DATA(sep);
9636 }
9637#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009638 for (i = 0, res_offset = 0; i < seqlen; ++i) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009639 Py_ssize_t itemlen;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009640 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009641 /* Copy item, and maybe the separator. */
Victor Stinner9ce5a832011-10-03 23:36:02 +02009642 if (i && seplen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009643 if (use_memcpy) {
9644 Py_MEMCPY(res_data,
9645 sep_data,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009646 kind * seplen);
9647 res_data += kind * seplen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009648 }
9649 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02009650 _PyUnicode_FastCopyCharacters(res, res_offset, sep, 0, seplen);
Victor Stinnerdd077322011-10-07 17:02:31 +02009651 res_offset += seplen;
9652 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009653 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009654 itemlen = PyUnicode_GET_LENGTH(item);
9655 if (itemlen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009656 if (use_memcpy) {
9657 Py_MEMCPY(res_data,
9658 PyUnicode_DATA(item),
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009659 kind * itemlen);
9660 res_data += kind * itemlen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009661 }
9662 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02009663 _PyUnicode_FastCopyCharacters(res, res_offset, item, 0, itemlen);
Victor Stinnerdd077322011-10-07 17:02:31 +02009664 res_offset += itemlen;
9665 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009666 }
Tim Peters05eba1f2004-08-27 21:32:02 +00009667 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009668 if (use_memcpy)
9669 assert(res_data == PyUnicode_1BYTE_DATA(res)
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009670 + kind * PyUnicode_GET_LENGTH(res));
Victor Stinnerdd077322011-10-07 17:02:31 +02009671 else
9672 assert(res_offset == PyUnicode_GET_LENGTH(res));
Tim Peters8ce9f162004-08-27 01:49:32 +00009673
Tim Peters05eba1f2004-08-27 21:32:02 +00009674 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009675 Py_XDECREF(sep);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009676 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009677 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009678
Benjamin Peterson29060642009-01-31 22:14:21 +00009679 onError:
Tim Peters05eba1f2004-08-27 21:32:02 +00009680 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009681 Py_XDECREF(sep);
Tim Peters8ce9f162004-08-27 01:49:32 +00009682 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009683 return NULL;
9684}
9685
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009686#define FILL(kind, data, value, start, length) \
9687 do { \
9688 Py_ssize_t i_ = 0; \
9689 assert(kind != PyUnicode_WCHAR_KIND); \
9690 switch ((kind)) { \
9691 case PyUnicode_1BYTE_KIND: { \
9692 unsigned char * to_ = (unsigned char *)((data)) + (start); \
Victor Stinnerf2c76aa2012-05-03 13:10:40 +02009693 memset(to_, (unsigned char)value, (length)); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009694 break; \
9695 } \
9696 case PyUnicode_2BYTE_KIND: { \
9697 Py_UCS2 * to_ = (Py_UCS2 *)((data)) + (start); \
9698 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9699 break; \
9700 } \
Benjamin Petersone157cf12012-01-01 15:56:20 -06009701 case PyUnicode_4BYTE_KIND: { \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009702 Py_UCS4 * to_ = (Py_UCS4 *)((data)) + (start); \
9703 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9704 break; \
Benjamin Petersone157cf12012-01-01 15:56:20 -06009705 default: assert(0); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009706 } \
9707 } \
9708 } while (0)
9709
Victor Stinnerd3f08822012-05-29 12:57:52 +02009710void
9711_PyUnicode_FastFill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
9712 Py_UCS4 fill_char)
9713{
9714 const enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
9715 const void *data = PyUnicode_DATA(unicode);
9716 assert(PyUnicode_IS_READY(unicode));
9717 assert(unicode_modifiable(unicode));
9718 assert(fill_char <= PyUnicode_MAX_CHAR_VALUE(unicode));
9719 assert(start >= 0);
9720 assert(start + length <= PyUnicode_GET_LENGTH(unicode));
9721 FILL(kind, data, fill_char, start, length);
9722}
9723
Victor Stinner3fe55312012-01-04 00:33:50 +01009724Py_ssize_t
9725PyUnicode_Fill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
9726 Py_UCS4 fill_char)
9727{
9728 Py_ssize_t maxlen;
Victor Stinner3fe55312012-01-04 00:33:50 +01009729
9730 if (!PyUnicode_Check(unicode)) {
9731 PyErr_BadInternalCall();
9732 return -1;
9733 }
9734 if (PyUnicode_READY(unicode) == -1)
9735 return -1;
9736 if (unicode_check_modifiable(unicode))
9737 return -1;
9738
Victor Stinnerd3f08822012-05-29 12:57:52 +02009739 if (start < 0) {
9740 PyErr_SetString(PyExc_IndexError, "string index out of range");
9741 return -1;
9742 }
Victor Stinner3fe55312012-01-04 00:33:50 +01009743 if (fill_char > PyUnicode_MAX_CHAR_VALUE(unicode)) {
9744 PyErr_SetString(PyExc_ValueError,
9745 "fill character is bigger than "
9746 "the string maximum character");
9747 return -1;
9748 }
9749
9750 maxlen = PyUnicode_GET_LENGTH(unicode) - start;
9751 length = Py_MIN(maxlen, length);
9752 if (length <= 0)
9753 return 0;
9754
Victor Stinnerd3f08822012-05-29 12:57:52 +02009755 _PyUnicode_FastFill(unicode, start, length, fill_char);
Victor Stinner3fe55312012-01-04 00:33:50 +01009756 return length;
9757}
9758
Victor Stinner9310abb2011-10-05 00:59:23 +02009759static PyObject *
9760pad(PyObject *self,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009761 Py_ssize_t left,
9762 Py_ssize_t right,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009763 Py_UCS4 fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009764{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009765 PyObject *u;
9766 Py_UCS4 maxchar;
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009767 int kind;
9768 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009769
9770 if (left < 0)
9771 left = 0;
9772 if (right < 0)
9773 right = 0;
9774
Victor Stinnerc4b49542011-12-11 22:44:26 +01009775 if (left == 0 && right == 0)
9776 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009777
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009778 if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
9779 right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +00009780 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
9781 return NULL;
9782 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009783 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Victor Stinnere6abb482012-05-02 01:15:40 +02009784 maxchar = MAX_MAXCHAR(maxchar, fill);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009785 u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009786 if (!u)
9787 return NULL;
9788
9789 kind = PyUnicode_KIND(u);
9790 data = PyUnicode_DATA(u);
9791 if (left)
9792 FILL(kind, data, fill, 0, left);
9793 if (right)
9794 FILL(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
Victor Stinnerd3f08822012-05-29 12:57:52 +02009795 _PyUnicode_FastCopyCharacters(u, left, self, 0, _PyUnicode_LENGTH(self));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009796 assert(_PyUnicode_CheckConsistency(u, 1));
9797 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009798}
9799
Alexander Belopolsky40018472011-02-26 01:02:56 +00009800PyObject *
9801PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009802{
Guido van Rossumd57fd912000-03-10 22:53:23 +00009803 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009804
9805 string = PyUnicode_FromObject(string);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009806 if (string == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009807 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -06009808 if (PyUnicode_READY(string) == -1) {
9809 Py_DECREF(string);
9810 return NULL;
9811 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009812
Benjamin Petersonead6b532011-12-20 17:23:42 -06009813 switch (PyUnicode_KIND(string)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009814 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009815 if (PyUnicode_IS_ASCII(string))
9816 list = asciilib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009817 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009818 PyUnicode_GET_LENGTH(string), keepends);
9819 else
9820 list = ucs1lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009821 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009822 PyUnicode_GET_LENGTH(string), keepends);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009823 break;
9824 case PyUnicode_2BYTE_KIND:
9825 list = ucs2lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009826 string, PyUnicode_2BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009827 PyUnicode_GET_LENGTH(string), keepends);
9828 break;
9829 case PyUnicode_4BYTE_KIND:
9830 list = ucs4lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009831 string, PyUnicode_4BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009832 PyUnicode_GET_LENGTH(string), keepends);
9833 break;
9834 default:
9835 assert(0);
9836 list = 0;
9837 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009838 Py_DECREF(string);
9839 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009840}
9841
Alexander Belopolsky40018472011-02-26 01:02:56 +00009842static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009843split(PyObject *self,
9844 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009845 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009846{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009847 int kind1, kind2, kind;
9848 void *buf1, *buf2;
9849 Py_ssize_t len1, len2;
9850 PyObject* out;
9851
Guido van Rossumd57fd912000-03-10 22:53:23 +00009852 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00009853 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009854
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009855 if (PyUnicode_READY(self) == -1)
9856 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009857
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009858 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -06009859 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009860 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009861 if (PyUnicode_IS_ASCII(self))
9862 return asciilib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009863 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009864 PyUnicode_GET_LENGTH(self), maxcount
9865 );
9866 else
9867 return ucs1lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009868 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009869 PyUnicode_GET_LENGTH(self), maxcount
9870 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009871 case PyUnicode_2BYTE_KIND:
9872 return ucs2lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009873 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009874 PyUnicode_GET_LENGTH(self), maxcount
9875 );
9876 case PyUnicode_4BYTE_KIND:
9877 return ucs4lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009878 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009879 PyUnicode_GET_LENGTH(self), maxcount
9880 );
9881 default:
9882 assert(0);
9883 return NULL;
9884 }
9885
9886 if (PyUnicode_READY(substring) == -1)
9887 return NULL;
9888
9889 kind1 = PyUnicode_KIND(self);
9890 kind2 = PyUnicode_KIND(substring);
9891 kind = kind1 > kind2 ? kind1 : kind2;
9892 buf1 = PyUnicode_DATA(self);
9893 buf2 = PyUnicode_DATA(substring);
9894 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009895 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009896 if (!buf1)
9897 return NULL;
9898 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009899 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009900 if (!buf2) {
9901 if (kind1 != kind) PyMem_Free(buf1);
9902 return NULL;
9903 }
9904 len1 = PyUnicode_GET_LENGTH(self);
9905 len2 = PyUnicode_GET_LENGTH(substring);
9906
Benjamin Petersonead6b532011-12-20 17:23:42 -06009907 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009908 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009909 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
9910 out = asciilib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009911 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +02009912 else
9913 out = ucs1lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009914 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009915 break;
9916 case PyUnicode_2BYTE_KIND:
9917 out = ucs2lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009918 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009919 break;
9920 case PyUnicode_4BYTE_KIND:
9921 out = ucs4lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009922 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009923 break;
9924 default:
9925 out = NULL;
9926 }
9927 if (kind1 != kind)
9928 PyMem_Free(buf1);
9929 if (kind2 != kind)
9930 PyMem_Free(buf2);
9931 return out;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009932}
9933
Alexander Belopolsky40018472011-02-26 01:02:56 +00009934static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009935rsplit(PyObject *self,
9936 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009937 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009938{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009939 int kind1, kind2, kind;
9940 void *buf1, *buf2;
9941 Py_ssize_t len1, len2;
9942 PyObject* out;
9943
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009944 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00009945 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009946
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009947 if (PyUnicode_READY(self) == -1)
9948 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009949
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009950 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -06009951 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009952 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009953 if (PyUnicode_IS_ASCII(self))
9954 return asciilib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009955 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009956 PyUnicode_GET_LENGTH(self), maxcount
9957 );
9958 else
9959 return ucs1lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009960 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009961 PyUnicode_GET_LENGTH(self), maxcount
9962 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009963 case PyUnicode_2BYTE_KIND:
9964 return ucs2lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009965 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009966 PyUnicode_GET_LENGTH(self), maxcount
9967 );
9968 case PyUnicode_4BYTE_KIND:
9969 return ucs4lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009970 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009971 PyUnicode_GET_LENGTH(self), maxcount
9972 );
9973 default:
9974 assert(0);
9975 return NULL;
9976 }
9977
9978 if (PyUnicode_READY(substring) == -1)
9979 return NULL;
9980
9981 kind1 = PyUnicode_KIND(self);
9982 kind2 = PyUnicode_KIND(substring);
9983 kind = kind1 > kind2 ? kind1 : kind2;
9984 buf1 = PyUnicode_DATA(self);
9985 buf2 = PyUnicode_DATA(substring);
9986 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009987 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009988 if (!buf1)
9989 return NULL;
9990 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009991 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009992 if (!buf2) {
9993 if (kind1 != kind) PyMem_Free(buf1);
9994 return NULL;
9995 }
9996 len1 = PyUnicode_GET_LENGTH(self);
9997 len2 = PyUnicode_GET_LENGTH(substring);
9998
Benjamin Petersonead6b532011-12-20 17:23:42 -06009999 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010000 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010001 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10002 out = asciilib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010003 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010004 else
10005 out = ucs1lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010006 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010007 break;
10008 case PyUnicode_2BYTE_KIND:
10009 out = ucs2lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010010 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010011 break;
10012 case PyUnicode_4BYTE_KIND:
10013 out = ucs4lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010014 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010015 break;
10016 default:
10017 out = NULL;
10018 }
10019 if (kind1 != kind)
10020 PyMem_Free(buf1);
10021 if (kind2 != kind)
10022 PyMem_Free(buf2);
10023 return out;
10024}
10025
10026static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010027anylib_find(int kind, PyObject *str1, void *buf1, Py_ssize_t len1,
10028 PyObject *str2, void *buf2, Py_ssize_t len2, Py_ssize_t offset)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010029{
Benjamin Petersonead6b532011-12-20 17:23:42 -060010030 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010031 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010032 if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
10033 return asciilib_find(buf1, len1, buf2, len2, offset);
10034 else
10035 return ucs1lib_find(buf1, len1, buf2, len2, offset);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010036 case PyUnicode_2BYTE_KIND:
10037 return ucs2lib_find(buf1, len1, buf2, len2, offset);
10038 case PyUnicode_4BYTE_KIND:
10039 return ucs4lib_find(buf1, len1, buf2, len2, offset);
10040 }
10041 assert(0);
10042 return -1;
10043}
10044
10045static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010046anylib_count(int kind, PyObject *sstr, void* sbuf, Py_ssize_t slen,
10047 PyObject *str1, void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010048{
Benjamin Petersonc0b95d12011-12-20 17:24:05 -060010049 switch (kind) {
10050 case PyUnicode_1BYTE_KIND:
10051 if (PyUnicode_IS_ASCII(sstr) && PyUnicode_IS_ASCII(str1))
10052 return asciilib_count(sbuf, slen, buf1, len1, maxcount);
10053 else
10054 return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
10055 case PyUnicode_2BYTE_KIND:
10056 return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
10057 case PyUnicode_4BYTE_KIND:
10058 return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
10059 }
10060 assert(0);
10061 return 0;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010062}
10063
Alexander Belopolsky40018472011-02-26 01:02:56 +000010064static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010065replace(PyObject *self, PyObject *str1,
10066 PyObject *str2, Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010067{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010068 PyObject *u;
10069 char *sbuf = PyUnicode_DATA(self);
10070 char *buf1 = PyUnicode_DATA(str1);
10071 char *buf2 = PyUnicode_DATA(str2);
10072 int srelease = 0, release1 = 0, release2 = 0;
10073 int skind = PyUnicode_KIND(self);
10074 int kind1 = PyUnicode_KIND(str1);
10075 int kind2 = PyUnicode_KIND(str2);
10076 Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
10077 Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
10078 Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010079 int mayshrink;
10080 Py_UCS4 maxchar, maxchar_str2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010081
10082 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010083 maxcount = PY_SSIZE_T_MAX;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010084 else if (maxcount == 0 || slen == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010085 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010086
Victor Stinner59de0ee2011-10-07 10:01:28 +020010087 if (str1 == str2)
10088 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010089 if (skind < kind1)
10090 /* substring too wide to be present */
10091 goto nothing;
10092
Victor Stinner49a0a212011-10-12 23:46:10 +020010093 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
10094 maxchar_str2 = PyUnicode_MAX_CHAR_VALUE(str2);
10095 /* Replacing str1 with str2 may cause a maxchar reduction in the
10096 result string. */
10097 mayshrink = (maxchar_str2 < maxchar);
Victor Stinnere6abb482012-05-02 01:15:40 +020010098 maxchar = MAX_MAXCHAR(maxchar, maxchar_str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010099
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010100 if (len1 == len2) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010101 /* same length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010102 if (len1 == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010103 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010104 if (len1 == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010105 /* replace characters */
Victor Stinner49a0a212011-10-12 23:46:10 +020010106 Py_UCS4 u1, u2;
10107 int rkind;
Victor Stinnerf6441102011-12-18 02:43:08 +010010108 Py_ssize_t index, pos;
10109 char *src;
10110
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010111 u1 = PyUnicode_READ_CHAR(str1, 0);
Victor Stinnerf6441102011-12-18 02:43:08 +010010112 pos = findchar(sbuf, PyUnicode_KIND(self), slen, u1, 1);
10113 if (pos < 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010114 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010115 u2 = PyUnicode_READ_CHAR(str2, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010116 u = PyUnicode_New(slen, maxchar);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010117 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010118 goto error;
Victor Stinnerd3f08822012-05-29 12:57:52 +020010119 _PyUnicode_FastCopyCharacters(u, 0, self, 0, slen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010120 rkind = PyUnicode_KIND(u);
Victor Stinnerf6441102011-12-18 02:43:08 +010010121
10122 PyUnicode_WRITE(rkind, PyUnicode_DATA(u), pos, u2);
10123 index = 0;
10124 src = sbuf;
10125 while (--maxcount)
10126 {
10127 pos++;
10128 src += pos * PyUnicode_KIND(self);
10129 slen -= pos;
10130 index += pos;
10131 pos = findchar(src, PyUnicode_KIND(self), slen, u1, 1);
10132 if (pos < 0)
10133 break;
10134 PyUnicode_WRITE(rkind, PyUnicode_DATA(u), index + pos, u2);
10135 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010136 }
10137 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010138 int rkind = skind;
10139 char *res;
Victor Stinnerf6441102011-12-18 02:43:08 +010010140 Py_ssize_t i;
Victor Stinner25a4b292011-10-06 12:31:55 +020010141
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010142 if (kind1 < rkind) {
10143 /* widen substring */
10144 buf1 = _PyUnicode_AsKind(str1, rkind);
10145 if (!buf1) goto error;
10146 release1 = 1;
10147 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010148 i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010149 if (i < 0)
10150 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010151 if (rkind > kind2) {
10152 /* widen replacement */
10153 buf2 = _PyUnicode_AsKind(str2, rkind);
10154 if (!buf2) goto error;
10155 release2 = 1;
10156 }
10157 else if (rkind < kind2) {
10158 /* widen self and buf1 */
10159 rkind = kind2;
10160 if (release1) PyMem_Free(buf1);
10161 sbuf = _PyUnicode_AsKind(self, rkind);
10162 if (!sbuf) goto error;
10163 srelease = 1;
10164 buf1 = _PyUnicode_AsKind(str1, rkind);
10165 if (!buf1) goto error;
10166 release1 = 1;
10167 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010168 u = PyUnicode_New(slen, maxchar);
10169 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010170 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010171 assert(PyUnicode_KIND(u) == rkind);
10172 res = PyUnicode_DATA(u);
Victor Stinner25a4b292011-10-06 12:31:55 +020010173
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010174 memcpy(res, sbuf, rkind * slen);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010175 /* change everything in-place, starting with this one */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010176 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010177 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010178 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010179 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010180
10181 while ( --maxcount > 0) {
Victor Stinnerc3cec782011-10-05 21:24:08 +020010182 i = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010183 sbuf+rkind*i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010184 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010185 if (i == -1)
10186 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010187 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010188 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010189 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010190 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010191 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010192 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010193 }
10194 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010195 Py_ssize_t n, i, j, ires;
10196 Py_ssize_t product, new_size;
10197 int rkind = skind;
10198 char *res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010199
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010200 if (kind1 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010201 /* widen substring */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010202 buf1 = _PyUnicode_AsKind(str1, rkind);
10203 if (!buf1) goto error;
10204 release1 = 1;
10205 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010206 n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010207 if (n == 0)
10208 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010209 if (kind2 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010210 /* widen replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010211 buf2 = _PyUnicode_AsKind(str2, rkind);
10212 if (!buf2) goto error;
10213 release2 = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010214 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010215 else if (kind2 > rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010216 /* widen self and buf1 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010217 rkind = kind2;
10218 sbuf = _PyUnicode_AsKind(self, rkind);
10219 if (!sbuf) goto error;
10220 srelease = 1;
10221 if (release1) PyMem_Free(buf1);
10222 buf1 = _PyUnicode_AsKind(str1, rkind);
10223 if (!buf1) goto error;
10224 release1 = 1;
10225 }
10226 /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
10227 PyUnicode_GET_LENGTH(str1))); */
10228 product = n * (len2-len1);
10229 if ((product / (len2-len1)) != n) {
10230 PyErr_SetString(PyExc_OverflowError,
10231 "replace string is too long");
10232 goto error;
10233 }
10234 new_size = slen + product;
Victor Stinner49a0a212011-10-12 23:46:10 +020010235 if (new_size == 0) {
10236 Py_INCREF(unicode_empty);
10237 u = unicode_empty;
10238 goto done;
10239 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010240 if (new_size < 0 || new_size > (PY_SSIZE_T_MAX >> (rkind-1))) {
10241 PyErr_SetString(PyExc_OverflowError,
10242 "replace string is too long");
10243 goto error;
10244 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010245 u = PyUnicode_New(new_size, maxchar);
10246 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010247 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010248 assert(PyUnicode_KIND(u) == rkind);
10249 res = PyUnicode_DATA(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010250 ires = i = 0;
10251 if (len1 > 0) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010252 while (n-- > 0) {
10253 /* look for next match */
Victor Stinnerc3cec782011-10-05 21:24:08 +020010254 j = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010255 sbuf + rkind * i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010256 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010257 if (j == -1)
10258 break;
10259 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010260 /* copy unchanged part [i:j] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010261 memcpy(res + rkind * ires,
10262 sbuf + rkind * i,
10263 rkind * (j-i));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010264 ires += j - i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010265 }
10266 /* copy substitution string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010267 if (len2 > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010268 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010269 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010270 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010271 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010272 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010273 i = j + len1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010274 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010275 if (i < slen)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010276 /* copy tail [i:] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010277 memcpy(res + rkind * ires,
10278 sbuf + rkind * i,
10279 rkind * (slen-i));
Victor Stinner49a0a212011-10-12 23:46:10 +020010280 }
10281 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010282 /* interleave */
10283 while (n > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010284 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010285 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010286 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010287 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010288 if (--n <= 0)
10289 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010290 memcpy(res + rkind * ires,
10291 sbuf + rkind * i,
10292 rkind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010293 ires++;
10294 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010295 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010296 memcpy(res + rkind * ires,
10297 sbuf + rkind * i,
10298 rkind * (slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +000010299 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010300 }
10301
10302 if (mayshrink) {
Victor Stinner25a4b292011-10-06 12:31:55 +020010303 unicode_adjust_maxchar(&u);
10304 if (u == NULL)
10305 goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010306 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010307
10308 done:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010309 if (srelease)
10310 PyMem_FREE(sbuf);
10311 if (release1)
10312 PyMem_FREE(buf1);
10313 if (release2)
10314 PyMem_FREE(buf2);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010315 assert(_PyUnicode_CheckConsistency(u, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010316 return u;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010317
Benjamin Peterson29060642009-01-31 22:14:21 +000010318 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +000010319 /* nothing to replace; return original string (when possible) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010320 if (srelease)
10321 PyMem_FREE(sbuf);
10322 if (release1)
10323 PyMem_FREE(buf1);
10324 if (release2)
10325 PyMem_FREE(buf2);
Victor Stinnerc4b49542011-12-11 22:44:26 +010010326 return unicode_result_unchanged(self);
10327
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010328 error:
10329 if (srelease && sbuf)
10330 PyMem_FREE(sbuf);
10331 if (release1 && buf1)
10332 PyMem_FREE(buf1);
10333 if (release2 && buf2)
10334 PyMem_FREE(buf2);
10335 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010336}
10337
10338/* --- Unicode Object Methods --------------------------------------------- */
10339
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010340PyDoc_STRVAR(title__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010341 "S.title() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010342\n\
10343Return a titlecased version of S, i.e. words start with title case\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010344characters, all remaining cased characters have lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010345
10346static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010347unicode_title(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010348{
Benjamin Petersoneea48462012-01-16 14:28:50 -050010349 if (PyUnicode_READY(self) == -1)
10350 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010351 return case_operation(self, do_title);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010352}
10353
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010354PyDoc_STRVAR(capitalize__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010355 "S.capitalize() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010356\n\
10357Return a capitalized version of S, i.e. make the first character\n\
Senthil Kumarane51ee8a2010-07-05 12:00:56 +000010358have upper case and the rest lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010359
10360static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010361unicode_capitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010362{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050010363 if (PyUnicode_READY(self) == -1)
10364 return NULL;
10365 if (PyUnicode_GET_LENGTH(self) == 0)
10366 return unicode_result_unchanged(self);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010367 return case_operation(self, do_capitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010368}
10369
Benjamin Petersond5890c82012-01-14 13:23:30 -050010370PyDoc_STRVAR(casefold__doc__,
10371 "S.casefold() -> str\n\
10372\n\
10373Return a version of S suitable for caseless comparisons.");
10374
10375static PyObject *
10376unicode_casefold(PyObject *self)
10377{
10378 if (PyUnicode_READY(self) == -1)
10379 return NULL;
10380 if (PyUnicode_IS_ASCII(self))
10381 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010382 return case_operation(self, do_casefold);
Benjamin Petersond5890c82012-01-14 13:23:30 -050010383}
10384
10385
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010386/* Argument converter. Coerces to a single unicode character */
10387
10388static int
10389convert_uc(PyObject *obj, void *addr)
10390{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010391 Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010392 PyObject *uniobj;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010393
Benjamin Peterson14339b62009-01-31 16:36:08 +000010394 uniobj = PyUnicode_FromObject(obj);
10395 if (uniobj == NULL) {
10396 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010397 "The fill character cannot be converted to Unicode");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010398 return 0;
10399 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010400 if (PyUnicode_GET_LENGTH(uniobj) != 1) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010401 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010402 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010403 Py_DECREF(uniobj);
10404 return 0;
10405 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010406 *fillcharloc = PyUnicode_READ_CHAR(uniobj, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010407 Py_DECREF(uniobj);
10408 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010409}
10410
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010411PyDoc_STRVAR(center__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010412 "S.center(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010413\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010414Return S centered in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010415done using the specified fill character (default is a space)");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010416
10417static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010418unicode_center(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010419{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010420 Py_ssize_t marg, left;
10421 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010422 Py_UCS4 fillchar = ' ';
10423
Victor Stinnere9a29352011-10-01 02:14:59 +020010424 if (!PyArg_ParseTuple(args, "n|O&:center", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010425 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010426
Benjamin Petersonbac79492012-01-14 13:34:47 -050010427 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010428 return NULL;
10429
Victor Stinnerc4b49542011-12-11 22:44:26 +010010430 if (PyUnicode_GET_LENGTH(self) >= width)
10431 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010432
Victor Stinnerc4b49542011-12-11 22:44:26 +010010433 marg = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010434 left = marg / 2 + (marg & width & 1);
10435
Victor Stinner9310abb2011-10-05 00:59:23 +020010436 return pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010437}
10438
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010439/* This function assumes that str1 and str2 are readied by the caller. */
10440
Marc-André Lemburge5034372000-08-08 08:04:29 +000010441static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010442unicode_compare(PyObject *str1, PyObject *str2)
Marc-André Lemburge5034372000-08-08 08:04:29 +000010443{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010444 int kind1, kind2;
10445 void *data1, *data2;
10446 Py_ssize_t len1, len2, i;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010447
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010448 kind1 = PyUnicode_KIND(str1);
10449 kind2 = PyUnicode_KIND(str2);
10450 data1 = PyUnicode_DATA(str1);
10451 data2 = PyUnicode_DATA(str2);
10452 len1 = PyUnicode_GET_LENGTH(str1);
10453 len2 = PyUnicode_GET_LENGTH(str2);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010454
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010455 for (i = 0; i < len1 && i < len2; ++i) {
10456 Py_UCS4 c1, c2;
10457 c1 = PyUnicode_READ(kind1, data1, i);
10458 c2 = PyUnicode_READ(kind2, data2, i);
Fredrik Lundh45714e92001-06-26 16:39:36 +000010459
10460 if (c1 != c2)
10461 return (c1 < c2) ? -1 : 1;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010462 }
10463
10464 return (len1 < len2) ? -1 : (len1 != len2);
10465}
10466
Alexander Belopolsky40018472011-02-26 01:02:56 +000010467int
10468PyUnicode_Compare(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010469{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010470 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10471 if (PyUnicode_READY(left) == -1 ||
10472 PyUnicode_READY(right) == -1)
10473 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010474 return unicode_compare(left, right);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010475 }
Guido van Rossum09dc34f2007-05-04 04:17:33 +000010476 PyErr_Format(PyExc_TypeError,
10477 "Can't compare %.100s and %.100s",
10478 left->ob_type->tp_name,
10479 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010480 return -1;
10481}
10482
Martin v. Löwis5b222132007-06-10 09:51:05 +000010483int
10484PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
10485{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010486 Py_ssize_t i;
10487 int kind;
10488 void *data;
10489 Py_UCS4 chr;
10490
Victor Stinner910337b2011-10-03 03:20:16 +020010491 assert(_PyUnicode_CHECK(uni));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010492 if (PyUnicode_READY(uni) == -1)
10493 return -1;
10494 kind = PyUnicode_KIND(uni);
10495 data = PyUnicode_DATA(uni);
Martin v. Löwis5b222132007-06-10 09:51:05 +000010496 /* Compare Unicode string and source character set string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010497 for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
10498 if (chr != str[i])
10499 return (chr < (unsigned char)(str[i])) ? -1 : 1;
Benjamin Peterson8667a9b2010-01-09 21:45:28 +000010500 /* This check keeps Python strings that end in '\0' from comparing equal
10501 to C strings identical up to that point. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010502 if (PyUnicode_GET_LENGTH(uni) != i || chr)
Benjamin Peterson29060642009-01-31 22:14:21 +000010503 return 1; /* uni is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010504 if (str[i])
Benjamin Peterson29060642009-01-31 22:14:21 +000010505 return -1; /* str is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010506 return 0;
10507}
10508
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010509
Benjamin Peterson29060642009-01-31 22:14:21 +000010510#define TEST_COND(cond) \
Benjamin Peterson14339b62009-01-31 16:36:08 +000010511 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010512
Alexander Belopolsky40018472011-02-26 01:02:56 +000010513PyObject *
10514PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010515{
10516 int result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010517
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010518 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10519 PyObject *v;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010520 if (PyUnicode_READY(left) == -1 ||
10521 PyUnicode_READY(right) == -1)
10522 return NULL;
10523 if (PyUnicode_GET_LENGTH(left) != PyUnicode_GET_LENGTH(right) ||
10524 PyUnicode_KIND(left) != PyUnicode_KIND(right)) {
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010525 if (op == Py_EQ) {
10526 Py_INCREF(Py_False);
10527 return Py_False;
10528 }
10529 if (op == Py_NE) {
10530 Py_INCREF(Py_True);
10531 return Py_True;
10532 }
10533 }
10534 if (left == right)
10535 result = 0;
10536 else
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010537 result = unicode_compare(left, right);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010538
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010539 /* Convert the return value to a Boolean */
10540 switch (op) {
10541 case Py_EQ:
10542 v = TEST_COND(result == 0);
10543 break;
10544 case Py_NE:
10545 v = TEST_COND(result != 0);
10546 break;
10547 case Py_LE:
10548 v = TEST_COND(result <= 0);
10549 break;
10550 case Py_GE:
10551 v = TEST_COND(result >= 0);
10552 break;
10553 case Py_LT:
10554 v = TEST_COND(result == -1);
10555 break;
10556 case Py_GT:
10557 v = TEST_COND(result == 1);
10558 break;
10559 default:
10560 PyErr_BadArgument();
10561 return NULL;
10562 }
10563 Py_INCREF(v);
10564 return v;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010565 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000010566
Brian Curtindfc80e32011-08-10 20:28:54 -050010567 Py_RETURN_NOTIMPLEMENTED;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010568}
10569
Alexander Belopolsky40018472011-02-26 01:02:56 +000010570int
10571PyUnicode_Contains(PyObject *container, PyObject *element)
Guido van Rossum403d68b2000-03-13 15:55:09 +000010572{
Thomas Wouters477c8d52006-05-27 19:21:47 +000010573 PyObject *str, *sub;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010574 int kind1, kind2, kind;
10575 void *buf1, *buf2;
10576 Py_ssize_t len1, len2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010577 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010578
10579 /* Coerce the two arguments */
Thomas Wouters477c8d52006-05-27 19:21:47 +000010580 sub = PyUnicode_FromObject(element);
10581 if (!sub) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010582 PyErr_Format(PyExc_TypeError,
10583 "'in <string>' requires string as left operand, not %s",
10584 element->ob_type->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010585 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010586 }
10587
Thomas Wouters477c8d52006-05-27 19:21:47 +000010588 str = PyUnicode_FromObject(container);
Benjamin Peterson22a29702012-01-02 09:00:30 -060010589 if (!str) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010590 Py_DECREF(sub);
10591 return -1;
10592 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060010593 if (PyUnicode_READY(sub) == -1 || PyUnicode_READY(str) == -1) {
10594 Py_DECREF(sub);
10595 Py_DECREF(str);
10596 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000010597
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010598 kind1 = PyUnicode_KIND(str);
10599 kind2 = PyUnicode_KIND(sub);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010600 kind = kind1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010601 buf1 = PyUnicode_DATA(str);
10602 buf2 = PyUnicode_DATA(sub);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010603 if (kind2 != kind) {
Antoine Pitrou758153b2012-05-12 15:51:51 +020010604 if (kind2 > kind) {
10605 Py_DECREF(sub);
10606 Py_DECREF(str);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010607 return 0;
Antoine Pitrou758153b2012-05-12 15:51:51 +020010608 }
Victor Stinner7931d9a2011-11-04 00:22:48 +010010609 buf2 = _PyUnicode_AsKind(sub, kind);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010610 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010611 if (!buf2) {
10612 Py_DECREF(sub);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010613 Py_DECREF(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010614 return -1;
10615 }
10616 len1 = PyUnicode_GET_LENGTH(str);
10617 len2 = PyUnicode_GET_LENGTH(sub);
10618
Benjamin Petersonead6b532011-12-20 17:23:42 -060010619 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010620 case PyUnicode_1BYTE_KIND:
10621 result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
10622 break;
10623 case PyUnicode_2BYTE_KIND:
10624 result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
10625 break;
10626 case PyUnicode_4BYTE_KIND:
10627 result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
10628 break;
10629 default:
10630 result = -1;
10631 assert(0);
10632 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000010633
10634 Py_DECREF(str);
10635 Py_DECREF(sub);
10636
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010637 if (kind2 != kind)
10638 PyMem_Free(buf2);
10639
Guido van Rossum403d68b2000-03-13 15:55:09 +000010640 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010641}
10642
Guido van Rossumd57fd912000-03-10 22:53:23 +000010643/* Concat to string or Unicode object giving a new Unicode object. */
10644
Alexander Belopolsky40018472011-02-26 01:02:56 +000010645PyObject *
10646PyUnicode_Concat(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010647{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010648 PyObject *u = NULL, *v = NULL, *w;
Victor Stinner127226b2011-10-13 01:12:34 +020010649 Py_UCS4 maxchar, maxchar2;
Victor Stinner488fa492011-12-12 00:01:39 +010010650 Py_ssize_t u_len, v_len, new_len;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010651
10652 /* Coerce the two arguments */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010653 u = PyUnicode_FromObject(left);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010654 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010655 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010656 v = PyUnicode_FromObject(right);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010657 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010658 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010659
10660 /* Shortcuts */
Victor Stinnera464fc12011-10-02 20:39:30 +020010661 if (v == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010662 Py_DECREF(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010663 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010664 }
Victor Stinnera464fc12011-10-02 20:39:30 +020010665 if (u == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010666 Py_DECREF(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010667 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010668 }
10669
Victor Stinner488fa492011-12-12 00:01:39 +010010670 u_len = PyUnicode_GET_LENGTH(u);
10671 v_len = PyUnicode_GET_LENGTH(v);
10672 if (u_len > PY_SSIZE_T_MAX - v_len) {
10673 PyErr_SetString(PyExc_OverflowError,
10674 "strings are too large to concat");
10675 goto onError;
10676 }
10677 new_len = u_len + v_len;
10678
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010679 maxchar = PyUnicode_MAX_CHAR_VALUE(u);
Victor Stinner127226b2011-10-13 01:12:34 +020010680 maxchar2 = PyUnicode_MAX_CHAR_VALUE(v);
Victor Stinnere6abb482012-05-02 01:15:40 +020010681 maxchar = MAX_MAXCHAR(maxchar, maxchar2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010682
Guido van Rossumd57fd912000-03-10 22:53:23 +000010683 /* Concat the two Unicode strings */
Victor Stinner488fa492011-12-12 00:01:39 +010010684 w = PyUnicode_New(new_len, maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010685 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010686 goto onError;
Victor Stinnerd3f08822012-05-29 12:57:52 +020010687 _PyUnicode_FastCopyCharacters(w, 0, u, 0, u_len);
10688 _PyUnicode_FastCopyCharacters(w, u_len, v, 0, v_len);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010689 Py_DECREF(u);
10690 Py_DECREF(v);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010691 assert(_PyUnicode_CheckConsistency(w, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010692 return w;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010693
Benjamin Peterson29060642009-01-31 22:14:21 +000010694 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000010695 Py_XDECREF(u);
10696 Py_XDECREF(v);
10697 return NULL;
10698}
10699
Walter Dörwald1ab83302007-05-18 17:15:44 +000010700void
Victor Stinner23e56682011-10-03 03:54:37 +020010701PyUnicode_Append(PyObject **p_left, PyObject *right)
Walter Dörwald1ab83302007-05-18 17:15:44 +000010702{
Victor Stinner23e56682011-10-03 03:54:37 +020010703 PyObject *left, *res;
Victor Stinner488fa492011-12-12 00:01:39 +010010704 Py_UCS4 maxchar, maxchar2;
10705 Py_ssize_t left_len, right_len, new_len;
Victor Stinner23e56682011-10-03 03:54:37 +020010706
10707 if (p_left == NULL) {
10708 if (!PyErr_Occurred())
10709 PyErr_BadInternalCall();
Benjamin Peterson14339b62009-01-31 16:36:08 +000010710 return;
10711 }
Victor Stinner23e56682011-10-03 03:54:37 +020010712 left = *p_left;
10713 if (right == NULL || !PyUnicode_Check(left)) {
10714 if (!PyErr_Occurred())
10715 PyErr_BadInternalCall();
10716 goto error;
10717 }
10718
Benjamin Petersonbac79492012-01-14 13:34:47 -050010719 if (PyUnicode_READY(left) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020010720 goto error;
Benjamin Petersonbac79492012-01-14 13:34:47 -050010721 if (PyUnicode_READY(right) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020010722 goto error;
10723
Victor Stinner488fa492011-12-12 00:01:39 +010010724 /* Shortcuts */
10725 if (left == unicode_empty) {
10726 Py_DECREF(left);
10727 Py_INCREF(right);
10728 *p_left = right;
10729 return;
10730 }
10731 if (right == unicode_empty)
10732 return;
10733
10734 left_len = PyUnicode_GET_LENGTH(left);
10735 right_len = PyUnicode_GET_LENGTH(right);
10736 if (left_len > PY_SSIZE_T_MAX - right_len) {
10737 PyErr_SetString(PyExc_OverflowError,
10738 "strings are too large to concat");
10739 goto error;
10740 }
10741 new_len = left_len + right_len;
10742
10743 if (unicode_modifiable(left)
10744 && PyUnicode_CheckExact(right)
10745 && PyUnicode_KIND(right) <= PyUnicode_KIND(left)
Victor Stinnerb0923652011-10-04 01:17:31 +020010746 /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
10747 to change the structure size, but characters are stored just after
Georg Brandl7597add2011-10-05 16:36:47 +020010748 the structure, and so it requires to move all characters which is
Victor Stinnerb0923652011-10-04 01:17:31 +020010749 not so different than duplicating the string. */
Victor Stinner488fa492011-12-12 00:01:39 +010010750 && !(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
10751 {
10752 /* append inplace */
10753 if (unicode_resize(p_left, new_len) != 0) {
10754 /* XXX if _PyUnicode_Resize() fails, 'left' has been
10755 * deallocated so it cannot be put back into
10756 * 'variable'. The MemoryError is raised when there
10757 * is no value in 'variable', which might (very
10758 * remotely) be a cause of incompatibilities.
10759 */
10760 goto error;
Victor Stinner23e56682011-10-03 03:54:37 +020010761 }
Victor Stinner488fa492011-12-12 00:01:39 +010010762 /* copy 'right' into the newly allocated area of 'left' */
Victor Stinnerd3f08822012-05-29 12:57:52 +020010763 _PyUnicode_FastCopyCharacters(*p_left, left_len, right, 0, right_len);
Victor Stinner23e56682011-10-03 03:54:37 +020010764 }
Victor Stinner488fa492011-12-12 00:01:39 +010010765 else {
10766 maxchar = PyUnicode_MAX_CHAR_VALUE(left);
10767 maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
Victor Stinnere6abb482012-05-02 01:15:40 +020010768 maxchar = MAX_MAXCHAR(maxchar, maxchar2);
Victor Stinner23e56682011-10-03 03:54:37 +020010769
Victor Stinner488fa492011-12-12 00:01:39 +010010770 /* Concat the two Unicode strings */
10771 res = PyUnicode_New(new_len, maxchar);
10772 if (res == NULL)
10773 goto error;
Victor Stinnerd3f08822012-05-29 12:57:52 +020010774 _PyUnicode_FastCopyCharacters(res, 0, left, 0, left_len);
10775 _PyUnicode_FastCopyCharacters(res, left_len, right, 0, right_len);
Victor Stinner488fa492011-12-12 00:01:39 +010010776 Py_DECREF(left);
10777 *p_left = res;
10778 }
10779 assert(_PyUnicode_CheckConsistency(*p_left, 1));
Victor Stinner23e56682011-10-03 03:54:37 +020010780 return;
10781
10782error:
Victor Stinner488fa492011-12-12 00:01:39 +010010783 Py_CLEAR(*p_left);
Walter Dörwald1ab83302007-05-18 17:15:44 +000010784}
10785
10786void
10787PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
10788{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010789 PyUnicode_Append(pleft, right);
10790 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +000010791}
10792
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010793PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010794 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010795\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000010796Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010797string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010798interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010799
10800static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010801unicode_count(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010802{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010803 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010804 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010805 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010806 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010807 int kind1, kind2, kind;
10808 void *buf1, *buf2;
10809 Py_ssize_t len1, len2, iresult;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010810
Jesus Ceaac451502011-04-20 17:09:23 +020010811 if (!stringlib_parse_args_finds_unicode("count", args, &substring,
10812 &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000010813 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000010814
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010815 kind1 = PyUnicode_KIND(self);
10816 kind2 = PyUnicode_KIND(substring);
Benjamin Petersonb63f49f2012-05-03 18:31:07 -040010817 if (kind2 > kind1)
10818 return PyLong_FromLong(0);
10819 kind = kind1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010820 buf1 = PyUnicode_DATA(self);
10821 buf2 = PyUnicode_DATA(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010822 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010823 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010824 if (!buf2) {
10825 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010826 return NULL;
10827 }
10828 len1 = PyUnicode_GET_LENGTH(self);
10829 len2 = PyUnicode_GET_LENGTH(substring);
10830
10831 ADJUST_INDICES(start, end, len1);
Benjamin Petersonead6b532011-12-20 17:23:42 -060010832 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010833 case PyUnicode_1BYTE_KIND:
10834 iresult = ucs1lib_count(
10835 ((Py_UCS1*)buf1) + start, end - start,
10836 buf2, len2, PY_SSIZE_T_MAX
10837 );
10838 break;
10839 case PyUnicode_2BYTE_KIND:
10840 iresult = ucs2lib_count(
10841 ((Py_UCS2*)buf1) + start, end - start,
10842 buf2, len2, PY_SSIZE_T_MAX
10843 );
10844 break;
10845 case PyUnicode_4BYTE_KIND:
10846 iresult = ucs4lib_count(
10847 ((Py_UCS4*)buf1) + start, end - start,
10848 buf2, len2, PY_SSIZE_T_MAX
10849 );
10850 break;
10851 default:
10852 assert(0); iresult = 0;
10853 }
10854
10855 result = PyLong_FromSsize_t(iresult);
10856
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010857 if (kind2 != kind)
10858 PyMem_Free(buf2);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010859
10860 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010861
Guido van Rossumd57fd912000-03-10 22:53:23 +000010862 return result;
10863}
10864
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010865PyDoc_STRVAR(encode__doc__,
Victor Stinnerc911bbf2010-11-07 19:04:46 +000010866 "S.encode(encoding='utf-8', errors='strict') -> bytes\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010867\n\
Victor Stinnere14e2122010-11-07 18:41:46 +000010868Encode S using the codec registered for encoding. Default encoding\n\
10869is 'utf-8'. errors may be given to set a different error\n\
Fred Drakee4315f52000-05-09 19:53:39 +000010870handling scheme. Default is 'strict' meaning that encoding errors raise\n\
Walter Dörwald3aeb6322002-09-02 13:14:32 +000010871a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
10872'xmlcharrefreplace' as well as any other name registered with\n\
10873codecs.register_error that can handle UnicodeEncodeErrors.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010874
10875static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010876unicode_encode(PyObject *self, PyObject *args, PyObject *kwargs)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010877{
Benjamin Peterson308d6372009-09-18 21:42:35 +000010878 static char *kwlist[] = {"encoding", "errors", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000010879 char *encoding = NULL;
10880 char *errors = NULL;
Guido van Rossum35d94282007-08-27 18:20:11 +000010881
Benjamin Peterson308d6372009-09-18 21:42:35 +000010882 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:encode",
10883 kwlist, &encoding, &errors))
Guido van Rossumd57fd912000-03-10 22:53:23 +000010884 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010885 return PyUnicode_AsEncodedString(self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +000010886}
10887
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010888PyDoc_STRVAR(expandtabs__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010889 "S.expandtabs([tabsize]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010890\n\
10891Return a copy of S where all tab characters are expanded using spaces.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010892If tabsize is not given, a tab size of 8 characters is assumed.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010893
10894static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010895unicode_expandtabs(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010896{
Antoine Pitroue71d5742011-10-04 15:55:09 +020010897 Py_ssize_t i, j, line_pos, src_len, incr;
10898 Py_UCS4 ch;
10899 PyObject *u;
10900 void *src_data, *dest_data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010901 int tabsize = 8;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010902 int kind;
Antoine Pitroue19aa382011-10-04 16:04:01 +020010903 int found;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010904
10905 if (!PyArg_ParseTuple(args, "|i:expandtabs", &tabsize))
Benjamin Peterson29060642009-01-31 22:14:21 +000010906 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010907
Antoine Pitrou22425222011-10-04 19:10:51 +020010908 if (PyUnicode_READY(self) == -1)
10909 return NULL;
10910
Thomas Wouters7e474022000-07-16 12:04:32 +000010911 /* First pass: determine size of output string */
Antoine Pitroue71d5742011-10-04 15:55:09 +020010912 src_len = PyUnicode_GET_LENGTH(self);
10913 i = j = line_pos = 0;
10914 kind = PyUnicode_KIND(self);
10915 src_data = PyUnicode_DATA(self);
Antoine Pitroue19aa382011-10-04 16:04:01 +020010916 found = 0;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010917 for (; i < src_len; i++) {
10918 ch = PyUnicode_READ(kind, src_data, i);
10919 if (ch == '\t') {
Antoine Pitroue19aa382011-10-04 16:04:01 +020010920 found = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000010921 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020010922 incr = tabsize - (line_pos % tabsize); /* cannot overflow */
Benjamin Peterson29060642009-01-31 22:14:21 +000010923 if (j > PY_SSIZE_T_MAX - incr)
Antoine Pitroue71d5742011-10-04 15:55:09 +020010924 goto overflow;
10925 line_pos += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000010926 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010927 }
Benjamin Peterson29060642009-01-31 22:14:21 +000010928 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010929 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000010930 if (j > PY_SSIZE_T_MAX - 1)
Antoine Pitroue71d5742011-10-04 15:55:09 +020010931 goto overflow;
10932 line_pos++;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010933 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010934 if (ch == '\n' || ch == '\r')
10935 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010936 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020010937 }
Victor Stinnerc4b49542011-12-11 22:44:26 +010010938 if (!found)
10939 return unicode_result_unchanged(self);
Guido van Rossumcd16bf62007-06-13 18:07:49 +000010940
Guido van Rossumd57fd912000-03-10 22:53:23 +000010941 /* Second pass: create output string and fill it */
Antoine Pitroue71d5742011-10-04 15:55:09 +020010942 u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +000010943 if (!u)
10944 return NULL;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010945 dest_data = PyUnicode_DATA(u);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010946
Antoine Pitroue71d5742011-10-04 15:55:09 +020010947 i = j = line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010948
Antoine Pitroue71d5742011-10-04 15:55:09 +020010949 for (; i < src_len; i++) {
10950 ch = PyUnicode_READ(kind, src_data, i);
10951 if (ch == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +000010952 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020010953 incr = tabsize - (line_pos % tabsize);
10954 line_pos += incr;
Victor Stinnerda79e632012-02-22 13:37:04 +010010955 FILL(kind, dest_data, ' ', j, incr);
10956 j += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000010957 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000010958 }
Benjamin Peterson29060642009-01-31 22:14:21 +000010959 else {
Antoine Pitroue71d5742011-10-04 15:55:09 +020010960 line_pos++;
10961 PyUnicode_WRITE(kind, dest_data, j, ch);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010962 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010963 if (ch == '\n' || ch == '\r')
10964 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010965 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020010966 }
10967 assert (j == PyUnicode_GET_LENGTH(u));
Victor Stinnerd3df8ab2011-11-22 01:22:34 +010010968 return unicode_result(u);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010969
Antoine Pitroue71d5742011-10-04 15:55:09 +020010970 overflow:
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010971 PyErr_SetString(PyExc_OverflowError, "new string is too long");
10972 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010973}
10974
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010975PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010976 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010977\n\
10978Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080010979such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010980arguments start and end are interpreted as in slice notation.\n\
10981\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010982Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010983
10984static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010985unicode_find(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010986{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010987 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000010988 Py_ssize_t start;
10989 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010990 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010991
Jesus Ceaac451502011-04-20 17:09:23 +020010992 if (!stringlib_parse_args_finds_unicode("find", args, &substring,
10993 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000010994 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010995
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010996 if (PyUnicode_READY(self) == -1)
10997 return NULL;
10998 if (PyUnicode_READY(substring) == -1)
10999 return NULL;
11000
Victor Stinner7931d9a2011-11-04 00:22:48 +010011001 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011002
11003 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011004
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011005 if (result == -2)
11006 return NULL;
11007
Christian Heimes217cfd12007-12-02 14:31:20 +000011008 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011009}
11010
11011static PyObject *
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011012unicode_getitem(PyObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011013{
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011014 void *data;
11015 enum PyUnicode_Kind kind;
11016 Py_UCS4 ch;
11017 PyObject *res;
11018
11019 if (!PyUnicode_Check(self) || PyUnicode_READY(self) == -1) {
11020 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011021 return NULL;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011022 }
11023 if (index < 0 || index >= PyUnicode_GET_LENGTH(self)) {
11024 PyErr_SetString(PyExc_IndexError, "string index out of range");
11025 return NULL;
11026 }
11027 kind = PyUnicode_KIND(self);
11028 data = PyUnicode_DATA(self);
11029 ch = PyUnicode_READ(kind, data, index);
11030 if (ch < 256)
11031 return get_latin1_char(ch);
11032
11033 res = PyUnicode_New(1, ch);
11034 if (res == NULL)
11035 return NULL;
11036 kind = PyUnicode_KIND(res);
11037 data = PyUnicode_DATA(res);
11038 PyUnicode_WRITE(kind, data, 0, ch);
11039 assert(_PyUnicode_CheckConsistency(res, 1));
11040 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011041}
11042
Guido van Rossumc2504932007-09-18 19:42:40 +000011043/* Believe it or not, this produces the same value for ASCII strings
Mark Dickinson57e683e2011-09-24 18:18:40 +010011044 as bytes_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +000011045static Py_hash_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011046unicode_hash(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011047{
Guido van Rossumc2504932007-09-18 19:42:40 +000011048 Py_ssize_t len;
Mark Dickinson57e683e2011-09-24 18:18:40 +010011049 Py_uhash_t x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011050
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011051#ifdef Py_DEBUG
Benjamin Peterson69e97272012-02-21 11:08:50 -050011052 assert(_Py_HashSecret_Initialized);
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011053#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011054 if (_PyUnicode_HASH(self) != -1)
11055 return _PyUnicode_HASH(self);
11056 if (PyUnicode_READY(self) == -1)
11057 return -1;
11058 len = PyUnicode_GET_LENGTH(self);
Georg Brandl16fa2a12012-02-21 00:50:13 +010011059 /*
11060 We make the hash of the empty string be 0, rather than using
11061 (prefix ^ suffix), since this slightly obfuscates the hash secret
11062 */
11063 if (len == 0) {
11064 _PyUnicode_HASH(self) = 0;
11065 return 0;
11066 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011067
11068 /* The hash function as a macro, gets expanded three times below. */
Georg Brandl2fb477c2012-02-21 00:33:36 +010011069#define HASH(P) \
11070 x ^= (Py_uhash_t) *P << 7; \
11071 while (--len >= 0) \
11072 x = (_PyHASH_MULTIPLIER * x) ^ (Py_uhash_t) *P++; \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011073
Georg Brandl2fb477c2012-02-21 00:33:36 +010011074 x = (Py_uhash_t) _Py_HashSecret.prefix;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011075 switch (PyUnicode_KIND(self)) {
11076 case PyUnicode_1BYTE_KIND: {
11077 const unsigned char *c = PyUnicode_1BYTE_DATA(self);
11078 HASH(c);
11079 break;
11080 }
11081 case PyUnicode_2BYTE_KIND: {
11082 const Py_UCS2 *s = PyUnicode_2BYTE_DATA(self);
11083 HASH(s);
11084 break;
11085 }
11086 default: {
11087 Py_UCS4 *l;
11088 assert(PyUnicode_KIND(self) == PyUnicode_4BYTE_KIND &&
11089 "Impossible switch case in unicode_hash");
11090 l = PyUnicode_4BYTE_DATA(self);
11091 HASH(l);
11092 break;
11093 }
11094 }
Georg Brandl2fb477c2012-02-21 00:33:36 +010011095 x ^= (Py_uhash_t) PyUnicode_GET_LENGTH(self);
11096 x ^= (Py_uhash_t) _Py_HashSecret.suffix;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011097
Guido van Rossumc2504932007-09-18 19:42:40 +000011098 if (x == -1)
11099 x = -2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011100 _PyUnicode_HASH(self) = x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011101 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011102}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011103#undef HASH
Guido van Rossumd57fd912000-03-10 22:53:23 +000011104
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011105PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011106 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011107\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011108Like S.find() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011109
11110static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011111unicode_index(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011112{
Martin v. Löwis18e16552006-02-15 17:27:45 +000011113 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011114 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011115 Py_ssize_t start;
11116 Py_ssize_t end;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011117
Jesus Ceaac451502011-04-20 17:09:23 +020011118 if (!stringlib_parse_args_finds_unicode("index", args, &substring,
11119 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011120 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011121
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011122 if (PyUnicode_READY(self) == -1)
11123 return NULL;
11124 if (PyUnicode_READY(substring) == -1)
11125 return NULL;
11126
Victor Stinner7931d9a2011-11-04 00:22:48 +010011127 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011128
11129 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011130
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011131 if (result == -2)
11132 return NULL;
11133
Guido van Rossumd57fd912000-03-10 22:53:23 +000011134 if (result < 0) {
11135 PyErr_SetString(PyExc_ValueError, "substring not found");
11136 return NULL;
11137 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011138
Christian Heimes217cfd12007-12-02 14:31:20 +000011139 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011140}
11141
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011142PyDoc_STRVAR(islower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011143 "S.islower() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011144\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011145Return True if all cased characters in S are lowercase 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_islower(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_ISLOWER(PyUnicode_READ(kind, data, 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_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
11176 return PyBool_FromLong(0);
11177 else if (!cased && Py_UNICODE_ISLOWER(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(isupper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011184 "S.isupper() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011185\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011186Return True if all cased characters in S are uppercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011187at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011188
11189static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011190unicode_isupper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011191{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011192 Py_ssize_t i, length;
11193 int kind;
11194 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011195 int cased;
11196
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011197 if (PyUnicode_READY(self) == -1)
11198 return NULL;
11199 length = PyUnicode_GET_LENGTH(self);
11200 kind = PyUnicode_KIND(self);
11201 data = PyUnicode_DATA(self);
11202
Guido van Rossumd57fd912000-03-10 22:53:23 +000011203 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011204 if (length == 1)
11205 return PyBool_FromLong(
11206 Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011207
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011208 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011209 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011210 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011211
Guido van Rossumd57fd912000-03-10 22:53:23 +000011212 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011213 for (i = 0; i < length; i++) {
11214 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011215
Benjamin Peterson29060642009-01-31 22:14:21 +000011216 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
11217 return PyBool_FromLong(0);
11218 else if (!cased && Py_UNICODE_ISUPPER(ch))
11219 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011220 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011221 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011222}
11223
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011224PyDoc_STRVAR(istitle__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011225 "S.istitle() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011226\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011227Return True if S is a titlecased string and there is at least one\n\
11228character in S, i.e. upper- and titlecase characters may only\n\
11229follow uncased characters and lowercase characters only cased ones.\n\
11230Return False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011231
11232static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011233unicode_istitle(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011234{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011235 Py_ssize_t i, length;
11236 int kind;
11237 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011238 int cased, previous_is_cased;
11239
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011240 if (PyUnicode_READY(self) == -1)
11241 return NULL;
11242 length = PyUnicode_GET_LENGTH(self);
11243 kind = PyUnicode_KIND(self);
11244 data = PyUnicode_DATA(self);
11245
Guido van Rossumd57fd912000-03-10 22:53:23 +000011246 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011247 if (length == 1) {
11248 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11249 return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
11250 (Py_UNICODE_ISUPPER(ch) != 0));
11251 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011252
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011253 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011254 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011255 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011256
Guido van Rossumd57fd912000-03-10 22:53:23 +000011257 cased = 0;
11258 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011259 for (i = 0; i < length; i++) {
11260 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011261
Benjamin Peterson29060642009-01-31 22:14:21 +000011262 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
11263 if (previous_is_cased)
11264 return PyBool_FromLong(0);
11265 previous_is_cased = 1;
11266 cased = 1;
11267 }
11268 else if (Py_UNICODE_ISLOWER(ch)) {
11269 if (!previous_is_cased)
11270 return PyBool_FromLong(0);
11271 previous_is_cased = 1;
11272 cased = 1;
11273 }
11274 else
11275 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011276 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011277 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011278}
11279
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011280PyDoc_STRVAR(isspace__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011281 "S.isspace() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011282\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011283Return True if all characters in S are whitespace\n\
11284and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011285
11286static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011287unicode_isspace(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011288{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011289 Py_ssize_t i, length;
11290 int kind;
11291 void *data;
11292
11293 if (PyUnicode_READY(self) == -1)
11294 return NULL;
11295 length = PyUnicode_GET_LENGTH(self);
11296 kind = PyUnicode_KIND(self);
11297 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011298
Guido van Rossumd57fd912000-03-10 22:53:23 +000011299 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011300 if (length == 1)
11301 return PyBool_FromLong(
11302 Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011303
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011304 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011305 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011306 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011307
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011308 for (i = 0; i < length; i++) {
11309 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011310 if (!Py_UNICODE_ISSPACE(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011311 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011312 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011313 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011314}
11315
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011316PyDoc_STRVAR(isalpha__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011317 "S.isalpha() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011318\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011319Return True if all characters in S are alphabetic\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011320and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011321
11322static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011323unicode_isalpha(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011324{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011325 Py_ssize_t i, length;
11326 int kind;
11327 void *data;
11328
11329 if (PyUnicode_READY(self) == -1)
11330 return NULL;
11331 length = PyUnicode_GET_LENGTH(self);
11332 kind = PyUnicode_KIND(self);
11333 data = PyUnicode_DATA(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011334
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011335 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011336 if (length == 1)
11337 return PyBool_FromLong(
11338 Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011339
11340 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011341 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011342 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011343
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011344 for (i = 0; i < length; i++) {
11345 if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011346 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011347 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011348 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011349}
11350
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011351PyDoc_STRVAR(isalnum__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011352 "S.isalnum() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011353\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011354Return True if all characters in S are alphanumeric\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011355and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011356
11357static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011358unicode_isalnum(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011359{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011360 int kind;
11361 void *data;
11362 Py_ssize_t len, i;
11363
11364 if (PyUnicode_READY(self) == -1)
11365 return NULL;
11366
11367 kind = PyUnicode_KIND(self);
11368 data = PyUnicode_DATA(self);
11369 len = PyUnicode_GET_LENGTH(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011370
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011371 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011372 if (len == 1) {
11373 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11374 return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
11375 }
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011376
11377 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011378 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011379 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011380
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011381 for (i = 0; i < len; i++) {
11382 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011383 if (!Py_UNICODE_ISALNUM(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011384 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011385 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011386 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011387}
11388
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011389PyDoc_STRVAR(isdecimal__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011390 "S.isdecimal() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011391\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011392Return True if there are only decimal characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011393False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011394
11395static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011396unicode_isdecimal(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011397{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011398 Py_ssize_t i, length;
11399 int kind;
11400 void *data;
11401
11402 if (PyUnicode_READY(self) == -1)
11403 return NULL;
11404 length = PyUnicode_GET_LENGTH(self);
11405 kind = PyUnicode_KIND(self);
11406 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011407
Guido van Rossumd57fd912000-03-10 22:53:23 +000011408 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011409 if (length == 1)
11410 return PyBool_FromLong(
11411 Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011412
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011413 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011414 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011415 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011416
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011417 for (i = 0; i < length; i++) {
11418 if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011419 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011420 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011421 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011422}
11423
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011424PyDoc_STRVAR(isdigit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011425 "S.isdigit() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011426\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011427Return True if all characters in S are digits\n\
11428and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011429
11430static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011431unicode_isdigit(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011432{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011433 Py_ssize_t i, length;
11434 int kind;
11435 void *data;
11436
11437 if (PyUnicode_READY(self) == -1)
11438 return NULL;
11439 length = PyUnicode_GET_LENGTH(self);
11440 kind = PyUnicode_KIND(self);
11441 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011442
Guido van Rossumd57fd912000-03-10 22:53:23 +000011443 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011444 if (length == 1) {
11445 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11446 return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
11447 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011448
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011449 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011450 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011451 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011452
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011453 for (i = 0; i < length; i++) {
11454 if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011455 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011456 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011457 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011458}
11459
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011460PyDoc_STRVAR(isnumeric__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011461 "S.isnumeric() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011462\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011463Return True if there are only numeric characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011464False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011465
11466static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011467unicode_isnumeric(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011468{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011469 Py_ssize_t i, length;
11470 int kind;
11471 void *data;
11472
11473 if (PyUnicode_READY(self) == -1)
11474 return NULL;
11475 length = PyUnicode_GET_LENGTH(self);
11476 kind = PyUnicode_KIND(self);
11477 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011478
Guido van Rossumd57fd912000-03-10 22:53:23 +000011479 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011480 if (length == 1)
11481 return PyBool_FromLong(
11482 Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011483
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011484 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011485 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011486 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011487
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011488 for (i = 0; i < length; i++) {
11489 if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011490 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011491 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011492 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011493}
11494
Martin v. Löwis47383402007-08-15 07:32:56 +000011495int
11496PyUnicode_IsIdentifier(PyObject *self)
11497{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011498 int kind;
11499 void *data;
11500 Py_ssize_t i;
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011501 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +000011502
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011503 if (PyUnicode_READY(self) == -1) {
11504 Py_FatalError("identifier not ready");
Benjamin Peterson29060642009-01-31 22:14:21 +000011505 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011506 }
11507
11508 /* Special case for empty strings */
11509 if (PyUnicode_GET_LENGTH(self) == 0)
11510 return 0;
11511 kind = PyUnicode_KIND(self);
11512 data = PyUnicode_DATA(self);
Martin v. Löwis47383402007-08-15 07:32:56 +000011513
11514 /* PEP 3131 says that the first character must be in
11515 XID_Start and subsequent characters in XID_Continue,
11516 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +000011517 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +000011518 letters, digits, underscore). However, given the current
11519 definition of XID_Start and XID_Continue, it is sufficient
11520 to check just for these, except that _ must be allowed
11521 as starting an identifier. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011522 first = PyUnicode_READ(kind, data, 0);
Benjamin Petersonf413b802011-08-12 22:17:18 -050011523 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +000011524 return 0;
11525
Benjamin Peterson9c6e6a02011-09-28 08:09:05 -040011526 for (i = 1; i < PyUnicode_GET_LENGTH(self); i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011527 if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011528 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +000011529 return 1;
11530}
11531
11532PyDoc_STRVAR(isidentifier__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011533 "S.isidentifier() -> bool\n\
Martin v. Löwis47383402007-08-15 07:32:56 +000011534\n\
11535Return True if S is a valid identifier according\n\
11536to the language definition.");
11537
11538static PyObject*
11539unicode_isidentifier(PyObject *self)
11540{
11541 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
11542}
11543
Georg Brandl559e5d72008-06-11 18:37:52 +000011544PyDoc_STRVAR(isprintable__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011545 "S.isprintable() -> bool\n\
Georg Brandl559e5d72008-06-11 18:37:52 +000011546\n\
11547Return True if all characters in S are considered\n\
11548printable in repr() or S is empty, False otherwise.");
11549
11550static PyObject*
11551unicode_isprintable(PyObject *self)
11552{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011553 Py_ssize_t i, length;
11554 int kind;
11555 void *data;
11556
11557 if (PyUnicode_READY(self) == -1)
11558 return NULL;
11559 length = PyUnicode_GET_LENGTH(self);
11560 kind = PyUnicode_KIND(self);
11561 data = PyUnicode_DATA(self);
Georg Brandl559e5d72008-06-11 18:37:52 +000011562
11563 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011564 if (length == 1)
11565 return PyBool_FromLong(
11566 Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
Georg Brandl559e5d72008-06-11 18:37:52 +000011567
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011568 for (i = 0; i < length; i++) {
11569 if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
Georg Brandl559e5d72008-06-11 18:37:52 +000011570 Py_RETURN_FALSE;
11571 }
11572 }
11573 Py_RETURN_TRUE;
11574}
11575
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011576PyDoc_STRVAR(join__doc__,
Georg Brandl495f7b52009-10-27 15:28:25 +000011577 "S.join(iterable) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011578\n\
11579Return a string which is the concatenation of the strings in the\n\
Georg Brandl495f7b52009-10-27 15:28:25 +000011580iterable. The separator between elements is S.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011581
11582static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011583unicode_join(PyObject *self, PyObject *data)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011584{
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011585 return PyUnicode_Join(self, data);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011586}
11587
Martin v. Löwis18e16552006-02-15 17:27:45 +000011588static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011589unicode_length(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011590{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011591 if (PyUnicode_READY(self) == -1)
11592 return -1;
11593 return PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011594}
11595
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011596PyDoc_STRVAR(ljust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011597 "S.ljust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011598\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000011599Return S left-justified in a Unicode string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011600done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011601
11602static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020011603unicode_ljust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011604{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011605 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011606 Py_UCS4 fillchar = ' ';
11607
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011608 if (!PyArg_ParseTuple(args, "n|O&:ljust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011609 return NULL;
11610
Benjamin Petersonbac79492012-01-14 13:34:47 -050011611 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010011612 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011613
Victor Stinnerc4b49542011-12-11 22:44:26 +010011614 if (PyUnicode_GET_LENGTH(self) >= width)
11615 return unicode_result_unchanged(self);
11616
11617 return pad(self, 0, width - PyUnicode_GET_LENGTH(self), fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011618}
11619
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011620PyDoc_STRVAR(lower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011621 "S.lower() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011622\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011623Return a copy of the string S converted to lowercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011624
11625static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020011626unicode_lower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011627{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050011628 if (PyUnicode_READY(self) == -1)
11629 return NULL;
11630 if (PyUnicode_IS_ASCII(self))
11631 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010011632 return case_operation(self, do_lower);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011633}
11634
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011635#define LEFTSTRIP 0
11636#define RIGHTSTRIP 1
11637#define BOTHSTRIP 2
11638
11639/* Arrays indexed by above */
11640static const char *stripformat[] = {"|O:lstrip", "|O:rstrip", "|O:strip"};
11641
11642#define STRIPNAME(i) (stripformat[i]+3)
11643
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011644/* externally visible for str.strip(unicode) */
11645PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011646_PyUnicode_XStrip(PyObject *self, int striptype, PyObject *sepobj)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011647{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011648 void *data;
11649 int kind;
11650 Py_ssize_t i, j, len;
11651 BLOOM_MASK sepmask;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011652
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011653 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
11654 return NULL;
11655
11656 kind = PyUnicode_KIND(self);
11657 data = PyUnicode_DATA(self);
11658 len = PyUnicode_GET_LENGTH(self);
11659 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
11660 PyUnicode_DATA(sepobj),
11661 PyUnicode_GET_LENGTH(sepobj));
Thomas Wouters477c8d52006-05-27 19:21:47 +000011662
Benjamin Peterson14339b62009-01-31 16:36:08 +000011663 i = 0;
11664 if (striptype != RIGHTSTRIP) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011665 while (i < len &&
11666 BLOOM_MEMBER(sepmask, PyUnicode_READ(kind, data, i), sepobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011667 i++;
11668 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011669 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011670
Benjamin Peterson14339b62009-01-31 16:36:08 +000011671 j = len;
11672 if (striptype != LEFTSTRIP) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011673 do {
11674 j--;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011675 } while (j >= i &&
11676 BLOOM_MEMBER(sepmask, PyUnicode_READ(kind, data, j), sepobj));
Benjamin Peterson29060642009-01-31 22:14:21 +000011677 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011678 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011679
Victor Stinner7931d9a2011-11-04 00:22:48 +010011680 return PyUnicode_Substring(self, i, j);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011681}
11682
11683PyObject*
11684PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
11685{
11686 unsigned char *data;
11687 int kind;
Victor Stinner12bab6d2011-10-01 01:53:49 +020011688 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011689
Victor Stinnerde636f32011-10-01 03:55:54 +020011690 if (PyUnicode_READY(self) == -1)
11691 return NULL;
11692
Victor Stinner684d5fd2012-05-03 02:32:34 +020011693 length = PyUnicode_GET_LENGTH(self);
11694 end = Py_MIN(end, length);
Victor Stinnerde636f32011-10-01 03:55:54 +020011695
Victor Stinner684d5fd2012-05-03 02:32:34 +020011696 if (start == 0 && end == length)
Victor Stinnerc4b49542011-12-11 22:44:26 +010011697 return unicode_result_unchanged(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011698
Victor Stinnerde636f32011-10-01 03:55:54 +020011699 if (start < 0 || end < 0) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020011700 PyErr_SetString(PyExc_IndexError, "string index out of range");
11701 return NULL;
11702 }
Victor Stinner684d5fd2012-05-03 02:32:34 +020011703 if (start >= length || end < start) {
Victor Stinner3a7f79772012-05-03 03:36:40 +020011704 Py_INCREF(unicode_empty);
11705 return unicode_empty;
Victor Stinner684d5fd2012-05-03 02:32:34 +020011706 }
Victor Stinner12bab6d2011-10-01 01:53:49 +020011707
Victor Stinner684d5fd2012-05-03 02:32:34 +020011708 length = end - start;
Victor Stinnerb9275c12011-10-05 14:01:42 +020011709 if (PyUnicode_IS_ASCII(self)) {
Victor Stinnerb9275c12011-10-05 14:01:42 +020011710 data = PyUnicode_1BYTE_DATA(self);
Victor Stinnerd3f08822012-05-29 12:57:52 +020011711 return _PyUnicode_FromASCII((char*)(data + start), length);
Victor Stinnerb9275c12011-10-05 14:01:42 +020011712 }
11713 else {
11714 kind = PyUnicode_KIND(self);
11715 data = PyUnicode_1BYTE_DATA(self);
11716 return PyUnicode_FromKindAndData(kind,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020011717 data + kind * start,
Victor Stinnerb9275c12011-10-05 14:01:42 +020011718 length);
11719 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011720}
Guido van Rossumd57fd912000-03-10 22:53:23 +000011721
11722static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011723do_strip(PyObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011724{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011725 int kind;
11726 void *data;
11727 Py_ssize_t len, i, j;
11728
11729 if (PyUnicode_READY(self) == -1)
11730 return NULL;
11731
11732 kind = PyUnicode_KIND(self);
11733 data = PyUnicode_DATA(self);
11734 len = PyUnicode_GET_LENGTH(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011735
Benjamin Peterson14339b62009-01-31 16:36:08 +000011736 i = 0;
11737 if (striptype != RIGHTSTRIP) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011738 while (i < len && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, i))) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000011739 i++;
11740 }
11741 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011742
Benjamin Peterson14339b62009-01-31 16:36:08 +000011743 j = len;
11744 if (striptype != LEFTSTRIP) {
11745 do {
11746 j--;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011747 } while (j >= i && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, j)));
Benjamin Peterson14339b62009-01-31 16:36:08 +000011748 j++;
11749 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011750
Victor Stinner7931d9a2011-11-04 00:22:48 +010011751 return PyUnicode_Substring(self, i, j);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011752}
11753
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011754
11755static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011756do_argstrip(PyObject *self, int striptype, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011757{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011758 PyObject *sep = NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011759
Benjamin Peterson14339b62009-01-31 16:36:08 +000011760 if (!PyArg_ParseTuple(args, (char *)stripformat[striptype], &sep))
11761 return NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011762
Benjamin Peterson14339b62009-01-31 16:36:08 +000011763 if (sep != NULL && sep != Py_None) {
11764 if (PyUnicode_Check(sep))
11765 return _PyUnicode_XStrip(self, striptype, sep);
11766 else {
11767 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000011768 "%s arg must be None or str",
11769 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +000011770 return NULL;
11771 }
11772 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011773
Benjamin Peterson14339b62009-01-31 16:36:08 +000011774 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011775}
11776
11777
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011778PyDoc_STRVAR(strip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011779 "S.strip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011780\n\
11781Return a copy of the string S with leading and trailing\n\
11782whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011783If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011784
11785static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011786unicode_strip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011787{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011788 if (PyTuple_GET_SIZE(args) == 0)
11789 return do_strip(self, BOTHSTRIP); /* Common case */
11790 else
11791 return do_argstrip(self, BOTHSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011792}
11793
11794
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011795PyDoc_STRVAR(lstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011796 "S.lstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011797\n\
11798Return a copy of the string S with leading whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011799If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011800
11801static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011802unicode_lstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011803{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011804 if (PyTuple_GET_SIZE(args) == 0)
11805 return do_strip(self, LEFTSTRIP); /* Common case */
11806 else
11807 return do_argstrip(self, LEFTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011808}
11809
11810
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011811PyDoc_STRVAR(rstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011812 "S.rstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011813\n\
11814Return a copy of the string S with trailing whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011815If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011816
11817static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011818unicode_rstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011819{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011820 if (PyTuple_GET_SIZE(args) == 0)
11821 return do_strip(self, RIGHTSTRIP); /* Common case */
11822 else
11823 return do_argstrip(self, RIGHTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011824}
11825
11826
Guido van Rossumd57fd912000-03-10 22:53:23 +000011827static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011828unicode_repeat(PyObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011829{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011830 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011831 Py_ssize_t nchars, n;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011832
Georg Brandl222de0f2009-04-12 12:01:50 +000011833 if (len < 1) {
11834 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +020011835 return unicode_empty;
Georg Brandl222de0f2009-04-12 12:01:50 +000011836 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011837
Victor Stinnerc4b49542011-12-11 22:44:26 +010011838 /* no repeat, return original string */
11839 if (len == 1)
11840 return unicode_result_unchanged(str);
Tim Peters8f422462000-09-09 06:13:41 +000011841
Benjamin Petersonbac79492012-01-14 13:34:47 -050011842 if (PyUnicode_READY(str) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011843 return NULL;
11844
Victor Stinnerc759f3e2011-10-01 03:09:58 +020011845 if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
Victor Stinner67ca64c2011-10-01 02:47:29 +020011846 PyErr_SetString(PyExc_OverflowError,
11847 "repeated string is too long");
11848 return NULL;
11849 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011850 nchars = len * PyUnicode_GET_LENGTH(str);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011851
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011852 u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011853 if (!u)
11854 return NULL;
Victor Stinner67ca64c2011-10-01 02:47:29 +020011855 assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011856
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011857 if (PyUnicode_GET_LENGTH(str) == 1) {
11858 const int kind = PyUnicode_KIND(str);
11859 const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
Victor Stinner73f53b52011-12-18 03:26:31 +010011860 if (kind == PyUnicode_1BYTE_KIND) {
11861 void *to = PyUnicode_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011862 memset(to, (unsigned char)fill_char, len);
Victor Stinner73f53b52011-12-18 03:26:31 +010011863 }
11864 else if (kind == PyUnicode_2BYTE_KIND) {
11865 Py_UCS2 *ucs2 = PyUnicode_2BYTE_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011866 for (n = 0; n < len; ++n)
Victor Stinner73f53b52011-12-18 03:26:31 +010011867 ucs2[n] = fill_char;
11868 } else {
11869 Py_UCS4 *ucs4 = PyUnicode_4BYTE_DATA(u);
11870 assert(kind == PyUnicode_4BYTE_KIND);
11871 for (n = 0; n < len; ++n)
11872 ucs4[n] = fill_char;
Victor Stinner67ca64c2011-10-01 02:47:29 +020011873 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011874 }
11875 else {
11876 /* number of characters copied this far */
11877 Py_ssize_t done = PyUnicode_GET_LENGTH(str);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020011878 const Py_ssize_t char_size = PyUnicode_KIND(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011879 char *to = (char *) PyUnicode_DATA(u);
11880 Py_MEMCPY(to, PyUnicode_DATA(str),
11881 PyUnicode_GET_LENGTH(str) * char_size);
Benjamin Peterson29060642009-01-31 22:14:21 +000011882 while (done < nchars) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011883 n = (done <= nchars-done) ? done : nchars-done;
11884 Py_MEMCPY(to + (done * char_size), to, n * char_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011885 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +000011886 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011887 }
11888
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020011889 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011890 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011891}
11892
Alexander Belopolsky40018472011-02-26 01:02:56 +000011893PyObject *
11894PyUnicode_Replace(PyObject *obj,
11895 PyObject *subobj,
11896 PyObject *replobj,
11897 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011898{
11899 PyObject *self;
11900 PyObject *str1;
11901 PyObject *str2;
11902 PyObject *result;
11903
11904 self = PyUnicode_FromObject(obj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060011905 if (self == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000011906 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011907 str1 = PyUnicode_FromObject(subobj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060011908 if (str1 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011909 Py_DECREF(self);
11910 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011911 }
11912 str2 = PyUnicode_FromObject(replobj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060011913 if (str2 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011914 Py_DECREF(self);
11915 Py_DECREF(str1);
11916 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011917 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060011918 if (PyUnicode_READY(self) == -1 ||
11919 PyUnicode_READY(str1) == -1 ||
11920 PyUnicode_READY(str2) == -1)
11921 result = NULL;
11922 else
11923 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011924 Py_DECREF(self);
11925 Py_DECREF(str1);
11926 Py_DECREF(str2);
11927 return result;
11928}
11929
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011930PyDoc_STRVAR(replace__doc__,
Ezio Melottic1897e72010-06-26 18:50:39 +000011931 "S.replace(old, new[, count]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011932\n\
11933Return a copy of S with all occurrences of substring\n\
Georg Brandlf08a9dd2008-06-10 16:57:31 +000011934old replaced by new. If the optional argument count is\n\
11935given, only the first count occurrences are replaced.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011936
11937static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011938unicode_replace(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011939{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011940 PyObject *str1;
11941 PyObject *str2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011942 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011943 PyObject *result;
11944
Martin v. Löwis18e16552006-02-15 17:27:45 +000011945 if (!PyArg_ParseTuple(args, "OO|n:replace", &str1, &str2, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011946 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060011947 if (PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000011948 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011949 str1 = PyUnicode_FromObject(str1);
Benjamin Peterson22a29702012-01-02 09:00:30 -060011950 if (str1 == NULL)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011951 return NULL;
11952 str2 = PyUnicode_FromObject(str2);
Benjamin Peterson22a29702012-01-02 09:00:30 -060011953 if (str2 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011954 Py_DECREF(str1);
11955 return NULL;
Walter Dörwaldf6b56ae2003-02-09 23:42:56 +000011956 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060011957 if (PyUnicode_READY(str1) == -1 || PyUnicode_READY(str2) == -1)
11958 result = NULL;
11959 else
11960 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011961
11962 Py_DECREF(str1);
11963 Py_DECREF(str2);
11964 return result;
11965}
11966
Alexander Belopolsky40018472011-02-26 01:02:56 +000011967static PyObject *
11968unicode_repr(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011969{
Walter Dörwald79e913e2007-05-12 11:08:06 +000011970 PyObject *repr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011971 Py_ssize_t isize;
11972 Py_ssize_t osize, squote, dquote, i, o;
11973 Py_UCS4 max, quote;
11974 int ikind, okind;
11975 void *idata, *odata;
Walter Dörwald79e913e2007-05-12 11:08:06 +000011976
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011977 if (PyUnicode_READY(unicode) == -1)
Walter Dörwald79e913e2007-05-12 11:08:06 +000011978 return NULL;
11979
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011980 isize = PyUnicode_GET_LENGTH(unicode);
11981 idata = PyUnicode_DATA(unicode);
Walter Dörwald79e913e2007-05-12 11:08:06 +000011982
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011983 /* Compute length of output, quote characters, and
11984 maximum character */
11985 osize = 2; /* quotes */
11986 max = 127;
11987 squote = dquote = 0;
11988 ikind = PyUnicode_KIND(unicode);
11989 for (i = 0; i < isize; i++) {
11990 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
11991 switch (ch) {
11992 case '\'': squote++; osize++; break;
11993 case '"': dquote++; osize++; break;
11994 case '\\': case '\t': case '\r': case '\n':
11995 osize += 2; break;
11996 default:
11997 /* Fast-path ASCII */
11998 if (ch < ' ' || ch == 0x7f)
11999 osize += 4; /* \xHH */
12000 else if (ch < 0x7f)
12001 osize++;
12002 else if (Py_UNICODE_ISPRINTABLE(ch)) {
12003 osize++;
12004 max = ch > max ? ch : max;
12005 }
12006 else if (ch < 0x100)
12007 osize += 4; /* \xHH */
12008 else if (ch < 0x10000)
12009 osize += 6; /* \uHHHH */
12010 else
12011 osize += 10; /* \uHHHHHHHH */
12012 }
12013 }
12014
12015 quote = '\'';
12016 if (squote) {
12017 if (dquote)
12018 /* Both squote and dquote present. Use squote,
12019 and escape them */
12020 osize += squote;
12021 else
12022 quote = '"';
12023 }
12024
12025 repr = PyUnicode_New(osize, max);
12026 if (repr == NULL)
12027 return NULL;
12028 okind = PyUnicode_KIND(repr);
12029 odata = PyUnicode_DATA(repr);
12030
12031 PyUnicode_WRITE(okind, odata, 0, quote);
12032 PyUnicode_WRITE(okind, odata, osize-1, quote);
12033
12034 for (i = 0, o = 1; i < isize; i++) {
12035 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012036
12037 /* Escape quotes and backslashes */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012038 if ((ch == quote) || (ch == '\\')) {
12039 PyUnicode_WRITE(okind, odata, o++, '\\');
12040 PyUnicode_WRITE(okind, odata, o++, ch);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012041 continue;
12042 }
12043
Benjamin Peterson29060642009-01-31 22:14:21 +000012044 /* Map special whitespace to '\t', \n', '\r' */
Georg Brandl559e5d72008-06-11 18:37:52 +000012045 if (ch == '\t') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012046 PyUnicode_WRITE(okind, odata, o++, '\\');
12047 PyUnicode_WRITE(okind, odata, o++, 't');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012048 }
12049 else if (ch == '\n') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012050 PyUnicode_WRITE(okind, odata, o++, '\\');
12051 PyUnicode_WRITE(okind, odata, o++, 'n');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012052 }
12053 else if (ch == '\r') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012054 PyUnicode_WRITE(okind, odata, o++, '\\');
12055 PyUnicode_WRITE(okind, odata, o++, 'r');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012056 }
12057
12058 /* Map non-printable US ASCII to '\xhh' */
Georg Brandl559e5d72008-06-11 18:37:52 +000012059 else if (ch < ' ' || ch == 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012060 PyUnicode_WRITE(okind, odata, o++, '\\');
12061 PyUnicode_WRITE(okind, odata, o++, 'x');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012062 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12063 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012064 }
12065
Georg Brandl559e5d72008-06-11 18:37:52 +000012066 /* Copy ASCII characters as-is */
12067 else if (ch < 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012068 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000012069 }
12070
Benjamin Peterson29060642009-01-31 22:14:21 +000012071 /* Non-ASCII characters */
Georg Brandl559e5d72008-06-11 18:37:52 +000012072 else {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012073 /* Map Unicode whitespace and control characters
Georg Brandl559e5d72008-06-11 18:37:52 +000012074 (categories Z* and C* except ASCII space)
12075 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012076 if (!Py_UNICODE_ISPRINTABLE(ch)) {
Kristján Valur Jónsson55e5dc82012-06-06 21:58:08 +000012077 PyUnicode_WRITE(okind, odata, o++, '\\');
Georg Brandl559e5d72008-06-11 18:37:52 +000012078 /* Map 8-bit characters to '\xhh' */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012079 if (ch <= 0xff) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012080 PyUnicode_WRITE(okind, odata, o++, 'x');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012081 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12082 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012083 }
Kristján Valur Jónsson55e5dc82012-06-06 21:58:08 +000012084 /* Map 16-bit characters to '\uxxxx' */
12085 else if (ch <= 0xffff) {
12086 PyUnicode_WRITE(okind, odata, o++, 'u');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012087 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12088 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12089 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12090 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012091 }
Kristján Valur Jónsson55e5dc82012-06-06 21:58:08 +000012092 /* Map 21-bit characters to '\U00xxxxxx' */
Georg Brandl559e5d72008-06-11 18:37:52 +000012093 else {
Kristján Valur Jónsson55e5dc82012-06-06 21:58:08 +000012094 PyUnicode_WRITE(okind, odata, o++, 'U');
12095 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 28) & 0xF]);
12096 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 24) & 0xF]);
12097 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 20) & 0xF]);
12098 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 16) & 0xF]);
Victor Stinnerf5cff562011-10-14 02:13:11 +020012099 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12100 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12101 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12102 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012103 }
12104 }
12105 /* Copy characters as-is */
12106 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012107 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000012108 }
12109 }
Walter Dörwald79e913e2007-05-12 11:08:06 +000012110 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012111 /* Closing quote already added at the beginning */
Victor Stinner05d11892011-10-06 01:13:58 +020012112 assert(_PyUnicode_CheckConsistency(repr, 1));
Walter Dörwald79e913e2007-05-12 11:08:06 +000012113 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012114}
12115
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012116PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012117 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012118\n\
12119Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080012120such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012121arguments start and end are interpreted as in slice notation.\n\
12122\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012123Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012124
12125static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012126unicode_rfind(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012127{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012128 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012129 Py_ssize_t start;
12130 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012131 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012132
Jesus Ceaac451502011-04-20 17:09:23 +020012133 if (!stringlib_parse_args_finds_unicode("rfind", args, &substring,
12134 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012135 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012136
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012137 if (PyUnicode_READY(self) == -1)
12138 return NULL;
12139 if (PyUnicode_READY(substring) == -1)
12140 return NULL;
12141
Victor Stinner7931d9a2011-11-04 00:22:48 +010012142 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012143
12144 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012145
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012146 if (result == -2)
12147 return NULL;
12148
Christian Heimes217cfd12007-12-02 14:31:20 +000012149 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012150}
12151
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012152PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012153 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012154\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012155Like S.rfind() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012156
12157static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012158unicode_rindex(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012159{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012160 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012161 Py_ssize_t start;
12162 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012163 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012164
Jesus Ceaac451502011-04-20 17:09:23 +020012165 if (!stringlib_parse_args_finds_unicode("rindex", args, &substring,
12166 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012167 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012168
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012169 if (PyUnicode_READY(self) == -1)
12170 return NULL;
12171 if (PyUnicode_READY(substring) == -1)
12172 return NULL;
12173
Victor Stinner7931d9a2011-11-04 00:22:48 +010012174 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012175
12176 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012177
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012178 if (result == -2)
12179 return NULL;
12180
Guido van Rossumd57fd912000-03-10 22:53:23 +000012181 if (result < 0) {
12182 PyErr_SetString(PyExc_ValueError, "substring not found");
12183 return NULL;
12184 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012185
Christian Heimes217cfd12007-12-02 14:31:20 +000012186 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012187}
12188
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012189PyDoc_STRVAR(rjust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012190 "S.rjust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012191\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012192Return S right-justified in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012193done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012194
12195static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012196unicode_rjust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012197{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012198 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012199 Py_UCS4 fillchar = ' ';
12200
Victor Stinnere9a29352011-10-01 02:14:59 +020012201 if (!PyArg_ParseTuple(args, "n|O&:rjust", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012202 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012203
Benjamin Petersonbac79492012-01-14 13:34:47 -050012204 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012205 return NULL;
12206
Victor Stinnerc4b49542011-12-11 22:44:26 +010012207 if (PyUnicode_GET_LENGTH(self) >= width)
12208 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012209
Victor Stinnerc4b49542011-12-11 22:44:26 +010012210 return pad(self, width - PyUnicode_GET_LENGTH(self), 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012211}
12212
Alexander Belopolsky40018472011-02-26 01:02:56 +000012213PyObject *
12214PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012215{
12216 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +000012217
Guido van Rossumd57fd912000-03-10 22:53:23 +000012218 s = PyUnicode_FromObject(s);
12219 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012220 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012221 if (sep != NULL) {
12222 sep = PyUnicode_FromObject(sep);
12223 if (sep == NULL) {
12224 Py_DECREF(s);
12225 return NULL;
12226 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012227 }
12228
Victor Stinner9310abb2011-10-05 00:59:23 +020012229 result = split(s, sep, maxsplit);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012230
12231 Py_DECREF(s);
12232 Py_XDECREF(sep);
12233 return result;
12234}
12235
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012236PyDoc_STRVAR(split__doc__,
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012237 "S.split(sep=None, maxsplit=-1) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012238\n\
12239Return a list of the words in S, using sep as the\n\
12240delimiter string. If maxsplit is given, at most maxsplit\n\
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000012241splits are done. If sep is not specified or is None, any\n\
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +000012242whitespace string is a separator and empty strings are\n\
12243removed from the result.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012244
12245static PyObject*
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012246unicode_split(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012247{
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012248 static char *kwlist[] = {"sep", "maxsplit", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000012249 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012250 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012251
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012252 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:split",
12253 kwlist, &substring, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012254 return NULL;
12255
12256 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012257 return split(self, NULL, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012258 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012259 return split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012260 else
Victor Stinner7931d9a2011-11-04 00:22:48 +010012261 return PyUnicode_Split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012262}
12263
Thomas Wouters477c8d52006-05-27 19:21:47 +000012264PyObject *
12265PyUnicode_Partition(PyObject *str_in, PyObject *sep_in)
12266{
12267 PyObject* str_obj;
12268 PyObject* sep_obj;
12269 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012270 int kind1, kind2, kind;
12271 void *buf1 = NULL, *buf2 = NULL;
12272 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012273
12274 str_obj = PyUnicode_FromObject(str_in);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012275 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012276 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012277 sep_obj = PyUnicode_FromObject(sep_in);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012278 if (!sep_obj) {
12279 Py_DECREF(str_obj);
12280 return NULL;
12281 }
12282 if (PyUnicode_READY(sep_obj) == -1 || PyUnicode_READY(str_obj) == -1) {
12283 Py_DECREF(sep_obj);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012284 Py_DECREF(str_obj);
12285 return NULL;
12286 }
12287
Victor Stinner14f8f022011-10-05 20:58:25 +020012288 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012289 kind2 = PyUnicode_KIND(sep_obj);
Victor Stinner14f8f022011-10-05 20:58:25 +020012290 kind = Py_MAX(kind1, kind2);
12291 buf1 = PyUnicode_DATA(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012292 if (kind1 != kind)
Victor Stinner14f8f022011-10-05 20:58:25 +020012293 buf1 = _PyUnicode_AsKind(str_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012294 if (!buf1)
12295 goto onError;
12296 buf2 = PyUnicode_DATA(sep_obj);
12297 if (kind2 != kind)
12298 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12299 if (!buf2)
12300 goto onError;
12301 len1 = PyUnicode_GET_LENGTH(str_obj);
12302 len2 = PyUnicode_GET_LENGTH(sep_obj);
12303
Benjamin Petersonead6b532011-12-20 17:23:42 -060012304 switch (PyUnicode_KIND(str_obj)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012305 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012306 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12307 out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12308 else
12309 out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012310 break;
12311 case PyUnicode_2BYTE_KIND:
12312 out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12313 break;
12314 case PyUnicode_4BYTE_KIND:
12315 out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12316 break;
12317 default:
12318 assert(0);
12319 out = 0;
12320 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012321
12322 Py_DECREF(sep_obj);
12323 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012324 if (kind1 != kind)
12325 PyMem_Free(buf1);
12326 if (kind2 != kind)
12327 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012328
12329 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012330 onError:
12331 Py_DECREF(sep_obj);
12332 Py_DECREF(str_obj);
12333 if (kind1 != kind && buf1)
12334 PyMem_Free(buf1);
12335 if (kind2 != kind && buf2)
12336 PyMem_Free(buf2);
12337 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012338}
12339
12340
12341PyObject *
12342PyUnicode_RPartition(PyObject *str_in, PyObject *sep_in)
12343{
12344 PyObject* str_obj;
12345 PyObject* sep_obj;
12346 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012347 int kind1, kind2, kind;
12348 void *buf1 = NULL, *buf2 = NULL;
12349 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012350
12351 str_obj = PyUnicode_FromObject(str_in);
12352 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012353 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012354 sep_obj = PyUnicode_FromObject(sep_in);
12355 if (!sep_obj) {
12356 Py_DECREF(str_obj);
12357 return NULL;
12358 }
12359
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012360 kind1 = PyUnicode_KIND(str_in);
12361 kind2 = PyUnicode_KIND(sep_obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +020012362 kind = Py_MAX(kind1, kind2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012363 buf1 = PyUnicode_DATA(str_in);
12364 if (kind1 != kind)
12365 buf1 = _PyUnicode_AsKind(str_in, kind);
12366 if (!buf1)
12367 goto onError;
12368 buf2 = PyUnicode_DATA(sep_obj);
12369 if (kind2 != kind)
12370 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12371 if (!buf2)
12372 goto onError;
12373 len1 = PyUnicode_GET_LENGTH(str_obj);
12374 len2 = PyUnicode_GET_LENGTH(sep_obj);
12375
Benjamin Petersonead6b532011-12-20 17:23:42 -060012376 switch (PyUnicode_KIND(str_in)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012377 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012378 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12379 out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12380 else
12381 out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012382 break;
12383 case PyUnicode_2BYTE_KIND:
12384 out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12385 break;
12386 case PyUnicode_4BYTE_KIND:
12387 out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12388 break;
12389 default:
12390 assert(0);
12391 out = 0;
12392 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012393
12394 Py_DECREF(sep_obj);
12395 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012396 if (kind1 != kind)
12397 PyMem_Free(buf1);
12398 if (kind2 != kind)
12399 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012400
12401 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012402 onError:
12403 Py_DECREF(sep_obj);
12404 Py_DECREF(str_obj);
12405 if (kind1 != kind && buf1)
12406 PyMem_Free(buf1);
12407 if (kind2 != kind && buf2)
12408 PyMem_Free(buf2);
12409 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012410}
12411
12412PyDoc_STRVAR(partition__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012413 "S.partition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012414\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012415Search for the separator sep in S, and return the part before it,\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012416the separator itself, and the part after it. If the separator is not\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012417found, return S and two empty strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012418
12419static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012420unicode_partition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012421{
Victor Stinner9310abb2011-10-05 00:59:23 +020012422 return PyUnicode_Partition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012423}
12424
12425PyDoc_STRVAR(rpartition__doc__,
Ezio Melotti5b2b2422010-01-25 11:58:28 +000012426 "S.rpartition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012427\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012428Search for the separator sep in S, starting at the end of S, and return\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012429the part before it, the separator itself, and the part after it. If the\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012430separator is not found, return two empty strings and S.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012431
12432static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012433unicode_rpartition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012434{
Victor Stinner9310abb2011-10-05 00:59:23 +020012435 return PyUnicode_RPartition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012436}
12437
Alexander Belopolsky40018472011-02-26 01:02:56 +000012438PyObject *
12439PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012440{
12441 PyObject *result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012442
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012443 s = PyUnicode_FromObject(s);
12444 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012445 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012446 if (sep != NULL) {
12447 sep = PyUnicode_FromObject(sep);
12448 if (sep == NULL) {
12449 Py_DECREF(s);
12450 return NULL;
12451 }
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012452 }
12453
Victor Stinner9310abb2011-10-05 00:59:23 +020012454 result = rsplit(s, sep, maxsplit);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012455
12456 Py_DECREF(s);
12457 Py_XDECREF(sep);
12458 return result;
12459}
12460
12461PyDoc_STRVAR(rsplit__doc__,
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012462 "S.rsplit(sep=None, maxsplit=-1) -> list of strings\n\
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012463\n\
12464Return a list of the words in S, using sep as the\n\
12465delimiter string, starting at the end of the string and\n\
12466working to the front. If maxsplit is given, at most maxsplit\n\
12467splits are done. If sep is not specified, any whitespace string\n\
12468is a separator.");
12469
12470static PyObject*
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012471unicode_rsplit(PyObject *self, PyObject *args, PyObject *kwds)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012472{
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012473 static char *kwlist[] = {"sep", "maxsplit", 0};
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012474 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012475 Py_ssize_t maxcount = -1;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012476
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012477 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:rsplit",
12478 kwlist, &substring, &maxcount))
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012479 return NULL;
12480
12481 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012482 return rsplit(self, NULL, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012483 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012484 return rsplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012485 else
Victor Stinner9310abb2011-10-05 00:59:23 +020012486 return PyUnicode_RSplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012487}
12488
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012489PyDoc_STRVAR(splitlines__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012490 "S.splitlines([keepends]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012491\n\
12492Return a list of the lines in S, breaking at line boundaries.\n\
Guido van Rossum86662912000-04-11 15:38:46 +000012493Line breaks are not included in the resulting list unless keepends\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012494is given and true.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012495
12496static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012497unicode_splitlines(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012498{
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012499 static char *kwlist[] = {"keepends", 0};
Guido van Rossum86662912000-04-11 15:38:46 +000012500 int keepends = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012501
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012502 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:splitlines",
12503 kwlist, &keepends))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012504 return NULL;
12505
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012506 return PyUnicode_Splitlines(self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012507}
12508
12509static
Guido van Rossumf15a29f2007-05-04 00:41:39 +000012510PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012511{
Victor Stinnerc4b49542011-12-11 22:44:26 +010012512 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012513}
12514
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012515PyDoc_STRVAR(swapcase__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012516 "S.swapcase() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012517\n\
12518Return a copy of S with uppercase characters converted to lowercase\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012519and vice versa.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012520
12521static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012522unicode_swapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012523{
Benjamin Petersoneea48462012-01-16 14:28:50 -050012524 if (PyUnicode_READY(self) == -1)
12525 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010012526 return case_operation(self, do_swapcase);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012527}
12528
Georg Brandlceee0772007-11-27 23:48:05 +000012529PyDoc_STRVAR(maketrans__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012530 "str.maketrans(x[, y[, z]]) -> dict (static method)\n\
Georg Brandlceee0772007-11-27 23:48:05 +000012531\n\
12532Return a translation table usable for str.translate().\n\
12533If there is only one argument, it must be a dictionary mapping Unicode\n\
12534ordinals (integers) or characters to Unicode ordinals, strings or None.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012535Character keys will be then converted to ordinals.\n\
Georg Brandlceee0772007-11-27 23:48:05 +000012536If there are two arguments, they must be strings of equal length, and\n\
12537in the resulting dictionary, each character in x will be mapped to the\n\
12538character at the same position in y. If there is a third argument, it\n\
12539must be a string, whose characters will be mapped to None in the result.");
12540
12541static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012542unicode_maketrans(PyObject *null, PyObject *args)
Georg Brandlceee0772007-11-27 23:48:05 +000012543{
12544 PyObject *x, *y = NULL, *z = NULL;
12545 PyObject *new = NULL, *key, *value;
12546 Py_ssize_t i = 0;
12547 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012548
Georg Brandlceee0772007-11-27 23:48:05 +000012549 if (!PyArg_ParseTuple(args, "O|UU:maketrans", &x, &y, &z))
12550 return NULL;
12551 new = PyDict_New();
12552 if (!new)
12553 return NULL;
12554 if (y != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012555 int x_kind, y_kind, z_kind;
12556 void *x_data, *y_data, *z_data;
12557
Georg Brandlceee0772007-11-27 23:48:05 +000012558 /* x must be a string too, of equal length */
Georg Brandlceee0772007-11-27 23:48:05 +000012559 if (!PyUnicode_Check(x)) {
12560 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
12561 "be a string if there is a second argument");
12562 goto err;
12563 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012564 if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012565 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
12566 "arguments must have equal length");
12567 goto err;
12568 }
12569 /* create entries for translating chars in x to those in y */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012570 x_kind = PyUnicode_KIND(x);
12571 y_kind = PyUnicode_KIND(y);
12572 x_data = PyUnicode_DATA(x);
12573 y_data = PyUnicode_DATA(y);
12574 for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
12575 key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060012576 if (!key)
Georg Brandlceee0772007-11-27 23:48:05 +000012577 goto err;
Benjamin Peterson822c7902011-12-20 13:32:50 -060012578 value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060012579 if (!value) {
12580 Py_DECREF(key);
12581 goto err;
12582 }
Georg Brandlceee0772007-11-27 23:48:05 +000012583 res = PyDict_SetItem(new, key, value);
12584 Py_DECREF(key);
12585 Py_DECREF(value);
12586 if (res < 0)
12587 goto err;
12588 }
12589 /* create entries for deleting chars in z */
12590 if (z != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012591 z_kind = PyUnicode_KIND(z);
12592 z_data = PyUnicode_DATA(z);
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012593 for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012594 key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000012595 if (!key)
12596 goto err;
12597 res = PyDict_SetItem(new, key, Py_None);
12598 Py_DECREF(key);
12599 if (res < 0)
12600 goto err;
12601 }
12602 }
12603 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012604 int kind;
12605 void *data;
12606
Georg Brandlceee0772007-11-27 23:48:05 +000012607 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +000012608 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012609 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
12610 "to maketrans it must be a dict");
12611 goto err;
12612 }
12613 /* copy entries into the new dict, converting string keys to int keys */
12614 while (PyDict_Next(x, &i, &key, &value)) {
12615 if (PyUnicode_Check(key)) {
12616 /* convert string keys to integer keys */
12617 PyObject *newkey;
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012618 if (PyUnicode_GET_LENGTH(key) != 1) {
Georg Brandlceee0772007-11-27 23:48:05 +000012619 PyErr_SetString(PyExc_ValueError, "string keys in translate "
12620 "table must be of length 1");
12621 goto err;
12622 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012623 kind = PyUnicode_KIND(key);
12624 data = PyUnicode_DATA(key);
12625 newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
Georg Brandlceee0772007-11-27 23:48:05 +000012626 if (!newkey)
12627 goto err;
12628 res = PyDict_SetItem(new, newkey, value);
12629 Py_DECREF(newkey);
12630 if (res < 0)
12631 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +000012632 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012633 /* just keep integer keys */
12634 if (PyDict_SetItem(new, key, value) < 0)
12635 goto err;
12636 } else {
12637 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
12638 "be strings or integers");
12639 goto err;
12640 }
12641 }
12642 }
12643 return new;
12644 err:
12645 Py_DECREF(new);
12646 return NULL;
12647}
12648
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012649PyDoc_STRVAR(translate__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012650 "S.translate(table) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012651\n\
12652Return a copy of the string S, where all characters have been mapped\n\
12653through the given translation table, which must be a mapping of\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012654Unicode ordinals to Unicode ordinals, strings, or None.\n\
Walter Dörwald5c1ee172002-09-04 20:31:32 +000012655Unmapped characters are left untouched. Characters mapped to None\n\
12656are deleted.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012657
12658static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012659unicode_translate(PyObject *self, PyObject *table)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012660{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012661 return _PyUnicode_TranslateCharmap(self, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012662}
12663
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012664PyDoc_STRVAR(upper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012665 "S.upper() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012666\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012667Return a copy of S converted to uppercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012668
12669static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012670unicode_upper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012671{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050012672 if (PyUnicode_READY(self) == -1)
12673 return NULL;
12674 if (PyUnicode_IS_ASCII(self))
12675 return ascii_upper_or_lower(self, 0);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010012676 return case_operation(self, do_upper);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012677}
12678
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012679PyDoc_STRVAR(zfill__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012680 "S.zfill(width) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012681\n\
Benjamin Peterson9aa42992008-09-10 21:57:34 +000012682Pad a numeric string S with zeros on the left, to fill a field\n\
12683of the specified width. The string S is never truncated.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012684
12685static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012686unicode_zfill(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012687{
Martin v. Löwis18e16552006-02-15 17:27:45 +000012688 Py_ssize_t fill;
Victor Stinner9310abb2011-10-05 00:59:23 +020012689 PyObject *u;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012690 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012691 int kind;
12692 void *data;
12693 Py_UCS4 chr;
12694
Martin v. Löwis18e16552006-02-15 17:27:45 +000012695 if (!PyArg_ParseTuple(args, "n:zfill", &width))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012696 return NULL;
12697
Benjamin Petersonbac79492012-01-14 13:34:47 -050012698 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010012699 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012700
Victor Stinnerc4b49542011-12-11 22:44:26 +010012701 if (PyUnicode_GET_LENGTH(self) >= width)
12702 return unicode_result_unchanged(self);
12703
12704 fill = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012705
12706 u = pad(self, fill, 0, '0');
12707
Walter Dörwald068325e2002-04-15 13:36:47 +000012708 if (u == NULL)
12709 return NULL;
12710
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012711 kind = PyUnicode_KIND(u);
12712 data = PyUnicode_DATA(u);
12713 chr = PyUnicode_READ(kind, data, fill);
12714
12715 if (chr == '+' || chr == '-') {
Guido van Rossumd57fd912000-03-10 22:53:23 +000012716 /* move sign to beginning of string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012717 PyUnicode_WRITE(kind, data, 0, chr);
12718 PyUnicode_WRITE(kind, data, fill, '0');
Guido van Rossumd57fd912000-03-10 22:53:23 +000012719 }
12720
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012721 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +010012722 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012723}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012724
12725#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012726static PyObject *
12727unicode__decimal2ascii(PyObject *self)
12728{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012729 return PyUnicode_TransformDecimalAndSpaceToASCII(self);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012730}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012731#endif
12732
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012733PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012734 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012735\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000012736Return True if S starts with the specified prefix, False otherwise.\n\
12737With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012738With optional end, stop comparing S at that position.\n\
12739prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012740
12741static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012742unicode_startswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000012743 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012744{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012745 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012746 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012747 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012748 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012749 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012750
Jesus Ceaac451502011-04-20 17:09:23 +020012751 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000012752 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012753 if (PyTuple_Check(subobj)) {
12754 Py_ssize_t i;
12755 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012756 substring = PyUnicode_FromObject(PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012757 if (substring == NULL)
12758 return NULL;
12759 result = tailmatch(self, substring, start, end, -1);
12760 Py_DECREF(substring);
12761 if (result) {
12762 Py_RETURN_TRUE;
12763 }
12764 }
12765 /* nothing matched */
12766 Py_RETURN_FALSE;
12767 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012768 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030012769 if (substring == NULL) {
12770 if (PyErr_ExceptionMatches(PyExc_TypeError))
12771 PyErr_Format(PyExc_TypeError, "startswith first arg must be str or "
12772 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000012773 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030012774 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012775 result = tailmatch(self, substring, start, end, -1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012776 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012777 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012778}
12779
12780
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012781PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012782 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012783\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000012784Return True if S ends with the specified suffix, False otherwise.\n\
12785With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012786With optional end, stop comparing S at that position.\n\
12787suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012788
12789static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012790unicode_endswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000012791 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012792{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012793 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012794 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012795 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012796 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012797 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012798
Jesus Ceaac451502011-04-20 17:09:23 +020012799 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000012800 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012801 if (PyTuple_Check(subobj)) {
12802 Py_ssize_t i;
12803 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012804 substring = PyUnicode_FromObject(
Benjamin Peterson29060642009-01-31 22:14:21 +000012805 PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012806 if (substring == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000012807 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012808 result = tailmatch(self, substring, start, end, +1);
12809 Py_DECREF(substring);
12810 if (result) {
12811 Py_RETURN_TRUE;
12812 }
12813 }
12814 Py_RETURN_FALSE;
12815 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012816 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030012817 if (substring == NULL) {
12818 if (PyErr_ExceptionMatches(PyExc_TypeError))
12819 PyErr_Format(PyExc_TypeError, "endswith first arg must be str or "
12820 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000012821 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030012822 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012823 result = tailmatch(self, substring, start, end, +1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012824 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012825 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012826}
12827
Victor Stinner202fdca2012-05-07 12:47:02 +020012828Py_LOCAL_INLINE(void)
Victor Stinner3b1a74a2012-05-09 22:25:00 +020012829_PyUnicodeWriter_Update(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020012830{
Victor Stinnerd3f08822012-05-29 12:57:52 +020012831 writer->size = PyUnicode_GET_LENGTH(writer->buffer);
Victor Stinner202fdca2012-05-07 12:47:02 +020012832 writer->maxchar = PyUnicode_MAX_CHAR_VALUE(writer->buffer);
12833 writer->data = PyUnicode_DATA(writer->buffer);
12834 writer->kind = PyUnicode_KIND(writer->buffer);
12835}
12836
Victor Stinnerd3f08822012-05-29 12:57:52 +020012837void
12838_PyUnicodeWriter_Init(_PyUnicodeWriter *writer, Py_ssize_t min_length)
Victor Stinner202fdca2012-05-07 12:47:02 +020012839{
Victor Stinnerd3f08822012-05-29 12:57:52 +020012840 memset(writer, 0, sizeof(*writer));
12841#ifdef Py_DEBUG
12842 writer->kind = 5; /* invalid kind */
12843#endif
12844 writer->min_length = Py_MAX(min_length, 100);
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012845 writer->overallocate = (min_length > 0);
Victor Stinner202fdca2012-05-07 12:47:02 +020012846}
12847
Victor Stinnerd3f08822012-05-29 12:57:52 +020012848int
12849_PyUnicodeWriter_PrepareInternal(_PyUnicodeWriter *writer,
12850 Py_ssize_t length, Py_UCS4 maxchar)
Victor Stinner202fdca2012-05-07 12:47:02 +020012851{
12852 Py_ssize_t newlen;
12853 PyObject *newbuffer;
12854
Victor Stinnerd3f08822012-05-29 12:57:52 +020012855 assert(length > 0);
12856
Victor Stinner202fdca2012-05-07 12:47:02 +020012857 if (length > PY_SSIZE_T_MAX - writer->pos) {
12858 PyErr_NoMemory();
12859 return -1;
12860 }
12861 newlen = writer->pos + length;
12862
Victor Stinnerd3f08822012-05-29 12:57:52 +020012863 if (writer->buffer == NULL) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012864 if (writer->overallocate) {
Victor Stinnerd3f08822012-05-29 12:57:52 +020012865 /* overallocate 25% to limit the number of resize */
12866 if (newlen <= (PY_SSIZE_T_MAX - newlen / 4))
12867 newlen += newlen / 4;
12868 if (newlen < writer->min_length)
12869 newlen = writer->min_length;
12870 }
12871 writer->buffer = PyUnicode_New(newlen, maxchar);
12872 if (writer->buffer == NULL)
12873 return -1;
12874 _PyUnicodeWriter_Update(writer);
12875 return 0;
12876 }
Victor Stinner202fdca2012-05-07 12:47:02 +020012877
Victor Stinnerd3f08822012-05-29 12:57:52 +020012878 if (newlen > writer->size) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012879 if (writer->overallocate) {
Victor Stinnerd3f08822012-05-29 12:57:52 +020012880 /* overallocate 25% to limit the number of resize */
12881 if (newlen <= (PY_SSIZE_T_MAX - newlen / 4))
12882 newlen += newlen / 4;
12883 if (newlen < writer->min_length)
12884 newlen = writer->min_length;
12885 }
12886
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012887 if (maxchar > writer->maxchar || writer->readonly) {
Victor Stinner202fdca2012-05-07 12:47:02 +020012888 /* resize + widen */
12889 newbuffer = PyUnicode_New(newlen, maxchar);
12890 if (newbuffer == NULL)
12891 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020012892 _PyUnicode_FastCopyCharacters(newbuffer, 0,
12893 writer->buffer, 0, writer->pos);
Victor Stinner202fdca2012-05-07 12:47:02 +020012894 Py_DECREF(writer->buffer);
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012895 writer->readonly = 0;
Victor Stinner202fdca2012-05-07 12:47:02 +020012896 }
12897 else {
12898 newbuffer = resize_compact(writer->buffer, newlen);
12899 if (newbuffer == NULL)
12900 return -1;
12901 }
12902 writer->buffer = newbuffer;
Victor Stinner3b1a74a2012-05-09 22:25:00 +020012903 _PyUnicodeWriter_Update(writer);
Victor Stinner202fdca2012-05-07 12:47:02 +020012904 }
12905 else if (maxchar > writer->maxchar) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012906 assert(!writer->readonly);
Victor Stinnerd3f08822012-05-29 12:57:52 +020012907 newbuffer = PyUnicode_New(writer->size, maxchar);
12908 if (newbuffer == NULL)
Victor Stinner202fdca2012-05-07 12:47:02 +020012909 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020012910 _PyUnicode_FastCopyCharacters(newbuffer, 0,
12911 writer->buffer, 0, writer->pos);
12912 Py_DECREF(writer->buffer);
12913 writer->buffer = newbuffer;
Victor Stinner3b1a74a2012-05-09 22:25:00 +020012914 _PyUnicodeWriter_Update(writer);
Victor Stinner202fdca2012-05-07 12:47:02 +020012915 }
12916 return 0;
12917}
12918
Victor Stinnerd3f08822012-05-29 12:57:52 +020012919int
12920_PyUnicodeWriter_WriteStr(_PyUnicodeWriter *writer, PyObject *str)
12921{
12922 Py_UCS4 maxchar;
12923 Py_ssize_t len;
12924
12925 if (PyUnicode_READY(str) == -1)
12926 return -1;
12927 len = PyUnicode_GET_LENGTH(str);
12928 if (len == 0)
12929 return 0;
12930 maxchar = PyUnicode_MAX_CHAR_VALUE(str);
12931 if (maxchar > writer->maxchar || len > writer->size - writer->pos) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012932 if (writer->buffer == NULL && !writer->overallocate) {
Victor Stinnerd3f08822012-05-29 12:57:52 +020012933 Py_INCREF(str);
12934 writer->buffer = str;
12935 _PyUnicodeWriter_Update(writer);
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012936 writer->readonly = 1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020012937 writer->size = 0;
12938 writer->pos += len;
12939 return 0;
12940 }
12941 if (_PyUnicodeWriter_PrepareInternal(writer, len, maxchar) == -1)
12942 return -1;
12943 }
12944 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
12945 str, 0, len);
12946 writer->pos += len;
12947 return 0;
12948}
12949
12950PyObject *
Victor Stinner3b1a74a2012-05-09 22:25:00 +020012951_PyUnicodeWriter_Finish(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020012952{
Victor Stinnerd3f08822012-05-29 12:57:52 +020012953 if (writer->pos == 0) {
12954 Py_XDECREF(writer->buffer);
12955 Py_INCREF(unicode_empty);
12956 return unicode_empty;
12957 }
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012958 if (writer->readonly) {
Victor Stinnerd3f08822012-05-29 12:57:52 +020012959 assert(PyUnicode_GET_LENGTH(writer->buffer) == writer->pos);
12960 return writer->buffer;
12961 }
12962 if (PyUnicode_GET_LENGTH(writer->buffer) != writer->pos) {
12963 PyObject *newbuffer;
12964 newbuffer = resize_compact(writer->buffer, writer->pos);
12965 if (newbuffer == NULL) {
12966 Py_DECREF(writer->buffer);
12967 return NULL;
12968 }
12969 writer->buffer = newbuffer;
Victor Stinner202fdca2012-05-07 12:47:02 +020012970 }
Victor Stinnerf59c28c2012-05-09 03:24:14 +020012971 assert(_PyUnicode_CheckConsistency(writer->buffer, 1));
Victor Stinner202fdca2012-05-07 12:47:02 +020012972 return writer->buffer;
12973}
12974
Victor Stinnerd3f08822012-05-29 12:57:52 +020012975void
Victor Stinner3b1a74a2012-05-09 22:25:00 +020012976_PyUnicodeWriter_Dealloc(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020012977{
12978 Py_CLEAR(writer->buffer);
12979}
12980
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012981#include "stringlib/unicode_format.h"
Eric Smith8c663262007-08-25 02:26:07 +000012982
12983PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012984 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000012985\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012986Return a formatted version of S, using substitutions from args and kwargs.\n\
12987The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +000012988
Eric Smith27bbca62010-11-04 17:06:58 +000012989PyDoc_STRVAR(format_map__doc__,
12990 "S.format_map(mapping) -> str\n\
12991\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012992Return a formatted version of S, using substitutions from mapping.\n\
12993The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +000012994
Eric Smith4a7d76d2008-05-30 18:10:19 +000012995static PyObject *
12996unicode__format__(PyObject* self, PyObject* args)
12997{
Victor Stinnerd3f08822012-05-29 12:57:52 +020012998 PyObject *format_spec;
12999 _PyUnicodeWriter writer;
13000 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +000013001
13002 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
13003 return NULL;
13004
Victor Stinnerd3f08822012-05-29 12:57:52 +020013005 if (PyUnicode_READY(self) == -1)
13006 return NULL;
13007 _PyUnicodeWriter_Init(&writer, 0);
13008 ret = _PyUnicode_FormatAdvancedWriter(&writer,
13009 self, format_spec, 0,
13010 PyUnicode_GET_LENGTH(format_spec));
13011 if (ret == -1) {
13012 _PyUnicodeWriter_Dealloc(&writer);
13013 return NULL;
13014 }
13015 return _PyUnicodeWriter_Finish(&writer);
Eric Smith4a7d76d2008-05-30 18:10:19 +000013016}
13017
Eric Smith8c663262007-08-25 02:26:07 +000013018PyDoc_STRVAR(p_format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013019 "S.__format__(format_spec) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000013020\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013021Return a formatted version of S as described by format_spec.");
Eric Smith8c663262007-08-25 02:26:07 +000013022
13023static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013024unicode__sizeof__(PyObject *v)
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013025{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013026 Py_ssize_t size;
13027
13028 /* If it's a compact object, account for base structure +
13029 character data. */
13030 if (PyUnicode_IS_COMPACT_ASCII(v))
13031 size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(v) + 1;
13032 else if (PyUnicode_IS_COMPACT(v))
13033 size = sizeof(PyCompactUnicodeObject) +
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013034 (PyUnicode_GET_LENGTH(v) + 1) * PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013035 else {
13036 /* If it is a two-block object, account for base object, and
13037 for character block if present. */
13038 size = sizeof(PyUnicodeObject);
Victor Stinnerc3c74152011-10-02 20:39:55 +020013039 if (_PyUnicode_DATA_ANY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013040 size += (PyUnicode_GET_LENGTH(v) + 1) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013041 PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013042 }
13043 /* If the wstr pointer is present, account for it unless it is shared
Victor Stinnera3be6132011-10-03 02:16:37 +020013044 with the data pointer. Check if the data is not shared. */
Victor Stinner03490912011-10-03 23:45:12 +020013045 if (_PyUnicode_HAS_WSTR_MEMORY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013046 size += (PyUnicode_WSTR_LENGTH(v) + 1) * sizeof(wchar_t);
Victor Stinner829c0ad2011-10-03 01:08:02 +020013047 if (_PyUnicode_HAS_UTF8_MEMORY(v))
Victor Stinnere90fe6a2011-10-01 16:48:13 +020013048 size += PyUnicode_UTF8_LENGTH(v) + 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013049
13050 return PyLong_FromSsize_t(size);
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013051}
13052
13053PyDoc_STRVAR(sizeof__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013054 "S.__sizeof__() -> size of S in memory, in bytes");
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013055
13056static PyObject *
Victor Stinner034f6cf2011-09-30 02:26:44 +020013057unicode_getnewargs(PyObject *v)
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013058{
Victor Stinnerbf6e5602011-12-12 01:53:47 +010013059 PyObject *copy = _PyUnicode_Copy(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013060 if (!copy)
13061 return NULL;
13062 return Py_BuildValue("(N)", copy);
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013063}
13064
Guido van Rossumd57fd912000-03-10 22:53:23 +000013065static PyMethodDef unicode_methods[] = {
Benjamin Peterson28a4dce2010-12-12 01:33:04 +000013066 {"encode", (PyCFunction) unicode_encode, METH_VARARGS | METH_KEYWORDS, encode__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013067 {"replace", (PyCFunction) unicode_replace, METH_VARARGS, replace__doc__},
Ezio Melotticda6b6d2012-02-26 09:39:55 +020013068 {"split", (PyCFunction) unicode_split, METH_VARARGS | METH_KEYWORDS, split__doc__},
13069 {"rsplit", (PyCFunction) unicode_rsplit, METH_VARARGS | METH_KEYWORDS, rsplit__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013070 {"join", (PyCFunction) unicode_join, METH_O, join__doc__},
13071 {"capitalize", (PyCFunction) unicode_capitalize, METH_NOARGS, capitalize__doc__},
Benjamin Petersond5890c82012-01-14 13:23:30 -050013072 {"casefold", (PyCFunction) unicode_casefold, METH_NOARGS, casefold__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013073 {"title", (PyCFunction) unicode_title, METH_NOARGS, title__doc__},
13074 {"center", (PyCFunction) unicode_center, METH_VARARGS, center__doc__},
13075 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
13076 {"expandtabs", (PyCFunction) unicode_expandtabs, METH_VARARGS, expandtabs__doc__},
13077 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013078 {"partition", (PyCFunction) unicode_partition, METH_O, partition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013079 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
13080 {"ljust", (PyCFunction) unicode_ljust, METH_VARARGS, ljust__doc__},
13081 {"lower", (PyCFunction) unicode_lower, METH_NOARGS, lower__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013082 {"lstrip", (PyCFunction) unicode_lstrip, METH_VARARGS, lstrip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013083 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
13084 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
13085 {"rjust", (PyCFunction) unicode_rjust, METH_VARARGS, rjust__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013086 {"rstrip", (PyCFunction) unicode_rstrip, METH_VARARGS, rstrip__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013087 {"rpartition", (PyCFunction) unicode_rpartition, METH_O, rpartition__doc__},
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010013088 {"splitlines", (PyCFunction) unicode_splitlines, METH_VARARGS | METH_KEYWORDS, splitlines__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013089 {"strip", (PyCFunction) unicode_strip, METH_VARARGS, strip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013090 {"swapcase", (PyCFunction) unicode_swapcase, METH_NOARGS, swapcase__doc__},
13091 {"translate", (PyCFunction) unicode_translate, METH_O, translate__doc__},
13092 {"upper", (PyCFunction) unicode_upper, METH_NOARGS, upper__doc__},
13093 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
13094 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
13095 {"islower", (PyCFunction) unicode_islower, METH_NOARGS, islower__doc__},
13096 {"isupper", (PyCFunction) unicode_isupper, METH_NOARGS, isupper__doc__},
13097 {"istitle", (PyCFunction) unicode_istitle, METH_NOARGS, istitle__doc__},
13098 {"isspace", (PyCFunction) unicode_isspace, METH_NOARGS, isspace__doc__},
13099 {"isdecimal", (PyCFunction) unicode_isdecimal, METH_NOARGS, isdecimal__doc__},
13100 {"isdigit", (PyCFunction) unicode_isdigit, METH_NOARGS, isdigit__doc__},
13101 {"isnumeric", (PyCFunction) unicode_isnumeric, METH_NOARGS, isnumeric__doc__},
13102 {"isalpha", (PyCFunction) unicode_isalpha, METH_NOARGS, isalpha__doc__},
13103 {"isalnum", (PyCFunction) unicode_isalnum, METH_NOARGS, isalnum__doc__},
Martin v. Löwis47383402007-08-15 07:32:56 +000013104 {"isidentifier", (PyCFunction) unicode_isidentifier, METH_NOARGS, isidentifier__doc__},
Georg Brandl559e5d72008-06-11 18:37:52 +000013105 {"isprintable", (PyCFunction) unicode_isprintable, METH_NOARGS, isprintable__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013106 {"zfill", (PyCFunction) unicode_zfill, METH_VARARGS, zfill__doc__},
Eric Smith9cd1e092007-08-31 18:39:38 +000013107 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +000013108 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
Eric Smith4a7d76d2008-05-30 18:10:19 +000013109 {"__format__", (PyCFunction) unicode__format__, METH_VARARGS, p_format__doc__},
Georg Brandlceee0772007-11-27 23:48:05 +000013110 {"maketrans", (PyCFunction) unicode_maketrans,
13111 METH_VARARGS | METH_STATIC, maketrans__doc__},
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013112 {"__sizeof__", (PyCFunction) unicode__sizeof__, METH_NOARGS, sizeof__doc__},
Walter Dörwald068325e2002-04-15 13:36:47 +000013113#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013114 /* These methods are just used for debugging the implementation. */
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013115 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013116#endif
13117
Benjamin Peterson14339b62009-01-31 16:36:08 +000013118 {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013119 {NULL, NULL}
13120};
13121
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013122static PyObject *
13123unicode_mod(PyObject *v, PyObject *w)
13124{
Brian Curtindfc80e32011-08-10 20:28:54 -050013125 if (!PyUnicode_Check(v))
13126 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson29060642009-01-31 22:14:21 +000013127 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013128}
13129
13130static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013131 0, /*nb_add*/
13132 0, /*nb_subtract*/
13133 0, /*nb_multiply*/
13134 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013135};
13136
Guido van Rossumd57fd912000-03-10 22:53:23 +000013137static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013138 (lenfunc) unicode_length, /* sq_length */
13139 PyUnicode_Concat, /* sq_concat */
13140 (ssizeargfunc) unicode_repeat, /* sq_repeat */
13141 (ssizeargfunc) unicode_getitem, /* sq_item */
13142 0, /* sq_slice */
13143 0, /* sq_ass_item */
13144 0, /* sq_ass_slice */
13145 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013146};
13147
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013148static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013149unicode_subscript(PyObject* self, PyObject* item)
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013150{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013151 if (PyUnicode_READY(self) == -1)
13152 return NULL;
13153
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000013154 if (PyIndex_Check(item)) {
13155 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013156 if (i == -1 && PyErr_Occurred())
13157 return NULL;
13158 if (i < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013159 i += PyUnicode_GET_LENGTH(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013160 return unicode_getitem(self, i);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013161 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000013162 Py_ssize_t start, stop, step, slicelength, cur, i;
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013163 PyObject *result;
13164 void *src_data, *dest_data;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013165 int src_kind, dest_kind;
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013166 Py_UCS4 ch, max_char, kind_limit;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013167
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013168 if (PySlice_GetIndicesEx(item, PyUnicode_GET_LENGTH(self),
Benjamin Peterson29060642009-01-31 22:14:21 +000013169 &start, &stop, &step, &slicelength) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013170 return NULL;
13171 }
13172
13173 if (slicelength <= 0) {
Victor Stinner382955f2011-12-11 21:44:00 +010013174 Py_INCREF(unicode_empty);
13175 return unicode_empty;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013176 } else if (start == 0 && step == 1 &&
Victor Stinnerc4b49542011-12-11 22:44:26 +010013177 slicelength == PyUnicode_GET_LENGTH(self)) {
13178 return unicode_result_unchanged(self);
Thomas Woutersed03b412007-08-28 21:37:11 +000013179 } else if (step == 1) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013180 return PyUnicode_Substring(self,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013181 start, start + slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013182 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013183 /* General case */
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013184 src_kind = PyUnicode_KIND(self);
13185 src_data = PyUnicode_DATA(self);
Victor Stinner55c99112011-10-13 01:17:06 +020013186 if (!PyUnicode_IS_ASCII(self)) {
13187 kind_limit = kind_maxchar_limit(src_kind);
13188 max_char = 0;
13189 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
13190 ch = PyUnicode_READ(src_kind, src_data, cur);
13191 if (ch > max_char) {
13192 max_char = ch;
13193 if (max_char >= kind_limit)
13194 break;
13195 }
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013196 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013197 }
Victor Stinner55c99112011-10-13 01:17:06 +020013198 else
13199 max_char = 127;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013200 result = PyUnicode_New(slicelength, max_char);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013201 if (result == NULL)
13202 return NULL;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013203 dest_kind = PyUnicode_KIND(result);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013204 dest_data = PyUnicode_DATA(result);
13205
13206 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013207 Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
13208 PyUnicode_WRITE(dest_kind, dest_data, i, ch);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013209 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013210 assert(_PyUnicode_CheckConsistency(result, 1));
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013211 return result;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013212 } else {
13213 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
13214 return NULL;
13215 }
13216}
13217
13218static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013219 (lenfunc)unicode_length, /* mp_length */
13220 (binaryfunc)unicode_subscript, /* mp_subscript */
13221 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013222};
13223
Guido van Rossumd57fd912000-03-10 22:53:23 +000013224
Guido van Rossumd57fd912000-03-10 22:53:23 +000013225/* Helpers for PyUnicode_Format() */
13226
13227static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +000013228getnextarg(PyObject *args, Py_ssize_t arglen, Py_ssize_t *p_argidx)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013229{
Martin v. Löwis18e16552006-02-15 17:27:45 +000013230 Py_ssize_t argidx = *p_argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013231 if (argidx < arglen) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013232 (*p_argidx)++;
13233 if (arglen < 0)
13234 return args;
13235 else
13236 return PyTuple_GetItem(args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013237 }
13238 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013239 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013240 return NULL;
13241}
13242
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013243/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013244
Victor Stinnerd3f08822012-05-29 12:57:52 +020013245static int
13246formatfloat(PyObject *v, int flags, int prec, int type,
13247 PyObject **p_output, _PyUnicodeWriter *writer)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013248{
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013249 char *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013250 double x;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013251 Py_ssize_t len;
Tim Petersced69f82003-09-16 20:30:58 +000013252
Guido van Rossumd57fd912000-03-10 22:53:23 +000013253 x = PyFloat_AsDouble(v);
13254 if (x == -1.0 && PyErr_Occurred())
Victor Stinnerd3f08822012-05-29 12:57:52 +020013255 return -1;
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013256
Guido van Rossumd57fd912000-03-10 22:53:23 +000013257 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000013258 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +000013259
Eric Smith0923d1d2009-04-16 20:16:10 +000013260 p = PyOS_double_to_string(x, type, prec,
13261 (flags & F_ALT) ? Py_DTSF_ALT : 0, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013262 if (p == NULL)
Victor Stinnerd3f08822012-05-29 12:57:52 +020013263 return -1;
13264 len = strlen(p);
13265 if (writer) {
Christian Heimesf4f99392012-09-10 11:48:41 +020013266 if (_PyUnicodeWriter_Prepare(writer, len, 127) == -1) {
13267 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013268 return -1;
Christian Heimesf4f99392012-09-10 11:48:41 +020013269 }
Victor Stinner184252a2012-06-16 02:57:41 +020013270 unicode_write_cstr(writer->buffer, writer->pos, p, len);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013271 writer->pos += len;
13272 }
13273 else
13274 *p_output = _PyUnicode_FromASCII(p, len);
Eric Smith0923d1d2009-04-16 20:16:10 +000013275 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013276 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013277}
13278
Victor Stinnerd0880d52012-04-27 23:40:13 +020013279/* formatlong() emulates the format codes d, u, o, x and X, and
13280 * the F_ALT flag, for Python's long (unbounded) ints. It's not used for
13281 * Python's regular ints.
13282 * Return value: a new PyUnicodeObject*, or NULL if error.
13283 * The output string is of the form
13284 * "-"? ("0x" | "0X")? digit+
13285 * "0x"/"0X" are present only for x and X conversions, with F_ALT
13286 * set in flags. The case of hex digits will be correct,
13287 * There will be at least prec digits, zero-filled on the left if
13288 * necessary to get that many.
13289 * val object to be converted
13290 * flags bitmask of format flags; only F_ALT is looked at
13291 * prec minimum number of digits; 0-fill on left if needed
13292 * type a character in [duoxX]; u acts the same as d
13293 *
13294 * CAUTION: o, x and X conversions on regular ints can never
13295 * produce a '-' sign, but can for Python's unbounded ints.
13296 */
Tim Peters38fd5b62000-09-21 05:43:11 +000013297static PyObject*
13298formatlong(PyObject *val, int flags, int prec, int type)
13299{
Victor Stinnerd0880d52012-04-27 23:40:13 +020013300 PyObject *result = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013301 char *buf;
Victor Stinnerd0880d52012-04-27 23:40:13 +020013302 Py_ssize_t i;
13303 int sign; /* 1 if '-', else 0 */
13304 int len; /* number of characters */
13305 Py_ssize_t llen;
13306 int numdigits; /* len == numnondigits + numdigits */
13307 int numnondigits = 0;
Tim Peters38fd5b62000-09-21 05:43:11 +000013308
Victor Stinnerd0880d52012-04-27 23:40:13 +020013309 /* Avoid exceeding SSIZE_T_MAX */
13310 if (prec > INT_MAX-3) {
13311 PyErr_SetString(PyExc_OverflowError,
13312 "precision too large");
Benjamin Peterson14339b62009-01-31 16:36:08 +000013313 return NULL;
Victor Stinnerd0880d52012-04-27 23:40:13 +020013314 }
13315
13316 assert(PyLong_Check(val));
13317
13318 switch (type) {
Victor Stinner621ef3d2012-10-02 00:33:47 +020013319 default:
13320 assert(!"'type' not in [diuoxX]");
Victor Stinnerd0880d52012-04-27 23:40:13 +020013321 case 'd':
Victor Stinner621ef3d2012-10-02 00:33:47 +020013322 case 'i':
Victor Stinnerd0880d52012-04-27 23:40:13 +020013323 case 'u':
13324 /* Special-case boolean: we want 0/1 */
Victor Stinnerb11d91d2012-04-28 00:25:34 +020013325 if (PyBool_Check(val))
13326 result = PyNumber_ToBase(val, 10);
13327 else
13328 result = Py_TYPE(val)->tp_str(val);
Victor Stinnerd0880d52012-04-27 23:40:13 +020013329 break;
13330 case 'o':
13331 numnondigits = 2;
13332 result = PyNumber_ToBase(val, 8);
13333 break;
13334 case 'x':
13335 case 'X':
13336 numnondigits = 2;
13337 result = PyNumber_ToBase(val, 16);
13338 break;
Victor Stinnerd0880d52012-04-27 23:40:13 +020013339 }
13340 if (!result)
13341 return NULL;
13342
13343 assert(unicode_modifiable(result));
13344 assert(PyUnicode_IS_READY(result));
13345 assert(PyUnicode_IS_ASCII(result));
13346
13347 /* To modify the string in-place, there can only be one reference. */
13348 if (Py_REFCNT(result) != 1) {
13349 PyErr_BadInternalCall();
13350 return NULL;
13351 }
13352 buf = PyUnicode_DATA(result);
13353 llen = PyUnicode_GET_LENGTH(result);
13354 if (llen > INT_MAX) {
13355 PyErr_SetString(PyExc_ValueError,
13356 "string too large in _PyBytes_FormatLong");
13357 return NULL;
13358 }
13359 len = (int)llen;
13360 sign = buf[0] == '-';
13361 numnondigits += sign;
13362 numdigits = len - numnondigits;
13363 assert(numdigits > 0);
13364
13365 /* Get rid of base marker unless F_ALT */
13366 if (((flags & F_ALT) == 0 &&
13367 (type == 'o' || type == 'x' || type == 'X'))) {
13368 assert(buf[sign] == '0');
13369 assert(buf[sign+1] == 'x' || buf[sign+1] == 'X' ||
13370 buf[sign+1] == 'o');
13371 numnondigits -= 2;
13372 buf += 2;
13373 len -= 2;
13374 if (sign)
13375 buf[0] = '-';
13376 assert(len == numnondigits + numdigits);
13377 assert(numdigits > 0);
13378 }
13379
13380 /* Fill with leading zeroes to meet minimum width. */
13381 if (prec > numdigits) {
13382 PyObject *r1 = PyBytes_FromStringAndSize(NULL,
13383 numnondigits + prec);
13384 char *b1;
13385 if (!r1) {
13386 Py_DECREF(result);
13387 return NULL;
13388 }
13389 b1 = PyBytes_AS_STRING(r1);
13390 for (i = 0; i < numnondigits; ++i)
13391 *b1++ = *buf++;
13392 for (i = 0; i < prec - numdigits; i++)
13393 *b1++ = '0';
13394 for (i = 0; i < numdigits; i++)
13395 *b1++ = *buf++;
13396 *b1 = '\0';
13397 Py_DECREF(result);
13398 result = r1;
13399 buf = PyBytes_AS_STRING(result);
13400 len = numnondigits + prec;
13401 }
13402
13403 /* Fix up case for hex conversions. */
13404 if (type == 'X') {
13405 /* Need to convert all lower case letters to upper case.
13406 and need to convert 0x to 0X (and -0x to -0X). */
13407 for (i = 0; i < len; i++)
13408 if (buf[i] >= 'a' && buf[i] <= 'x')
13409 buf[i] -= 'a'-'A';
13410 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020013411 if (!PyUnicode_Check(result)
13412 || buf != PyUnicode_DATA(result)) {
Victor Stinnerd0880d52012-04-27 23:40:13 +020013413 PyObject *unicode;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013414 unicode = _PyUnicode_FromASCII(buf, len);
Victor Stinnerd0880d52012-04-27 23:40:13 +020013415 Py_DECREF(result);
13416 result = unicode;
13417 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020013418 else if (len != PyUnicode_GET_LENGTH(result)) {
13419 if (PyUnicode_Resize(&result, len) < 0)
13420 Py_CLEAR(result);
13421 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000013422 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +000013423}
13424
Victor Stinner621ef3d2012-10-02 00:33:47 +020013425/* Format an integer.
13426 * Return 1 if the number has been formatted into the writer,
13427 * 0 if the number has been formatted into *p_result
13428 * -1 and raise an exception on error */
13429static int
13430mainformatlong(_PyUnicodeWriter *writer, PyObject *v,
13431 int c, Py_ssize_t width, int prec, int flags,
13432 PyObject **p_result)
13433{
13434 PyObject *iobj, *res;
13435
13436 if (!PyNumber_Check(v))
13437 goto wrongtype;
13438
13439 if (!PyLong_Check(v)) {
13440 iobj = PyNumber_Long(v);
13441 if (iobj == NULL) {
13442 if (PyErr_ExceptionMatches(PyExc_TypeError))
13443 goto wrongtype;
13444 return -1;
13445 }
13446 assert(PyLong_Check(iobj));
13447 }
13448 else {
13449 iobj = v;
13450 Py_INCREF(iobj);
13451 }
13452
13453 if (PyLong_CheckExact(v)
13454 && width == -1 && prec == -1
13455 && !(flags & (F_SIGN | F_BLANK))
13456 && c != 'X')
13457 {
13458 /* Fast path */
13459 int alternate = flags & F_ALT;
13460 int base;
13461
13462 switch(c)
13463 {
13464 default:
13465 assert(0 && "'type' not in [diuoxX]");
13466 case 'd':
13467 case 'i':
13468 case 'u':
13469 base = 10;
13470 break;
13471 case 'o':
13472 base = 8;
13473 break;
13474 case 'x':
13475 case 'X':
13476 base = 16;
13477 break;
13478 }
13479
Victor Stinnerc89d28f2012-10-02 12:54:07 +020013480 if (_PyLong_FormatWriter(writer, v, base, alternate) == -1) {
13481 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020013482 return -1;
Victor Stinnerc89d28f2012-10-02 12:54:07 +020013483 }
13484 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020013485 return 1;
13486 }
13487
13488 res = formatlong(iobj, flags, prec, c);
13489 Py_DECREF(iobj);
13490 if (res == NULL)
13491 return -1;
13492 *p_result = res;
13493 return 0;
13494
13495wrongtype:
13496 PyErr_Format(PyExc_TypeError,
13497 "%%%c format: a number is required, "
13498 "not %.200s", (char)c, Py_TYPE(v)->tp_name);
13499 return -1;
13500}
13501
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013502static Py_UCS4
13503formatchar(PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013504{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000013505 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000013506 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013507 if (PyUnicode_GET_LENGTH(v) == 1) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013508 return PyUnicode_READ_CHAR(v, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +000013509 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013510 goto onError;
13511 }
13512 else {
13513 /* Integer input truncated to a character */
13514 long x;
13515 x = PyLong_AsLong(v);
13516 if (x == -1 && PyErr_Occurred())
13517 goto onError;
13518
Victor Stinner8faf8212011-12-08 22:14:11 +010013519 if (x < 0 || x > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013520 PyErr_SetString(PyExc_OverflowError,
13521 "%c arg not in range(0x110000)");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013522 return (Py_UCS4) -1;
Benjamin Peterson29060642009-01-31 22:14:21 +000013523 }
13524
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013525 return (Py_UCS4) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013526 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000013527
Benjamin Peterson29060642009-01-31 22:14:21 +000013528 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000013529 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013530 "%c requires int or char");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013531 return (Py_UCS4) -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013532}
13533
Alexander Belopolsky40018472011-02-26 01:02:56 +000013534PyObject *
13535PyUnicode_Format(PyObject *format, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013536{
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013537 Py_ssize_t fmtcnt, fmtpos, arglen, argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013538 int args_owned = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013539 PyObject *dict = NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013540 PyObject *temp = NULL;
13541 PyObject *second = NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013542 PyObject *uformat;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013543 void *fmt;
13544 enum PyUnicode_Kind kind, fmtkind;
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013545 _PyUnicodeWriter writer;
Victor Stinneree4544c2012-05-09 22:24:08 +020013546 Py_ssize_t sublen;
13547 Py_UCS4 maxchar;
Tim Petersced69f82003-09-16 20:30:58 +000013548
Guido van Rossumd57fd912000-03-10 22:53:23 +000013549 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013550 PyErr_BadInternalCall();
13551 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013552 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013553 uformat = PyUnicode_FromObject(format);
Benjamin Peterson22a29702012-01-02 09:00:30 -060013554 if (uformat == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000013555 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060013556 if (PyUnicode_READY(uformat) == -1)
13557 Py_DECREF(uformat);
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013558
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013559 fmt = PyUnicode_DATA(uformat);
13560 fmtkind = PyUnicode_KIND(uformat);
13561 fmtcnt = PyUnicode_GET_LENGTH(uformat);
13562 fmtpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013563
Victor Stinnerd3f08822012-05-29 12:57:52 +020013564 _PyUnicodeWriter_Init(&writer, fmtcnt + 100);
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013565
Guido van Rossumd57fd912000-03-10 22:53:23 +000013566 if (PyTuple_Check(args)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013567 arglen = PyTuple_Size(args);
13568 argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013569 }
13570 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013571 arglen = -1;
13572 argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013573 }
Benjamin Peterson28a6cfa2012-08-28 17:55:35 -040013574 if (PyMapping_Check(args) && !PyTuple_Check(args) && !PyUnicode_Check(args))
Benjamin Peterson29060642009-01-31 22:14:21 +000013575 dict = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013576
13577 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013578 if (PyUnicode_READ(fmtkind, fmt, fmtpos) != '%') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013579 Py_ssize_t nonfmtpos;
13580 nonfmtpos = fmtpos++;
13581 while (fmtcnt >= 0 &&
13582 PyUnicode_READ(fmtkind, fmt, fmtpos) != '%') {
13583 fmtpos++;
13584 fmtcnt--;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013585 }
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013586 if (fmtcnt < 0)
13587 fmtpos--;
Victor Stinneree4544c2012-05-09 22:24:08 +020013588 sublen = fmtpos - nonfmtpos;
13589 maxchar = _PyUnicode_FindMaxChar(uformat,
13590 nonfmtpos, nonfmtpos + sublen);
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013591 if (_PyUnicodeWriter_Prepare(&writer, sublen, maxchar) == -1)
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013592 goto onError;
Victor Stinneree4544c2012-05-09 22:24:08 +020013593
Victor Stinnerd3f08822012-05-29 12:57:52 +020013594 _PyUnicode_FastCopyCharacters(writer.buffer, writer.pos,
13595 uformat, nonfmtpos, sublen);
Victor Stinneree4544c2012-05-09 22:24:08 +020013596 writer.pos += sublen;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013597 }
13598 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013599 /* Got a format specifier */
13600 int flags = 0;
13601 Py_ssize_t width = -1;
13602 int prec = -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013603 Py_UCS4 c = '\0';
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013604 Py_UCS4 fill;
13605 int sign;
13606 Py_UCS4 signchar;
Benjamin Peterson29060642009-01-31 22:14:21 +000013607 PyObject *v = NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013608 void *pbuf = NULL;
13609 Py_ssize_t pindex, len;
Victor Stinneree4544c2012-05-09 22:24:08 +020013610 Py_UCS4 bufmaxchar;
13611 Py_ssize_t buflen;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013612
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013613 fmtpos++;
Victor Stinner438106b2012-05-02 00:41:57 +020013614 c = PyUnicode_READ(fmtkind, fmt, fmtpos);
13615 if (c == '(') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013616 Py_ssize_t keystart;
Benjamin Peterson29060642009-01-31 22:14:21 +000013617 Py_ssize_t keylen;
13618 PyObject *key;
13619 int pcount = 1;
Christian Heimesa612dc02008-02-24 13:08:18 +000013620
Benjamin Peterson29060642009-01-31 22:14:21 +000013621 if (dict == NULL) {
13622 PyErr_SetString(PyExc_TypeError,
13623 "format requires a mapping");
13624 goto onError;
13625 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013626 ++fmtpos;
Benjamin Peterson29060642009-01-31 22:14:21 +000013627 --fmtcnt;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013628 keystart = fmtpos;
Benjamin Peterson29060642009-01-31 22:14:21 +000013629 /* Skip over balanced parentheses */
13630 while (pcount > 0 && --fmtcnt >= 0) {
Victor Stinnerbff7c962012-05-03 01:44:59 +020013631 c = PyUnicode_READ(fmtkind, fmt, fmtpos);
13632 if (c == ')')
Benjamin Peterson29060642009-01-31 22:14:21 +000013633 --pcount;
Victor Stinnerbff7c962012-05-03 01:44:59 +020013634 else if (c == '(')
Benjamin Peterson29060642009-01-31 22:14:21 +000013635 ++pcount;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013636 fmtpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +000013637 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013638 keylen = fmtpos - keystart - 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000013639 if (fmtcnt < 0 || pcount > 0) {
13640 PyErr_SetString(PyExc_ValueError,
13641 "incomplete format key");
13642 goto onError;
13643 }
Victor Stinner7931d9a2011-11-04 00:22:48 +010013644 key = PyUnicode_Substring(uformat,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013645 keystart, keystart + keylen);
Benjamin Peterson29060642009-01-31 22:14:21 +000013646 if (key == NULL)
13647 goto onError;
13648 if (args_owned) {
13649 Py_DECREF(args);
13650 args_owned = 0;
13651 }
13652 args = PyObject_GetItem(dict, key);
13653 Py_DECREF(key);
13654 if (args == NULL) {
13655 goto onError;
13656 }
13657 args_owned = 1;
13658 arglen = -1;
13659 argidx = -2;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013660 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013661 while (--fmtcnt >= 0) {
Victor Stinner438106b2012-05-02 00:41:57 +020013662 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
13663 switch (c) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013664 case '-': flags |= F_LJUST; continue;
13665 case '+': flags |= F_SIGN; continue;
13666 case ' ': flags |= F_BLANK; continue;
13667 case '#': flags |= F_ALT; continue;
13668 case '0': flags |= F_ZERO; continue;
13669 }
13670 break;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013671 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013672 if (c == '*') {
13673 v = getnextarg(args, arglen, &argidx);
13674 if (v == NULL)
13675 goto onError;
13676 if (!PyLong_Check(v)) {
13677 PyErr_SetString(PyExc_TypeError,
13678 "* wants int");
13679 goto onError;
13680 }
13681 width = PyLong_AsLong(v);
13682 if (width == -1 && PyErr_Occurred())
13683 goto onError;
13684 if (width < 0) {
13685 flags |= F_LJUST;
13686 width = -width;
13687 }
13688 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013689 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013690 }
13691 else if (c >= '0' && c <= '9') {
13692 width = c - '0';
13693 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013694 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013695 if (c < '0' || c > '9')
13696 break;
Martin v. Löwisb05c0732012-05-15 13:45:49 +020013697 /* Since c is unsigned, the RHS would end up as unsigned,
13698 mixing signed and unsigned comparison. Since c is between
13699 '0' and '9', casting to int is safe. */
13700 if (width > (PY_SSIZE_T_MAX - ((int)c - '0')) / 10) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013701 PyErr_SetString(PyExc_ValueError,
13702 "width too big");
Benjamin Peterson14339b62009-01-31 16:36:08 +000013703 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +000013704 }
13705 width = width*10 + (c - '0');
13706 }
13707 }
13708 if (c == '.') {
13709 prec = 0;
13710 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013711 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013712 if (c == '*') {
13713 v = getnextarg(args, arglen, &argidx);
13714 if (v == NULL)
13715 goto onError;
13716 if (!PyLong_Check(v)) {
13717 PyErr_SetString(PyExc_TypeError,
13718 "* wants int");
13719 goto onError;
13720 }
13721 prec = PyLong_AsLong(v);
13722 if (prec == -1 && PyErr_Occurred())
13723 goto onError;
13724 if (prec < 0)
13725 prec = 0;
13726 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013727 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013728 }
13729 else if (c >= '0' && c <= '9') {
13730 prec = c - '0';
13731 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013732 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013733 if (c < '0' || c > '9')
13734 break;
Martin v. Löwisb05c0732012-05-15 13:45:49 +020013735 if (prec > (INT_MAX - ((int)c - '0')) / 10) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013736 PyErr_SetString(PyExc_ValueError,
13737 "prec too big");
13738 goto onError;
13739 }
13740 prec = prec*10 + (c - '0');
13741 }
13742 }
13743 } /* prec */
13744 if (fmtcnt >= 0) {
13745 if (c == 'h' || c == 'l' || c == 'L') {
13746 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013747 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013748 }
13749 }
13750 if (fmtcnt < 0) {
13751 PyErr_SetString(PyExc_ValueError,
13752 "incomplete format");
13753 goto onError;
13754 }
Victor Stinnerd3f08822012-05-29 12:57:52 +020013755 if (fmtcnt == 0)
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013756 writer.overallocate = 0;
Victor Stinneraff3cc62012-04-30 05:19:21 +020013757
13758 if (c == '%') {
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013759 if (_PyUnicodeWriter_Prepare(&writer, 1, '%') == -1)
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013760 goto onError;
Victor Stinneree4544c2012-05-09 22:24:08 +020013761 PyUnicode_WRITE(writer.kind, writer.data, writer.pos, '%');
13762 writer.pos += 1;
Victor Stinneraff3cc62012-04-30 05:19:21 +020013763 continue;
Benjamin Peterson29060642009-01-31 22:14:21 +000013764 }
Victor Stinneraff3cc62012-04-30 05:19:21 +020013765
Victor Stinneraff3cc62012-04-30 05:19:21 +020013766 v = getnextarg(args, arglen, &argidx);
13767 if (v == NULL)
13768 goto onError;
13769
Benjamin Peterson29060642009-01-31 22:14:21 +000013770 sign = 0;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013771 signchar = '\0';
Benjamin Peterson29060642009-01-31 22:14:21 +000013772 fill = ' ';
13773 switch (c) {
13774
Benjamin Peterson29060642009-01-31 22:14:21 +000013775 case 's':
13776 case 'r':
13777 case 'a':
Victor Stinnerd3f08822012-05-29 12:57:52 +020013778 if (PyLong_CheckExact(v) && width == -1 && prec == -1) {
13779 /* Fast path */
13780 if (_PyLong_FormatWriter(&writer, v, 10, flags & F_ALT) == -1)
13781 goto onError;
13782 goto nextarg;
13783 }
13784
Victor Stinner808fc0a2010-03-22 12:50:40 +000013785 if (PyUnicode_CheckExact(v) && c == 's') {
Benjamin Peterson29060642009-01-31 22:14:21 +000013786 temp = v;
13787 Py_INCREF(temp);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013788 }
13789 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013790 if (c == 's')
13791 temp = PyObject_Str(v);
13792 else if (c == 'r')
13793 temp = PyObject_Repr(v);
13794 else
13795 temp = PyObject_ASCII(v);
Benjamin Peterson29060642009-01-31 22:14:21 +000013796 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013797 break;
13798
13799 case 'i':
13800 case 'd':
13801 case 'u':
13802 case 'o':
13803 case 'x':
13804 case 'X':
Victor Stinner621ef3d2012-10-02 00:33:47 +020013805 {
13806 int ret = mainformatlong(&writer, v, c, width, prec,
13807 flags, &temp);
13808 if (ret == 1)
13809 goto nextarg;
13810 if (ret == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000013811 goto onError;
Victor Stinner621ef3d2012-10-02 00:33:47 +020013812 sign = 1;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013813 if (flags & F_ZERO)
Benjamin Peterson29060642009-01-31 22:14:21 +000013814 fill = '0';
13815 break;
Victor Stinner621ef3d2012-10-02 00:33:47 +020013816 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013817
13818 case 'e':
13819 case 'E':
13820 case 'f':
13821 case 'F':
13822 case 'g':
13823 case 'G':
Victor Stinnerd3f08822012-05-29 12:57:52 +020013824 if (width == -1 && prec == -1
13825 && !(flags & (F_SIGN | F_BLANK)))
13826 {
13827 /* Fast path */
13828 if (formatfloat(v, flags, prec, c, NULL, &writer) == -1)
13829 goto onError;
13830 goto nextarg;
13831 }
13832
Benjamin Peterson29060642009-01-31 22:14:21 +000013833 sign = 1;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013834 if (flags & F_ZERO)
Benjamin Peterson29060642009-01-31 22:14:21 +000013835 fill = '0';
Victor Stinnerd3f08822012-05-29 12:57:52 +020013836 if (formatfloat(v, flags, prec, c, &temp, NULL) == -1)
13837 temp = NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000013838 break;
13839
13840 case 'c':
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013841 {
13842 Py_UCS4 ch = formatchar(v);
13843 if (ch == (Py_UCS4) -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000013844 goto onError;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013845 if (width == -1 && prec == -1) {
13846 /* Fast path */
13847 if (_PyUnicodeWriter_Prepare(&writer, 1, ch) == -1)
13848 goto onError;
13849 PyUnicode_WRITE(writer.kind, writer.data, writer.pos, ch);
13850 writer.pos += 1;
13851 goto nextarg;
13852 }
Victor Stinnerb5c3ea32012-05-02 00:29:36 +020013853 temp = PyUnicode_FromOrdinal(ch);
Benjamin Peterson29060642009-01-31 22:14:21 +000013854 break;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013855 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013856
13857 default:
13858 PyErr_Format(PyExc_ValueError,
13859 "unsupported format character '%c' (0x%x) "
13860 "at index %zd",
13861 (31<=c && c<=126) ? (char)c : '?',
13862 (int)c,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013863 fmtpos - 1);
Benjamin Peterson29060642009-01-31 22:14:21 +000013864 goto onError;
13865 }
Victor Stinneraff3cc62012-04-30 05:19:21 +020013866 if (temp == NULL)
13867 goto onError;
13868 assert (PyUnicode_Check(temp));
Victor Stinnerd3f08822012-05-29 12:57:52 +020013869
Victor Stinner621ef3d2012-10-02 00:33:47 +020013870 if (PyUnicode_READY(temp) == -1) {
13871 Py_CLEAR(temp);
13872 goto onError;
13873 }
13874
13875 len = PyUnicode_GET_LENGTH(temp);
13876 if ((width == -1 || width <= len)
13877 && (prec == -1 || prec >= len)
Victor Stinnerd3f08822012-05-29 12:57:52 +020013878 && !(flags & (F_SIGN | F_BLANK)))
13879 {
13880 /* Fast path */
13881 if (_PyUnicodeWriter_WriteStr(&writer, temp) == -1)
13882 goto onError;
13883 goto nextarg;
13884 }
13885
Victor Stinneraff3cc62012-04-30 05:19:21 +020013886 if (c == 's' || c == 'r' || c == 'a') {
13887 if (prec >= 0 && len > prec)
13888 len = prec;
13889 }
13890
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013891 /* pbuf is initialized here. */
Victor Stinner621ef3d2012-10-02 00:33:47 +020013892 kind = PyUnicode_KIND(temp);
13893 pbuf = PyUnicode_DATA(temp);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013894 pindex = 0;
Benjamin Peterson29060642009-01-31 22:14:21 +000013895 if (sign) {
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013896 Py_UCS4 ch = PyUnicode_READ(kind, pbuf, pindex);
13897 if (ch == '-' || ch == '+') {
13898 signchar = ch;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013899 len--;
13900 pindex++;
Benjamin Peterson29060642009-01-31 22:14:21 +000013901 }
13902 else if (flags & F_SIGN)
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013903 signchar = '+';
Benjamin Peterson29060642009-01-31 22:14:21 +000013904 else if (flags & F_BLANK)
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013905 signchar = ' ';
Benjamin Peterson29060642009-01-31 22:14:21 +000013906 else
13907 sign = 0;
13908 }
13909 if (width < len)
13910 width = len;
Victor Stinneree4544c2012-05-09 22:24:08 +020013911
13912 /* Compute the length and maximum character of the
13913 written characters */
13914 bufmaxchar = 127;
13915 if (!(flags & F_LJUST)) {
13916 if (sign) {
13917 if ((width-1) > len)
Victor Stinnerd3f08822012-05-29 12:57:52 +020013918 bufmaxchar = MAX_MAXCHAR(bufmaxchar, fill);
Victor Stinneree4544c2012-05-09 22:24:08 +020013919 }
13920 else {
13921 if (width > len)
Victor Stinnerd3f08822012-05-29 12:57:52 +020013922 bufmaxchar = MAX_MAXCHAR(bufmaxchar, fill);
Victor Stinneree4544c2012-05-09 22:24:08 +020013923 }
13924 }
13925 maxchar = _PyUnicode_FindMaxChar(temp, 0, pindex+len);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013926 bufmaxchar = MAX_MAXCHAR(bufmaxchar, maxchar);
Victor Stinneree4544c2012-05-09 22:24:08 +020013927
13928 buflen = width;
13929 if (sign && len == width)
13930 buflen++;
13931
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013932 if (_PyUnicodeWriter_Prepare(&writer, buflen, bufmaxchar) == -1)
Victor Stinneree4544c2012-05-09 22:24:08 +020013933 goto onError;
13934
13935 /* Write characters */
Benjamin Peterson29060642009-01-31 22:14:21 +000013936 if (sign) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013937 if (fill != ' ') {
Victor Stinneree4544c2012-05-09 22:24:08 +020013938 PyUnicode_WRITE(writer.kind, writer.data, writer.pos, signchar);
13939 writer.pos += 1;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013940 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013941 if (width > len)
13942 width--;
13943 }
13944 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013945 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013946 assert(PyUnicode_READ(kind, pbuf, pindex + 1) == c);
Benjamin Peterson29060642009-01-31 22:14:21 +000013947 if (fill != ' ') {
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013948 PyUnicode_WRITE(writer.kind, writer.data, writer.pos, '0');
13949 PyUnicode_WRITE(writer.kind, writer.data, writer.pos+1, c);
13950 writer.pos += 2;
13951 pindex += 2;
Benjamin Peterson29060642009-01-31 22:14:21 +000013952 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013953 width -= 2;
13954 if (width < 0)
13955 width = 0;
13956 len -= 2;
13957 }
13958 if (width > len && !(flags & F_LJUST)) {
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013959 sublen = width - len;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013960 FILL(writer.kind, writer.data, fill, writer.pos, sublen);
13961 writer.pos += sublen;
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013962 width = len;
Benjamin Peterson29060642009-01-31 22:14:21 +000013963 }
13964 if (fill == ' ') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013965 if (sign) {
Victor Stinneree4544c2012-05-09 22:24:08 +020013966 PyUnicode_WRITE(writer.kind, writer.data, writer.pos, signchar);
13967 writer.pos += 1;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013968 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013969 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013970 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
13971 assert(PyUnicode_READ(kind, pbuf, pindex+1) == c);
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013972 PyUnicode_WRITE(writer.kind, writer.data, writer.pos, '0');
13973 PyUnicode_WRITE(writer.kind, writer.data, writer.pos+1, c);
13974 writer.pos += 2;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013975 pindex += 2;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013976 }
13977 }
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013978
Victor Stinnerc9d369f2012-06-16 02:22:37 +020013979 if (len) {
13980 _PyUnicode_FastCopyCharacters(writer.buffer, writer.pos,
13981 temp, pindex, len);
13982 writer.pos += len;
13983 }
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013984 if (width > len) {
Victor Stinneree4544c2012-05-09 22:24:08 +020013985 sublen = width - len;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013986 FILL(writer.kind, writer.data, ' ', writer.pos, sublen);
13987 writer.pos += sublen;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013988 }
Victor Stinneree4544c2012-05-09 22:24:08 +020013989
Victor Stinnerd3f08822012-05-29 12:57:52 +020013990nextarg:
Benjamin Peterson29060642009-01-31 22:14:21 +000013991 if (dict && (argidx < arglen) && c != '%') {
13992 PyErr_SetString(PyExc_TypeError,
13993 "not all arguments converted during string formatting");
Benjamin Peterson29060642009-01-31 22:14:21 +000013994 goto onError;
13995 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013996 Py_CLEAR(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013997 } /* '%' */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013998 } /* until end */
13999 if (argidx < arglen && !dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014000 PyErr_SetString(PyExc_TypeError,
14001 "not all arguments converted during string formatting");
14002 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014003 }
14004
14005 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014006 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014007 }
14008 Py_DECREF(uformat);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014009 Py_XDECREF(temp);
14010 Py_XDECREF(second);
Victor Stinner3b1a74a2012-05-09 22:25:00 +020014011 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014012
Benjamin Peterson29060642009-01-31 22:14:21 +000014013 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000014014 Py_DECREF(uformat);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014015 Py_XDECREF(temp);
14016 Py_XDECREF(second);
Victor Stinner3b1a74a2012-05-09 22:25:00 +020014017 _PyUnicodeWriter_Dealloc(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014018 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014019 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014020 }
14021 return NULL;
14022}
14023
Jeremy Hylton938ace62002-07-17 16:30:39 +000014024static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +000014025unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
14026
Tim Peters6d6c1a32001-08-02 04:15:00 +000014027static PyObject *
14028unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
14029{
Benjamin Peterson29060642009-01-31 22:14:21 +000014030 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014031 static char *kwlist[] = {"object", "encoding", "errors", 0};
14032 char *encoding = NULL;
14033 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000014034
Benjamin Peterson14339b62009-01-31 16:36:08 +000014035 if (type != &PyUnicode_Type)
14036 return unicode_subtype_new(type, args, kwds);
14037 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +000014038 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +000014039 return NULL;
Victor Stinner382955f2011-12-11 21:44:00 +010014040 if (x == NULL) {
14041 Py_INCREF(unicode_empty);
14042 return unicode_empty;
14043 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000014044 if (encoding == NULL && errors == NULL)
14045 return PyObject_Str(x);
14046 else
Benjamin Peterson29060642009-01-31 22:14:21 +000014047 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +000014048}
14049
Guido van Rossume023fe02001-08-30 03:12:59 +000014050static PyObject *
14051unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
14052{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014053 PyObject *unicode, *self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014054 Py_ssize_t length, char_size;
14055 int share_wstr, share_utf8;
14056 unsigned int kind;
14057 void *data;
Guido van Rossume023fe02001-08-30 03:12:59 +000014058
Benjamin Peterson14339b62009-01-31 16:36:08 +000014059 assert(PyType_IsSubtype(type, &PyUnicode_Type));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014060
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014061 unicode = unicode_new(&PyUnicode_Type, args, kwds);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014062 if (unicode == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000014063 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020014064 assert(_PyUnicode_CHECK(unicode));
Benjamin Petersonbac79492012-01-14 13:34:47 -050014065 if (PyUnicode_READY(unicode) == -1) {
Benjamin Peterson22a29702012-01-02 09:00:30 -060014066 Py_DECREF(unicode);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014067 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060014068 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014069
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014070 self = type->tp_alloc(type, 0);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014071 if (self == NULL) {
14072 Py_DECREF(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014073 return NULL;
14074 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014075 kind = PyUnicode_KIND(unicode);
14076 length = PyUnicode_GET_LENGTH(unicode);
14077
14078 _PyUnicode_LENGTH(self) = length;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014079#ifdef Py_DEBUG
14080 _PyUnicode_HASH(self) = -1;
14081#else
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014082 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014083#endif
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014084 _PyUnicode_STATE(self).interned = 0;
14085 _PyUnicode_STATE(self).kind = kind;
14086 _PyUnicode_STATE(self).compact = 0;
Victor Stinner3cf46372011-10-03 14:42:15 +020014087 _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014088 _PyUnicode_STATE(self).ready = 1;
14089 _PyUnicode_WSTR(self) = NULL;
14090 _PyUnicode_UTF8_LENGTH(self) = 0;
14091 _PyUnicode_UTF8(self) = NULL;
14092 _PyUnicode_WSTR_LENGTH(self) = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +020014093 _PyUnicode_DATA_ANY(self) = NULL;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014094
14095 share_utf8 = 0;
14096 share_wstr = 0;
14097 if (kind == PyUnicode_1BYTE_KIND) {
14098 char_size = 1;
14099 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
14100 share_utf8 = 1;
14101 }
14102 else if (kind == PyUnicode_2BYTE_KIND) {
14103 char_size = 2;
14104 if (sizeof(wchar_t) == 2)
14105 share_wstr = 1;
14106 }
14107 else {
14108 assert(kind == PyUnicode_4BYTE_KIND);
14109 char_size = 4;
14110 if (sizeof(wchar_t) == 4)
14111 share_wstr = 1;
14112 }
14113
14114 /* Ensure we won't overflow the length. */
14115 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
14116 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014117 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014118 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014119 data = PyObject_MALLOC((length + 1) * char_size);
14120 if (data == NULL) {
14121 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014122 goto onError;
14123 }
14124
Victor Stinnerc3c74152011-10-02 20:39:55 +020014125 _PyUnicode_DATA_ANY(self) = data;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014126 if (share_utf8) {
14127 _PyUnicode_UTF8_LENGTH(self) = length;
14128 _PyUnicode_UTF8(self) = data;
14129 }
14130 if (share_wstr) {
14131 _PyUnicode_WSTR_LENGTH(self) = length;
14132 _PyUnicode_WSTR(self) = (wchar_t *)data;
14133 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014134
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014135 Py_MEMCPY(data, PyUnicode_DATA(unicode),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020014136 kind * (length + 1));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020014137 assert(_PyUnicode_CheckConsistency(self, 1));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014138#ifdef Py_DEBUG
14139 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
14140#endif
Victor Stinnerdd18d3a2011-10-22 11:08:10 +020014141 Py_DECREF(unicode);
Victor Stinner7931d9a2011-11-04 00:22:48 +010014142 return self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014143
14144onError:
14145 Py_DECREF(unicode);
14146 Py_DECREF(self);
14147 return NULL;
Guido van Rossume023fe02001-08-30 03:12:59 +000014148}
14149
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000014150PyDoc_STRVAR(unicode_doc,
Nick Coghlan573b1fd2012-08-16 14:13:07 +100014151 "str(object[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +000014152\n\
Nick Coghlan573b1fd2012-08-16 14:13:07 +100014153Create a new string object from the given object. If encoding or\n\
14154errors is specified, then the object must expose a data buffer\n\
14155that will be decoded using the given encoding and error handler.\n\
14156Otherwise, returns the result of object.__str__() (if defined)\n\
14157or repr(object).\n\
14158encoding defaults to sys.getdefaultencoding().\n\
14159errors defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +000014160
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014161static PyObject *unicode_iter(PyObject *seq);
14162
Guido van Rossumd57fd912000-03-10 22:53:23 +000014163PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000014164 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Benjamin Peterson14339b62009-01-31 16:36:08 +000014165 "str", /* tp_name */
14166 sizeof(PyUnicodeObject), /* tp_size */
14167 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014168 /* Slots */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014169 (destructor)unicode_dealloc, /* tp_dealloc */
14170 0, /* tp_print */
14171 0, /* tp_getattr */
14172 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000014173 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014174 unicode_repr, /* tp_repr */
14175 &unicode_as_number, /* tp_as_number */
14176 &unicode_as_sequence, /* tp_as_sequence */
14177 &unicode_as_mapping, /* tp_as_mapping */
14178 (hashfunc) unicode_hash, /* tp_hash*/
14179 0, /* tp_call*/
14180 (reprfunc) unicode_str, /* tp_str */
14181 PyObject_GenericGetAttr, /* tp_getattro */
14182 0, /* tp_setattro */
14183 0, /* tp_as_buffer */
14184 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Benjamin Peterson29060642009-01-31 22:14:21 +000014185 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014186 unicode_doc, /* tp_doc */
14187 0, /* tp_traverse */
14188 0, /* tp_clear */
14189 PyUnicode_RichCompare, /* tp_richcompare */
14190 0, /* tp_weaklistoffset */
14191 unicode_iter, /* tp_iter */
14192 0, /* tp_iternext */
14193 unicode_methods, /* tp_methods */
14194 0, /* tp_members */
14195 0, /* tp_getset */
14196 &PyBaseObject_Type, /* tp_base */
14197 0, /* tp_dict */
14198 0, /* tp_descr_get */
14199 0, /* tp_descr_set */
14200 0, /* tp_dictoffset */
14201 0, /* tp_init */
14202 0, /* tp_alloc */
14203 unicode_new, /* tp_new */
14204 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014205};
14206
14207/* Initialize the Unicode implementation */
14208
Victor Stinner3a50e702011-10-18 21:21:00 +020014209int _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014210{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014211 int i;
14212
Thomas Wouters477c8d52006-05-27 19:21:47 +000014213 /* XXX - move this array to unicodectype.c ? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014214 Py_UCS2 linebreak[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +000014215 0x000A, /* LINE FEED */
14216 0x000D, /* CARRIAGE RETURN */
14217 0x001C, /* FILE SEPARATOR */
14218 0x001D, /* GROUP SEPARATOR */
14219 0x001E, /* RECORD SEPARATOR */
14220 0x0085, /* NEXT LINE */
14221 0x2028, /* LINE SEPARATOR */
14222 0x2029, /* PARAGRAPH SEPARATOR */
14223 };
14224
Fred Drakee4315f52000-05-09 19:53:39 +000014225 /* Init the implementation */
Victor Stinnera464fc12011-10-02 20:39:30 +020014226 unicode_empty = PyUnicode_New(0, 0);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014227 if (!unicode_empty)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014228 Py_FatalError("Can't create empty string");
Victor Stinnerd3df8ab2011-11-22 01:22:34 +010014229 assert(_PyUnicode_CheckConsistency(unicode_empty, 1));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014230
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014231 for (i = 0; i < 256; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +000014232 unicode_latin1[i] = NULL;
Guido van Rossumcacfc072002-05-24 19:01:59 +000014233 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000014234 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +000014235
14236 /* initialize the linebreak bloom filter */
14237 bloom_linebreak = make_bloom_mask(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014238 PyUnicode_2BYTE_KIND, linebreak,
Victor Stinner63941882011-09-29 00:42:28 +020014239 Py_ARRAY_LENGTH(linebreak));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014240
14241 PyType_Ready(&EncodingMapType);
Victor Stinner3a50e702011-10-18 21:21:00 +020014242
14243#ifdef HAVE_MBCS
14244 winver.dwOSVersionInfoSize = sizeof(winver);
14245 if (!GetVersionEx((OSVERSIONINFO*)&winver)) {
14246 PyErr_SetFromWindowsErr(0);
14247 return -1;
14248 }
14249#endif
14250 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014251}
14252
14253/* Finalize the Unicode implementation */
14254
Christian Heimesa156e092008-02-16 07:38:31 +000014255int
14256PyUnicode_ClearFreeList(void)
14257{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014258 return 0;
Christian Heimesa156e092008-02-16 07:38:31 +000014259}
14260
Guido van Rossumd57fd912000-03-10 22:53:23 +000014261void
Thomas Wouters78890102000-07-22 19:25:51 +000014262_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014263{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014264 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014265
Guido van Rossum4ae8ef82000-10-03 18:09:04 +000014266 Py_XDECREF(unicode_empty);
14267 unicode_empty = NULL;
Barry Warsaw5b4c2282000-10-03 20:45:26 +000014268
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014269 for (i = 0; i < 256; i++) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014270 if (unicode_latin1[i]) {
14271 Py_DECREF(unicode_latin1[i]);
14272 unicode_latin1[i] = NULL;
14273 }
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014274 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020014275 _PyUnicode_ClearStaticStrings();
Christian Heimesa156e092008-02-16 07:38:31 +000014276 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +000014277}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000014278
Walter Dörwald16807132007-05-25 13:52:07 +000014279void
14280PyUnicode_InternInPlace(PyObject **p)
14281{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014282 register PyObject *s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014283 PyObject *t;
Victor Stinner4fae54c2011-10-03 02:01:52 +020014284#ifdef Py_DEBUG
14285 assert(s != NULL);
14286 assert(_PyUnicode_CHECK(s));
14287#else
Benjamin Peterson14339b62009-01-31 16:36:08 +000014288 if (s == NULL || !PyUnicode_Check(s))
Victor Stinner4fae54c2011-10-03 02:01:52 +020014289 return;
14290#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000014291 /* If it's a subclass, we don't really know what putting
14292 it in the interned dict might do. */
14293 if (!PyUnicode_CheckExact(s))
14294 return;
14295 if (PyUnicode_CHECK_INTERNED(s))
14296 return;
14297 if (interned == NULL) {
14298 interned = PyDict_New();
14299 if (interned == NULL) {
14300 PyErr_Clear(); /* Don't leave an exception */
14301 return;
14302 }
14303 }
14304 /* It might be that the GetItem call fails even
14305 though the key is present in the dictionary,
14306 namely when this happens during a stack overflow. */
14307 Py_ALLOW_RECURSION
Victor Stinner7931d9a2011-11-04 00:22:48 +010014308 t = PyDict_GetItem(interned, s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014309 Py_END_ALLOW_RECURSION
Martin v. Löwis5b222132007-06-10 09:51:05 +000014310
Benjamin Peterson29060642009-01-31 22:14:21 +000014311 if (t) {
14312 Py_INCREF(t);
14313 Py_DECREF(*p);
14314 *p = t;
14315 return;
14316 }
Walter Dörwald16807132007-05-25 13:52:07 +000014317
Benjamin Peterson14339b62009-01-31 16:36:08 +000014318 PyThreadState_GET()->recursion_critical = 1;
Victor Stinner7931d9a2011-11-04 00:22:48 +010014319 if (PyDict_SetItem(interned, s, s) < 0) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014320 PyErr_Clear();
14321 PyThreadState_GET()->recursion_critical = 0;
14322 return;
14323 }
14324 PyThreadState_GET()->recursion_critical = 0;
14325 /* The two references in interned are not counted by refcnt.
14326 The deallocator will take care of this */
14327 Py_REFCNT(s) -= 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014328 _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000014329}
14330
14331void
14332PyUnicode_InternImmortal(PyObject **p)
14333{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014334 PyUnicode_InternInPlace(p);
14335 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
Victor Stinneraf9e4b82011-10-23 20:07:00 +020014336 _PyUnicode_STATE(*p).interned = SSTATE_INTERNED_IMMORTAL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014337 Py_INCREF(*p);
14338 }
Walter Dörwald16807132007-05-25 13:52:07 +000014339}
14340
14341PyObject *
14342PyUnicode_InternFromString(const char *cp)
14343{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014344 PyObject *s = PyUnicode_FromString(cp);
14345 if (s == NULL)
14346 return NULL;
14347 PyUnicode_InternInPlace(&s);
14348 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000014349}
14350
Alexander Belopolsky40018472011-02-26 01:02:56 +000014351void
14352_Py_ReleaseInternedUnicodeStrings(void)
Walter Dörwald16807132007-05-25 13:52:07 +000014353{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014354 PyObject *keys;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014355 PyObject *s;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014356 Py_ssize_t i, n;
14357 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000014358
Benjamin Peterson14339b62009-01-31 16:36:08 +000014359 if (interned == NULL || !PyDict_Check(interned))
14360 return;
14361 keys = PyDict_Keys(interned);
14362 if (keys == NULL || !PyList_Check(keys)) {
14363 PyErr_Clear();
14364 return;
14365 }
Walter Dörwald16807132007-05-25 13:52:07 +000014366
Benjamin Peterson14339b62009-01-31 16:36:08 +000014367 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
14368 detector, interned unicode strings are not forcibly deallocated;
14369 rather, we give them their stolen references back, and then clear
14370 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000014371
Benjamin Peterson14339b62009-01-31 16:36:08 +000014372 n = PyList_GET_SIZE(keys);
14373 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000014374 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014375 for (i = 0; i < n; i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014376 s = PyList_GET_ITEM(keys, i);
Victor Stinner6b56a7f2011-10-04 20:04:52 +020014377 if (PyUnicode_READY(s) == -1) {
14378 assert(0 && "could not ready string");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014379 fprintf(stderr, "could not ready string\n");
Victor Stinner6b56a7f2011-10-04 20:04:52 +020014380 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014381 switch (PyUnicode_CHECK_INTERNED(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014382 case SSTATE_NOT_INTERNED:
14383 /* XXX Shouldn't happen */
14384 break;
14385 case SSTATE_INTERNED_IMMORTAL:
14386 Py_REFCNT(s) += 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014387 immortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014388 break;
14389 case SSTATE_INTERNED_MORTAL:
14390 Py_REFCNT(s) += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014391 mortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014392 break;
14393 default:
14394 Py_FatalError("Inconsistent interned string state.");
14395 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014396 _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014397 }
14398 fprintf(stderr, "total size of all interned strings: "
14399 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
14400 "mortal/immortal\n", mortal_size, immortal_size);
14401 Py_DECREF(keys);
14402 PyDict_Clear(interned);
14403 Py_DECREF(interned);
14404 interned = NULL;
Walter Dörwald16807132007-05-25 13:52:07 +000014405}
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014406
14407
14408/********************* Unicode Iterator **************************/
14409
14410typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014411 PyObject_HEAD
14412 Py_ssize_t it_index;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014413 PyObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014414} unicodeiterobject;
14415
14416static void
14417unicodeiter_dealloc(unicodeiterobject *it)
14418{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014419 _PyObject_GC_UNTRACK(it);
14420 Py_XDECREF(it->it_seq);
14421 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014422}
14423
14424static int
14425unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
14426{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014427 Py_VISIT(it->it_seq);
14428 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014429}
14430
14431static PyObject *
14432unicodeiter_next(unicodeiterobject *it)
14433{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014434 PyObject *seq, *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014435
Benjamin Peterson14339b62009-01-31 16:36:08 +000014436 assert(it != NULL);
14437 seq = it->it_seq;
14438 if (seq == NULL)
14439 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020014440 assert(_PyUnicode_CHECK(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014441
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014442 if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
14443 int kind = PyUnicode_KIND(seq);
14444 void *data = PyUnicode_DATA(seq);
14445 Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
14446 item = PyUnicode_FromOrdinal(chr);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014447 if (item != NULL)
14448 ++it->it_index;
14449 return item;
14450 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014451
Benjamin Peterson14339b62009-01-31 16:36:08 +000014452 Py_DECREF(seq);
14453 it->it_seq = NULL;
14454 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014455}
14456
14457static PyObject *
14458unicodeiter_len(unicodeiterobject *it)
14459{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014460 Py_ssize_t len = 0;
14461 if (it->it_seq)
Victor Stinnerc4f281e2011-10-11 22:11:42 +020014462 len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014463 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014464}
14465
14466PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
14467
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000014468static PyObject *
14469unicodeiter_reduce(unicodeiterobject *it)
14470{
14471 if (it->it_seq != NULL) {
Antoine Pitroua7013882012-04-05 00:04:20 +020014472 return Py_BuildValue("N(O)n", _PyObject_GetBuiltin("iter"),
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000014473 it->it_seq, it->it_index);
14474 } else {
14475 PyObject *u = PyUnicode_FromUnicode(NULL, 0);
14476 if (u == NULL)
14477 return NULL;
Antoine Pitroua7013882012-04-05 00:04:20 +020014478 return Py_BuildValue("N(N)", _PyObject_GetBuiltin("iter"), u);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000014479 }
14480}
14481
14482PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
14483
14484static PyObject *
14485unicodeiter_setstate(unicodeiterobject *it, PyObject *state)
14486{
14487 Py_ssize_t index = PyLong_AsSsize_t(state);
14488 if (index == -1 && PyErr_Occurred())
14489 return NULL;
14490 if (index < 0)
14491 index = 0;
14492 it->it_index = index;
14493 Py_RETURN_NONE;
14494}
14495
14496PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
14497
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014498static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014499 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000014500 length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000014501 {"__reduce__", (PyCFunction)unicodeiter_reduce, METH_NOARGS,
14502 reduce_doc},
14503 {"__setstate__", (PyCFunction)unicodeiter_setstate, METH_O,
14504 setstate_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000014505 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014506};
14507
14508PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014509 PyVarObject_HEAD_INIT(&PyType_Type, 0)
14510 "str_iterator", /* tp_name */
14511 sizeof(unicodeiterobject), /* tp_basicsize */
14512 0, /* tp_itemsize */
14513 /* methods */
14514 (destructor)unicodeiter_dealloc, /* tp_dealloc */
14515 0, /* tp_print */
14516 0, /* tp_getattr */
14517 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000014518 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014519 0, /* tp_repr */
14520 0, /* tp_as_number */
14521 0, /* tp_as_sequence */
14522 0, /* tp_as_mapping */
14523 0, /* tp_hash */
14524 0, /* tp_call */
14525 0, /* tp_str */
14526 PyObject_GenericGetAttr, /* tp_getattro */
14527 0, /* tp_setattro */
14528 0, /* tp_as_buffer */
14529 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
14530 0, /* tp_doc */
14531 (traverseproc)unicodeiter_traverse, /* tp_traverse */
14532 0, /* tp_clear */
14533 0, /* tp_richcompare */
14534 0, /* tp_weaklistoffset */
14535 PyObject_SelfIter, /* tp_iter */
14536 (iternextfunc)unicodeiter_next, /* tp_iternext */
14537 unicodeiter_methods, /* tp_methods */
14538 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014539};
14540
14541static PyObject *
14542unicode_iter(PyObject *seq)
14543{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014544 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014545
Benjamin Peterson14339b62009-01-31 16:36:08 +000014546 if (!PyUnicode_Check(seq)) {
14547 PyErr_BadInternalCall();
14548 return NULL;
14549 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014550 if (PyUnicode_READY(seq) == -1)
14551 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014552 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
14553 if (it == NULL)
14554 return NULL;
14555 it->it_index = 0;
14556 Py_INCREF(seq);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014557 it->it_seq = seq;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014558 _PyObject_GC_TRACK(it);
14559 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014560}
14561
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010014562
14563size_t
14564Py_UNICODE_strlen(const Py_UNICODE *u)
14565{
14566 int res = 0;
14567 while(*u++)
14568 res++;
14569 return res;
14570}
14571
14572Py_UNICODE*
14573Py_UNICODE_strcpy(Py_UNICODE *s1, const Py_UNICODE *s2)
14574{
14575 Py_UNICODE *u = s1;
14576 while ((*u++ = *s2++));
14577 return s1;
14578}
14579
14580Py_UNICODE*
14581Py_UNICODE_strncpy(Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
14582{
14583 Py_UNICODE *u = s1;
14584 while ((*u++ = *s2++))
14585 if (n-- == 0)
14586 break;
14587 return s1;
14588}
14589
14590Py_UNICODE*
14591Py_UNICODE_strcat(Py_UNICODE *s1, const Py_UNICODE *s2)
14592{
14593 Py_UNICODE *u1 = s1;
14594 u1 += Py_UNICODE_strlen(u1);
14595 Py_UNICODE_strcpy(u1, s2);
14596 return s1;
14597}
14598
14599int
14600Py_UNICODE_strcmp(const Py_UNICODE *s1, const Py_UNICODE *s2)
14601{
14602 while (*s1 && *s2 && *s1 == *s2)
14603 s1++, s2++;
14604 if (*s1 && *s2)
14605 return (*s1 < *s2) ? -1 : +1;
14606 if (*s1)
14607 return 1;
14608 if (*s2)
14609 return -1;
14610 return 0;
14611}
14612
14613int
14614Py_UNICODE_strncmp(const Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
14615{
14616 register Py_UNICODE u1, u2;
14617 for (; n != 0; n--) {
14618 u1 = *s1;
14619 u2 = *s2;
14620 if (u1 != u2)
14621 return (u1 < u2) ? -1 : +1;
14622 if (u1 == '\0')
14623 return 0;
14624 s1++;
14625 s2++;
14626 }
14627 return 0;
14628}
14629
14630Py_UNICODE*
14631Py_UNICODE_strchr(const Py_UNICODE *s, Py_UNICODE c)
14632{
14633 const Py_UNICODE *p;
14634 for (p = s; *p; p++)
14635 if (*p == c)
14636 return (Py_UNICODE*)p;
14637 return NULL;
14638}
14639
14640Py_UNICODE*
14641Py_UNICODE_strrchr(const Py_UNICODE *s, Py_UNICODE c)
14642{
14643 const Py_UNICODE *p;
14644 p = s + Py_UNICODE_strlen(s);
14645 while (p != s) {
14646 p--;
14647 if (*p == c)
14648 return (Py_UNICODE*)p;
14649 }
14650 return NULL;
14651}
Victor Stinner331ea922010-08-10 16:37:20 +000014652
Victor Stinner71133ff2010-09-01 23:43:53 +000014653Py_UNICODE*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014654PyUnicode_AsUnicodeCopy(PyObject *unicode)
Victor Stinner71133ff2010-09-01 23:43:53 +000014655{
Victor Stinner577db2c2011-10-11 22:12:48 +020014656 Py_UNICODE *u, *copy;
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014657 Py_ssize_t len, size;
Victor Stinner71133ff2010-09-01 23:43:53 +000014658
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014659 if (!PyUnicode_Check(unicode)) {
14660 PyErr_BadArgument();
14661 return NULL;
14662 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014663 u = PyUnicode_AsUnicodeAndSize(unicode, &len);
Victor Stinner577db2c2011-10-11 22:12:48 +020014664 if (u == NULL)
14665 return NULL;
Victor Stinner71133ff2010-09-01 23:43:53 +000014666 /* Ensure we won't overflow the size. */
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014667 if (len > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
Victor Stinner71133ff2010-09-01 23:43:53 +000014668 PyErr_NoMemory();
14669 return NULL;
14670 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014671 size = len + 1; /* copy the null character */
Victor Stinner71133ff2010-09-01 23:43:53 +000014672 size *= sizeof(Py_UNICODE);
14673 copy = PyMem_Malloc(size);
14674 if (copy == NULL) {
14675 PyErr_NoMemory();
14676 return NULL;
14677 }
Victor Stinner577db2c2011-10-11 22:12:48 +020014678 memcpy(copy, u, size);
Victor Stinner71133ff2010-09-01 23:43:53 +000014679 return copy;
14680}
Martin v. Löwis5b222132007-06-10 09:51:05 +000014681
Georg Brandl66c221e2010-10-14 07:04:07 +000014682/* A _string module, to export formatter_parser and formatter_field_name_split
14683 to the string.Formatter class implemented in Python. */
14684
14685static PyMethodDef _string_methods[] = {
14686 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
14687 METH_O, PyDoc_STR("split the argument as a field name")},
14688 {"formatter_parser", (PyCFunction) formatter_parser,
14689 METH_O, PyDoc_STR("parse the argument as a format string")},
14690 {NULL, NULL}
14691};
14692
14693static struct PyModuleDef _string_module = {
14694 PyModuleDef_HEAD_INIT,
14695 "_string",
14696 PyDoc_STR("string helper module"),
14697 0,
14698 _string_methods,
14699 NULL,
14700 NULL,
14701 NULL,
14702 NULL
14703};
14704
14705PyMODINIT_FUNC
14706PyInit__string(void)
14707{
14708 return PyModule_Create(&_string_module);
14709}
14710
14711
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000014712#ifdef __cplusplus
14713}
14714#endif