blob: 5ca2c533e527ed79021809790dccbd6c2ba4b0c2 [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"
Guido van Rossumd57fd912000-03-10 22:53:23 +000044
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000045#ifdef MS_WINDOWS
Guido van Rossumb7a40ba2000-03-28 02:01:52 +000046#include <windows.h>
47#endif
Guido van Rossumfd4b9572000-04-10 13:51:10 +000048
Guido van Rossumd57fd912000-03-10 22:53:23 +000049/* Endianness switches; defaults to little endian */
50
51#ifdef WORDS_BIGENDIAN
52# define BYTEORDER_IS_BIG_ENDIAN
53#else
54# define BYTEORDER_IS_LITTLE_ENDIAN
55#endif
56
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000057/* --- Globals ------------------------------------------------------------
58
59 The globals are initialized by the _PyUnicode_Init() API and should
60 not be used before calling that API.
61
62*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000063
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000064
65#ifdef __cplusplus
66extern "C" {
67#endif
68
Victor Stinner8faf8212011-12-08 22:14:11 +010069/* Maximum code point of Unicode 6.0: 0x10ffff (1,114,111) */
70#define MAX_UNICODE 0x10ffff
71
Victor Stinner910337b2011-10-03 03:20:16 +020072#ifdef Py_DEBUG
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020073# define _PyUnicode_CHECK(op) _PyUnicode_CheckConsistency(op, 0)
Victor Stinner910337b2011-10-03 03:20:16 +020074#else
75# define _PyUnicode_CHECK(op) PyUnicode_Check(op)
76#endif
Victor Stinnerfb5f5f22011-09-28 21:39:49 +020077
Victor Stinnere90fe6a2011-10-01 16:48:13 +020078#define _PyUnicode_UTF8(op) \
79 (((PyCompactUnicodeObject*)(op))->utf8)
80#define PyUnicode_UTF8(op) \
Victor Stinner910337b2011-10-03 03:20:16 +020081 (assert(_PyUnicode_CHECK(op)), \
Victor Stinnere90fe6a2011-10-01 16:48:13 +020082 assert(PyUnicode_IS_READY(op)), \
83 PyUnicode_IS_COMPACT_ASCII(op) ? \
84 ((char*)((PyASCIIObject*)(op) + 1)) : \
85 _PyUnicode_UTF8(op))
Victor Stinnerbc8b81b2011-09-29 19:31:34 +020086#define _PyUnicode_UTF8_LENGTH(op) \
Victor Stinnere90fe6a2011-10-01 16:48:13 +020087 (((PyCompactUnicodeObject*)(op))->utf8_length)
88#define PyUnicode_UTF8_LENGTH(op) \
Victor Stinner910337b2011-10-03 03:20:16 +020089 (assert(_PyUnicode_CHECK(op)), \
Victor Stinnere90fe6a2011-10-01 16:48:13 +020090 assert(PyUnicode_IS_READY(op)), \
91 PyUnicode_IS_COMPACT_ASCII(op) ? \
92 ((PyASCIIObject*)(op))->length : \
93 _PyUnicode_UTF8_LENGTH(op))
Victor Stinnera5f91632011-10-04 01:07:11 +020094#define _PyUnicode_WSTR(op) \
95 (((PyASCIIObject*)(op))->wstr)
96#define _PyUnicode_WSTR_LENGTH(op) \
97 (((PyCompactUnicodeObject*)(op))->wstr_length)
98#define _PyUnicode_LENGTH(op) \
99 (((PyASCIIObject *)(op))->length)
100#define _PyUnicode_STATE(op) \
101 (((PyASCIIObject *)(op))->state)
102#define _PyUnicode_HASH(op) \
103 (((PyASCIIObject *)(op))->hash)
Victor Stinner910337b2011-10-03 03:20:16 +0200104#define _PyUnicode_KIND(op) \
105 (assert(_PyUnicode_CHECK(op)), \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200106 ((PyASCIIObject *)(op))->state.kind)
Victor Stinner910337b2011-10-03 03:20:16 +0200107#define _PyUnicode_GET_LENGTH(op) \
108 (assert(_PyUnicode_CHECK(op)), \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200109 ((PyASCIIObject *)(op))->length)
Victor Stinnera5f91632011-10-04 01:07:11 +0200110#define _PyUnicode_DATA_ANY(op) \
111 (((PyUnicodeObject*)(op))->data.any)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200112
Victor Stinner910337b2011-10-03 03:20:16 +0200113#undef PyUnicode_READY
114#define PyUnicode_READY(op) \
115 (assert(_PyUnicode_CHECK(op)), \
116 (PyUnicode_IS_READY(op) ? \
Victor Stinnera5f91632011-10-04 01:07:11 +0200117 0 : \
Victor Stinner7931d9a2011-11-04 00:22:48 +0100118 _PyUnicode_Ready(op)))
Victor Stinner910337b2011-10-03 03:20:16 +0200119
Victor Stinnerc379ead2011-10-03 12:52:27 +0200120#define _PyUnicode_SHARE_UTF8(op) \
121 (assert(_PyUnicode_CHECK(op)), \
122 assert(!PyUnicode_IS_COMPACT_ASCII(op)), \
123 (_PyUnicode_UTF8(op) == PyUnicode_DATA(op)))
124#define _PyUnicode_SHARE_WSTR(op) \
125 (assert(_PyUnicode_CHECK(op)), \
126 (_PyUnicode_WSTR(unicode) == PyUnicode_DATA(op)))
127
Victor Stinner829c0ad2011-10-03 01:08:02 +0200128/* true if the Unicode object has an allocated UTF-8 memory block
129 (not shared with other data) */
Victor Stinner910337b2011-10-03 03:20:16 +0200130#define _PyUnicode_HAS_UTF8_MEMORY(op) \
131 (assert(_PyUnicode_CHECK(op)), \
132 (!PyUnicode_IS_COMPACT_ASCII(op) \
133 && _PyUnicode_UTF8(op) \
Victor Stinner829c0ad2011-10-03 01:08:02 +0200134 && _PyUnicode_UTF8(op) != PyUnicode_DATA(op)))
135
Victor Stinner03490912011-10-03 23:45:12 +0200136/* true if the Unicode object has an allocated wstr memory block
137 (not shared with other data) */
138#define _PyUnicode_HAS_WSTR_MEMORY(op) \
139 (assert(_PyUnicode_CHECK(op)), \
140 (_PyUnicode_WSTR(op) && \
141 (!PyUnicode_IS_READY(op) || \
142 _PyUnicode_WSTR(op) != PyUnicode_DATA(op))))
143
Victor Stinner910337b2011-10-03 03:20:16 +0200144/* Generic helper macro to convert characters of different types.
145 from_type and to_type have to be valid type names, begin and end
146 are pointers to the source characters which should be of type
147 "from_type *". to is a pointer of type "to_type *" and points to the
148 buffer where the result characters are written to. */
149#define _PyUnicode_CONVERT_BYTES(from_type, to_type, begin, end, to) \
150 do { \
Antoine Pitroue459a082011-10-11 20:58:41 +0200151 to_type *_to = (to_type *) to; \
152 const from_type *_iter = (begin); \
153 const from_type *_end = (end); \
154 Py_ssize_t n = (_end) - (_iter); \
155 const from_type *_unrolled_end = \
156 _iter + (n & ~ (Py_ssize_t) 3); \
157 while (_iter < (_unrolled_end)) { \
158 _to[0] = (to_type) _iter[0]; \
159 _to[1] = (to_type) _iter[1]; \
160 _to[2] = (to_type) _iter[2]; \
161 _to[3] = (to_type) _iter[3]; \
162 _iter += 4; _to += 4; \
Victor Stinner910337b2011-10-03 03:20:16 +0200163 } \
Antoine Pitroue459a082011-10-11 20:58:41 +0200164 while (_iter < (_end)) \
165 *_to++ = (to_type) *_iter++; \
Victor Stinner910337b2011-10-03 03:20:16 +0200166 } while (0)
Victor Stinner829c0ad2011-10-03 01:08:02 +0200167
Walter Dörwald16807132007-05-25 13:52:07 +0000168/* This dictionary holds all interned unicode strings. Note that references
169 to strings in this dictionary are *not* counted in the string's ob_refcnt.
170 When the interned string reaches a refcnt of 0 the string deallocation
171 function will delete the reference from this dictionary.
172
173 Another way to look at this is that to say that the actual reference
Guido van Rossum98297ee2007-11-06 21:34:58 +0000174 count of a string is: s->ob_refcnt + (s->state ? 2 : 0)
Walter Dörwald16807132007-05-25 13:52:07 +0000175*/
176static PyObject *interned;
177
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000178/* The empty Unicode object is shared to improve performance. */
Victor Stinnera464fc12011-10-02 20:39:30 +0200179static PyObject *unicode_empty;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000180
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200181/* List of static strings. */
182static _Py_Identifier *static_strings;
183
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000184/* Single character Unicode strings in the Latin-1 range are being
185 shared as well. */
Victor Stinnera464fc12011-10-02 20:39:30 +0200186static PyObject *unicode_latin1[256];
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000187
Christian Heimes190d79e2008-01-30 11:58:22 +0000188/* Fast detection of the most frequent whitespace characters */
189const unsigned char _Py_ascii_whitespace[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000190 0, 0, 0, 0, 0, 0, 0, 0,
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000191/* case 0x0009: * CHARACTER TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000192/* case 0x000A: * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000193/* case 0x000B: * LINE TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000194/* case 0x000C: * FORM FEED */
195/* case 0x000D: * CARRIAGE RETURN */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000196 0, 1, 1, 1, 1, 1, 0, 0,
197 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000198/* case 0x001C: * FILE SEPARATOR */
199/* case 0x001D: * GROUP SEPARATOR */
200/* case 0x001E: * RECORD SEPARATOR */
201/* case 0x001F: * UNIT SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000202 0, 0, 0, 0, 1, 1, 1, 1,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000203/* case 0x0020: * SPACE */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000204 1, 0, 0, 0, 0, 0, 0, 0,
205 0, 0, 0, 0, 0, 0, 0, 0,
206 0, 0, 0, 0, 0, 0, 0, 0,
207 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes190d79e2008-01-30 11:58:22 +0000208
Benjamin Peterson14339b62009-01-31 16:36:08 +0000209 0, 0, 0, 0, 0, 0, 0, 0,
210 0, 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,
214 0, 0, 0, 0, 0, 0, 0, 0,
215 0, 0, 0, 0, 0, 0, 0, 0,
216 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000217};
218
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200219/* forward */
Victor Stinnerfe226c02011-10-03 03:52:20 +0200220static PyUnicodeObject *_PyUnicode_New(Py_ssize_t length);
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200221static PyObject* get_latin1_char(unsigned char ch);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200222static void copy_characters(
223 PyObject *to, Py_ssize_t to_start,
224 PyObject *from, Py_ssize_t from_start,
225 Py_ssize_t how_many);
Victor Stinner488fa492011-12-12 00:01:39 +0100226static int unicode_modifiable(PyObject *unicode);
227
Victor Stinnerfe226c02011-10-03 03:52:20 +0200228
Alexander Belopolsky40018472011-02-26 01:02:56 +0000229static PyObject *
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200230unicode_fromascii(const unsigned char *s, Py_ssize_t size);
231static PyObject *
232_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;
377 void *data = PyUnicode_DATA(ascii);
378 for (i=0; i < ascii->length; i++)
379 {
380 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
381 if (ch > maxchar)
382 maxchar = ch;
383 }
384 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinner77faf692011-11-20 18:56:05 +0100385 if (ascii->state.ascii == 0) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200386 assert(maxchar >= 128);
Victor Stinner77faf692011-11-20 18:56:05 +0100387 assert(maxchar <= 255);
388 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200389 else
390 assert(maxchar < 128);
391 }
Victor Stinner77faf692011-11-20 18:56:05 +0100392 else if (kind == PyUnicode_2BYTE_KIND) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200393 assert(maxchar >= 0x100);
Victor Stinner77faf692011-11-20 18:56:05 +0100394 assert(maxchar <= 0xFFFF);
395 }
396 else {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200397 assert(maxchar >= 0x10000);
Victor Stinner8faf8212011-12-08 22:14:11 +0100398 assert(maxchar <= MAX_UNICODE);
Victor Stinner77faf692011-11-20 18:56:05 +0100399 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200400 }
Benjamin Petersonccc51c12011-10-03 19:34:12 -0400401 return 1;
402}
Victor Stinner910337b2011-10-03 03:20:16 +0200403#endif
404
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100405static PyObject*
406unicode_result_wchar(PyObject *unicode)
407{
408#ifndef Py_DEBUG
409 Py_ssize_t len;
410
411 assert(Py_REFCNT(unicode) == 1);
412
413 len = _PyUnicode_WSTR_LENGTH(unicode);
414 if (len == 0) {
415 Py_INCREF(unicode_empty);
416 Py_DECREF(unicode);
417 return unicode_empty;
418 }
419
420 if (len == 1) {
421 wchar_t ch = _PyUnicode_WSTR(unicode)[0];
422 if (ch < 256) {
423 PyObject *latin1_char = get_latin1_char((unsigned char)ch);
424 Py_DECREF(unicode);
425 return latin1_char;
426 }
427 }
428
429 if (_PyUnicode_Ready(unicode) < 0) {
430 Py_XDECREF(unicode);
431 return NULL;
432 }
433#else
434 /* don't make the result ready in debug mode to ensure that the caller
435 makes the string ready before using it */
436 assert(_PyUnicode_CheckConsistency(unicode, 1));
437#endif
438 return unicode;
439}
440
441static PyObject*
442unicode_result_ready(PyObject *unicode)
443{
444 Py_ssize_t length;
445
446 length = PyUnicode_GET_LENGTH(unicode);
447 if (length == 0) {
448 if (unicode != unicode_empty) {
449 Py_INCREF(unicode_empty);
450 Py_DECREF(unicode);
451 }
452 return unicode_empty;
453 }
454
455 if (length == 1) {
456 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, 0);
457 if (ch < 256) {
458 PyObject *latin1_char = unicode_latin1[ch];
459 if (latin1_char != NULL) {
460 if (unicode != latin1_char) {
461 Py_INCREF(latin1_char);
462 Py_DECREF(unicode);
463 }
464 return latin1_char;
465 }
466 else {
467 assert(_PyUnicode_CheckConsistency(unicode, 1));
468 Py_INCREF(unicode);
469 unicode_latin1[ch] = unicode;
470 return unicode;
471 }
472 }
473 }
474
475 assert(_PyUnicode_CheckConsistency(unicode, 1));
476 return unicode;
477}
478
479static PyObject*
480unicode_result(PyObject *unicode)
481{
482 assert(_PyUnicode_CHECK(unicode));
483 if (PyUnicode_IS_READY(unicode))
484 return unicode_result_ready(unicode);
485 else
486 return unicode_result_wchar(unicode);
487}
488
Victor Stinnerc4b49542011-12-11 22:44:26 +0100489static PyObject*
490unicode_result_unchanged(PyObject *unicode)
491{
492 if (PyUnicode_CheckExact(unicode)) {
493 if (PyUnicode_READY(unicode) < 0)
494 return NULL;
495 Py_INCREF(unicode);
496 return unicode;
497 }
498 else
499 /* Subtype -- return genuine unicode string with the same value. */
Victor Stinnerbf6e5602011-12-12 01:53:47 +0100500 return _PyUnicode_Copy(unicode);
Victor Stinnerc4b49542011-12-11 22:44:26 +0100501}
502
Victor Stinner3a50e702011-10-18 21:21:00 +0200503#ifdef HAVE_MBCS
504static OSVERSIONINFOEX winver;
505#endif
506
Thomas Wouters477c8d52006-05-27 19:21:47 +0000507/* --- Bloom Filters ----------------------------------------------------- */
508
509/* stuff to implement simple "bloom filters" for Unicode characters.
510 to keep things simple, we use a single bitmask, using the least 5
511 bits from each unicode characters as the bit index. */
512
513/* the linebreak mask is set up by Unicode_Init below */
514
Antoine Pitrouf068f942010-01-13 14:19:12 +0000515#if LONG_BIT >= 128
516#define BLOOM_WIDTH 128
517#elif LONG_BIT >= 64
518#define BLOOM_WIDTH 64
519#elif LONG_BIT >= 32
520#define BLOOM_WIDTH 32
521#else
522#error "LONG_BIT is smaller than 32"
523#endif
524
Thomas Wouters477c8d52006-05-27 19:21:47 +0000525#define BLOOM_MASK unsigned long
526
527static BLOOM_MASK bloom_linebreak;
528
Antoine Pitrouf068f942010-01-13 14:19:12 +0000529#define BLOOM_ADD(mask, ch) ((mask |= (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
530#define BLOOM(mask, ch) ((mask & (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000531
Benjamin Peterson29060642009-01-31 22:14:21 +0000532#define BLOOM_LINEBREAK(ch) \
533 ((ch) < 128U ? ascii_linebreak[(ch)] : \
534 (BLOOM(bloom_linebreak, (ch)) && Py_UNICODE_ISLINEBREAK(ch)))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000535
Alexander Belopolsky40018472011-02-26 01:02:56 +0000536Py_LOCAL_INLINE(BLOOM_MASK)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200537make_bloom_mask(int kind, void* ptr, Py_ssize_t len)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000538{
539 /* calculate simple bloom-style bitmask for a given unicode string */
540
Antoine Pitrouf068f942010-01-13 14:19:12 +0000541 BLOOM_MASK mask;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000542 Py_ssize_t i;
543
544 mask = 0;
545 for (i = 0; i < len; i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200546 BLOOM_ADD(mask, PyUnicode_READ(kind, ptr, i));
Thomas Wouters477c8d52006-05-27 19:21:47 +0000547
548 return mask;
549}
550
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200551#define BLOOM_MEMBER(mask, chr, str) \
552 (BLOOM(mask, chr) \
553 && (PyUnicode_FindChar(str, chr, 0, PyUnicode_GET_LENGTH(str), 1) >= 0))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000554
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200555/* Compilation of templated routines */
556
557#include "stringlib/asciilib.h"
558#include "stringlib/fastsearch.h"
559#include "stringlib/partition.h"
560#include "stringlib/split.h"
561#include "stringlib/count.h"
562#include "stringlib/find.h"
563#include "stringlib/find_max_char.h"
564#include "stringlib/localeutil.h"
565#include "stringlib/undef.h"
566
567#include "stringlib/ucs1lib.h"
568#include "stringlib/fastsearch.h"
569#include "stringlib/partition.h"
570#include "stringlib/split.h"
571#include "stringlib/count.h"
572#include "stringlib/find.h"
573#include "stringlib/find_max_char.h"
574#include "stringlib/localeutil.h"
575#include "stringlib/undef.h"
576
577#include "stringlib/ucs2lib.h"
578#include "stringlib/fastsearch.h"
579#include "stringlib/partition.h"
580#include "stringlib/split.h"
581#include "stringlib/count.h"
582#include "stringlib/find.h"
583#include "stringlib/find_max_char.h"
584#include "stringlib/localeutil.h"
585#include "stringlib/undef.h"
586
587#include "stringlib/ucs4lib.h"
588#include "stringlib/fastsearch.h"
589#include "stringlib/partition.h"
590#include "stringlib/split.h"
591#include "stringlib/count.h"
592#include "stringlib/find.h"
593#include "stringlib/find_max_char.h"
594#include "stringlib/localeutil.h"
595#include "stringlib/undef.h"
596
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200597#include "stringlib/unicodedefs.h"
598#include "stringlib/fastsearch.h"
599#include "stringlib/count.h"
600#include "stringlib/find.h"
Antoine Pitrou0a3229d2011-11-21 20:39:13 +0100601#include "stringlib/undef.h"
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200602
Guido van Rossumd57fd912000-03-10 22:53:23 +0000603/* --- Unicode Object ----------------------------------------------------- */
604
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200605static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +0200606fixup(PyObject *self, Py_UCS4 (*fixfct)(PyObject *s));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200607
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200608Py_LOCAL_INLINE(Py_ssize_t) findchar(void *s, int kind,
609 Py_ssize_t size, Py_UCS4 ch,
610 int direction)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200611{
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200612 int mode = (direction == 1) ? FAST_SEARCH : FAST_RSEARCH;
613
614 switch (kind) {
615 case PyUnicode_1BYTE_KIND:
616 {
617 Py_UCS1 ch1 = (Py_UCS1) ch;
618 if (ch1 == ch)
619 return ucs1lib_fastsearch((Py_UCS1 *) s, size, &ch1, 1, 0, mode);
620 else
621 return -1;
622 }
623 case PyUnicode_2BYTE_KIND:
624 {
625 Py_UCS2 ch2 = (Py_UCS2) ch;
626 if (ch2 == ch)
627 return ucs2lib_fastsearch((Py_UCS2 *) s, size, &ch2, 1, 0, mode);
628 else
629 return -1;
630 }
631 case PyUnicode_4BYTE_KIND:
632 return ucs4lib_fastsearch((Py_UCS4 *) s, size, &ch, 1, 0, mode);
633 default:
634 assert(0);
635 return -1;
Victor Stinner9e7a1bc2011-10-13 00:18:12 +0200636 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200637}
638
Victor Stinnerfe226c02011-10-03 03:52:20 +0200639static PyObject*
640resize_compact(PyObject *unicode, Py_ssize_t length)
641{
642 Py_ssize_t char_size;
643 Py_ssize_t struct_size;
644 Py_ssize_t new_size;
645 int share_wstr;
Victor Stinner84def372011-12-11 20:04:56 +0100646 PyObject *new_unicode;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200647 assert(PyUnicode_IS_READY(unicode));
Victor Stinner488fa492011-12-12 00:01:39 +0100648 assert(PyUnicode_IS_COMPACT(unicode));
649
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200650 char_size = PyUnicode_KIND(unicode);
Victor Stinner488fa492011-12-12 00:01:39 +0100651 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerfe226c02011-10-03 03:52:20 +0200652 struct_size = sizeof(PyASCIIObject);
653 else
654 struct_size = sizeof(PyCompactUnicodeObject);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200655 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200656
Victor Stinnerfe226c02011-10-03 03:52:20 +0200657 if (length > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1)) {
658 PyErr_NoMemory();
659 return NULL;
660 }
661 new_size = (struct_size + (length + 1) * char_size);
662
Victor Stinner84def372011-12-11 20:04:56 +0100663 _Py_DEC_REFTOTAL;
664 _Py_ForgetReference(unicode);
665
666 new_unicode = (PyObject *)PyObject_REALLOC((char *)unicode, new_size);
667 if (new_unicode == NULL) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +0100668 _Py_NewReference(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200669 PyErr_NoMemory();
670 return NULL;
671 }
Victor Stinner84def372011-12-11 20:04:56 +0100672 unicode = new_unicode;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200673 _Py_NewReference(unicode);
Victor Stinner84def372011-12-11 20:04:56 +0100674
Victor Stinnerfe226c02011-10-03 03:52:20 +0200675 _PyUnicode_LENGTH(unicode) = length;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200676 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200677 _PyUnicode_WSTR(unicode) = PyUnicode_DATA(unicode);
Victor Stinner488fa492011-12-12 00:01:39 +0100678 if (!PyUnicode_IS_ASCII(unicode))
Victor Stinnerc379ead2011-10-03 12:52:27 +0200679 _PyUnicode_WSTR_LENGTH(unicode) = length;
680 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200681 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
682 length, 0);
683 return unicode;
684}
685
Alexander Belopolsky40018472011-02-26 01:02:56 +0000686static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200687resize_inplace(PyObject *unicode, Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000688{
Victor Stinner95663112011-10-04 01:03:50 +0200689 wchar_t *wstr;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100690 Py_ssize_t new_size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200691 assert(!PyUnicode_IS_COMPACT(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200692 assert(Py_REFCNT(unicode) == 1);
Tim Petersced69f82003-09-16 20:30:58 +0000693
Victor Stinnerfe226c02011-10-03 03:52:20 +0200694 if (PyUnicode_IS_READY(unicode)) {
695 Py_ssize_t char_size;
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200696 int share_wstr, share_utf8;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200697 void *data;
698
699 data = _PyUnicode_DATA_ANY(unicode);
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200700 char_size = PyUnicode_KIND(unicode);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200701 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
702 share_utf8 = _PyUnicode_SHARE_UTF8(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200703
704 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
705 PyErr_NoMemory();
706 return -1;
707 }
708 new_size = (length + 1) * char_size;
709
Victor Stinner7a9105a2011-12-12 00:13:42 +0100710 if (!share_utf8 && _PyUnicode_HAS_UTF8_MEMORY(unicode))
711 {
712 PyObject_DEL(_PyUnicode_UTF8(unicode));
713 _PyUnicode_UTF8(unicode) = NULL;
714 _PyUnicode_UTF8_LENGTH(unicode) = 0;
715 }
716
Victor Stinnerfe226c02011-10-03 03:52:20 +0200717 data = (PyObject *)PyObject_REALLOC(data, new_size);
718 if (data == NULL) {
719 PyErr_NoMemory();
720 return -1;
721 }
722 _PyUnicode_DATA_ANY(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200723 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200724 _PyUnicode_WSTR(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200725 _PyUnicode_WSTR_LENGTH(unicode) = length;
726 }
727 if (share_utf8) {
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200728 _PyUnicode_UTF8(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200729 _PyUnicode_UTF8_LENGTH(unicode) = length;
730 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200731 _PyUnicode_LENGTH(unicode) = length;
732 PyUnicode_WRITE(PyUnicode_KIND(unicode), data, length, 0);
Victor Stinner95663112011-10-04 01:03:50 +0200733 if (share_wstr || _PyUnicode_WSTR(unicode) == NULL) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200734 assert(_PyUnicode_CheckConsistency(unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200735 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200736 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200737 }
Victor Stinner95663112011-10-04 01:03:50 +0200738 assert(_PyUnicode_WSTR(unicode) != NULL);
739
740 /* check for integer overflow */
741 if (length > PY_SSIZE_T_MAX / sizeof(wchar_t) - 1) {
742 PyErr_NoMemory();
743 return -1;
744 }
Victor Stinner7a9105a2011-12-12 00:13:42 +0100745 new_size = sizeof(wchar_t) * (length + 1);
Victor Stinner95663112011-10-04 01:03:50 +0200746 wstr = _PyUnicode_WSTR(unicode);
Victor Stinner7a9105a2011-12-12 00:13:42 +0100747 wstr = PyObject_REALLOC(wstr, new_size);
Victor Stinner95663112011-10-04 01:03:50 +0200748 if (!wstr) {
749 PyErr_NoMemory();
750 return -1;
751 }
752 _PyUnicode_WSTR(unicode) = wstr;
753 _PyUnicode_WSTR(unicode)[length] = 0;
754 _PyUnicode_WSTR_LENGTH(unicode) = length;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200755 assert(_PyUnicode_CheckConsistency(unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +0000756 return 0;
757}
758
Victor Stinnerfe226c02011-10-03 03:52:20 +0200759static PyObject*
760resize_copy(PyObject *unicode, Py_ssize_t length)
761{
762 Py_ssize_t copy_length;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100763 if (_PyUnicode_KIND(unicode) != PyUnicode_WCHAR_KIND) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200764 PyObject *copy;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100765
766 if (PyUnicode_READY(unicode) < 0)
767 return NULL;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200768
769 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
770 if (copy == NULL)
771 return NULL;
772
773 copy_length = Py_MIN(length, PyUnicode_GET_LENGTH(unicode));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200774 copy_characters(copy, 0, unicode, 0, copy_length);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200775 return copy;
Victor Stinner8cfcbed2011-10-03 23:19:21 +0200776 }
777 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200778 PyObject *w;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100779
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200780 w = (PyObject*)_PyUnicode_New(length);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200781 if (w == NULL)
782 return NULL;
783 copy_length = _PyUnicode_WSTR_LENGTH(unicode);
784 copy_length = Py_MIN(copy_length, length);
785 Py_UNICODE_COPY(_PyUnicode_WSTR(w), _PyUnicode_WSTR(unicode),
786 copy_length);
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200787 return w;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200788 }
789}
790
Guido van Rossumd57fd912000-03-10 22:53:23 +0000791/* We allocate one more byte to make sure the string is
Martin v. Löwis47383402007-08-15 07:32:56 +0000792 Ux0000 terminated; some code (e.g. new_identifier)
793 relies on that.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000794
795 XXX This allocator could further be enhanced by assuring that the
Benjamin Peterson29060642009-01-31 22:14:21 +0000796 free list never reduces its size below 1.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000797
798*/
799
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200800#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +0200801static int unicode_old_new_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200802#endif
803
Alexander Belopolsky40018472011-02-26 01:02:56 +0000804static PyUnicodeObject *
805_PyUnicode_New(Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000806{
807 register PyUnicodeObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200808 size_t new_size;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000809
Thomas Wouters477c8d52006-05-27 19:21:47 +0000810 /* Optimization for empty strings */
Guido van Rossumd57fd912000-03-10 22:53:23 +0000811 if (length == 0 && unicode_empty != NULL) {
812 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +0200813 return (PyUnicodeObject*)unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000814 }
815
Neal Norwitz3ce5d922008-08-24 07:08:55 +0000816 /* Ensure we won't overflow the size. */
817 if (length > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
818 return (PyUnicodeObject *)PyErr_NoMemory();
819 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200820 if (length < 0) {
821 PyErr_SetString(PyExc_SystemError,
822 "Negative size passed to _PyUnicode_New");
823 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000824 }
825
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200826#ifdef Py_DEBUG
827 ++unicode_old_new_calls;
828#endif
829
830 unicode = PyObject_New(PyUnicodeObject, &PyUnicode_Type);
831 if (unicode == NULL)
832 return NULL;
833 new_size = sizeof(Py_UNICODE) * ((size_t)length + 1);
834 _PyUnicode_WSTR(unicode) = (Py_UNICODE*) PyObject_MALLOC(new_size);
835 if (!_PyUnicode_WSTR(unicode)) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +0100836 Py_DECREF(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +0000837 PyErr_NoMemory();
Victor Stinnerb0a82a62011-12-12 13:08:33 +0100838 return NULL;
Guido van Rossum3c1bb802000-04-27 20:13:50 +0000839 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200840
Jeremy Hyltond8082792003-09-16 19:41:39 +0000841 /* Initialize the first element to guard against cases where
Tim Petersced69f82003-09-16 20:30:58 +0000842 * the caller fails before initializing str -- unicode_resize()
843 * reads str[0], and the Keep-Alive optimization can keep memory
844 * allocated for str alive across a call to unicode_dealloc(unicode).
845 * We don't want unicode_resize to read uninitialized memory in
846 * that case.
847 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200848 _PyUnicode_WSTR(unicode)[0] = 0;
849 _PyUnicode_WSTR(unicode)[length] = 0;
850 _PyUnicode_WSTR_LENGTH(unicode) = length;
851 _PyUnicode_HASH(unicode) = -1;
852 _PyUnicode_STATE(unicode).interned = 0;
853 _PyUnicode_STATE(unicode).kind = 0;
854 _PyUnicode_STATE(unicode).compact = 0;
855 _PyUnicode_STATE(unicode).ready = 0;
856 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +0200857 _PyUnicode_DATA_ANY(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200858 _PyUnicode_LENGTH(unicode) = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200859 _PyUnicode_UTF8(unicode) = NULL;
860 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner7931d9a2011-11-04 00:22:48 +0100861 assert(_PyUnicode_CheckConsistency((PyObject *)unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +0000862 return unicode;
863}
864
Victor Stinnerf42dc442011-10-02 23:33:16 +0200865static const char*
866unicode_kind_name(PyObject *unicode)
867{
Victor Stinner42dfd712011-10-03 14:41:45 +0200868 /* don't check consistency: unicode_kind_name() is called from
869 _PyUnicode_Dump() */
Victor Stinnerf42dc442011-10-02 23:33:16 +0200870 if (!PyUnicode_IS_COMPACT(unicode))
871 {
872 if (!PyUnicode_IS_READY(unicode))
873 return "wstr";
Benjamin Petersonead6b532011-12-20 17:23:42 -0600874 switch (PyUnicode_KIND(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200875 {
876 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200877 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200878 return "legacy ascii";
879 else
880 return "legacy latin1";
881 case PyUnicode_2BYTE_KIND:
882 return "legacy UCS2";
883 case PyUnicode_4BYTE_KIND:
884 return "legacy UCS4";
885 default:
886 return "<legacy invalid kind>";
887 }
888 }
889 assert(PyUnicode_IS_READY(unicode));
Benjamin Petersonead6b532011-12-20 17:23:42 -0600890 switch (PyUnicode_KIND(unicode)) {
Victor Stinnerf42dc442011-10-02 23:33:16 +0200891 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200892 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200893 return "ascii";
894 else
Victor Stinnera3b334d2011-10-03 13:53:37 +0200895 return "latin1";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200896 case PyUnicode_2BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200897 return "UCS2";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200898 case PyUnicode_4BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200899 return "UCS4";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200900 default:
901 return "<invalid compact kind>";
902 }
903}
904
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200905#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +0200906static int unicode_new_new_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200907
908/* Functions wrapping macros for use in debugger */
909char *_PyUnicode_utf8(void *unicode){
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200910 return PyUnicode_UTF8(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200911}
912
913void *_PyUnicode_compact_data(void *unicode) {
914 return _PyUnicode_COMPACT_DATA(unicode);
915}
916void *_PyUnicode_data(void *unicode){
917 printf("obj %p\n", unicode);
918 printf("compact %d\n", PyUnicode_IS_COMPACT(unicode));
919 printf("compact ascii %d\n", PyUnicode_IS_COMPACT_ASCII(unicode));
920 printf("ascii op %p\n", ((void*)((PyASCIIObject*)(unicode) + 1)));
921 printf("compact op %p\n", ((void*)((PyCompactUnicodeObject*)(unicode) + 1)));
922 printf("compact data %p\n", _PyUnicode_COMPACT_DATA(unicode));
923 return PyUnicode_DATA(unicode);
924}
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200925
926void
927_PyUnicode_Dump(PyObject *op)
928{
929 PyASCIIObject *ascii = (PyASCIIObject *)op;
Victor Stinnera849a4b2011-10-03 12:12:11 +0200930 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
931 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
932 void *data;
Victor Stinner0d60e872011-10-23 19:47:19 +0200933
Victor Stinnera849a4b2011-10-03 12:12:11 +0200934 if (ascii->state.compact)
Victor Stinner0d60e872011-10-23 19:47:19 +0200935 {
936 if (ascii->state.ascii)
937 data = (ascii + 1);
938 else
939 data = (compact + 1);
940 }
Victor Stinnera849a4b2011-10-03 12:12:11 +0200941 else
942 data = unicode->data.any;
Victor Stinner0d60e872011-10-23 19:47:19 +0200943 printf("%s: len=%zu, ",unicode_kind_name(op), ascii->length);
944
Victor Stinnera849a4b2011-10-03 12:12:11 +0200945 if (ascii->wstr == data)
946 printf("shared ");
947 printf("wstr=%p", ascii->wstr);
Victor Stinner0d60e872011-10-23 19:47:19 +0200948
Victor Stinnera3b334d2011-10-03 13:53:37 +0200949 if (!(ascii->state.ascii == 1 && ascii->state.compact == 1)) {
Victor Stinnera849a4b2011-10-03 12:12:11 +0200950 printf(" (%zu), ", compact->wstr_length);
951 if (!ascii->state.compact && compact->utf8 == unicode->data.any)
952 printf("shared ");
953 printf("utf8=%p (%zu)", compact->utf8, compact->utf8_length);
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200954 }
Victor Stinnera849a4b2011-10-03 12:12:11 +0200955 printf(", data=%p\n", data);
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200956}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200957#endif
958
959PyObject *
960PyUnicode_New(Py_ssize_t size, Py_UCS4 maxchar)
961{
962 PyObject *obj;
963 PyCompactUnicodeObject *unicode;
964 void *data;
965 int kind_state;
Victor Stinner9e9d6892011-10-04 01:02:02 +0200966 int is_sharing, is_ascii;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200967 Py_ssize_t char_size;
968 Py_ssize_t struct_size;
969
970 /* Optimization for empty strings */
971 if (size == 0 && unicode_empty != NULL) {
972 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +0200973 return unicode_empty;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200974 }
975
976#ifdef Py_DEBUG
977 ++unicode_new_new_calls;
978#endif
979
Victor Stinner9e9d6892011-10-04 01:02:02 +0200980 is_ascii = 0;
981 is_sharing = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200982 struct_size = sizeof(PyCompactUnicodeObject);
983 if (maxchar < 128) {
984 kind_state = PyUnicode_1BYTE_KIND;
985 char_size = 1;
986 is_ascii = 1;
987 struct_size = sizeof(PyASCIIObject);
988 }
989 else if (maxchar < 256) {
990 kind_state = PyUnicode_1BYTE_KIND;
991 char_size = 1;
992 }
993 else if (maxchar < 65536) {
994 kind_state = PyUnicode_2BYTE_KIND;
995 char_size = 2;
996 if (sizeof(wchar_t) == 2)
997 is_sharing = 1;
998 }
999 else {
1000 kind_state = PyUnicode_4BYTE_KIND;
1001 char_size = 4;
1002 if (sizeof(wchar_t) == 4)
1003 is_sharing = 1;
1004 }
1005
1006 /* Ensure we won't overflow the size. */
1007 if (size < 0) {
1008 PyErr_SetString(PyExc_SystemError,
1009 "Negative size passed to PyUnicode_New");
1010 return NULL;
1011 }
1012 if (size > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1))
1013 return PyErr_NoMemory();
1014
1015 /* Duplicated allocation code from _PyObject_New() instead of a call to
1016 * PyObject_New() so we are able to allocate space for the object and
1017 * it's data buffer.
1018 */
1019 obj = (PyObject *) PyObject_MALLOC(struct_size + (size + 1) * char_size);
1020 if (obj == NULL)
1021 return PyErr_NoMemory();
1022 obj = PyObject_INIT(obj, &PyUnicode_Type);
1023 if (obj == NULL)
1024 return NULL;
1025
1026 unicode = (PyCompactUnicodeObject *)obj;
1027 if (is_ascii)
1028 data = ((PyASCIIObject*)obj) + 1;
1029 else
1030 data = unicode + 1;
1031 _PyUnicode_LENGTH(unicode) = size;
1032 _PyUnicode_HASH(unicode) = -1;
1033 _PyUnicode_STATE(unicode).interned = 0;
1034 _PyUnicode_STATE(unicode).kind = kind_state;
1035 _PyUnicode_STATE(unicode).compact = 1;
1036 _PyUnicode_STATE(unicode).ready = 1;
1037 _PyUnicode_STATE(unicode).ascii = is_ascii;
1038 if (is_ascii) {
1039 ((char*)data)[size] = 0;
1040 _PyUnicode_WSTR(unicode) = NULL;
1041 }
1042 else if (kind_state == PyUnicode_1BYTE_KIND) {
1043 ((char*)data)[size] = 0;
1044 _PyUnicode_WSTR(unicode) = NULL;
1045 _PyUnicode_WSTR_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001046 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001047 unicode->utf8_length = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001048 }
1049 else {
1050 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001051 unicode->utf8_length = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001052 if (kind_state == PyUnicode_2BYTE_KIND)
1053 ((Py_UCS2*)data)[size] = 0;
1054 else /* kind_state == PyUnicode_4BYTE_KIND */
1055 ((Py_UCS4*)data)[size] = 0;
1056 if (is_sharing) {
1057 _PyUnicode_WSTR_LENGTH(unicode) = size;
1058 _PyUnicode_WSTR(unicode) = (wchar_t *)data;
1059 }
1060 else {
1061 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1062 _PyUnicode_WSTR(unicode) = NULL;
1063 }
1064 }
Victor Stinner7931d9a2011-11-04 00:22:48 +01001065 assert(_PyUnicode_CheckConsistency((PyObject*)unicode, 0));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001066 return obj;
1067}
1068
1069#if SIZEOF_WCHAR_T == 2
1070/* Helper function to convert a 16-bits wchar_t representation to UCS4, this
1071 will decode surrogate pairs, the other conversions are implemented as macros
Georg Brandl7597add2011-10-05 16:36:47 +02001072 for efficiency.
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001073
1074 This function assumes that unicode can hold one more code point than wstr
1075 characters for a terminating null character. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001076static void
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001077unicode_convert_wchar_to_ucs4(const wchar_t *begin, const wchar_t *end,
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001078 PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001079{
1080 const wchar_t *iter;
1081 Py_UCS4 *ucs4_out;
1082
Victor Stinner910337b2011-10-03 03:20:16 +02001083 assert(unicode != NULL);
1084 assert(_PyUnicode_CHECK(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001085 assert(_PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
1086 ucs4_out = PyUnicode_4BYTE_DATA(unicode);
1087
1088 for (iter = begin; iter < end; ) {
1089 assert(ucs4_out < (PyUnicode_4BYTE_DATA(unicode) +
1090 _PyUnicode_GET_LENGTH(unicode)));
Victor Stinner551ac952011-11-29 22:58:13 +01001091 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1092 && (iter+1) < end
1093 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001094 {
Victor Stinner551ac952011-11-29 22:58:13 +01001095 *ucs4_out++ = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001096 iter += 2;
1097 }
1098 else {
1099 *ucs4_out++ = *iter;
1100 iter++;
1101 }
1102 }
1103 assert(ucs4_out == (PyUnicode_4BYTE_DATA(unicode) +
1104 _PyUnicode_GET_LENGTH(unicode)));
1105
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001106}
1107#endif
1108
Victor Stinnercd9950f2011-10-02 00:34:53 +02001109static int
Victor Stinner488fa492011-12-12 00:01:39 +01001110unicode_check_modifiable(PyObject *unicode)
Victor Stinnercd9950f2011-10-02 00:34:53 +02001111{
Victor Stinner488fa492011-12-12 00:01:39 +01001112 if (!unicode_modifiable(unicode)) {
Victor Stinner01698042011-10-04 00:04:26 +02001113 PyErr_SetString(PyExc_SystemError,
Victor Stinner488fa492011-12-12 00:01:39 +01001114 "Cannot modify a string currently used");
Victor Stinnercd9950f2011-10-02 00:34:53 +02001115 return -1;
1116 }
Victor Stinnercd9950f2011-10-02 00:34:53 +02001117 return 0;
1118}
1119
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001120static int
1121_copy_characters(PyObject *to, Py_ssize_t to_start,
1122 PyObject *from, Py_ssize_t from_start,
1123 Py_ssize_t how_many, int check_maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001124{
Victor Stinnera0702ab2011-09-29 14:14:38 +02001125 unsigned int from_kind, to_kind;
1126 void *from_data, *to_data;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001127 int fast;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001128
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001129 assert(PyUnicode_Check(from));
1130 assert(PyUnicode_Check(to));
1131 assert(PyUnicode_IS_READY(from));
1132 assert(PyUnicode_IS_READY(to));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001133
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001134 assert(PyUnicode_GET_LENGTH(from) >= how_many);
1135 assert(to_start + how_many <= PyUnicode_GET_LENGTH(to));
1136 assert(0 <= how_many);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001137
Victor Stinnerf5ca1a22011-09-28 23:54:59 +02001138 if (how_many == 0)
1139 return 0;
1140
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001141 from_kind = PyUnicode_KIND(from);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001142 from_data = PyUnicode_DATA(from);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001143 to_kind = PyUnicode_KIND(to);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001144 to_data = PyUnicode_DATA(to);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001145
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001146#ifdef Py_DEBUG
1147 if (!check_maxchar
1148 && (from_kind > to_kind
1149 || (!PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to))))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001150 {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001151 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
1152 Py_UCS4 ch;
1153 Py_ssize_t i;
1154 for (i=0; i < how_many; i++) {
1155 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1156 assert(ch <= to_maxchar);
1157 }
1158 }
1159#endif
1160 fast = (from_kind == to_kind);
1161 if (check_maxchar
1162 && (!PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to)))
1163 {
1164 /* deny latin1 => ascii */
1165 fast = 0;
1166 }
1167
1168 if (fast) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +02001169 Py_MEMCPY((char*)to_data + to_kind * to_start,
1170 (char*)from_data + from_kind * from_start,
1171 to_kind * how_many);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001172 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001173 else if (from_kind == PyUnicode_1BYTE_KIND
1174 && to_kind == PyUnicode_2BYTE_KIND)
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001175 {
1176 _PyUnicode_CONVERT_BYTES(
1177 Py_UCS1, Py_UCS2,
1178 PyUnicode_1BYTE_DATA(from) + from_start,
1179 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1180 PyUnicode_2BYTE_DATA(to) + to_start
1181 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001182 }
Victor Stinner157f83f2011-09-28 21:41:31 +02001183 else if (from_kind == PyUnicode_1BYTE_KIND
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001184 && to_kind == PyUnicode_4BYTE_KIND)
1185 {
1186 _PyUnicode_CONVERT_BYTES(
1187 Py_UCS1, Py_UCS4,
1188 PyUnicode_1BYTE_DATA(from) + from_start,
1189 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1190 PyUnicode_4BYTE_DATA(to) + to_start
1191 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001192 }
1193 else if (from_kind == PyUnicode_2BYTE_KIND
1194 && to_kind == PyUnicode_4BYTE_KIND)
1195 {
1196 _PyUnicode_CONVERT_BYTES(
1197 Py_UCS2, Py_UCS4,
1198 PyUnicode_2BYTE_DATA(from) + from_start,
1199 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1200 PyUnicode_4BYTE_DATA(to) + to_start
1201 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001202 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001203 else {
Victor Stinnerf42dc442011-10-02 23:33:16 +02001204 /* check if max_char(from substring) <= max_char(to) */
1205 if (from_kind > to_kind
1206 /* latin1 => ascii */
Victor Stinnerb9275c12011-10-05 14:01:42 +02001207 || (!PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to)))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001208 {
Victor Stinnera0702ab2011-09-29 14:14:38 +02001209 /* slow path to check for character overflow */
1210 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001211 Py_UCS4 ch;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001212 Py_ssize_t i;
1213
Victor Stinner56c161a2011-10-06 02:47:11 +02001214#ifdef Py_DEBUG
Victor Stinnera0702ab2011-09-29 14:14:38 +02001215 for (i=0; i < how_many; i++) {
1216 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
Victor Stinner56c161a2011-10-06 02:47:11 +02001217 assert(ch <= to_maxchar);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001218 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1219 }
Victor Stinner56c161a2011-10-06 02:47:11 +02001220#else
1221 if (!check_maxchar) {
1222 for (i=0; i < how_many; i++) {
1223 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1224 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1225 }
1226 }
1227 else {
1228 for (i=0; i < how_many; i++) {
1229 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1230 if (ch > to_maxchar)
1231 return 1;
1232 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1233 }
1234 }
1235#endif
Victor Stinnera0702ab2011-09-29 14:14:38 +02001236 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001237 else {
Victor Stinner56c161a2011-10-06 02:47:11 +02001238 assert(0 && "inconsistent state");
1239 return 1;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001240 }
1241 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001242 return 0;
1243}
1244
1245static void
1246copy_characters(PyObject *to, Py_ssize_t to_start,
1247 PyObject *from, Py_ssize_t from_start,
1248 Py_ssize_t how_many)
1249{
1250 (void)_copy_characters(to, to_start, from, from_start, how_many, 0);
1251}
1252
1253Py_ssize_t
1254PyUnicode_CopyCharacters(PyObject *to, Py_ssize_t to_start,
1255 PyObject *from, Py_ssize_t from_start,
1256 Py_ssize_t how_many)
1257{
1258 int err;
1259
1260 if (!PyUnicode_Check(from) || !PyUnicode_Check(to)) {
1261 PyErr_BadInternalCall();
1262 return -1;
1263 }
1264
1265 if (PyUnicode_READY(from))
1266 return -1;
1267 if (PyUnicode_READY(to))
1268 return -1;
1269
1270 how_many = Py_MIN(PyUnicode_GET_LENGTH(from), how_many);
1271 if (to_start + how_many > PyUnicode_GET_LENGTH(to)) {
1272 PyErr_Format(PyExc_SystemError,
1273 "Cannot write %zi characters at %zi "
1274 "in a string of %zi characters",
1275 how_many, to_start, PyUnicode_GET_LENGTH(to));
1276 return -1;
1277 }
1278
1279 if (how_many == 0)
1280 return 0;
1281
Victor Stinner488fa492011-12-12 00:01:39 +01001282 if (unicode_check_modifiable(to))
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001283 return -1;
1284
1285 err = _copy_characters(to, to_start, from, from_start, how_many, 1);
1286 if (err) {
1287 PyErr_Format(PyExc_SystemError,
1288 "Cannot copy %s characters "
1289 "into a string of %s characters",
1290 unicode_kind_name(from),
1291 unicode_kind_name(to));
1292 return -1;
1293 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001294 return how_many;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001295}
1296
Victor Stinner17222162011-09-28 22:15:37 +02001297/* Find the maximum code point and count the number of surrogate pairs so a
1298 correct string length can be computed before converting a string to UCS4.
1299 This function counts single surrogates as a character and not as a pair.
1300
1301 Return 0 on success, or -1 on error. */
1302static int
1303find_maxchar_surrogates(const wchar_t *begin, const wchar_t *end,
1304 Py_UCS4 *maxchar, Py_ssize_t *num_surrogates)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001305{
1306 const wchar_t *iter;
Victor Stinner8faf8212011-12-08 22:14:11 +01001307 Py_UCS4 ch;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001308
Victor Stinnerc53be962011-10-02 21:33:54 +02001309 assert(num_surrogates != NULL && maxchar != NULL);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001310 *num_surrogates = 0;
1311 *maxchar = 0;
1312
1313 for (iter = begin; iter < end; ) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001314#if SIZEOF_WCHAR_T == 2
Victor Stinnerca4f2072011-11-22 03:38:40 +01001315 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1316 && (iter+1) < end
1317 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001318 {
Victor Stinner8faf8212011-12-08 22:14:11 +01001319 ch = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001320 ++(*num_surrogates);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001321 iter += 2;
1322 }
1323 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001324#endif
Victor Stinner8faf8212011-12-08 22:14:11 +01001325 {
1326 ch = *iter;
1327 iter++;
1328 }
1329 if (ch > *maxchar) {
1330 *maxchar = ch;
1331 if (*maxchar > MAX_UNICODE) {
1332 PyErr_Format(PyExc_ValueError,
1333 "character U+%x is not in range [U+0000; U+10ffff]",
1334 ch);
1335 return -1;
1336 }
1337 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001338 }
1339 return 0;
1340}
1341
1342#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +02001343static int unicode_ready_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001344#endif
1345
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001346int
1347_PyUnicode_Ready(PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001348{
1349 wchar_t *end;
1350 Py_UCS4 maxchar = 0;
1351 Py_ssize_t num_surrogates;
1352#if SIZEOF_WCHAR_T == 2
1353 Py_ssize_t length_wo_surrogates;
1354#endif
1355
Georg Brandl7597add2011-10-05 16:36:47 +02001356 /* _PyUnicode_Ready() is only intended for old-style API usage where
Victor Stinnerd8f65102011-09-29 19:43:17 +02001357 strings were created using _PyObject_New() and where no canonical
1358 representation (the str field) has been set yet aka strings
1359 which are not yet ready. */
Victor Stinner910337b2011-10-03 03:20:16 +02001360 assert(_PyUnicode_CHECK(unicode));
1361 assert(_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001362 assert(_PyUnicode_WSTR(unicode) != NULL);
Victor Stinnerc3c74152011-10-02 20:39:55 +02001363 assert(_PyUnicode_DATA_ANY(unicode) == NULL);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001364 assert(_PyUnicode_UTF8(unicode) == NULL);
Victor Stinnerd8f65102011-09-29 19:43:17 +02001365 /* Actually, it should neither be interned nor be anything else: */
1366 assert(_PyUnicode_STATE(unicode).interned == SSTATE_NOT_INTERNED);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001367
1368#ifdef Py_DEBUG
1369 ++unicode_ready_calls;
1370#endif
1371
1372 end = _PyUnicode_WSTR(unicode) + _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinner17222162011-09-28 22:15:37 +02001373 if (find_maxchar_surrogates(_PyUnicode_WSTR(unicode), end,
Victor Stinnerd8f65102011-09-29 19:43:17 +02001374 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001375 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001376
1377 if (maxchar < 256) {
Victor Stinnerc3c74152011-10-02 20:39:55 +02001378 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(_PyUnicode_WSTR_LENGTH(unicode) + 1);
1379 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001380 PyErr_NoMemory();
1381 return -1;
1382 }
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001383 _PyUnicode_CONVERT_BYTES(wchar_t, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001384 _PyUnicode_WSTR(unicode), end,
1385 PyUnicode_1BYTE_DATA(unicode));
1386 PyUnicode_1BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1387 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1388 _PyUnicode_STATE(unicode).kind = PyUnicode_1BYTE_KIND;
1389 if (maxchar < 128) {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001390 _PyUnicode_STATE(unicode).ascii = 1;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001391 _PyUnicode_UTF8(unicode) = _PyUnicode_DATA_ANY(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001392 _PyUnicode_UTF8_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001393 }
1394 else {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001395 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001396 _PyUnicode_UTF8(unicode) = NULL;
1397 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001398 }
1399 PyObject_FREE(_PyUnicode_WSTR(unicode));
1400 _PyUnicode_WSTR(unicode) = NULL;
1401 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1402 }
1403 /* In this case we might have to convert down from 4-byte native
1404 wchar_t to 2-byte unicode. */
1405 else if (maxchar < 65536) {
1406 assert(num_surrogates == 0 &&
1407 "FindMaxCharAndNumSurrogatePairs() messed up");
1408
Victor Stinner506f5922011-09-28 22:34:18 +02001409#if SIZEOF_WCHAR_T == 2
1410 /* We can share representations and are done. */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001411 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Victor Stinner506f5922011-09-28 22:34:18 +02001412 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1413 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1414 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001415 _PyUnicode_UTF8(unicode) = NULL;
1416 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001417#else
1418 /* sizeof(wchar_t) == 4 */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001419 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(
Victor Stinner506f5922011-09-28 22:34:18 +02001420 2 * (_PyUnicode_WSTR_LENGTH(unicode) + 1));
Victor Stinnerc3c74152011-10-02 20:39:55 +02001421 if (!_PyUnicode_DATA_ANY(unicode)) {
Victor Stinner506f5922011-09-28 22:34:18 +02001422 PyErr_NoMemory();
1423 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001424 }
Victor Stinner506f5922011-09-28 22:34:18 +02001425 _PyUnicode_CONVERT_BYTES(wchar_t, Py_UCS2,
1426 _PyUnicode_WSTR(unicode), end,
1427 PyUnicode_2BYTE_DATA(unicode));
1428 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1429 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1430 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001431 _PyUnicode_UTF8(unicode) = NULL;
1432 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001433 PyObject_FREE(_PyUnicode_WSTR(unicode));
1434 _PyUnicode_WSTR(unicode) = NULL;
1435 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1436#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001437 }
1438 /* maxchar exeeds 16 bit, wee need 4 bytes for unicode characters */
1439 else {
1440#if SIZEOF_WCHAR_T == 2
1441 /* in case the native representation is 2-bytes, we need to allocate a
1442 new normalized 4-byte version. */
1443 length_wo_surrogates = _PyUnicode_WSTR_LENGTH(unicode) - num_surrogates;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001444 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(4 * (length_wo_surrogates + 1));
1445 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001446 PyErr_NoMemory();
1447 return -1;
1448 }
1449 _PyUnicode_LENGTH(unicode) = length_wo_surrogates;
1450 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001451 _PyUnicode_UTF8(unicode) = NULL;
1452 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner126c5592011-10-03 04:17:10 +02001453 /* unicode_convert_wchar_to_ucs4() requires a ready string */
1454 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerc53be962011-10-02 21:33:54 +02001455 unicode_convert_wchar_to_ucs4(_PyUnicode_WSTR(unicode), end, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001456 PyObject_FREE(_PyUnicode_WSTR(unicode));
1457 _PyUnicode_WSTR(unicode) = NULL;
1458 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1459#else
1460 assert(num_surrogates == 0);
1461
Victor Stinnerc3c74152011-10-02 20:39:55 +02001462 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001463 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001464 _PyUnicode_UTF8(unicode) = NULL;
1465 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001466 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
1467#endif
1468 PyUnicode_4BYTE_DATA(unicode)[_PyUnicode_LENGTH(unicode)] = '\0';
1469 }
1470 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001471 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001472 return 0;
1473}
1474
Alexander Belopolsky40018472011-02-26 01:02:56 +00001475static void
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001476unicode_dealloc(register PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001477{
Walter Dörwald16807132007-05-25 13:52:07 +00001478 switch (PyUnicode_CHECK_INTERNED(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001479 case SSTATE_NOT_INTERNED:
1480 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001481
Benjamin Peterson29060642009-01-31 22:14:21 +00001482 case SSTATE_INTERNED_MORTAL:
1483 /* revive dead object temporarily for DelItem */
1484 Py_REFCNT(unicode) = 3;
Victor Stinner7931d9a2011-11-04 00:22:48 +01001485 if (PyDict_DelItem(interned, unicode) != 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00001486 Py_FatalError(
1487 "deletion of interned string failed");
1488 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001489
Benjamin Peterson29060642009-01-31 22:14:21 +00001490 case SSTATE_INTERNED_IMMORTAL:
1491 Py_FatalError("Immortal interned string died.");
Walter Dörwald16807132007-05-25 13:52:07 +00001492
Benjamin Peterson29060642009-01-31 22:14:21 +00001493 default:
1494 Py_FatalError("Inconsistent interned string state.");
Walter Dörwald16807132007-05-25 13:52:07 +00001495 }
1496
Victor Stinner03490912011-10-03 23:45:12 +02001497 if (_PyUnicode_HAS_WSTR_MEMORY(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001498 PyObject_DEL(_PyUnicode_WSTR(unicode));
Victor Stinner829c0ad2011-10-03 01:08:02 +02001499 if (_PyUnicode_HAS_UTF8_MEMORY(unicode))
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001500 PyObject_DEL(_PyUnicode_UTF8(unicode));
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001501 if (!PyUnicode_IS_COMPACT(unicode) && _PyUnicode_DATA_ANY(unicode))
1502 PyObject_DEL(_PyUnicode_DATA_ANY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001503
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001504 Py_TYPE(unicode)->tp_free(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001505}
1506
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001507#ifdef Py_DEBUG
1508static int
1509unicode_is_singleton(PyObject *unicode)
1510{
1511 PyASCIIObject *ascii = (PyASCIIObject *)unicode;
1512 if (unicode == unicode_empty)
1513 return 1;
1514 if (ascii->state.kind != PyUnicode_WCHAR_KIND && ascii->length == 1)
1515 {
1516 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, 0);
1517 if (ch < 256 && unicode_latin1[ch] == unicode)
1518 return 1;
1519 }
1520 return 0;
1521}
1522#endif
1523
Alexander Belopolsky40018472011-02-26 01:02:56 +00001524static int
Victor Stinner488fa492011-12-12 00:01:39 +01001525unicode_modifiable(PyObject *unicode)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001526{
Victor Stinner488fa492011-12-12 00:01:39 +01001527 assert(_PyUnicode_CHECK(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001528 if (Py_REFCNT(unicode) != 1)
1529 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001530 if (_PyUnicode_HASH(unicode) != -1)
1531 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001532 if (PyUnicode_CHECK_INTERNED(unicode))
1533 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001534 if (!PyUnicode_CheckExact(unicode))
1535 return 0;
Victor Stinner77bb47b2011-10-03 20:06:05 +02001536#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001537 /* singleton refcount is greater than 1 */
1538 assert(!unicode_is_singleton(unicode));
Victor Stinner77bb47b2011-10-03 20:06:05 +02001539#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +02001540 return 1;
1541}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001542
Victor Stinnerfe226c02011-10-03 03:52:20 +02001543static int
1544unicode_resize(PyObject **p_unicode, Py_ssize_t length)
1545{
1546 PyObject *unicode;
1547 Py_ssize_t old_length;
1548
1549 assert(p_unicode != NULL);
1550 unicode = *p_unicode;
1551
1552 assert(unicode != NULL);
1553 assert(PyUnicode_Check(unicode));
1554 assert(0 <= length);
1555
Victor Stinner910337b2011-10-03 03:20:16 +02001556 if (_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001557 old_length = PyUnicode_WSTR_LENGTH(unicode);
1558 else
1559 old_length = PyUnicode_GET_LENGTH(unicode);
1560 if (old_length == length)
1561 return 0;
1562
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001563 if (length == 0) {
1564 Py_DECREF(*p_unicode);
1565 *p_unicode = unicode_empty;
1566 Py_INCREF(*p_unicode);
1567 return 0;
1568 }
1569
Victor Stinner488fa492011-12-12 00:01:39 +01001570 if (!unicode_modifiable(unicode)) {
Victor Stinnerfe226c02011-10-03 03:52:20 +02001571 PyObject *copy = resize_copy(unicode, length);
1572 if (copy == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001573 return -1;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001574 Py_DECREF(*p_unicode);
1575 *p_unicode = copy;
Benjamin Peterson29060642009-01-31 22:14:21 +00001576 return 0;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001577 }
1578
Victor Stinnerfe226c02011-10-03 03:52:20 +02001579 if (PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001580 PyObject *new_unicode = resize_compact(unicode, length);
1581 if (new_unicode == NULL)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001582 return -1;
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001583 *p_unicode = new_unicode;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001584 assert(_PyUnicode_CheckConsistency(*p_unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001585 return 0;
Benjamin Peterson4bfce8f2011-10-03 19:35:07 -04001586 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001587 return resize_inplace(unicode, length);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001588}
1589
Alexander Belopolsky40018472011-02-26 01:02:56 +00001590int
Victor Stinnerfe226c02011-10-03 03:52:20 +02001591PyUnicode_Resize(PyObject **p_unicode, Py_ssize_t length)
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001592{
Victor Stinnerfe226c02011-10-03 03:52:20 +02001593 PyObject *unicode;
1594 if (p_unicode == NULL) {
1595 PyErr_BadInternalCall();
1596 return -1;
1597 }
1598 unicode = *p_unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001599 if (unicode == NULL || !PyUnicode_Check(unicode) || length < 0)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001600 {
1601 PyErr_BadInternalCall();
1602 return -1;
1603 }
1604 return unicode_resize(p_unicode, length);
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001605}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001606
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001607static int
Victor Stinner0a045ef2011-11-09 00:02:42 +01001608unicode_widen(PyObject **p_unicode, unsigned int maxchar)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001609{
1610 PyObject *result;
1611 assert(PyUnicode_IS_READY(*p_unicode));
1612 if (maxchar <= PyUnicode_MAX_CHAR_VALUE(*p_unicode))
1613 return 0;
1614 result = PyUnicode_New(PyUnicode_GET_LENGTH(*p_unicode),
1615 maxchar);
1616 if (result == NULL)
1617 return -1;
1618 PyUnicode_CopyCharacters(result, 0, *p_unicode, 0,
1619 PyUnicode_GET_LENGTH(*p_unicode));
1620 Py_DECREF(*p_unicode);
1621 *p_unicode = result;
1622 return 0;
1623}
1624
1625static int
1626unicode_putchar(PyObject **p_unicode, Py_ssize_t *pos,
1627 Py_UCS4 ch)
1628{
1629 if (unicode_widen(p_unicode, ch) < 0)
1630 return -1;
1631 PyUnicode_WRITE(PyUnicode_KIND(*p_unicode),
1632 PyUnicode_DATA(*p_unicode),
1633 (*pos)++, ch);
1634 return 0;
1635}
1636
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001637static PyObject*
1638get_latin1_char(unsigned char ch)
1639{
Victor Stinnera464fc12011-10-02 20:39:30 +02001640 PyObject *unicode = unicode_latin1[ch];
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001641 if (!unicode) {
Victor Stinnera464fc12011-10-02 20:39:30 +02001642 unicode = PyUnicode_New(1, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001643 if (!unicode)
1644 return NULL;
1645 PyUnicode_1BYTE_DATA(unicode)[0] = ch;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001646 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001647 unicode_latin1[ch] = unicode;
1648 }
1649 Py_INCREF(unicode);
Victor Stinnera464fc12011-10-02 20:39:30 +02001650 return unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001651}
1652
Alexander Belopolsky40018472011-02-26 01:02:56 +00001653PyObject *
1654PyUnicode_FromUnicode(const Py_UNICODE *u, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001655{
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001656 PyObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001657 Py_UCS4 maxchar = 0;
1658 Py_ssize_t num_surrogates;
1659
1660 if (u == NULL)
1661 return (PyObject*)_PyUnicode_New(size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001662
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001663 /* If the Unicode data is known at construction time, we can apply
1664 some optimizations which share commonly used objects. */
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001665
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001666 /* Optimization for empty strings */
1667 if (size == 0 && unicode_empty != NULL) {
1668 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001669 return unicode_empty;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001670 }
Tim Petersced69f82003-09-16 20:30:58 +00001671
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001672 /* Single character Unicode objects in the Latin-1 range are
1673 shared when using this constructor */
1674 if (size == 1 && *u < 256)
1675 return get_latin1_char((unsigned char)*u);
1676
1677 /* If not empty and not single character, copy the Unicode data
1678 into the new object */
Victor Stinnerd8f65102011-09-29 19:43:17 +02001679 if (find_maxchar_surrogates(u, u + size,
1680 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001681 return NULL;
1682
Victor Stinner8faf8212011-12-08 22:14:11 +01001683 unicode = PyUnicode_New(size - num_surrogates, maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001684 if (!unicode)
1685 return NULL;
1686
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001687 switch (PyUnicode_KIND(unicode)) {
1688 case PyUnicode_1BYTE_KIND:
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001689 _PyUnicode_CONVERT_BYTES(Py_UNICODE, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001690 u, u + size, PyUnicode_1BYTE_DATA(unicode));
1691 break;
1692 case PyUnicode_2BYTE_KIND:
1693#if Py_UNICODE_SIZE == 2
1694 Py_MEMCPY(PyUnicode_2BYTE_DATA(unicode), u, size * 2);
1695#else
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001696 _PyUnicode_CONVERT_BYTES(Py_UNICODE, Py_UCS2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001697 u, u + size, PyUnicode_2BYTE_DATA(unicode));
1698#endif
1699 break;
1700 case PyUnicode_4BYTE_KIND:
1701#if SIZEOF_WCHAR_T == 2
1702 /* This is the only case which has to process surrogates, thus
1703 a simple copy loop is not enough and we need a function. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001704 unicode_convert_wchar_to_ucs4(u, u + size, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001705#else
1706 assert(num_surrogates == 0);
1707 Py_MEMCPY(PyUnicode_4BYTE_DATA(unicode), u, size * 4);
1708#endif
1709 break;
1710 default:
1711 assert(0 && "Impossible state");
1712 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00001713
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001714 return unicode_result(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001715}
1716
Alexander Belopolsky40018472011-02-26 01:02:56 +00001717PyObject *
1718PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size)
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001719{
Benjamin Peterson14339b62009-01-31 16:36:08 +00001720 if (size < 0) {
1721 PyErr_SetString(PyExc_SystemError,
Benjamin Peterson29060642009-01-31 22:14:21 +00001722 "Negative size passed to PyUnicode_FromStringAndSize");
Benjamin Peterson14339b62009-01-31 16:36:08 +00001723 return NULL;
1724 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01001725 if (u != NULL)
1726 return PyUnicode_DecodeUTF8Stateful(u, size, NULL, NULL);
1727 else
1728 return (PyObject *)_PyUnicode_New(size);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001729}
1730
Alexander Belopolsky40018472011-02-26 01:02:56 +00001731PyObject *
1732PyUnicode_FromString(const char *u)
Walter Dörwaldd2034312007-05-18 16:29:38 +00001733{
1734 size_t size = strlen(u);
1735 if (size > PY_SSIZE_T_MAX) {
1736 PyErr_SetString(PyExc_OverflowError, "input too long");
1737 return NULL;
1738 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01001739 return PyUnicode_DecodeUTF8Stateful(u, (Py_ssize_t)size, NULL, NULL);
Walter Dörwaldd2034312007-05-18 16:29:38 +00001740}
1741
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001742PyObject *
1743_PyUnicode_FromId(_Py_Identifier *id)
1744{
1745 if (!id->object) {
Victor Stinnera1d12bb2011-12-11 21:53:09 +01001746 id->object = PyUnicode_DecodeUTF8Stateful(id->string,
1747 strlen(id->string),
1748 NULL, NULL);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001749 if (!id->object)
1750 return NULL;
1751 PyUnicode_InternInPlace(&id->object);
1752 assert(!id->next);
1753 id->next = static_strings;
1754 static_strings = id;
1755 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001756 return id->object;
1757}
1758
1759void
1760_PyUnicode_ClearStaticStrings()
1761{
1762 _Py_Identifier *i;
1763 for (i = static_strings; i; i = i->next) {
1764 Py_DECREF(i->object);
1765 i->object = NULL;
1766 i->next = NULL;
1767 }
1768}
1769
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001770/* Internal function, don't check maximum character */
1771
Victor Stinnere57b1c02011-09-28 22:20:48 +02001772static PyObject*
Victor Stinner0617b6e2011-10-05 23:26:01 +02001773unicode_fromascii(const unsigned char* s, Py_ssize_t size)
Victor Stinner702c7342011-10-05 13:50:52 +02001774{
Victor Stinner785938e2011-12-11 20:09:03 +01001775 PyObject *unicode;
Victor Stinnere6b2d442011-12-11 21:54:30 +01001776 if (size == 1) {
Victor Stinner0617b6e2011-10-05 23:26:01 +02001777#ifdef Py_DEBUG
Victor Stinnere6b2d442011-12-11 21:54:30 +01001778 assert(s[0] < 128);
Victor Stinner0617b6e2011-10-05 23:26:01 +02001779#endif
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001780 return get_latin1_char(s[0]);
Victor Stinnere6b2d442011-12-11 21:54:30 +01001781 }
Victor Stinner785938e2011-12-11 20:09:03 +01001782 unicode = PyUnicode_New(size, 127);
1783 if (!unicode)
Victor Stinner702c7342011-10-05 13:50:52 +02001784 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01001785 memcpy(PyUnicode_1BYTE_DATA(unicode), s, size);
1786 assert(_PyUnicode_CheckConsistency(unicode, 1));
1787 return unicode;
Victor Stinner702c7342011-10-05 13:50:52 +02001788}
1789
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001790static Py_UCS4
1791kind_maxchar_limit(unsigned int kind)
1792{
Benjamin Petersonead6b532011-12-20 17:23:42 -06001793 switch (kind) {
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001794 case PyUnicode_1BYTE_KIND:
1795 return 0x80;
1796 case PyUnicode_2BYTE_KIND:
1797 return 0x100;
1798 case PyUnicode_4BYTE_KIND:
1799 return 0x10000;
1800 default:
1801 assert(0 && "invalid kind");
Victor Stinner8faf8212011-12-08 22:14:11 +01001802 return MAX_UNICODE;
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001803 }
1804}
1805
Victor Stinner702c7342011-10-05 13:50:52 +02001806static PyObject*
Victor Stinnere57b1c02011-09-28 22:20:48 +02001807_PyUnicode_FromUCS1(const unsigned char* u, Py_ssize_t size)
Mark Dickinson081dfee2009-03-18 14:47:41 +00001808{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001809 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001810 unsigned char max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001811
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001812 if (size == 0) {
1813 Py_INCREF(unicode_empty);
1814 return unicode_empty;
1815 }
1816 assert(size > 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001817 if (size == 1)
1818 return get_latin1_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001819
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001820 max_char = ucs1lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001821 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001822 if (!res)
1823 return NULL;
1824 memcpy(PyUnicode_1BYTE_DATA(res), u, size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001825 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001826 return res;
Mark Dickinson081dfee2009-03-18 14:47:41 +00001827}
1828
Victor Stinnere57b1c02011-09-28 22:20:48 +02001829static PyObject*
1830_PyUnicode_FromUCS2(const Py_UCS2 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001831{
1832 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001833 Py_UCS2 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001834
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001835 if (size == 0) {
1836 Py_INCREF(unicode_empty);
1837 return unicode_empty;
1838 }
1839 assert(size > 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001840 if (size == 1 && u[0] < 256)
Victor Stinner4e101002011-10-11 23:27:52 +02001841 return get_latin1_char((unsigned char)u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001842
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001843 max_char = ucs2lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001844 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001845 if (!res)
1846 return NULL;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001847 if (max_char >= 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001848 memcpy(PyUnicode_2BYTE_DATA(res), u, sizeof(Py_UCS2)*size);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001849 else {
1850 _PyUnicode_CONVERT_BYTES(
1851 Py_UCS2, Py_UCS1, u, u + size, PyUnicode_1BYTE_DATA(res));
1852 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001853 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001854 return res;
1855}
1856
Victor Stinnere57b1c02011-09-28 22:20:48 +02001857static PyObject*
1858_PyUnicode_FromUCS4(const Py_UCS4 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001859{
1860 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001861 Py_UCS4 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001862
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001863 if (size == 0) {
1864 Py_INCREF(unicode_empty);
1865 return unicode_empty;
1866 }
1867 assert(size > 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001868 if (size == 1 && u[0] < 256)
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001869 return get_latin1_char((unsigned char)u[0]);
1870
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001871 max_char = ucs4lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001872 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001873 if (!res)
1874 return NULL;
Antoine Pitrou950468e2011-10-11 22:45:48 +02001875 if (max_char < 256)
1876 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, u, u + size,
1877 PyUnicode_1BYTE_DATA(res));
1878 else if (max_char < 0x10000)
1879 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, u, u + size,
1880 PyUnicode_2BYTE_DATA(res));
1881 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001882 memcpy(PyUnicode_4BYTE_DATA(res), u, sizeof(Py_UCS4)*size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001883 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001884 return res;
1885}
1886
1887PyObject*
1888PyUnicode_FromKindAndData(int kind, const void *buffer, Py_ssize_t size)
1889{
Victor Stinnercfed46e2011-11-22 01:29:14 +01001890 if (size < 0) {
1891 PyErr_SetString(PyExc_ValueError, "size must be positive");
1892 return NULL;
1893 }
Benjamin Petersonead6b532011-12-20 17:23:42 -06001894 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001895 case PyUnicode_1BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02001896 return _PyUnicode_FromUCS1(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001897 case PyUnicode_2BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02001898 return _PyUnicode_FromUCS2(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001899 case PyUnicode_4BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02001900 return _PyUnicode_FromUCS4(buffer, size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001901 default:
Victor Stinnerb9275c12011-10-05 14:01:42 +02001902 PyErr_SetString(PyExc_SystemError, "invalid kind");
1903 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001904 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001905}
1906
Victor Stinner25a4b292011-10-06 12:31:55 +02001907/* Ensure that a string uses the most efficient storage, if it is not the
1908 case: create a new string with of the right kind. Write NULL into *p_unicode
1909 on error. */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02001910static void
Victor Stinner25a4b292011-10-06 12:31:55 +02001911unicode_adjust_maxchar(PyObject **p_unicode)
1912{
1913 PyObject *unicode, *copy;
1914 Py_UCS4 max_char;
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001915 Py_ssize_t len;
Victor Stinner25a4b292011-10-06 12:31:55 +02001916 unsigned int kind;
1917
1918 assert(p_unicode != NULL);
1919 unicode = *p_unicode;
1920 assert(PyUnicode_IS_READY(unicode));
1921 if (PyUnicode_IS_ASCII(unicode))
1922 return;
1923
1924 len = PyUnicode_GET_LENGTH(unicode);
1925 kind = PyUnicode_KIND(unicode);
1926 if (kind == PyUnicode_1BYTE_KIND) {
1927 const Py_UCS1 *u = PyUnicode_1BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001928 max_char = ucs1lib_find_max_char(u, u + len);
1929 if (max_char >= 128)
1930 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02001931 }
1932 else if (kind == PyUnicode_2BYTE_KIND) {
1933 const Py_UCS2 *u = PyUnicode_2BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001934 max_char = ucs2lib_find_max_char(u, u + len);
1935 if (max_char >= 256)
1936 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02001937 }
1938 else {
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001939 const Py_UCS4 *u = PyUnicode_4BYTE_DATA(unicode);
Victor Stinner25a4b292011-10-06 12:31:55 +02001940 assert(kind == PyUnicode_4BYTE_KIND);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001941 max_char = ucs4lib_find_max_char(u, u + len);
1942 if (max_char >= 0x10000)
1943 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02001944 }
Victor Stinner25a4b292011-10-06 12:31:55 +02001945 copy = PyUnicode_New(len, max_char);
1946 copy_characters(copy, 0, unicode, 0, len);
1947 Py_DECREF(unicode);
1948 *p_unicode = copy;
1949}
1950
Victor Stinner034f6cf2011-09-30 02:26:44 +02001951PyObject*
Victor Stinnerbf6e5602011-12-12 01:53:47 +01001952_PyUnicode_Copy(PyObject *unicode)
Victor Stinner034f6cf2011-09-30 02:26:44 +02001953{
Victor Stinner87af4f22011-11-21 23:03:47 +01001954 Py_ssize_t length;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02001955 PyObject *copy;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02001956
Victor Stinner034f6cf2011-09-30 02:26:44 +02001957 if (!PyUnicode_Check(unicode)) {
1958 PyErr_BadInternalCall();
1959 return NULL;
1960 }
1961 if (PyUnicode_READY(unicode))
1962 return NULL;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02001963
Victor Stinner87af4f22011-11-21 23:03:47 +01001964 length = PyUnicode_GET_LENGTH(unicode);
1965 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02001966 if (!copy)
1967 return NULL;
1968 assert(PyUnicode_KIND(copy) == PyUnicode_KIND(unicode));
1969
Victor Stinner87af4f22011-11-21 23:03:47 +01001970 Py_MEMCPY(PyUnicode_DATA(copy), PyUnicode_DATA(unicode),
1971 length * PyUnicode_KIND(unicode));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001972 assert(_PyUnicode_CheckConsistency(copy, 1));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02001973 return copy;
Victor Stinner034f6cf2011-09-30 02:26:44 +02001974}
1975
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001976
Victor Stinnerbc603d12011-10-02 01:00:40 +02001977/* Widen Unicode objects to larger buffers. Don't write terminating null
1978 character. Return NULL on error. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001979
1980void*
1981_PyUnicode_AsKind(PyObject *s, unsigned int kind)
1982{
Victor Stinnerbc603d12011-10-02 01:00:40 +02001983 Py_ssize_t len;
1984 void *result;
1985 unsigned int skind;
1986
1987 if (PyUnicode_READY(s))
1988 return NULL;
1989
1990 len = PyUnicode_GET_LENGTH(s);
1991 skind = PyUnicode_KIND(s);
1992 if (skind >= kind) {
Victor Stinner01698042011-10-04 00:04:26 +02001993 PyErr_SetString(PyExc_SystemError, "invalid widening attempt");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001994 return NULL;
1995 }
Benjamin Petersonead6b532011-12-20 17:23:42 -06001996 switch (kind) {
Victor Stinnerbc603d12011-10-02 01:00:40 +02001997 case PyUnicode_2BYTE_KIND:
1998 result = PyMem_Malloc(len * sizeof(Py_UCS2));
1999 if (!result)
2000 return PyErr_NoMemory();
2001 assert(skind == PyUnicode_1BYTE_KIND);
2002 _PyUnicode_CONVERT_BYTES(
2003 Py_UCS1, Py_UCS2,
2004 PyUnicode_1BYTE_DATA(s),
2005 PyUnicode_1BYTE_DATA(s) + len,
2006 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002007 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002008 case PyUnicode_4BYTE_KIND:
2009 result = PyMem_Malloc(len * sizeof(Py_UCS4));
2010 if (!result)
2011 return PyErr_NoMemory();
2012 if (skind == PyUnicode_2BYTE_KIND) {
2013 _PyUnicode_CONVERT_BYTES(
2014 Py_UCS2, Py_UCS4,
2015 PyUnicode_2BYTE_DATA(s),
2016 PyUnicode_2BYTE_DATA(s) + len,
2017 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002018 }
Victor Stinnerbc603d12011-10-02 01:00:40 +02002019 else {
2020 assert(skind == PyUnicode_1BYTE_KIND);
2021 _PyUnicode_CONVERT_BYTES(
2022 Py_UCS1, Py_UCS4,
2023 PyUnicode_1BYTE_DATA(s),
2024 PyUnicode_1BYTE_DATA(s) + len,
2025 result);
2026 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002027 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002028 default:
2029 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002030 }
Victor Stinner01698042011-10-04 00:04:26 +02002031 PyErr_SetString(PyExc_SystemError, "invalid kind");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002032 return NULL;
2033}
2034
2035static Py_UCS4*
2036as_ucs4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2037 int copy_null)
2038{
2039 int kind;
2040 void *data;
2041 Py_ssize_t len, targetlen;
2042 if (PyUnicode_READY(string) == -1)
2043 return NULL;
2044 kind = PyUnicode_KIND(string);
2045 data = PyUnicode_DATA(string);
2046 len = PyUnicode_GET_LENGTH(string);
2047 targetlen = len;
2048 if (copy_null)
2049 targetlen++;
2050 if (!target) {
2051 if (PY_SSIZE_T_MAX / sizeof(Py_UCS4) < targetlen) {
2052 PyErr_NoMemory();
2053 return NULL;
2054 }
2055 target = PyMem_Malloc(targetlen * sizeof(Py_UCS4));
2056 if (!target) {
2057 PyErr_NoMemory();
2058 return NULL;
2059 }
2060 }
2061 else {
2062 if (targetsize < targetlen) {
2063 PyErr_Format(PyExc_SystemError,
2064 "string is longer than the buffer");
2065 if (copy_null && 0 < targetsize)
2066 target[0] = 0;
2067 return NULL;
2068 }
2069 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002070 if (kind == PyUnicode_1BYTE_KIND) {
2071 Py_UCS1 *start = (Py_UCS1 *) data;
2072 _PyUnicode_CONVERT_BYTES(Py_UCS1, Py_UCS4, start, start + len, target);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002073 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002074 else if (kind == PyUnicode_2BYTE_KIND) {
2075 Py_UCS2 *start = (Py_UCS2 *) data;
2076 _PyUnicode_CONVERT_BYTES(Py_UCS2, Py_UCS4, start, start + len, target);
2077 }
2078 else {
2079 assert(kind == PyUnicode_4BYTE_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002080 Py_MEMCPY(target, data, len * sizeof(Py_UCS4));
Antoine Pitrou950468e2011-10-11 22:45:48 +02002081 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002082 if (copy_null)
2083 target[len] = 0;
2084 return target;
2085}
2086
2087Py_UCS4*
2088PyUnicode_AsUCS4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2089 int copy_null)
2090{
Antoine Pitroude20b0b2011-11-10 21:47:38 +01002091 if (target == NULL || targetsize < 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002092 PyErr_BadInternalCall();
2093 return NULL;
2094 }
2095 return as_ucs4(string, target, targetsize, copy_null);
2096}
2097
2098Py_UCS4*
2099PyUnicode_AsUCS4Copy(PyObject *string)
2100{
2101 return as_ucs4(string, NULL, 0, 1);
2102}
2103
2104#ifdef HAVE_WCHAR_H
Mark Dickinson081dfee2009-03-18 14:47:41 +00002105
Alexander Belopolsky40018472011-02-26 01:02:56 +00002106PyObject *
2107PyUnicode_FromWideChar(register const wchar_t *w, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002108{
Guido van Rossumd57fd912000-03-10 22:53:23 +00002109 if (w == NULL) {
Victor Stinner382955f2011-12-11 21:44:00 +01002110 if (size == 0) {
2111 Py_INCREF(unicode_empty);
2112 return unicode_empty;
2113 }
Benjamin Peterson29060642009-01-31 22:14:21 +00002114 PyErr_BadInternalCall();
2115 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002116 }
2117
Martin v. Löwis790465f2008-04-05 20:41:37 +00002118 if (size == -1) {
2119 size = wcslen(w);
2120 }
2121
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002122 return PyUnicode_FromUnicode(w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002123}
2124
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002125#endif /* HAVE_WCHAR_H */
Mark Dickinson081dfee2009-03-18 14:47:41 +00002126
Walter Dörwald346737f2007-05-31 10:44:43 +00002127static void
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002128makefmt(char *fmt, int longflag, int longlongflag, int size_tflag,
2129 int zeropad, int width, int precision, char c)
Walter Dörwald346737f2007-05-31 10:44:43 +00002130{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002131 *fmt++ = '%';
2132 if (width) {
2133 if (zeropad)
2134 *fmt++ = '0';
2135 fmt += sprintf(fmt, "%d", width);
2136 }
2137 if (precision)
2138 fmt += sprintf(fmt, ".%d", precision);
2139 if (longflag)
2140 *fmt++ = 'l';
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002141 else if (longlongflag) {
2142 /* longlongflag should only ever be nonzero on machines with
2143 HAVE_LONG_LONG defined */
2144#ifdef HAVE_LONG_LONG
2145 char *f = PY_FORMAT_LONG_LONG;
2146 while (*f)
2147 *fmt++ = *f++;
2148#else
2149 /* we shouldn't ever get here */
2150 assert(0);
2151 *fmt++ = 'l';
2152#endif
2153 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002154 else if (size_tflag) {
2155 char *f = PY_FORMAT_SIZE_T;
2156 while (*f)
2157 *fmt++ = *f++;
2158 }
2159 *fmt++ = c;
2160 *fmt = '\0';
Walter Dörwald346737f2007-05-31 10:44:43 +00002161}
2162
Victor Stinner96865452011-03-01 23:44:09 +00002163/* helper for PyUnicode_FromFormatV() */
2164
2165static const char*
2166parse_format_flags(const char *f,
2167 int *p_width, int *p_precision,
2168 int *p_longflag, int *p_longlongflag, int *p_size_tflag)
2169{
2170 int width, precision, longflag, longlongflag, size_tflag;
2171
2172 /* parse the width.precision part, e.g. "%2.5s" => width=2, precision=5 */
2173 f++;
2174 width = 0;
2175 while (Py_ISDIGIT((unsigned)*f))
2176 width = (width*10) + *f++ - '0';
2177 precision = 0;
2178 if (*f == '.') {
2179 f++;
2180 while (Py_ISDIGIT((unsigned)*f))
2181 precision = (precision*10) + *f++ - '0';
2182 if (*f == '%') {
2183 /* "%.3%s" => f points to "3" */
2184 f--;
2185 }
2186 }
2187 if (*f == '\0') {
2188 /* bogus format "%.1" => go backward, f points to "1" */
2189 f--;
2190 }
2191 if (p_width != NULL)
2192 *p_width = width;
2193 if (p_precision != NULL)
2194 *p_precision = precision;
2195
2196 /* Handle %ld, %lu, %lld and %llu. */
2197 longflag = 0;
2198 longlongflag = 0;
Victor Stinnere7faec12011-03-02 00:01:53 +00002199 size_tflag = 0;
Victor Stinner96865452011-03-01 23:44:09 +00002200
2201 if (*f == 'l') {
Victor Stinner6d970f42011-03-02 00:04:25 +00002202 if (f[1] == 'd' || f[1] == 'u' || f[1] == 'i') {
Victor Stinner96865452011-03-01 23:44:09 +00002203 longflag = 1;
2204 ++f;
2205 }
2206#ifdef HAVE_LONG_LONG
2207 else if (f[1] == 'l' &&
Victor Stinner6d970f42011-03-02 00:04:25 +00002208 (f[2] == 'd' || f[2] == 'u' || f[2] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002209 longlongflag = 1;
2210 f += 2;
2211 }
2212#endif
2213 }
2214 /* handle the size_t flag. */
Victor Stinner6d970f42011-03-02 00:04:25 +00002215 else if (*f == 'z' && (f[1] == 'd' || f[1] == 'u' || f[1] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002216 size_tflag = 1;
2217 ++f;
2218 }
2219 if (p_longflag != NULL)
2220 *p_longflag = longflag;
2221 if (p_longlongflag != NULL)
2222 *p_longlongflag = longlongflag;
2223 if (p_size_tflag != NULL)
2224 *p_size_tflag = size_tflag;
2225 return f;
2226}
2227
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002228/* maximum number of characters required for output of %ld. 21 characters
2229 allows for 64-bit integers (in decimal) and an optional sign. */
2230#define MAX_LONG_CHARS 21
2231/* maximum number of characters required for output of %lld.
2232 We need at most ceil(log10(256)*SIZEOF_LONG_LONG) digits,
2233 plus 1 for the sign. 53/22 is an upper bound for log10(256). */
2234#define MAX_LONG_LONG_CHARS (2 + (SIZEOF_LONG_LONG*53-1) / 22)
2235
Walter Dörwaldd2034312007-05-18 16:29:38 +00002236PyObject *
2237PyUnicode_FromFormatV(const char *format, va_list vargs)
2238{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002239 va_list count;
2240 Py_ssize_t callcount = 0;
2241 PyObject **callresults = NULL;
2242 PyObject **callresult = NULL;
2243 Py_ssize_t n = 0;
2244 int width = 0;
2245 int precision = 0;
2246 int zeropad;
2247 const char* f;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002248 PyObject *string;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002249 /* used by sprintf */
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002250 char fmt[61]; /* should be enough for %0width.precisionlld */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002251 Py_UCS4 maxchar = 127; /* result is ASCII by default */
2252 Py_UCS4 argmaxchar;
2253 Py_ssize_t numbersize = 0;
2254 char *numberresults = NULL;
2255 char *numberresult = NULL;
2256 Py_ssize_t i;
2257 int kind;
2258 void *data;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002259
Victor Stinner4a2b7a12010-08-13 14:03:48 +00002260 Py_VA_COPY(count, vargs);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002261 /* step 1: count the number of %S/%R/%A/%s format specifications
2262 * (we call PyObject_Str()/PyObject_Repr()/PyObject_ASCII()/
2263 * PyUnicode_DecodeUTF8() for these objects once during step 3 and put the
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002264 * result in an array)
Georg Brandl7597add2011-10-05 16:36:47 +02002265 * also estimate a upper bound for all the number formats in the string,
2266 * numbers will be formatted in step 3 and be kept in a '\0'-separated
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002267 * buffer before putting everything together. */
Benjamin Peterson14339b62009-01-31 16:36:08 +00002268 for (f = format; *f; f++) {
2269 if (*f == '%') {
Victor Stinner96865452011-03-01 23:44:09 +00002270 int longlongflag;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002271 /* skip width or width.precision (eg. "1.2" of "%1.2f") */
2272 f = parse_format_flags(f, &width, NULL, NULL, &longlongflag, NULL);
2273 if (*f == 's' || *f=='S' || *f=='R' || *f=='A' || *f=='V')
2274 ++callcount;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002275
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002276 else if (*f == 'd' || *f=='u' || *f=='i' || *f=='x' || *f=='p') {
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002277#ifdef HAVE_LONG_LONG
2278 if (longlongflag) {
2279 if (width < MAX_LONG_LONG_CHARS)
2280 width = MAX_LONG_LONG_CHARS;
2281 }
2282 else
2283#endif
2284 /* MAX_LONG_CHARS is enough to hold a 64-bit integer,
2285 including sign. Decimal takes the most space. This
2286 isn't enough for octal. If a width is specified we
2287 need more (which we allocate later). */
2288 if (width < MAX_LONG_CHARS)
2289 width = MAX_LONG_CHARS;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002290
2291 /* account for the size + '\0' to separate numbers
2292 inside of the numberresults buffer */
2293 numbersize += (width + 1);
2294 }
2295 }
2296 else if ((unsigned char)*f > 127) {
2297 PyErr_Format(PyExc_ValueError,
2298 "PyUnicode_FromFormatV() expects an ASCII-encoded format "
2299 "string, got a non-ASCII byte: 0x%02x",
2300 (unsigned char)*f);
2301 return NULL;
2302 }
2303 }
2304 /* step 2: allocate memory for the results of
2305 * PyObject_Str()/PyObject_Repr()/PyUnicode_DecodeUTF8() calls */
2306 if (callcount) {
2307 callresults = PyObject_Malloc(sizeof(PyObject *) * callcount);
2308 if (!callresults) {
2309 PyErr_NoMemory();
2310 return NULL;
2311 }
2312 callresult = callresults;
2313 }
2314 /* step 2.5: allocate memory for the results of formating numbers */
2315 if (numbersize) {
2316 numberresults = PyObject_Malloc(numbersize);
2317 if (!numberresults) {
2318 PyErr_NoMemory();
2319 goto fail;
2320 }
2321 numberresult = numberresults;
2322 }
2323
2324 /* step 3: format numbers and figure out how large a buffer we need */
2325 for (f = format; *f; f++) {
2326 if (*f == '%') {
2327 const char* p;
2328 int longflag;
2329 int longlongflag;
2330 int size_tflag;
2331 int numprinted;
2332
2333 p = f;
2334 zeropad = (f[1] == '0');
2335 f = parse_format_flags(f, &width, &precision,
2336 &longflag, &longlongflag, &size_tflag);
2337 switch (*f) {
2338 case 'c':
2339 {
2340 Py_UCS4 ordinal = va_arg(count, int);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002341 maxchar = Py_MAX(maxchar, ordinal);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002342 n++;
2343 break;
2344 }
2345 case '%':
2346 n++;
2347 break;
2348 case 'i':
2349 case 'd':
2350 makefmt(fmt, longflag, longlongflag, size_tflag, zeropad,
2351 width, precision, *f);
2352 if (longflag)
2353 numprinted = sprintf(numberresult, fmt,
2354 va_arg(count, long));
2355#ifdef HAVE_LONG_LONG
2356 else if (longlongflag)
2357 numprinted = sprintf(numberresult, fmt,
2358 va_arg(count, PY_LONG_LONG));
2359#endif
2360 else if (size_tflag)
2361 numprinted = sprintf(numberresult, fmt,
2362 va_arg(count, Py_ssize_t));
2363 else
2364 numprinted = sprintf(numberresult, fmt,
2365 va_arg(count, int));
2366 n += numprinted;
2367 /* advance by +1 to skip over the '\0' */
2368 numberresult += (numprinted + 1);
2369 assert(*(numberresult - 1) == '\0');
2370 assert(*(numberresult - 2) != '\0');
2371 assert(numprinted >= 0);
2372 assert(numberresult <= numberresults + numbersize);
2373 break;
2374 case 'u':
2375 makefmt(fmt, longflag, longlongflag, size_tflag, zeropad,
2376 width, precision, 'u');
2377 if (longflag)
2378 numprinted = sprintf(numberresult, fmt,
2379 va_arg(count, unsigned long));
2380#ifdef HAVE_LONG_LONG
2381 else if (longlongflag)
2382 numprinted = sprintf(numberresult, fmt,
2383 va_arg(count, unsigned PY_LONG_LONG));
2384#endif
2385 else if (size_tflag)
2386 numprinted = sprintf(numberresult, fmt,
2387 va_arg(count, size_t));
2388 else
2389 numprinted = sprintf(numberresult, fmt,
2390 va_arg(count, unsigned int));
2391 n += numprinted;
2392 numberresult += (numprinted + 1);
2393 assert(*(numberresult - 1) == '\0');
2394 assert(*(numberresult - 2) != '\0');
2395 assert(numprinted >= 0);
2396 assert(numberresult <= numberresults + numbersize);
2397 break;
2398 case 'x':
2399 makefmt(fmt, 0, 0, 0, zeropad, width, precision, 'x');
2400 numprinted = sprintf(numberresult, fmt, va_arg(count, int));
2401 n += numprinted;
2402 numberresult += (numprinted + 1);
2403 assert(*(numberresult - 1) == '\0');
2404 assert(*(numberresult - 2) != '\0');
2405 assert(numprinted >= 0);
2406 assert(numberresult <= numberresults + numbersize);
2407 break;
2408 case 'p':
2409 numprinted = sprintf(numberresult, "%p", va_arg(count, void*));
2410 /* %p is ill-defined: ensure leading 0x. */
2411 if (numberresult[1] == 'X')
2412 numberresult[1] = 'x';
2413 else if (numberresult[1] != 'x') {
2414 memmove(numberresult + 2, numberresult,
2415 strlen(numberresult) + 1);
2416 numberresult[0] = '0';
2417 numberresult[1] = 'x';
2418 numprinted += 2;
2419 }
2420 n += numprinted;
2421 numberresult += (numprinted + 1);
2422 assert(*(numberresult - 1) == '\0');
2423 assert(*(numberresult - 2) != '\0');
2424 assert(numprinted >= 0);
2425 assert(numberresult <= numberresults + numbersize);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002426 break;
2427 case 's':
2428 {
2429 /* UTF-8 */
Georg Brandl780b2a62009-05-05 09:19:59 +00002430 const char *s = va_arg(count, const char*);
Victor Stinnera1d12bb2011-12-11 21:53:09 +01002431 PyObject *str = PyUnicode_DecodeUTF8Stateful(s, strlen(s), "replace", NULL);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002432 if (!str)
2433 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002434 /* since PyUnicode_DecodeUTF8 returns already flexible
2435 unicode objects, there is no need to call ready on them */
2436 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002437 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002438 n += PyUnicode_GET_LENGTH(str);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002439 /* Remember the str and switch to the next slot */
2440 *callresult++ = str;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002441 break;
2442 }
2443 case 'U':
2444 {
2445 PyObject *obj = va_arg(count, PyObject *);
Victor Stinner910337b2011-10-03 03:20:16 +02002446 assert(obj && _PyUnicode_CHECK(obj));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002447 if (PyUnicode_READY(obj) == -1)
2448 goto fail;
2449 argmaxchar = PyUnicode_MAX_CHAR_VALUE(obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002450 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002451 n += PyUnicode_GET_LENGTH(obj);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002452 break;
2453 }
2454 case 'V':
2455 {
2456 PyObject *obj = va_arg(count, PyObject *);
2457 const char *str = va_arg(count, const char *);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002458 PyObject *str_obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002459 assert(obj || str);
Victor Stinner910337b2011-10-03 03:20:16 +02002460 assert(!obj || _PyUnicode_CHECK(obj));
Victor Stinner2512a8b2011-03-01 22:46:52 +00002461 if (obj) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002462 if (PyUnicode_READY(obj) == -1)
2463 goto fail;
2464 argmaxchar = PyUnicode_MAX_CHAR_VALUE(obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002465 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002466 n += PyUnicode_GET_LENGTH(obj);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002467 *callresult++ = NULL;
2468 }
2469 else {
Victor Stinnera1d12bb2011-12-11 21:53:09 +01002470 str_obj = PyUnicode_DecodeUTF8Stateful(str, strlen(str), "replace", NULL);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002471 if (!str_obj)
2472 goto fail;
Victor Stinnere1335c72011-10-04 20:53:03 +02002473 if (PyUnicode_READY(str_obj)) {
2474 Py_DECREF(str_obj);
2475 goto fail;
2476 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002477 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str_obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002478 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002479 n += PyUnicode_GET_LENGTH(str_obj);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002480 *callresult++ = str_obj;
2481 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002482 break;
2483 }
2484 case 'S':
2485 {
2486 PyObject *obj = va_arg(count, PyObject *);
2487 PyObject *str;
2488 assert(obj);
2489 str = PyObject_Str(obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002490 if (!str || PyUnicode_READY(str) == -1)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002491 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002492 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002493 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002494 n += PyUnicode_GET_LENGTH(str);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002495 /* Remember the str and switch to the next slot */
2496 *callresult++ = str;
2497 break;
2498 }
2499 case 'R':
2500 {
2501 PyObject *obj = va_arg(count, PyObject *);
2502 PyObject *repr;
2503 assert(obj);
2504 repr = PyObject_Repr(obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002505 if (!repr || PyUnicode_READY(repr) == -1)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002506 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002507 argmaxchar = PyUnicode_MAX_CHAR_VALUE(repr);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002508 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002509 n += PyUnicode_GET_LENGTH(repr);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002510 /* Remember the repr and switch to the next slot */
2511 *callresult++ = repr;
2512 break;
2513 }
2514 case 'A':
2515 {
2516 PyObject *obj = va_arg(count, PyObject *);
2517 PyObject *ascii;
2518 assert(obj);
2519 ascii = PyObject_ASCII(obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002520 if (!ascii || PyUnicode_READY(ascii) == -1)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002521 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002522 argmaxchar = PyUnicode_MAX_CHAR_VALUE(ascii);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002523 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002524 n += PyUnicode_GET_LENGTH(ascii);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002525 /* Remember the repr and switch to the next slot */
2526 *callresult++ = ascii;
2527 break;
2528 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002529 default:
2530 /* if we stumble upon an unknown
2531 formatting code, copy the rest of
2532 the format string to the output
2533 string. (we cannot just skip the
2534 code, since there's no way to know
2535 what's in the argument list) */
2536 n += strlen(p);
2537 goto expand;
2538 }
2539 } else
2540 n++;
2541 }
Benjamin Peterson29060642009-01-31 22:14:21 +00002542 expand:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002543 /* step 4: fill the buffer */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002544 /* Since we've analyzed how much space we need,
Benjamin Peterson14339b62009-01-31 16:36:08 +00002545 we don't have to resize the string.
2546 There can be no errors beyond this point. */
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002547 string = PyUnicode_New(n, maxchar);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002548 if (!string)
2549 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002550 kind = PyUnicode_KIND(string);
2551 data = PyUnicode_DATA(string);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002552 callresult = callresults;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002553 numberresult = numberresults;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002554
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002555 for (i = 0, f = format; *f; f++) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00002556 if (*f == '%') {
Victor Stinner96865452011-03-01 23:44:09 +00002557 const char* p;
Victor Stinner96865452011-03-01 23:44:09 +00002558
2559 p = f;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002560 f = parse_format_flags(f, NULL, NULL, NULL, NULL, NULL);
2561 /* checking for == because the last argument could be a empty
2562 string, which causes i to point to end, the assert at the end of
2563 the loop */
2564 assert(i <= PyUnicode_GET_LENGTH(string));
Walter Dörwaldd2034312007-05-18 16:29:38 +00002565
Benjamin Peterson14339b62009-01-31 16:36:08 +00002566 switch (*f) {
2567 case 'c':
Victor Stinner5ed8b2c2011-02-21 21:13:44 +00002568 {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002569 const int ordinal = va_arg(vargs, int);
2570 PyUnicode_WRITE(kind, data, i++, ordinal);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002571 break;
Victor Stinner5ed8b2c2011-02-21 21:13:44 +00002572 }
Victor Stinner6d970f42011-03-02 00:04:25 +00002573 case 'i':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002574 case 'd':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002575 case 'u':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002576 case 'x':
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002577 case 'p':
2578 /* unused, since we already have the result */
2579 if (*f == 'p')
2580 (void) va_arg(vargs, void *);
2581 else
2582 (void) va_arg(vargs, int);
2583 /* extract the result from numberresults and append. */
2584 for (; *numberresult; ++i, ++numberresult)
2585 PyUnicode_WRITE(kind, data, i, *numberresult);
2586 /* skip over the separating '\0' */
2587 assert(*numberresult == '\0');
2588 numberresult++;
2589 assert(numberresult <= numberresults + numbersize);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002590 break;
2591 case 's':
2592 {
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002593 /* unused, since we already have the result */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002594 Py_ssize_t size;
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002595 (void) va_arg(vargs, char *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002596 size = PyUnicode_GET_LENGTH(*callresult);
2597 assert(PyUnicode_KIND(*callresult) <= PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002598 copy_characters(string, i, *callresult, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002599 i += size;
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002600 /* We're done with the unicode()/repr() => forget it */
2601 Py_DECREF(*callresult);
2602 /* switch to next unicode()/repr() result */
2603 ++callresult;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002604 break;
2605 }
2606 case 'U':
2607 {
2608 PyObject *obj = va_arg(vargs, PyObject *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002609 Py_ssize_t size;
2610 assert(PyUnicode_KIND(obj) <= PyUnicode_KIND(string));
2611 size = PyUnicode_GET_LENGTH(obj);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002612 copy_characters(string, i, obj, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002613 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002614 break;
2615 }
2616 case 'V':
2617 {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002618 Py_ssize_t size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002619 PyObject *obj = va_arg(vargs, PyObject *);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002620 va_arg(vargs, const char *);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002621 if (obj) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002622 size = PyUnicode_GET_LENGTH(obj);
2623 assert(PyUnicode_KIND(obj) <= PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002624 copy_characters(string, i, obj, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002625 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002626 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002627 size = PyUnicode_GET_LENGTH(*callresult);
2628 assert(PyUnicode_KIND(*callresult) <=
2629 PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002630 copy_characters(string, i, *callresult, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002631 i += size;
Victor Stinner2512a8b2011-03-01 22:46:52 +00002632 Py_DECREF(*callresult);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002633 }
Victor Stinner2512a8b2011-03-01 22:46:52 +00002634 ++callresult;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002635 break;
2636 }
2637 case 'S':
2638 case 'R':
Victor Stinner9a909002010-10-18 20:59:24 +00002639 case 'A':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002640 {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002641 Py_ssize_t size = PyUnicode_GET_LENGTH(*callresult);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002642 /* unused, since we already have the result */
2643 (void) va_arg(vargs, PyObject *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002644 assert(PyUnicode_KIND(*callresult) <= PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002645 copy_characters(string, i, *callresult, 0, size);
2646 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002647 /* We're done with the unicode()/repr() => forget it */
2648 Py_DECREF(*callresult);
2649 /* switch to next unicode()/repr() result */
2650 ++callresult;
2651 break;
2652 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002653 case '%':
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002654 PyUnicode_WRITE(kind, data, i++, '%');
Benjamin Peterson14339b62009-01-31 16:36:08 +00002655 break;
2656 default:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002657 for (; *p; ++p, ++i)
2658 PyUnicode_WRITE(kind, data, i, *p);
2659 assert(i == PyUnicode_GET_LENGTH(string));
Benjamin Peterson14339b62009-01-31 16:36:08 +00002660 goto end;
2661 }
Victor Stinner1205f272010-09-11 00:54:47 +00002662 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002663 else {
2664 assert(i < PyUnicode_GET_LENGTH(string));
2665 PyUnicode_WRITE(kind, data, i++, *f);
2666 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002667 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002668 assert(i == PyUnicode_GET_LENGTH(string));
Walter Dörwaldd2034312007-05-18 16:29:38 +00002669
Benjamin Peterson29060642009-01-31 22:14:21 +00002670 end:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002671 if (callresults)
2672 PyObject_Free(callresults);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002673 if (numberresults)
2674 PyObject_Free(numberresults);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002675 return unicode_result(string);
Benjamin Peterson29060642009-01-31 22:14:21 +00002676 fail:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002677 if (callresults) {
2678 PyObject **callresult2 = callresults;
2679 while (callresult2 < callresult) {
Victor Stinner2512a8b2011-03-01 22:46:52 +00002680 Py_XDECREF(*callresult2);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002681 ++callresult2;
2682 }
2683 PyObject_Free(callresults);
2684 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002685 if (numberresults)
2686 PyObject_Free(numberresults);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002687 return NULL;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002688}
2689
Walter Dörwaldd2034312007-05-18 16:29:38 +00002690PyObject *
2691PyUnicode_FromFormat(const char *format, ...)
2692{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002693 PyObject* ret;
2694 va_list vargs;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002695
2696#ifdef HAVE_STDARG_PROTOTYPES
Benjamin Peterson14339b62009-01-31 16:36:08 +00002697 va_start(vargs, format);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002698#else
Benjamin Peterson14339b62009-01-31 16:36:08 +00002699 va_start(vargs);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002700#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00002701 ret = PyUnicode_FromFormatV(format, vargs);
2702 va_end(vargs);
2703 return ret;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002704}
2705
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002706#ifdef HAVE_WCHAR_H
2707
Victor Stinner5593d8a2010-10-02 11:11:27 +00002708/* Helper function for PyUnicode_AsWideChar() and PyUnicode_AsWideCharString():
2709 convert a Unicode object to a wide character string.
2710
Victor Stinnerd88d9832011-09-06 02:00:05 +02002711 - If w is NULL: return the number of wide characters (including the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002712 character) required to convert the unicode object. Ignore size argument.
2713
Victor Stinnerd88d9832011-09-06 02:00:05 +02002714 - Otherwise: return the number of wide characters (excluding the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002715 character) written into w. Write at most size wide characters (including
Victor Stinnerd88d9832011-09-06 02:00:05 +02002716 the null character). */
Victor Stinner5593d8a2010-10-02 11:11:27 +00002717static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002718unicode_aswidechar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002719 wchar_t *w,
2720 Py_ssize_t size)
2721{
Victor Stinner5593d8a2010-10-02 11:11:27 +00002722 Py_ssize_t res;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002723 const wchar_t *wstr;
2724
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002725 wstr = PyUnicode_AsUnicodeAndSize(unicode, &res);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002726 if (wstr == NULL)
2727 return -1;
2728
Victor Stinner5593d8a2010-10-02 11:11:27 +00002729 if (w != NULL) {
Victor Stinner5593d8a2010-10-02 11:11:27 +00002730 if (size > res)
2731 size = res + 1;
2732 else
2733 res = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002734 Py_MEMCPY(w, wstr, size * sizeof(wchar_t));
Victor Stinner5593d8a2010-10-02 11:11:27 +00002735 return res;
2736 }
2737 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002738 return res + 1;
Victor Stinner137c34c2010-09-29 10:25:54 +00002739}
2740
2741Py_ssize_t
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002742PyUnicode_AsWideChar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002743 wchar_t *w,
2744 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002745{
2746 if (unicode == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002747 PyErr_BadInternalCall();
2748 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002749 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002750 return unicode_aswidechar(unicode, w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002751}
2752
Victor Stinner137c34c2010-09-29 10:25:54 +00002753wchar_t*
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00002754PyUnicode_AsWideCharString(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002755 Py_ssize_t *size)
2756{
2757 wchar_t* buffer;
2758 Py_ssize_t buflen;
2759
2760 if (unicode == NULL) {
2761 PyErr_BadInternalCall();
2762 return NULL;
2763 }
2764
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002765 buflen = unicode_aswidechar(unicode, NULL, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002766 if (buflen == -1)
2767 return NULL;
Victor Stinner5593d8a2010-10-02 11:11:27 +00002768 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < buflen) {
Victor Stinner137c34c2010-09-29 10:25:54 +00002769 PyErr_NoMemory();
2770 return NULL;
2771 }
2772
Victor Stinner137c34c2010-09-29 10:25:54 +00002773 buffer = PyMem_MALLOC(buflen * sizeof(wchar_t));
2774 if (buffer == NULL) {
2775 PyErr_NoMemory();
2776 return NULL;
2777 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002778 buflen = unicode_aswidechar(unicode, buffer, buflen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002779 if (buflen == -1)
2780 return NULL;
Victor Stinner5593d8a2010-10-02 11:11:27 +00002781 if (size != NULL)
2782 *size = buflen;
Victor Stinner137c34c2010-09-29 10:25:54 +00002783 return buffer;
2784}
2785
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002786#endif /* HAVE_WCHAR_H */
Guido van Rossumd57fd912000-03-10 22:53:23 +00002787
Alexander Belopolsky40018472011-02-26 01:02:56 +00002788PyObject *
2789PyUnicode_FromOrdinal(int ordinal)
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002790{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002791 PyObject *v;
Victor Stinner8faf8212011-12-08 22:14:11 +01002792 if (ordinal < 0 || ordinal > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002793 PyErr_SetString(PyExc_ValueError,
2794 "chr() arg not in range(0x110000)");
2795 return NULL;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002796 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00002797
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002798 if (ordinal < 256)
2799 return get_latin1_char(ordinal);
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002800
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002801 v = PyUnicode_New(1, ordinal);
2802 if (v == NULL)
2803 return NULL;
2804 PyUnicode_WRITE(PyUnicode_KIND(v), PyUnicode_DATA(v), 0, ordinal);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002805 assert(_PyUnicode_CheckConsistency(v, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002806 return v;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002807}
2808
Alexander Belopolsky40018472011-02-26 01:02:56 +00002809PyObject *
2810PyUnicode_FromObject(register PyObject *obj)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002811{
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002812 /* XXX Perhaps we should make this API an alias of
Benjamin Peterson29060642009-01-31 22:14:21 +00002813 PyObject_Str() instead ?! */
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002814 if (PyUnicode_CheckExact(obj)) {
Victor Stinnerd3a83d52011-10-01 03:09:33 +02002815 if (PyUnicode_READY(obj))
2816 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +00002817 Py_INCREF(obj);
2818 return obj;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002819 }
2820 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002821 /* For a Unicode subtype that's not a Unicode object,
2822 return a true Unicode object with the same data. */
Victor Stinnerbf6e5602011-12-12 01:53:47 +01002823 return _PyUnicode_Copy(obj);
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002824 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00002825 PyErr_Format(PyExc_TypeError,
2826 "Can't convert '%.100s' object to str implicitly",
Christian Heimes90aa7642007-12-19 02:45:37 +00002827 Py_TYPE(obj)->tp_name);
Guido van Rossum98297ee2007-11-06 21:34:58 +00002828 return NULL;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002829}
2830
Alexander Belopolsky40018472011-02-26 01:02:56 +00002831PyObject *
2832PyUnicode_FromEncodedObject(register PyObject *obj,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002833 const char *encoding,
2834 const char *errors)
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002835{
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002836 Py_buffer buffer;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002837 PyObject *v;
Tim Petersced69f82003-09-16 20:30:58 +00002838
Guido van Rossumd57fd912000-03-10 22:53:23 +00002839 if (obj == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002840 PyErr_BadInternalCall();
2841 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002842 }
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002843
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002844 /* Decoding bytes objects is the most common case and should be fast */
2845 if (PyBytes_Check(obj)) {
2846 if (PyBytes_GET_SIZE(obj) == 0) {
2847 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02002848 v = unicode_empty;
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002849 }
2850 else {
2851 v = PyUnicode_Decode(
2852 PyBytes_AS_STRING(obj), PyBytes_GET_SIZE(obj),
2853 encoding, errors);
2854 }
2855 return v;
2856 }
2857
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002858 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002859 PyErr_SetString(PyExc_TypeError,
2860 "decoding str is not supported");
2861 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002862 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002863
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002864 /* Retrieve a bytes buffer view through the PEP 3118 buffer interface */
2865 if (PyObject_GetBuffer(obj, &buffer, PyBUF_SIMPLE) < 0) {
2866 PyErr_Format(PyExc_TypeError,
2867 "coercing to str: need bytes, bytearray "
2868 "or buffer-like object, %.80s found",
2869 Py_TYPE(obj)->tp_name);
2870 return NULL;
Marc-André Lemburg6871f6a2001-09-20 12:53:16 +00002871 }
Tim Petersced69f82003-09-16 20:30:58 +00002872
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002873 if (buffer.len == 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002874 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02002875 v = unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002876 }
Tim Petersced69f82003-09-16 20:30:58 +00002877 else
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002878 v = PyUnicode_Decode((char*) buffer.buf, buffer.len, encoding, errors);
Marc-André Lemburgad7c98e2001-01-17 17:09:53 +00002879
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002880 PyBuffer_Release(&buffer);
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002881 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002882}
2883
Victor Stinner600d3be2010-06-10 12:00:55 +00002884/* Convert encoding to lower case and replace '_' with '-' in order to
Victor Stinner37296e82010-06-10 13:36:23 +00002885 catch e.g. UTF_8. Return 0 on error (encoding is longer than lower_len-1),
2886 1 on success. */
2887static int
2888normalize_encoding(const char *encoding,
2889 char *lower,
2890 size_t lower_len)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002891{
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002892 const char *e;
Victor Stinner600d3be2010-06-10 12:00:55 +00002893 char *l;
2894 char *l_end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002895
Benjamin Peterson7a6debe2011-10-15 09:25:28 -04002896 if (encoding == NULL) {
2897 strcpy(lower, "utf-8");
2898 return 1;
2899 }
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002900 e = encoding;
2901 l = lower;
Victor Stinner600d3be2010-06-10 12:00:55 +00002902 l_end = &lower[lower_len - 1];
Victor Stinner37296e82010-06-10 13:36:23 +00002903 while (*e) {
2904 if (l == l_end)
2905 return 0;
David Malcolm96960882010-11-05 17:23:41 +00002906 if (Py_ISUPPER(*e)) {
2907 *l++ = Py_TOLOWER(*e++);
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002908 }
2909 else if (*e == '_') {
2910 *l++ = '-';
2911 e++;
2912 }
2913 else {
2914 *l++ = *e++;
2915 }
2916 }
2917 *l = '\0';
Victor Stinner37296e82010-06-10 13:36:23 +00002918 return 1;
Victor Stinner600d3be2010-06-10 12:00:55 +00002919}
2920
Alexander Belopolsky40018472011-02-26 01:02:56 +00002921PyObject *
2922PyUnicode_Decode(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002923 Py_ssize_t size,
2924 const char *encoding,
2925 const char *errors)
Victor Stinner600d3be2010-06-10 12:00:55 +00002926{
2927 PyObject *buffer = NULL, *unicode;
2928 Py_buffer info;
2929 char lower[11]; /* Enough for any encoding shortcut */
2930
Fred Drakee4315f52000-05-09 19:53:39 +00002931 /* Shortcuts for common default encodings */
Victor Stinner37296e82010-06-10 13:36:23 +00002932 if (normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00002933 if ((strcmp(lower, "utf-8") == 0) ||
2934 (strcmp(lower, "utf8") == 0))
Victor Stinnera1d12bb2011-12-11 21:53:09 +01002935 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
Victor Stinner37296e82010-06-10 13:36:23 +00002936 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00002937 (strcmp(lower, "latin1") == 0) ||
Victor Stinner37296e82010-06-10 13:36:23 +00002938 (strcmp(lower, "iso-8859-1") == 0))
2939 return PyUnicode_DecodeLatin1(s, size, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02002940#ifdef HAVE_MBCS
Victor Stinner37296e82010-06-10 13:36:23 +00002941 else if (strcmp(lower, "mbcs") == 0)
2942 return PyUnicode_DecodeMBCS(s, size, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00002943#endif
Victor Stinner37296e82010-06-10 13:36:23 +00002944 else if (strcmp(lower, "ascii") == 0)
2945 return PyUnicode_DecodeASCII(s, size, errors);
2946 else if (strcmp(lower, "utf-16") == 0)
2947 return PyUnicode_DecodeUTF16(s, size, errors, 0);
2948 else if (strcmp(lower, "utf-32") == 0)
2949 return PyUnicode_DecodeUTF32(s, size, errors, 0);
2950 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002951
2952 /* Decode via the codec registry */
Guido van Rossumbe801ac2007-10-08 03:32:34 +00002953 buffer = NULL;
Antoine Pitrouc3b39242009-01-03 16:59:18 +00002954 if (PyBuffer_FillInfo(&info, NULL, (void *)s, size, 1, PyBUF_FULL_RO) < 0)
Guido van Rossumbe801ac2007-10-08 03:32:34 +00002955 goto onError;
Antoine Pitrouee58fa42008-08-19 18:22:14 +00002956 buffer = PyMemoryView_FromBuffer(&info);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002957 if (buffer == NULL)
2958 goto onError;
2959 unicode = PyCodec_Decode(buffer, encoding, errors);
2960 if (unicode == NULL)
2961 goto onError;
2962 if (!PyUnicode_Check(unicode)) {
2963 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00002964 "decoder did not return a str object (type=%.400s)",
Christian Heimes90aa7642007-12-19 02:45:37 +00002965 Py_TYPE(unicode)->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002966 Py_DECREF(unicode);
2967 goto onError;
2968 }
2969 Py_DECREF(buffer);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002970 return unicode_result(unicode);
Tim Petersced69f82003-09-16 20:30:58 +00002971
Benjamin Peterson29060642009-01-31 22:14:21 +00002972 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00002973 Py_XDECREF(buffer);
2974 return NULL;
2975}
2976
Alexander Belopolsky40018472011-02-26 01:02:56 +00002977PyObject *
2978PyUnicode_AsDecodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002979 const char *encoding,
2980 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002981{
2982 PyObject *v;
2983
2984 if (!PyUnicode_Check(unicode)) {
2985 PyErr_BadArgument();
2986 goto onError;
2987 }
2988
2989 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00002990 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002991
2992 /* Decode via the codec registry */
2993 v = PyCodec_Decode(unicode, encoding, errors);
2994 if (v == NULL)
2995 goto onError;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002996 return unicode_result(v);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002997
Benjamin Peterson29060642009-01-31 22:14:21 +00002998 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002999 return NULL;
3000}
3001
Alexander Belopolsky40018472011-02-26 01:02:56 +00003002PyObject *
3003PyUnicode_AsDecodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003004 const char *encoding,
3005 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003006{
3007 PyObject *v;
3008
3009 if (!PyUnicode_Check(unicode)) {
3010 PyErr_BadArgument();
3011 goto onError;
3012 }
3013
3014 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003015 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003016
3017 /* Decode via the codec registry */
3018 v = PyCodec_Decode(unicode, encoding, errors);
3019 if (v == NULL)
3020 goto onError;
3021 if (!PyUnicode_Check(v)) {
3022 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00003023 "decoder did not return a str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003024 Py_TYPE(v)->tp_name);
3025 Py_DECREF(v);
3026 goto onError;
3027 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003028 return unicode_result(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003029
Benjamin Peterson29060642009-01-31 22:14:21 +00003030 onError:
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003031 return NULL;
3032}
3033
Alexander Belopolsky40018472011-02-26 01:02:56 +00003034PyObject *
3035PyUnicode_Encode(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003036 Py_ssize_t size,
3037 const char *encoding,
3038 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003039{
3040 PyObject *v, *unicode;
Tim Petersced69f82003-09-16 20:30:58 +00003041
Guido van Rossumd57fd912000-03-10 22:53:23 +00003042 unicode = PyUnicode_FromUnicode(s, size);
3043 if (unicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003044 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003045 v = PyUnicode_AsEncodedString(unicode, encoding, errors);
3046 Py_DECREF(unicode);
3047 return v;
3048}
3049
Alexander Belopolsky40018472011-02-26 01:02:56 +00003050PyObject *
3051PyUnicode_AsEncodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003052 const char *encoding,
3053 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003054{
3055 PyObject *v;
3056
3057 if (!PyUnicode_Check(unicode)) {
3058 PyErr_BadArgument();
3059 goto onError;
3060 }
3061
3062 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003063 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003064
3065 /* Encode via the codec registry */
3066 v = PyCodec_Encode(unicode, encoding, errors);
3067 if (v == NULL)
3068 goto onError;
3069 return v;
3070
Benjamin Peterson29060642009-01-31 22:14:21 +00003071 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003072 return NULL;
3073}
3074
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003075static size_t
3076wcstombs_errorpos(const wchar_t *wstr)
3077{
3078 size_t len;
3079#if SIZEOF_WCHAR_T == 2
3080 wchar_t buf[3];
3081#else
3082 wchar_t buf[2];
3083#endif
3084 char outbuf[MB_LEN_MAX];
3085 const wchar_t *start, *previous;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003086
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003087#if SIZEOF_WCHAR_T == 2
3088 buf[2] = 0;
3089#else
3090 buf[1] = 0;
3091#endif
3092 start = wstr;
3093 while (*wstr != L'\0')
3094 {
3095 previous = wstr;
3096#if SIZEOF_WCHAR_T == 2
3097 if (Py_UNICODE_IS_HIGH_SURROGATE(wstr[0])
3098 && Py_UNICODE_IS_LOW_SURROGATE(wstr[1]))
3099 {
3100 buf[0] = wstr[0];
3101 buf[1] = wstr[1];
3102 wstr += 2;
3103 }
3104 else {
3105 buf[0] = *wstr;
3106 buf[1] = 0;
3107 wstr++;
3108 }
3109#else
3110 buf[0] = *wstr;
3111 wstr++;
3112#endif
3113 len = wcstombs(outbuf, buf, sizeof(outbuf));
Victor Stinner2f197072011-12-17 07:08:30 +01003114 if (len == (size_t)-1)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003115 return previous - start;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003116 }
3117
3118 /* failed to find the unencodable character */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003119 return 0;
3120}
3121
Victor Stinner1b579672011-12-17 05:47:23 +01003122static int
3123locale_error_handler(const char *errors, int *surrogateescape)
3124{
3125 if (errors == NULL) {
3126 *surrogateescape = 0;
3127 return 0;
3128 }
3129
3130 if (strcmp(errors, "strict") == 0) {
3131 *surrogateescape = 0;
3132 return 0;
3133 }
3134 if (strcmp(errors, "surrogateescape") == 0) {
3135 *surrogateescape = 1;
3136 return 0;
3137 }
3138 PyErr_Format(PyExc_ValueError,
3139 "only 'strict' and 'surrogateescape' error handlers "
3140 "are supported, not '%s'",
3141 errors);
3142 return -1;
3143}
3144
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003145PyObject *
Victor Stinner1b579672011-12-17 05:47:23 +01003146PyUnicode_EncodeLocale(PyObject *unicode, const char *errors)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003147{
3148 Py_ssize_t wlen, wlen2;
3149 wchar_t *wstr;
3150 PyObject *bytes = NULL;
3151 char *errmsg;
Victor Stinner1f33f2b2011-12-17 04:45:09 +01003152 PyObject *reason;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003153 PyObject *exc;
3154 size_t error_pos;
Victor Stinner1b579672011-12-17 05:47:23 +01003155 int surrogateescape;
3156
3157 if (locale_error_handler(errors, &surrogateescape) < 0)
3158 return NULL;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003159
3160 wstr = PyUnicode_AsWideCharString(unicode, &wlen);
3161 if (wstr == NULL)
3162 return NULL;
3163
3164 wlen2 = wcslen(wstr);
3165 if (wlen2 != wlen) {
3166 PyMem_Free(wstr);
3167 PyErr_SetString(PyExc_TypeError, "embedded null character");
3168 return NULL;
3169 }
3170
3171 if (surrogateescape) {
3172 /* locale encoding with surrogateescape */
3173 char *str;
3174
3175 str = _Py_wchar2char(wstr, &error_pos);
3176 if (str == NULL) {
3177 if (error_pos == (size_t)-1) {
3178 PyErr_NoMemory();
3179 PyMem_Free(wstr);
3180 return NULL;
3181 }
3182 else {
3183 goto encode_error;
3184 }
3185 }
3186 PyMem_Free(wstr);
3187
3188 bytes = PyBytes_FromString(str);
3189 PyMem_Free(str);
3190 }
3191 else {
3192 size_t len, len2;
3193
3194 len = wcstombs(NULL, wstr, 0);
3195 if (len == (size_t)-1) {
Victor Stinner2f197072011-12-17 07:08:30 +01003196 error_pos = (size_t)-1;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003197 goto encode_error;
3198 }
3199
3200 bytes = PyBytes_FromStringAndSize(NULL, len);
3201 if (bytes == NULL) {
3202 PyMem_Free(wstr);
3203 return NULL;
3204 }
3205
3206 len2 = wcstombs(PyBytes_AS_STRING(bytes), wstr, len+1);
3207 if (len2 == (size_t)-1 || len2 > len) {
Victor Stinner2f197072011-12-17 07:08:30 +01003208 error_pos = (size_t)-1;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003209 goto encode_error;
3210 }
3211 PyMem_Free(wstr);
3212 }
3213 return bytes;
3214
3215encode_error:
3216 errmsg = strerror(errno);
3217 assert(errmsg != NULL);
Victor Stinner2f197072011-12-17 07:08:30 +01003218
3219 if (error_pos == (size_t)-1)
3220 error_pos = wcstombs_errorpos(wstr);
3221
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003222 PyMem_Free(wstr);
3223 Py_XDECREF(bytes);
3224
Victor Stinner2f197072011-12-17 07:08:30 +01003225 if (errmsg != NULL) {
3226 size_t errlen;
3227 wstr = _Py_char2wchar(errmsg, &errlen);
3228 if (wstr != NULL) {
3229 reason = PyUnicode_FromWideChar(wstr, errlen);
3230 PyMem_Free(wstr);
3231 } else
3232 errmsg = NULL;
3233 }
3234 if (errmsg == NULL)
Victor Stinner1f33f2b2011-12-17 04:45:09 +01003235 reason = PyUnicode_FromString(
3236 "wcstombs() encountered an unencodable "
3237 "wide character");
3238 if (reason == NULL)
3239 return NULL;
3240
3241 exc = PyObject_CallFunction(PyExc_UnicodeEncodeError, "sOnnO",
3242 "locale", unicode,
3243 (Py_ssize_t)error_pos,
3244 (Py_ssize_t)(error_pos+1),
3245 reason);
3246 Py_DECREF(reason);
3247 if (exc != NULL) {
3248 PyCodec_StrictErrors(exc);
3249 Py_XDECREF(exc);
3250 }
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003251 return NULL;
3252}
3253
Victor Stinnerad158722010-10-27 00:25:46 +00003254PyObject *
3255PyUnicode_EncodeFSDefault(PyObject *unicode)
Victor Stinnerae6265f2010-05-15 16:27:27 +00003256{
Victor Stinner99b95382011-07-04 14:23:54 +02003257#ifdef HAVE_MBCS
Victor Stinnerac931b12011-11-20 18:27:03 +01003258 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003259#elif defined(__APPLE__)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003260 return _PyUnicode_AsUTF8String(unicode, "surrogateescape");
Victor Stinnerad158722010-10-27 00:25:46 +00003261#else
Victor Stinner793b5312011-04-27 00:24:21 +02003262 PyInterpreterState *interp = PyThreadState_GET()->interp;
3263 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3264 cannot use it to encode and decode filenames before it is loaded. Load
3265 the Python codec requires to encode at least its own filename. Use the C
3266 version of the locale codec until the codec registry is initialized and
3267 the Python codec is loaded.
3268
3269 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3270 cannot only rely on it: check also interp->fscodec_initialized for
3271 subinterpreters. */
3272 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Victor Stinnerae6265f2010-05-15 16:27:27 +00003273 return PyUnicode_AsEncodedString(unicode,
3274 Py_FileSystemDefaultEncoding,
3275 "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00003276 }
3277 else {
Victor Stinner1b579672011-12-17 05:47:23 +01003278 return PyUnicode_EncodeLocale(unicode, "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00003279 }
Victor Stinnerad158722010-10-27 00:25:46 +00003280#endif
Victor Stinnerae6265f2010-05-15 16:27:27 +00003281}
3282
Alexander Belopolsky40018472011-02-26 01:02:56 +00003283PyObject *
3284PyUnicode_AsEncodedString(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003285 const char *encoding,
3286 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003287{
3288 PyObject *v;
Victor Stinner600d3be2010-06-10 12:00:55 +00003289 char lower[11]; /* Enough for any encoding shortcut */
Tim Petersced69f82003-09-16 20:30:58 +00003290
Guido van Rossumd57fd912000-03-10 22:53:23 +00003291 if (!PyUnicode_Check(unicode)) {
3292 PyErr_BadArgument();
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003293 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003294 }
Fred Drakee4315f52000-05-09 19:53:39 +00003295
Fred Drakee4315f52000-05-09 19:53:39 +00003296 /* Shortcuts for common default encodings */
Victor Stinner37296e82010-06-10 13:36:23 +00003297 if (normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003298 if ((strcmp(lower, "utf-8") == 0) ||
3299 (strcmp(lower, "utf8") == 0))
Victor Stinnera5c68c32011-03-02 01:03:14 +00003300 {
Victor Stinner2f283c22011-03-02 01:21:46 +00003301 if (errors == NULL || strcmp(errors, "strict") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003302 return _PyUnicode_AsUTF8String(unicode, NULL);
Victor Stinner2f283c22011-03-02 01:21:46 +00003303 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003304 return _PyUnicode_AsUTF8String(unicode, errors);
Victor Stinnera5c68c32011-03-02 01:03:14 +00003305 }
Victor Stinner37296e82010-06-10 13:36:23 +00003306 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003307 (strcmp(lower, "latin1") == 0) ||
Victor Stinner37296e82010-06-10 13:36:23 +00003308 (strcmp(lower, "iso-8859-1") == 0))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003309 return _PyUnicode_AsLatin1String(unicode, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02003310#ifdef HAVE_MBCS
Victor Stinnerac931b12011-11-20 18:27:03 +01003311 else if (strcmp(lower, "mbcs") == 0)
3312 return PyUnicode_EncodeCodePage(CP_ACP, unicode, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003313#endif
Victor Stinner37296e82010-06-10 13:36:23 +00003314 else if (strcmp(lower, "ascii") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003315 return _PyUnicode_AsASCIIString(unicode, errors);
Victor Stinner37296e82010-06-10 13:36:23 +00003316 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003317
3318 /* Encode via the codec registry */
3319 v = PyCodec_Encode(unicode, encoding, errors);
3320 if (v == NULL)
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003321 return NULL;
3322
3323 /* The normal path */
3324 if (PyBytes_Check(v))
3325 return v;
3326
3327 /* If the codec returns a buffer, raise a warning and convert to bytes */
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003328 if (PyByteArray_Check(v)) {
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003329 int error;
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003330 PyObject *b;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003331
3332 error = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
3333 "encoder %s returned bytearray instead of bytes",
3334 encoding);
3335 if (error) {
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003336 Py_DECREF(v);
3337 return NULL;
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003338 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003339
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003340 b = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(v), Py_SIZE(v));
3341 Py_DECREF(v);
3342 return b;
3343 }
3344
3345 PyErr_Format(PyExc_TypeError,
3346 "encoder did not return a bytes object (type=%.400s)",
3347 Py_TYPE(v)->tp_name);
3348 Py_DECREF(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003349 return NULL;
3350}
3351
Alexander Belopolsky40018472011-02-26 01:02:56 +00003352PyObject *
3353PyUnicode_AsEncodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003354 const char *encoding,
3355 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003356{
3357 PyObject *v;
3358
3359 if (!PyUnicode_Check(unicode)) {
3360 PyErr_BadArgument();
3361 goto onError;
3362 }
3363
3364 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003365 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003366
3367 /* Encode via the codec registry */
3368 v = PyCodec_Encode(unicode, encoding, errors);
3369 if (v == NULL)
3370 goto onError;
3371 if (!PyUnicode_Check(v)) {
3372 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00003373 "encoder did not return an str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003374 Py_TYPE(v)->tp_name);
3375 Py_DECREF(v);
3376 goto onError;
3377 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003378 return v;
Tim Petersced69f82003-09-16 20:30:58 +00003379
Benjamin Peterson29060642009-01-31 22:14:21 +00003380 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003381 return NULL;
3382}
3383
Victor Stinner2f197072011-12-17 07:08:30 +01003384static size_t
3385mbstowcs_errorpos(const char *str, size_t len)
3386{
3387#ifdef HAVE_MBRTOWC
3388 const char *start = str;
3389 mbstate_t mbs;
3390 size_t converted;
3391 wchar_t ch;
3392
3393 memset(&mbs, 0, sizeof mbs);
3394 while (len)
3395 {
3396 converted = mbrtowc(&ch, (char*)str, len, &mbs);
3397 if (converted == 0)
3398 /* Reached end of string */
3399 break;
3400 if (converted == (size_t)-1 || converted == (size_t)-2) {
3401 /* Conversion error or incomplete character */
3402 return str - start;
3403 }
3404 else {
3405 str += converted;
3406 len -= converted;
3407 }
3408 }
3409 /* failed to find the undecodable byte sequence */
3410 return 0;
3411#endif
3412 return 0;
3413}
3414
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003415PyObject*
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003416PyUnicode_DecodeLocaleAndSize(const char *str, Py_ssize_t len,
Victor Stinner1b579672011-12-17 05:47:23 +01003417 const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003418{
3419 wchar_t smallbuf[256];
3420 size_t smallbuf_len = Py_ARRAY_LENGTH(smallbuf);
3421 wchar_t *wstr;
3422 size_t wlen, wlen2;
3423 PyObject *unicode;
Victor Stinner1b579672011-12-17 05:47:23 +01003424 int surrogateescape;
Victor Stinner2f197072011-12-17 07:08:30 +01003425 size_t error_pos;
3426 char *errmsg;
3427 PyObject *reason, *exc;
Victor Stinner1b579672011-12-17 05:47:23 +01003428
3429 if (locale_error_handler(errors, &surrogateescape) < 0)
3430 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003431
3432 if (str[len] != '\0' || len != strlen(str)) {
3433 PyErr_SetString(PyExc_TypeError, "embedded null character");
3434 return NULL;
3435 }
3436
3437 if (surrogateescape)
3438 {
3439 wstr = _Py_char2wchar(str, &wlen);
3440 if (wstr == NULL) {
3441 if (wlen == (size_t)-1)
3442 PyErr_NoMemory();
3443 else
3444 PyErr_SetFromErrno(PyExc_OSError);
3445 return NULL;
3446 }
3447
3448 unicode = PyUnicode_FromWideChar(wstr, wlen);
3449 PyMem_Free(wstr);
3450 }
3451 else {
3452#ifndef HAVE_BROKEN_MBSTOWCS
3453 wlen = mbstowcs(NULL, str, 0);
3454#else
3455 wlen = len;
3456#endif
Victor Stinner2f197072011-12-17 07:08:30 +01003457 if (wlen == (size_t)-1)
3458 goto decode_error;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003459 if (wlen+1 <= smallbuf_len) {
3460 wstr = smallbuf;
3461 }
3462 else {
3463 if (wlen > PY_SSIZE_T_MAX / sizeof(wchar_t) - 1)
3464 return PyErr_NoMemory();
3465
3466 wstr = PyMem_Malloc((wlen+1) * sizeof(wchar_t));
3467 if (!wstr)
3468 return PyErr_NoMemory();
3469 }
3470
3471 /* This shouldn't fail now */
3472 wlen2 = mbstowcs(wstr, str, wlen+1);
3473 if (wlen2 == (size_t)-1) {
3474 if (wstr != smallbuf)
3475 PyMem_Free(wstr);
Victor Stinner2f197072011-12-17 07:08:30 +01003476 goto decode_error;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003477 }
3478#ifdef HAVE_BROKEN_MBSTOWCS
3479 assert(wlen2 == wlen);
3480#endif
3481 unicode = PyUnicode_FromWideChar(wstr, wlen2);
3482 if (wstr != smallbuf)
3483 PyMem_Free(wstr);
3484 }
3485 return unicode;
Victor Stinner2f197072011-12-17 07:08:30 +01003486
3487decode_error:
3488 errmsg = strerror(errno);
3489 assert(errmsg != NULL);
3490
3491 error_pos = mbstowcs_errorpos(str, len);
3492 if (errmsg != NULL) {
3493 size_t errlen;
3494 wstr = _Py_char2wchar(errmsg, &errlen);
3495 if (wstr != NULL) {
3496 reason = PyUnicode_FromWideChar(wstr, errlen);
3497 PyMem_Free(wstr);
3498 } else
3499 errmsg = NULL;
3500 }
3501 if (errmsg == NULL)
3502 reason = PyUnicode_FromString(
3503 "mbstowcs() encountered an invalid multibyte sequence");
3504 if (reason == NULL)
3505 return NULL;
3506
3507 exc = PyObject_CallFunction(PyExc_UnicodeDecodeError, "sy#nnO",
3508 "locale", str, len,
3509 (Py_ssize_t)error_pos,
3510 (Py_ssize_t)(error_pos+1),
3511 reason);
3512 Py_DECREF(reason);
3513 if (exc != NULL) {
3514 PyCodec_StrictErrors(exc);
3515 Py_XDECREF(exc);
3516 }
3517 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003518}
3519
3520PyObject*
Victor Stinner1b579672011-12-17 05:47:23 +01003521PyUnicode_DecodeLocale(const char *str, const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003522{
3523 Py_ssize_t size = (Py_ssize_t)strlen(str);
Victor Stinner1b579672011-12-17 05:47:23 +01003524 return PyUnicode_DecodeLocaleAndSize(str, size, errors);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003525}
3526
3527
3528PyObject*
Christian Heimes5894ba72007-11-04 11:43:14 +00003529PyUnicode_DecodeFSDefault(const char *s) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003530 Py_ssize_t size = (Py_ssize_t)strlen(s);
Christian Heimes5894ba72007-11-04 11:43:14 +00003531 return PyUnicode_DecodeFSDefaultAndSize(s, size);
3532}
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003533
Christian Heimes5894ba72007-11-04 11:43:14 +00003534PyObject*
3535PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
3536{
Victor Stinner99b95382011-07-04 14:23:54 +02003537#ifdef HAVE_MBCS
Victor Stinnerad158722010-10-27 00:25:46 +00003538 return PyUnicode_DecodeMBCS(s, size, NULL);
3539#elif defined(__APPLE__)
Victor Stinnera1d12bb2011-12-11 21:53:09 +01003540 return PyUnicode_DecodeUTF8Stateful(s, size, "surrogateescape", NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003541#else
Victor Stinner793b5312011-04-27 00:24:21 +02003542 PyInterpreterState *interp = PyThreadState_GET()->interp;
3543 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3544 cannot use it to encode and decode filenames before it is loaded. Load
3545 the Python codec requires to encode at least its own filename. Use the C
3546 version of the locale codec until the codec registry is initialized and
3547 the Python codec is loaded.
3548
3549 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3550 cannot only rely on it: check also interp->fscodec_initialized for
3551 subinterpreters. */
3552 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003553 return PyUnicode_Decode(s, size,
3554 Py_FileSystemDefaultEncoding,
Victor Stinnerb9a20ad2010-04-30 16:37:52 +00003555 "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003556 }
3557 else {
Victor Stinner1b579672011-12-17 05:47:23 +01003558 return PyUnicode_DecodeLocaleAndSize(s, size, "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003559 }
Victor Stinnerad158722010-10-27 00:25:46 +00003560#endif
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003561}
3562
Martin v. Löwis011e8422009-05-05 04:43:17 +00003563
3564int
3565PyUnicode_FSConverter(PyObject* arg, void* addr)
3566{
3567 PyObject *output = NULL;
3568 Py_ssize_t size;
3569 void *data;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003570 if (arg == NULL) {
3571 Py_DECREF(*(PyObject**)addr);
3572 return 1;
3573 }
Victor Stinnerdcb24032010-04-22 12:08:36 +00003574 if (PyBytes_Check(arg)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00003575 output = arg;
3576 Py_INCREF(output);
3577 }
3578 else {
3579 arg = PyUnicode_FromObject(arg);
3580 if (!arg)
3581 return 0;
Victor Stinnerae6265f2010-05-15 16:27:27 +00003582 output = PyUnicode_EncodeFSDefault(arg);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003583 Py_DECREF(arg);
3584 if (!output)
3585 return 0;
3586 if (!PyBytes_Check(output)) {
3587 Py_DECREF(output);
3588 PyErr_SetString(PyExc_TypeError, "encoder failed to return bytes");
3589 return 0;
3590 }
3591 }
Victor Stinner0ea2a462010-04-30 00:22:08 +00003592 size = PyBytes_GET_SIZE(output);
3593 data = PyBytes_AS_STRING(output);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003594 if (size != strlen(data)) {
Benjamin Peterson7a6b44a2011-08-18 13:51:47 -05003595 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
Martin v. Löwis011e8422009-05-05 04:43:17 +00003596 Py_DECREF(output);
3597 return 0;
3598 }
3599 *(PyObject**)addr = output;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003600 return Py_CLEANUP_SUPPORTED;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003601}
3602
3603
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003604int
3605PyUnicode_FSDecoder(PyObject* arg, void* addr)
3606{
3607 PyObject *output = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003608 if (arg == NULL) {
3609 Py_DECREF(*(PyObject**)addr);
3610 return 1;
3611 }
3612 if (PyUnicode_Check(arg)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003613 if (PyUnicode_READY(arg))
3614 return 0;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003615 output = arg;
3616 Py_INCREF(output);
3617 }
3618 else {
3619 arg = PyBytes_FromObject(arg);
3620 if (!arg)
3621 return 0;
3622 output = PyUnicode_DecodeFSDefaultAndSize(PyBytes_AS_STRING(arg),
3623 PyBytes_GET_SIZE(arg));
3624 Py_DECREF(arg);
3625 if (!output)
3626 return 0;
3627 if (!PyUnicode_Check(output)) {
3628 Py_DECREF(output);
3629 PyErr_SetString(PyExc_TypeError, "decoder failed to return unicode");
3630 return 0;
3631 }
3632 }
Victor Stinner065836e2011-10-27 01:56:33 +02003633 if (PyUnicode_READY(output) < 0) {
3634 Py_DECREF(output);
3635 return 0;
3636 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003637 if (findchar(PyUnicode_DATA(output), PyUnicode_KIND(output),
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02003638 PyUnicode_GET_LENGTH(output), 0, 1) >= 0) {
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003639 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
3640 Py_DECREF(output);
3641 return 0;
3642 }
3643 *(PyObject**)addr = output;
3644 return Py_CLEANUP_SUPPORTED;
3645}
3646
3647
Martin v. Löwis5b222132007-06-10 09:51:05 +00003648char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003649PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *psize)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003650{
Christian Heimesf3863112007-11-22 07:46:41 +00003651 PyObject *bytes;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003652
Neal Norwitze0a0a6e2007-08-25 01:04:21 +00003653 if (!PyUnicode_Check(unicode)) {
3654 PyErr_BadArgument();
3655 return NULL;
3656 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003657 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003658 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003659
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003660 if (PyUnicode_UTF8(unicode) == NULL) {
3661 assert(!PyUnicode_IS_COMPACT_ASCII(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003662 bytes = _PyUnicode_AsUTF8String(unicode, "strict");
3663 if (bytes == NULL)
3664 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003665 _PyUnicode_UTF8(unicode) = PyObject_MALLOC(PyBytes_GET_SIZE(bytes) + 1);
3666 if (_PyUnicode_UTF8(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003667 Py_DECREF(bytes);
3668 return NULL;
3669 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003670 _PyUnicode_UTF8_LENGTH(unicode) = PyBytes_GET_SIZE(bytes);
3671 Py_MEMCPY(_PyUnicode_UTF8(unicode),
3672 PyBytes_AS_STRING(bytes),
3673 _PyUnicode_UTF8_LENGTH(unicode) + 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003674 Py_DECREF(bytes);
3675 }
3676
3677 if (psize)
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003678 *psize = PyUnicode_UTF8_LENGTH(unicode);
3679 return PyUnicode_UTF8(unicode);
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003680}
3681
3682char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003683PyUnicode_AsUTF8(PyObject *unicode)
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003684{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003685 return PyUnicode_AsUTF8AndSize(unicode, NULL);
3686}
3687
3688#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +02003689static int unicode_as_unicode_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003690#endif
3691
3692
3693Py_UNICODE *
3694PyUnicode_AsUnicodeAndSize(PyObject *unicode, Py_ssize_t *size)
3695{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003696 const unsigned char *one_byte;
3697#if SIZEOF_WCHAR_T == 4
3698 const Py_UCS2 *two_bytes;
3699#else
3700 const Py_UCS4 *four_bytes;
3701 const Py_UCS4 *ucs4_end;
3702 Py_ssize_t num_surrogates;
3703#endif
3704 wchar_t *w;
3705 wchar_t *wchar_end;
3706
3707 if (!PyUnicode_Check(unicode)) {
3708 PyErr_BadArgument();
3709 return NULL;
3710 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003711 if (_PyUnicode_WSTR(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003712 /* Non-ASCII compact unicode object */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003713 assert(_PyUnicode_KIND(unicode) != 0);
3714 assert(PyUnicode_IS_READY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003715
3716#ifdef Py_DEBUG
3717 ++unicode_as_unicode_calls;
3718#endif
3719
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003720 if (PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003721#if SIZEOF_WCHAR_T == 2
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003722 four_bytes = PyUnicode_4BYTE_DATA(unicode);
3723 ucs4_end = four_bytes + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003724 num_surrogates = 0;
3725
3726 for (; four_bytes < ucs4_end; ++four_bytes) {
3727 if (*four_bytes > 0xFFFF)
3728 ++num_surrogates;
3729 }
3730
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003731 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(
3732 sizeof(wchar_t) * (_PyUnicode_LENGTH(unicode) + 1 + num_surrogates));
3733 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003734 PyErr_NoMemory();
3735 return NULL;
3736 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003737 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode) + num_surrogates;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003738
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003739 w = _PyUnicode_WSTR(unicode);
3740 wchar_end = w + _PyUnicode_WSTR_LENGTH(unicode);
3741 four_bytes = PyUnicode_4BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003742 for (; four_bytes < ucs4_end; ++four_bytes, ++w) {
3743 if (*four_bytes > 0xFFFF) {
Victor Stinner8faf8212011-12-08 22:14:11 +01003744 assert(*four_bytes <= MAX_UNICODE);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003745 /* encode surrogate pair in this case */
Victor Stinner551ac952011-11-29 22:58:13 +01003746 *w++ = Py_UNICODE_HIGH_SURROGATE(*four_bytes);
3747 *w = Py_UNICODE_LOW_SURROGATE(*four_bytes);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003748 }
3749 else
3750 *w = *four_bytes;
3751
3752 if (w > wchar_end) {
3753 assert(0 && "Miscalculated string end");
3754 }
3755 }
3756 *w = 0;
3757#else
3758 /* sizeof(wchar_t) == 4 */
3759 Py_FatalError("Impossible unicode object state, wstr and str "
3760 "should share memory already.");
3761 return NULL;
3762#endif
3763 }
3764 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003765 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(sizeof(wchar_t) *
3766 (_PyUnicode_LENGTH(unicode) + 1));
3767 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003768 PyErr_NoMemory();
3769 return NULL;
3770 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003771 if (!PyUnicode_IS_COMPACT_ASCII(unicode))
3772 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode);
3773 w = _PyUnicode_WSTR(unicode);
3774 wchar_end = w + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003775
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003776 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND) {
3777 one_byte = PyUnicode_1BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003778 for (; w < wchar_end; ++one_byte, ++w)
3779 *w = *one_byte;
3780 /* null-terminate the wstr */
3781 *w = 0;
3782 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003783 else if (PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003784#if SIZEOF_WCHAR_T == 4
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003785 two_bytes = PyUnicode_2BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003786 for (; w < wchar_end; ++two_bytes, ++w)
3787 *w = *two_bytes;
3788 /* null-terminate the wstr */
3789 *w = 0;
3790#else
3791 /* sizeof(wchar_t) == 2 */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003792 PyObject_FREE(_PyUnicode_WSTR(unicode));
3793 _PyUnicode_WSTR(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003794 Py_FatalError("Impossible unicode object state, wstr "
3795 "and str should share memory already.");
3796 return NULL;
3797#endif
3798 }
3799 else {
3800 assert(0 && "This should never happen.");
3801 }
3802 }
3803 }
3804 if (size != NULL)
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003805 *size = PyUnicode_WSTR_LENGTH(unicode);
3806 return _PyUnicode_WSTR(unicode);
Martin v. Löwis5b222132007-06-10 09:51:05 +00003807}
3808
Alexander Belopolsky40018472011-02-26 01:02:56 +00003809Py_UNICODE *
3810PyUnicode_AsUnicode(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003811{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003812 return PyUnicode_AsUnicodeAndSize(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003813}
3814
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003815
Alexander Belopolsky40018472011-02-26 01:02:56 +00003816Py_ssize_t
3817PyUnicode_GetSize(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003818{
3819 if (!PyUnicode_Check(unicode)) {
3820 PyErr_BadArgument();
3821 goto onError;
3822 }
3823 return PyUnicode_GET_SIZE(unicode);
3824
Benjamin Peterson29060642009-01-31 22:14:21 +00003825 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003826 return -1;
3827}
3828
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003829Py_ssize_t
3830PyUnicode_GetLength(PyObject *unicode)
3831{
Victor Stinner5a706cf2011-10-02 00:36:53 +02003832 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003833 PyErr_BadArgument();
3834 return -1;
3835 }
3836
3837 return PyUnicode_GET_LENGTH(unicode);
3838}
3839
3840Py_UCS4
3841PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
3842{
Victor Stinner2fe5ced2011-10-02 00:25:40 +02003843 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
3844 PyErr_BadArgument();
3845 return (Py_UCS4)-1;
3846 }
Victor Stinnerc4b49542011-12-11 22:44:26 +01003847 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinner2fe5ced2011-10-02 00:25:40 +02003848 PyErr_SetString(PyExc_IndexError, "string index out of range");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003849 return (Py_UCS4)-1;
3850 }
3851 return PyUnicode_READ_CHAR(unicode, index);
3852}
3853
3854int
3855PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 ch)
3856{
3857 if (!PyUnicode_Check(unicode) || !PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02003858 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003859 return -1;
3860 }
Victor Stinner488fa492011-12-12 00:01:39 +01003861 assert(PyUnicode_IS_READY(unicode));
Victor Stinnerc4b49542011-12-11 22:44:26 +01003862 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02003863 PyErr_SetString(PyExc_IndexError, "string index out of range");
3864 return -1;
3865 }
Victor Stinner488fa492011-12-12 00:01:39 +01003866 if (unicode_check_modifiable(unicode))
Victor Stinnercd9950f2011-10-02 00:34:53 +02003867 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003868 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
3869 index, ch);
3870 return 0;
3871}
3872
Alexander Belopolsky40018472011-02-26 01:02:56 +00003873const char *
3874PyUnicode_GetDefaultEncoding(void)
Fred Drakee4315f52000-05-09 19:53:39 +00003875{
Victor Stinner42cb4622010-09-01 19:39:01 +00003876 return "utf-8";
Fred Drakee4315f52000-05-09 19:53:39 +00003877}
3878
Victor Stinner554f3f02010-06-16 23:33:54 +00003879/* create or adjust a UnicodeDecodeError */
3880static void
3881make_decode_exception(PyObject **exceptionObject,
3882 const char *encoding,
3883 const char *input, Py_ssize_t length,
3884 Py_ssize_t startpos, Py_ssize_t endpos,
3885 const char *reason)
3886{
3887 if (*exceptionObject == NULL) {
3888 *exceptionObject = PyUnicodeDecodeError_Create(
3889 encoding, input, length, startpos, endpos, reason);
3890 }
3891 else {
3892 if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
3893 goto onError;
3894 if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
3895 goto onError;
3896 if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
3897 goto onError;
3898 }
3899 return;
3900
3901onError:
3902 Py_DECREF(*exceptionObject);
3903 *exceptionObject = NULL;
3904}
3905
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003906/* error handling callback helper:
3907 build arguments, call the callback and check the arguments,
Fred Drakedb390c12005-10-28 14:39:47 +00003908 if no exception occurred, copy the replacement to the output
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003909 and adjust various state variables.
3910 return 0 on success, -1 on error
3911*/
3912
Alexander Belopolsky40018472011-02-26 01:02:56 +00003913static int
3914unicode_decode_call_errorhandler(const char *errors, PyObject **errorHandler,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003915 const char *encoding, const char *reason,
3916 const char **input, const char **inend, Py_ssize_t *startinpos,
3917 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003918 PyObject **output, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003919{
Benjamin Peterson142957c2008-07-04 19:55:29 +00003920 static char *argparse = "O!n;decoding error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003921
3922 PyObject *restuple = NULL;
3923 PyObject *repunicode = NULL;
Victor Stinner596a6c42011-11-09 00:02:18 +01003924 Py_ssize_t outsize;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003925 Py_ssize_t insize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003926 Py_ssize_t requiredsize;
3927 Py_ssize_t newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003928 PyObject *inputobj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003929 int res = -1;
3930
Victor Stinner596a6c42011-11-09 00:02:18 +01003931 if (_PyUnicode_KIND(*output) != PyUnicode_WCHAR_KIND)
3932 outsize = PyUnicode_GET_LENGTH(*output);
3933 else
3934 outsize = _PyUnicode_WSTR_LENGTH(*output);
3935
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003936 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003937 *errorHandler = PyCodec_LookupError(errors);
3938 if (*errorHandler == NULL)
3939 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003940 }
3941
Victor Stinner554f3f02010-06-16 23:33:54 +00003942 make_decode_exception(exceptionObject,
3943 encoding,
3944 *input, *inend - *input,
3945 *startinpos, *endinpos,
3946 reason);
3947 if (*exceptionObject == NULL)
3948 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003949
3950 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
3951 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003952 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003953 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00003954 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00003955 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003956 }
3957 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00003958 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003959 if (PyUnicode_READY(repunicode) < 0)
3960 goto onError;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003961
3962 /* Copy back the bytes variables, which might have been modified by the
3963 callback */
3964 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
3965 if (!inputobj)
3966 goto onError;
Christian Heimes72b710a2008-05-26 13:28:38 +00003967 if (!PyBytes_Check(inputobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003968 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
Walter Dörwalde78178e2007-07-30 13:31:40 +00003969 }
Christian Heimes72b710a2008-05-26 13:28:38 +00003970 *input = PyBytes_AS_STRING(inputobj);
3971 insize = PyBytes_GET_SIZE(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00003972 *inend = *input + insize;
Walter Dörwald36f938f2007-08-10 10:11:43 +00003973 /* we can DECREF safely, as the exception has another reference,
3974 so the object won't go away. */
3975 Py_DECREF(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00003976
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003977 if (newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00003978 newpos = insize+newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00003979 if (newpos<0 || newpos>insize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003980 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
3981 goto onError;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00003982 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003983
Victor Stinner596a6c42011-11-09 00:02:18 +01003984 if (_PyUnicode_KIND(*output) != PyUnicode_WCHAR_KIND) {
3985 /* need more space? (at least enough for what we
3986 have+the replacement+the rest of the string (starting
3987 at the new input position), so we won't have to check space
3988 when there are no errors in the rest of the string) */
3989 Py_ssize_t replen = PyUnicode_GET_LENGTH(repunicode);
3990 requiredsize = *outpos + replen + insize-newpos;
3991 if (requiredsize > outsize) {
3992 if (requiredsize<2*outsize)
3993 requiredsize = 2*outsize;
3994 if (unicode_resize(output, requiredsize) < 0)
3995 goto onError;
3996 }
3997 if (unicode_widen(output, PyUnicode_MAX_CHAR_VALUE(repunicode)) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00003998 goto onError;
Victor Stinner596a6c42011-11-09 00:02:18 +01003999 copy_characters(*output, *outpos, repunicode, 0, replen);
4000 *outpos += replen;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004001 }
Victor Stinner596a6c42011-11-09 00:02:18 +01004002 else {
4003 wchar_t *repwstr;
4004 Py_ssize_t repwlen;
4005 repwstr = PyUnicode_AsUnicodeAndSize(repunicode, &repwlen);
4006 if (repwstr == NULL)
4007 goto onError;
4008 /* need more space? (at least enough for what we
4009 have+the replacement+the rest of the string (starting
4010 at the new input position), so we won't have to check space
4011 when there are no errors in the rest of the string) */
4012 requiredsize = *outpos + repwlen + insize-newpos;
4013 if (requiredsize > outsize) {
4014 if (requiredsize < 2*outsize)
4015 requiredsize = 2*outsize;
4016 if (unicode_resize(output, requiredsize) < 0)
4017 goto onError;
4018 }
4019 wcsncpy(_PyUnicode_WSTR(*output) + *outpos, repwstr, repwlen);
4020 *outpos += repwlen;
4021 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004022 *endinpos = newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004023 *inptr = *input + newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004024
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004025 /* we made it! */
4026 res = 0;
4027
Benjamin Peterson29060642009-01-31 22:14:21 +00004028 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004029 Py_XDECREF(restuple);
4030 return res;
4031}
4032
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004033/* --- UTF-7 Codec -------------------------------------------------------- */
4034
Antoine Pitrou244651a2009-05-04 18:56:13 +00004035/* See RFC2152 for details. We encode conservatively and decode liberally. */
4036
4037/* Three simple macros defining base-64. */
4038
4039/* Is c a base-64 character? */
4040
4041#define IS_BASE64(c) \
4042 (((c) >= 'A' && (c) <= 'Z') || \
4043 ((c) >= 'a' && (c) <= 'z') || \
4044 ((c) >= '0' && (c) <= '9') || \
4045 (c) == '+' || (c) == '/')
4046
4047/* given that c is a base-64 character, what is its base-64 value? */
4048
4049#define FROM_BASE64(c) \
4050 (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' : \
4051 ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 : \
4052 ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 : \
4053 (c) == '+' ? 62 : 63)
4054
4055/* What is the base-64 character of the bottom 6 bits of n? */
4056
4057#define TO_BASE64(n) \
4058 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
4059
4060/* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
4061 * decoded as itself. We are permissive on decoding; the only ASCII
4062 * byte not decoding to itself is the + which begins a base64
4063 * string. */
4064
4065#define DECODE_DIRECT(c) \
4066 ((c) <= 127 && (c) != '+')
4067
4068/* The UTF-7 encoder treats ASCII characters differently according to
4069 * whether they are Set D, Set O, Whitespace, or special (i.e. none of
4070 * the above). See RFC2152. This array identifies these different
4071 * sets:
4072 * 0 : "Set D"
4073 * alphanumeric and '(),-./:?
4074 * 1 : "Set O"
4075 * !"#$%&*;<=>@[]^_`{|}
4076 * 2 : "whitespace"
4077 * ht nl cr sp
4078 * 3 : special (must be base64 encoded)
4079 * everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
4080 */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004081
Tim Petersced69f82003-09-16 20:30:58 +00004082static
Antoine Pitrou244651a2009-05-04 18:56:13 +00004083char utf7_category[128] = {
4084/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
4085 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
4086/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
4087 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
4088/* sp ! " # $ % & ' ( ) * + , - . / */
4089 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
4090/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
4091 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
4092/* @ A B C D E F G H I J K L M N O */
4093 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4094/* P Q R S T U V W X Y Z [ \ ] ^ _ */
4095 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
4096/* ` a b c d e f g h i j k l m n o */
4097 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4098/* p q r s t u v w x y z { | } ~ del */
4099 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004100};
4101
Antoine Pitrou244651a2009-05-04 18:56:13 +00004102/* ENCODE_DIRECT: this character should be encoded as itself. The
4103 * answer depends on whether we are encoding set O as itself, and also
4104 * on whether we are encoding whitespace as itself. RFC2152 makes it
4105 * clear that the answers to these questions vary between
4106 * applications, so this code needs to be flexible. */
Marc-André Lemburge115ec82005-10-19 22:33:31 +00004107
Antoine Pitrou244651a2009-05-04 18:56:13 +00004108#define ENCODE_DIRECT(c, directO, directWS) \
4109 ((c) < 128 && (c) > 0 && \
4110 ((utf7_category[(c)] == 0) || \
4111 (directWS && (utf7_category[(c)] == 2)) || \
4112 (directO && (utf7_category[(c)] == 1))))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004113
Alexander Belopolsky40018472011-02-26 01:02:56 +00004114PyObject *
4115PyUnicode_DecodeUTF7(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004116 Py_ssize_t size,
4117 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004118{
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004119 return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
4120}
4121
Antoine Pitrou244651a2009-05-04 18:56:13 +00004122/* The decoder. The only state we preserve is our read position,
4123 * i.e. how many characters we have consumed. So if we end in the
4124 * middle of a shift sequence we have to back off the read position
4125 * and the output to the beginning of the sequence, otherwise we lose
4126 * all the shift state (seen bits, number of bits seen, high
4127 * surrogate). */
4128
Alexander Belopolsky40018472011-02-26 01:02:56 +00004129PyObject *
4130PyUnicode_DecodeUTF7Stateful(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004131 Py_ssize_t size,
4132 const char *errors,
4133 Py_ssize_t *consumed)
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004134{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004135 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004136 Py_ssize_t startinpos;
4137 Py_ssize_t endinpos;
4138 Py_ssize_t outpos;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004139 const char *e;
Victor Stinner7931d9a2011-11-04 00:22:48 +01004140 PyObject *unicode;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004141 const char *errmsg = "";
4142 int inShift = 0;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004143 Py_ssize_t shiftOutStart;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004144 unsigned int base64bits = 0;
4145 unsigned long base64buffer = 0;
Victor Stinner24729f32011-11-10 20:31:37 +01004146 Py_UCS4 surrogate = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004147 PyObject *errorHandler = NULL;
4148 PyObject *exc = NULL;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004149
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004150 /* Start off assuming it's all ASCII. Widen later as necessary. */
4151 unicode = PyUnicode_New(size, 127);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004152 if (!unicode)
4153 return NULL;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004154 if (size == 0) {
4155 if (consumed)
4156 *consumed = 0;
Victor Stinner7931d9a2011-11-04 00:22:48 +01004157 return unicode;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004158 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004159
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004160 shiftOutStart = outpos = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004161 e = s + size;
4162
4163 while (s < e) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004164 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00004165 restart:
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00004166 ch = (unsigned char) *s;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004167
Antoine Pitrou244651a2009-05-04 18:56:13 +00004168 if (inShift) { /* in a base-64 section */
4169 if (IS_BASE64(ch)) { /* consume a base-64 character */
4170 base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
4171 base64bits += 6;
4172 s++;
4173 if (base64bits >= 16) {
4174 /* we have enough bits for a UTF-16 value */
Victor Stinner24729f32011-11-10 20:31:37 +01004175 Py_UCS4 outCh = (Py_UCS4)(base64buffer >> (base64bits-16));
Antoine Pitrou244651a2009-05-04 18:56:13 +00004176 base64bits -= 16;
4177 base64buffer &= (1 << base64bits) - 1; /* clear high bits */
4178 if (surrogate) {
4179 /* expecting a second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004180 if (Py_UNICODE_IS_LOW_SURROGATE(outCh)) {
4181 Py_UCS4 ch2 = Py_UNICODE_JOIN_SURROGATES(surrogate, outCh);
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004182 if (unicode_putchar(&unicode, &outpos, ch2) < 0)
4183 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004184 surrogate = 0;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01004185 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004186 }
4187 else {
Antoine Pitrou78edf752011-11-15 01:44:16 +01004188 if (unicode_putchar(&unicode, &outpos, surrogate) < 0)
4189 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004190 surrogate = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004191 }
4192 }
Victor Stinner551ac952011-11-29 22:58:13 +01004193 if (Py_UNICODE_IS_HIGH_SURROGATE(outCh)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004194 /* first surrogate */
4195 surrogate = outCh;
4196 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004197 else {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004198 if (unicode_putchar(&unicode, &outpos, outCh) < 0)
4199 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004200 }
4201 }
4202 }
4203 else { /* now leaving a base-64 section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004204 inShift = 0;
4205 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004206 if (surrogate) {
Antoine Pitrou78edf752011-11-15 01:44:16 +01004207 if (unicode_putchar(&unicode, &outpos, surrogate) < 0)
4208 goto onError;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01004209 surrogate = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004210 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004211 if (base64bits > 0) { /* left-over bits */
4212 if (base64bits >= 6) {
4213 /* We've seen at least one base-64 character */
4214 errmsg = "partial character in shift sequence";
4215 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004216 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004217 else {
4218 /* Some bits remain; they should be zero */
4219 if (base64buffer != 0) {
4220 errmsg = "non-zero padding bits in shift sequence";
4221 goto utf7Error;
4222 }
4223 }
4224 }
4225 if (ch != '-') {
4226 /* '-' is absorbed; other terminating
4227 characters are preserved */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004228 if (unicode_putchar(&unicode, &outpos, ch) < 0)
4229 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004230 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004231 }
4232 }
4233 else if ( ch == '+' ) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004234 startinpos = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004235 s++; /* consume '+' */
4236 if (s < e && *s == '-') { /* '+-' encodes '+' */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004237 s++;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004238 if (unicode_putchar(&unicode, &outpos, '+') < 0)
4239 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004240 }
4241 else { /* begin base64-encoded section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004242 inShift = 1;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004243 shiftOutStart = outpos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004244 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004245 }
4246 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004247 else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004248 if (unicode_putchar(&unicode, &outpos, ch) < 0)
4249 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004250 s++;
4251 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004252 else {
4253 startinpos = s-starts;
4254 s++;
4255 errmsg = "unexpected special character";
4256 goto utf7Error;
4257 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004258 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004259utf7Error:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004260 endinpos = s-starts;
4261 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00004262 errors, &errorHandler,
4263 "utf7", errmsg,
4264 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004265 &unicode, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00004266 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004267 }
4268
Antoine Pitrou244651a2009-05-04 18:56:13 +00004269 /* end of string */
4270
4271 if (inShift && !consumed) { /* in shift sequence, no more to follow */
4272 /* if we're in an inconsistent state, that's an error */
4273 if (surrogate ||
4274 (base64bits >= 6) ||
4275 (base64bits > 0 && base64buffer != 0)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004276 endinpos = size;
4277 if (unicode_decode_call_errorhandler(
4278 errors, &errorHandler,
4279 "utf7", "unterminated shift sequence",
4280 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004281 &unicode, &outpos))
Antoine Pitrou244651a2009-05-04 18:56:13 +00004282 goto onError;
4283 if (s < e)
4284 goto restart;
4285 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004286 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004287
4288 /* return state */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004289 if (consumed) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004290 if (inShift) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004291 outpos = shiftOutStart; /* back off output */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004292 *consumed = startinpos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004293 }
4294 else {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004295 *consumed = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004296 }
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004297 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004298
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004299 if (unicode_resize(&unicode, outpos) < 0)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004300 goto onError;
4301
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004302 Py_XDECREF(errorHandler);
4303 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01004304 return unicode_result(unicode);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004305
Benjamin Peterson29060642009-01-31 22:14:21 +00004306 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004307 Py_XDECREF(errorHandler);
4308 Py_XDECREF(exc);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004309 Py_DECREF(unicode);
4310 return NULL;
4311}
4312
4313
Alexander Belopolsky40018472011-02-26 01:02:56 +00004314PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004315_PyUnicode_EncodeUTF7(PyObject *str,
4316 int base64SetO,
4317 int base64WhiteSpace,
4318 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004319{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004320 int kind;
4321 void *data;
4322 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004323 PyObject *v;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004324 Py_ssize_t allocated;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004325 int inShift = 0;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004326 Py_ssize_t i;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004327 unsigned int base64bits = 0;
4328 unsigned long base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004329 char * out;
4330 char * start;
4331
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004332 if (PyUnicode_READY(str) < 0)
4333 return NULL;
4334 kind = PyUnicode_KIND(str);
4335 data = PyUnicode_DATA(str);
4336 len = PyUnicode_GET_LENGTH(str);
4337
4338 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004339 return PyBytes_FromStringAndSize(NULL, 0);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004340
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004341 /* It might be possible to tighten this worst case */
4342 allocated = 8 * len;
4343 if (allocated / 8 != len)
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004344 return PyErr_NoMemory();
4345
Antoine Pitrou244651a2009-05-04 18:56:13 +00004346 v = PyBytes_FromStringAndSize(NULL, allocated);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004347 if (v == NULL)
4348 return NULL;
4349
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004350 start = out = PyBytes_AS_STRING(v);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004351 for (i = 0; i < len; ++i) {
Victor Stinner0e368262011-11-10 20:12:49 +01004352 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004353
Antoine Pitrou244651a2009-05-04 18:56:13 +00004354 if (inShift) {
4355 if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4356 /* shifting out */
4357 if (base64bits) { /* output remaining bits */
4358 *out++ = TO_BASE64(base64buffer << (6-base64bits));
4359 base64buffer = 0;
4360 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004361 }
4362 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004363 /* Characters not in the BASE64 set implicitly unshift the sequence
4364 so no '-' is required, except if the character is itself a '-' */
4365 if (IS_BASE64(ch) || ch == '-') {
4366 *out++ = '-';
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004367 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004368 *out++ = (char) ch;
4369 }
4370 else {
4371 goto encode_char;
Tim Petersced69f82003-09-16 20:30:58 +00004372 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004373 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004374 else { /* not in a shift sequence */
4375 if (ch == '+') {
4376 *out++ = '+';
4377 *out++ = '-';
4378 }
4379 else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4380 *out++ = (char) ch;
4381 }
4382 else {
4383 *out++ = '+';
4384 inShift = 1;
4385 goto encode_char;
4386 }
4387 }
4388 continue;
4389encode_char:
Antoine Pitrou244651a2009-05-04 18:56:13 +00004390 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01004391 assert(ch <= MAX_UNICODE);
Victor Stinner0d3721d2011-11-22 03:27:53 +01004392
Antoine Pitrou244651a2009-05-04 18:56:13 +00004393 /* code first surrogate */
4394 base64bits += 16;
4395 base64buffer = (base64buffer << 16) | 0xd800 | ((ch-0x10000) >> 10);
4396 while (base64bits >= 6) {
4397 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4398 base64bits -= 6;
4399 }
4400 /* prepare second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004401 ch = Py_UNICODE_LOW_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004402 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004403 base64bits += 16;
4404 base64buffer = (base64buffer << 16) | ch;
4405 while (base64bits >= 6) {
4406 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4407 base64bits -= 6;
4408 }
Hye-Shik Chang1bc09b72004-01-03 19:35:43 +00004409 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004410 if (base64bits)
4411 *out++= TO_BASE64(base64buffer << (6-base64bits) );
4412 if (inShift)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004413 *out++ = '-';
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004414 if (_PyBytes_Resize(&v, out - start) < 0)
4415 return NULL;
4416 return v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004417}
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004418PyObject *
4419PyUnicode_EncodeUTF7(const Py_UNICODE *s,
4420 Py_ssize_t size,
4421 int base64SetO,
4422 int base64WhiteSpace,
4423 const char *errors)
4424{
4425 PyObject *result;
4426 PyObject *tmp = PyUnicode_FromUnicode(s, size);
4427 if (tmp == NULL)
4428 return NULL;
Victor Stinner0e368262011-11-10 20:12:49 +01004429 result = _PyUnicode_EncodeUTF7(tmp, base64SetO,
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004430 base64WhiteSpace, errors);
4431 Py_DECREF(tmp);
4432 return result;
4433}
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004434
Antoine Pitrou244651a2009-05-04 18:56:13 +00004435#undef IS_BASE64
4436#undef FROM_BASE64
4437#undef TO_BASE64
4438#undef DECODE_DIRECT
4439#undef ENCODE_DIRECT
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004440
Guido van Rossumd57fd912000-03-10 22:53:23 +00004441/* --- UTF-8 Codec -------------------------------------------------------- */
4442
Tim Petersced69f82003-09-16 20:30:58 +00004443static
Guido van Rossumd57fd912000-03-10 22:53:23 +00004444char utf8_code_length[256] = {
Ezio Melotti57221d02010-07-01 07:32:02 +00004445 /* Map UTF-8 encoded prefix byte to sequence length. Zero means
4446 illegal prefix. See RFC 3629 for details */
4447 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 00-0F */
4448 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Victor Stinner4a2b7a12010-08-13 14:03:48 +00004449 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Guido van Rossumd57fd912000-03-10 22:53:23 +00004450 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
4451 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
4452 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
4453 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Ezio Melotti57221d02010-07-01 07:32:02 +00004454 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 70-7F */
4455 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 80-8F */
Guido van Rossumd57fd912000-03-10 22:53:23 +00004456 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4457 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
Ezio Melotti57221d02010-07-01 07:32:02 +00004458 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* B0-BF */
4459 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* C0-C1 + C2-CF */
4460 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* D0-DF */
4461 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, /* E0-EF */
4462 4, 4, 4, 4, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 /* F0-F4 + F5-FF */
Guido van Rossumd57fd912000-03-10 22:53:23 +00004463};
4464
Alexander Belopolsky40018472011-02-26 01:02:56 +00004465PyObject *
4466PyUnicode_DecodeUTF8(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004467 Py_ssize_t size,
4468 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004469{
Walter Dörwald69652032004-09-07 20:24:22 +00004470 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
4471}
4472
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004473#include "stringlib/ucs1lib.h"
4474#include "stringlib/codecs.h"
4475#include "stringlib/undef.h"
4476
4477#include "stringlib/ucs2lib.h"
4478#include "stringlib/codecs.h"
4479#include "stringlib/undef.h"
4480
4481#include "stringlib/ucs4lib.h"
4482#include "stringlib/codecs.h"
4483#include "stringlib/undef.h"
4484
Antoine Pitrouab868312009-01-10 15:40:25 +00004485/* Mask to check or force alignment of a pointer to C 'long' boundaries */
4486#define LONG_PTR_MASK (size_t) (SIZEOF_LONG - 1)
4487
4488/* Mask to quickly check whether a C 'long' contains a
4489 non-ASCII, UTF8-encoded char. */
4490#if (SIZEOF_LONG == 8)
4491# define ASCII_CHAR_MASK 0x8080808080808080L
4492#elif (SIZEOF_LONG == 4)
4493# define ASCII_CHAR_MASK 0x80808080L
4494#else
4495# error C 'long' size should be either 4 or 8!
4496#endif
4497
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004498/* Scans a UTF-8 string and returns the maximum character to be expected
4499 and the size of the decoded unicode string.
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004500
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004501 This function doesn't check for errors, these checks are performed in
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004502 PyUnicode_DecodeUTF8Stateful.
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004503 */
4504static Py_UCS4
Victor Stinnera1d12bb2011-12-11 21:53:09 +01004505utf8_scanner(const unsigned char *p, Py_ssize_t string_size, Py_ssize_t *unicode_size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004506{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004507 Py_ssize_t char_count = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004508 const unsigned char *end = p + string_size;
4509 const unsigned char *aligned_end = (const unsigned char *) ((size_t) end & ~LONG_PTR_MASK);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004510
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004511 assert(unicode_size != NULL);
4512
4513 /* By having a cascade of independent loops which fallback onto each
4514 other, we minimize the amount of work done in the average loop
4515 iteration, and we also maximize the CPU's ability to predict
4516 branches correctly (because a given condition will have always the
4517 same boolean outcome except perhaps in the last iteration of the
4518 corresponding loop).
4519 In the general case this brings us rather close to decoding
4520 performance pre-PEP 393, despite the two-pass decoding.
4521
4522 Note that the pure ASCII loop is not duplicated once a non-ASCII
4523 character has been encountered. It is actually a pessimization (by
4524 a significant factor) to use this loop on text with many non-ASCII
4525 characters, and it is important to avoid bad performance on valid
4526 utf-8 data (invalid utf-8 being a different can of worms).
4527 */
4528
4529 /* ASCII */
4530 for (; p < end; ++p) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004531 /* Only check value if it's not a ASCII char... */
4532 if (*p < 0x80) {
4533 /* Fast path, see below in PyUnicode_DecodeUTF8Stateful for
4534 an explanation. */
4535 if (!((size_t) p & LONG_PTR_MASK)) {
4536 /* Help register allocation */
4537 register const unsigned char *_p = p;
4538 while (_p < aligned_end) {
4539 unsigned long value = *(unsigned long *) _p;
4540 if (value & ASCII_CHAR_MASK)
4541 break;
4542 _p += SIZEOF_LONG;
4543 char_count += SIZEOF_LONG;
4544 }
4545 p = _p;
4546 if (p == end)
4547 break;
4548 }
4549 }
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004550 if (*p < 0x80)
4551 ++char_count;
4552 else
4553 goto _ucs1loop;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004554 }
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004555 *unicode_size = char_count;
4556 return 127;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004557
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004558_ucs1loop:
4559 for (; p < end; ++p) {
4560 if (*p < 0xc4)
4561 char_count += ((*p & 0xc0) != 0x80);
4562 else
4563 goto _ucs2loop;
4564 }
4565 *unicode_size = char_count;
4566 return 255;
4567
4568_ucs2loop:
4569 for (; p < end; ++p) {
4570 if (*p < 0xf0)
4571 char_count += ((*p & 0xc0) != 0x80);
4572 else
4573 goto _ucs4loop;
4574 }
4575 *unicode_size = char_count;
4576 return 65535;
4577
4578_ucs4loop:
4579 for (; p < end; ++p) {
4580 char_count += ((*p & 0xc0) != 0x80);
4581 }
4582 *unicode_size = char_count;
4583 return 65537;
4584}
4585
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004586/* Similar to PyUnicode_WRITE but may attempt to widen and resize the string
Victor Stinner785938e2011-12-11 20:09:03 +01004587 in case of errors. Implicit parameters: unicode, kind, data, onError.
4588 Potential resizing overallocates, so the result needs to shrink at the end.
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004589*/
Victor Stinner785938e2011-12-11 20:09:03 +01004590#define WRITE_MAYBE_FAIL(index, value) \
4591 do { \
4592 Py_ssize_t pos = index; \
4593 if (pos > PyUnicode_GET_LENGTH(unicode) && \
4594 unicode_resize(&unicode, pos + pos/8) < 0) \
4595 goto onError; \
4596 if (unicode_putchar(&unicode, &pos, value) < 0) \
4597 goto onError; \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004598 } while (0)
4599
Victor Stinnerbf6e5602011-12-12 01:53:47 +01004600static PyObject *
Victor Stinner785938e2011-12-11 20:09:03 +01004601decode_utf8_errors(const char *starts,
4602 Py_ssize_t size,
4603 const char *errors,
4604 Py_ssize_t *consumed,
4605 const char *s,
4606 PyObject *unicode,
4607 Py_ssize_t i)
Walter Dörwald69652032004-09-07 20:24:22 +00004608{
Guido van Rossumd57fd912000-03-10 22:53:23 +00004609 int n;
Ezio Melotti57221d02010-07-01 07:32:02 +00004610 int k;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004611 Py_ssize_t startinpos;
4612 Py_ssize_t endinpos;
Victor Stinner785938e2011-12-11 20:09:03 +01004613 const char *e = starts + size;
4614 const char *aligned_end;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004615 const char *errmsg = "";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004616 PyObject *errorHandler = NULL;
4617 PyObject *exc = NULL;
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004618
Antoine Pitrouab868312009-01-10 15:40:25 +00004619 aligned_end = (const char *) ((size_t) e & ~LONG_PTR_MASK);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004620
4621 while (s < e) {
Marc-André Lemburge12896e2000-07-07 17:51:08 +00004622 Py_UCS4 ch = (unsigned char)*s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004623
4624 if (ch < 0x80) {
Antoine Pitrouab868312009-01-10 15:40:25 +00004625 /* Fast path for runs of ASCII characters. Given that common UTF-8
4626 input will consist of an overwhelming majority of ASCII
4627 characters, we try to optimize for this case by checking
4628 as many characters as a C 'long' can contain.
4629 First, check if we can do an aligned read, as most CPUs have
4630 a penalty for unaligned reads.
4631 */
4632 if (!((size_t) s & LONG_PTR_MASK)) {
4633 /* Help register allocation */
4634 register const char *_s = s;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004635 register Py_ssize_t _i = i;
Antoine Pitrouab868312009-01-10 15:40:25 +00004636 while (_s < aligned_end) {
4637 /* Read a whole long at a time (either 4 or 8 bytes),
4638 and do a fast unrolled copy if it only contains ASCII
4639 characters. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004640 unsigned long value = *(unsigned long *) _s;
4641 if (value & ASCII_CHAR_MASK)
Antoine Pitrouab868312009-01-10 15:40:25 +00004642 break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004643 WRITE_MAYBE_FAIL(_i+0, _s[0]);
4644 WRITE_MAYBE_FAIL(_i+1, _s[1]);
4645 WRITE_MAYBE_FAIL(_i+2, _s[2]);
4646 WRITE_MAYBE_FAIL(_i+3, _s[3]);
Antoine Pitrouab868312009-01-10 15:40:25 +00004647#if (SIZEOF_LONG == 8)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004648 WRITE_MAYBE_FAIL(_i+4, _s[4]);
4649 WRITE_MAYBE_FAIL(_i+5, _s[5]);
4650 WRITE_MAYBE_FAIL(_i+6, _s[6]);
4651 WRITE_MAYBE_FAIL(_i+7, _s[7]);
Antoine Pitrouab868312009-01-10 15:40:25 +00004652#endif
4653 _s += SIZEOF_LONG;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004654 _i += SIZEOF_LONG;
Antoine Pitrouab868312009-01-10 15:40:25 +00004655 }
4656 s = _s;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004657 i = _i;
Antoine Pitrouab868312009-01-10 15:40:25 +00004658 if (s == e)
4659 break;
4660 ch = (unsigned char)*s;
4661 }
4662 }
4663
4664 if (ch < 0x80) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004665 WRITE_MAYBE_FAIL(i++, ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004666 s++;
4667 continue;
4668 }
4669
4670 n = utf8_code_length[ch];
4671
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004672 if (s + n > e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004673 if (consumed)
4674 break;
4675 else {
4676 errmsg = "unexpected end of data";
4677 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004678 endinpos = startinpos+1;
4679 for (k=1; (k < size-startinpos) && ((s[k]&0xC0) == 0x80); k++)
4680 endinpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00004681 goto utf8Error;
4682 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00004683 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004684
4685 switch (n) {
4686
4687 case 0:
Ezio Melotti57221d02010-07-01 07:32:02 +00004688 errmsg = "invalid start byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004689 startinpos = s-starts;
4690 endinpos = startinpos+1;
4691 goto utf8Error;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004692
4693 case 1:
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004694 errmsg = "internal error";
Benjamin Peterson29060642009-01-31 22:14:21 +00004695 startinpos = s-starts;
4696 endinpos = startinpos+1;
4697 goto utf8Error;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004698
4699 case 2:
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004700 if ((s[1] & 0xc0) != 0x80) {
Ezio Melotti57221d02010-07-01 07:32:02 +00004701 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004702 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004703 endinpos = startinpos + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00004704 goto utf8Error;
4705 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004706 ch = ((s[0] & 0x1f) << 6) + (s[1] & 0x3f);
Ezio Melotti57221d02010-07-01 07:32:02 +00004707 assert ((ch > 0x007F) && (ch <= 0x07FF));
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004708 WRITE_MAYBE_FAIL(i++, ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004709 break;
4710
4711 case 3:
Ezio Melotti9bf2b3a2010-07-03 04:52:19 +00004712 /* Decoding UTF-8 sequences in range \xed\xa0\x80-\xed\xbf\xbf
4713 will result in surrogates in range d800-dfff. Surrogates are
4714 not valid UTF-8 so they are rejected.
4715 See http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf
4716 (table 3-7) and http://www.rfc-editor.org/rfc/rfc3629.txt */
Tim Petersced69f82003-09-16 20:30:58 +00004717 if ((s[1] & 0xc0) != 0x80 ||
Ezio Melotti57221d02010-07-01 07:32:02 +00004718 (s[2] & 0xc0) != 0x80 ||
4719 ((unsigned char)s[0] == 0xE0 &&
4720 (unsigned char)s[1] < 0xA0) ||
4721 ((unsigned char)s[0] == 0xED &&
4722 (unsigned char)s[1] > 0x9F)) {
4723 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004724 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004725 endinpos = startinpos + 1;
4726
4727 /* if s[1] first two bits are 1 and 0, then the invalid
4728 continuation byte is s[2], so increment endinpos by 1,
4729 if not, s[1] is invalid and endinpos doesn't need to
4730 be incremented. */
4731 if ((s[1] & 0xC0) == 0x80)
4732 endinpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00004733 goto utf8Error;
4734 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004735 ch = ((s[0] & 0x0f) << 12) + ((s[1] & 0x3f) << 6) + (s[2] & 0x3f);
Ezio Melotti57221d02010-07-01 07:32:02 +00004736 assert ((ch > 0x07FF) && (ch <= 0xFFFF));
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004737 WRITE_MAYBE_FAIL(i++, ch);
Marc-André Lemburge12896e2000-07-07 17:51:08 +00004738 break;
4739
4740 case 4:
4741 if ((s[1] & 0xc0) != 0x80 ||
4742 (s[2] & 0xc0) != 0x80 ||
Ezio Melotti57221d02010-07-01 07:32:02 +00004743 (s[3] & 0xc0) != 0x80 ||
4744 ((unsigned char)s[0] == 0xF0 &&
4745 (unsigned char)s[1] < 0x90) ||
4746 ((unsigned char)s[0] == 0xF4 &&
4747 (unsigned char)s[1] > 0x8F)) {
4748 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004749 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004750 endinpos = startinpos + 1;
4751 if ((s[1] & 0xC0) == 0x80) {
4752 endinpos++;
4753 if ((s[2] & 0xC0) == 0x80)
4754 endinpos++;
4755 }
Benjamin Peterson29060642009-01-31 22:14:21 +00004756 goto utf8Error;
4757 }
Marc-André Lemburge12896e2000-07-07 17:51:08 +00004758 ch = ((s[0] & 0x7) << 18) + ((s[1] & 0x3f) << 12) +
Ezio Melotti57221d02010-07-01 07:32:02 +00004759 ((s[2] & 0x3f) << 6) + (s[3] & 0x3f);
Victor Stinner8faf8212011-12-08 22:14:11 +01004760 assert ((ch > 0xFFFF) && (ch <= MAX_UNICODE));
Ezio Melotti57221d02010-07-01 07:32:02 +00004761
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004762 WRITE_MAYBE_FAIL(i++, ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004763 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004764 }
4765 s += n;
Benjamin Peterson29060642009-01-31 22:14:21 +00004766 continue;
Tim Petersced69f82003-09-16 20:30:58 +00004767
Benjamin Peterson29060642009-01-31 22:14:21 +00004768 utf8Error:
Benjamin Peterson29060642009-01-31 22:14:21 +00004769 if (unicode_decode_call_errorhandler(
4770 errors, &errorHandler,
4771 "utf8", errmsg,
4772 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004773 &unicode, &i))
Benjamin Peterson29060642009-01-31 22:14:21 +00004774 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004775 /* Update data because unicode_decode_call_errorhandler might have
4776 re-created or resized the unicode object. */
Benjamin Peterson29060642009-01-31 22:14:21 +00004777 aligned_end = (const char *) ((size_t) e & ~LONG_PTR_MASK);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004778 }
Walter Dörwald69652032004-09-07 20:24:22 +00004779 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00004780 *consumed = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004781
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004782 /* Adjust length and ready string when it contained errors and
4783 is of the old resizable kind. */
Victor Stinner785938e2011-12-11 20:09:03 +01004784 if (unicode_resize(&unicode, i) < 0)
4785 goto onError;
4786 unicode_adjust_maxchar(&unicode);
4787 if (unicode == NULL)
4788 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004789
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004790 Py_XDECREF(errorHandler);
4791 Py_XDECREF(exc);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02004792 assert(_PyUnicode_CheckConsistency(unicode, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01004793 return unicode;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004794
Benjamin Peterson29060642009-01-31 22:14:21 +00004795 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004796 Py_XDECREF(errorHandler);
4797 Py_XDECREF(exc);
Victor Stinner785938e2011-12-11 20:09:03 +01004798 Py_XDECREF(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004799 return NULL;
4800}
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004801#undef WRITE_MAYBE_FAIL
Antoine Pitrouab868312009-01-10 15:40:25 +00004802
Victor Stinner785938e2011-12-11 20:09:03 +01004803PyObject *
4804PyUnicode_DecodeUTF8Stateful(const char *s,
4805 Py_ssize_t size,
4806 const char *errors,
4807 Py_ssize_t *consumed)
4808{
4809 Py_UCS4 maxchar = 0;
4810 Py_ssize_t unicode_size;
4811 int has_errors = 0;
4812 PyObject *unicode;
4813 int kind;
4814 void *data;
4815 const char *starts = s;
4816 const char *e;
4817 Py_ssize_t i;
4818
4819 if (size == 0) {
4820 if (consumed)
4821 *consumed = 0;
Victor Stinner382955f2011-12-11 21:44:00 +01004822 Py_INCREF(unicode_empty);
4823 return unicode_empty;
Victor Stinner785938e2011-12-11 20:09:03 +01004824 }
4825
Victor Stinnera1d12bb2011-12-11 21:53:09 +01004826 maxchar = utf8_scanner((const unsigned char *)s, size, &unicode_size);
Victor Stinner785938e2011-12-11 20:09:03 +01004827
4828 /* When the string is ASCII only, just use memcpy and return.
4829 unicode_size may be != size if there is an incomplete UTF-8
4830 sequence at the end of the ASCII block. */
4831 if (maxchar < 128 && size == unicode_size) {
4832 if (consumed)
4833 *consumed = size;
Victor Stinnerab870212011-12-17 22:39:43 +01004834 return unicode_fromascii((const unsigned char *)s, size);
Victor Stinner785938e2011-12-11 20:09:03 +01004835 }
4836
4837 unicode = PyUnicode_New(unicode_size, maxchar);
4838 if (!unicode)
4839 return NULL;
4840 kind = PyUnicode_KIND(unicode);
4841 data = PyUnicode_DATA(unicode);
4842
4843 /* Unpack UTF-8 encoded data */
4844 i = 0;
4845 e = starts + size;
4846 switch (kind) {
4847 case PyUnicode_1BYTE_KIND:
4848 has_errors = ucs1lib_utf8_try_decode(s, e, (Py_UCS1 *) data, &s, &i);
4849 break;
4850 case PyUnicode_2BYTE_KIND:
4851 has_errors = ucs2lib_utf8_try_decode(s, e, (Py_UCS2 *) data, &s, &i);
4852 break;
4853 case PyUnicode_4BYTE_KIND:
4854 has_errors = ucs4lib_utf8_try_decode(s, e, (Py_UCS4 *) data, &s, &i);
4855 break;
4856 }
4857 if (!has_errors) {
4858 /* Ensure the unicode size calculation was correct */
4859 assert(i == unicode_size);
4860 assert(s == e);
4861 if (consumed)
4862 *consumed = size;
4863 return unicode;
4864 }
4865
4866 /* In case of errors, maxchar and size computation might be incorrect;
4867 code below refits and resizes as necessary. */
4868 return decode_utf8_errors(starts, size, errors, consumed, s, unicode, i);
4869}
4870
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004871#ifdef __APPLE__
4872
4873/* Simplified UTF-8 decoder using surrogateescape error handler,
4874 used to decode the command line arguments on Mac OS X. */
4875
4876wchar_t*
4877_Py_DecodeUTF8_surrogateescape(const char *s, Py_ssize_t size)
4878{
4879 int n;
4880 const char *e;
4881 wchar_t *unicode, *p;
4882
4883 /* Note: size will always be longer than the resulting Unicode
4884 character count */
4885 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < (size + 1)) {
4886 PyErr_NoMemory();
4887 return NULL;
4888 }
4889 unicode = PyMem_Malloc((size + 1) * sizeof(wchar_t));
4890 if (!unicode)
4891 return NULL;
4892
4893 /* Unpack UTF-8 encoded data */
4894 p = unicode;
4895 e = s + size;
4896 while (s < e) {
4897 Py_UCS4 ch = (unsigned char)*s;
4898
4899 if (ch < 0x80) {
4900 *p++ = (wchar_t)ch;
4901 s++;
4902 continue;
4903 }
4904
4905 n = utf8_code_length[ch];
4906 if (s + n > e) {
4907 goto surrogateescape;
4908 }
4909
4910 switch (n) {
4911 case 0:
4912 case 1:
4913 goto surrogateescape;
4914
4915 case 2:
4916 if ((s[1] & 0xc0) != 0x80)
4917 goto surrogateescape;
4918 ch = ((s[0] & 0x1f) << 6) + (s[1] & 0x3f);
4919 assert ((ch > 0x007F) && (ch <= 0x07FF));
4920 *p++ = (wchar_t)ch;
4921 break;
4922
4923 case 3:
4924 /* Decoding UTF-8 sequences in range \xed\xa0\x80-\xed\xbf\xbf
4925 will result in surrogates in range d800-dfff. Surrogates are
4926 not valid UTF-8 so they are rejected.
4927 See http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf
4928 (table 3-7) and http://www.rfc-editor.org/rfc/rfc3629.txt */
4929 if ((s[1] & 0xc0) != 0x80 ||
4930 (s[2] & 0xc0) != 0x80 ||
4931 ((unsigned char)s[0] == 0xE0 &&
4932 (unsigned char)s[1] < 0xA0) ||
4933 ((unsigned char)s[0] == 0xED &&
4934 (unsigned char)s[1] > 0x9F)) {
4935
4936 goto surrogateescape;
4937 }
4938 ch = ((s[0] & 0x0f) << 12) + ((s[1] & 0x3f) << 6) + (s[2] & 0x3f);
4939 assert ((ch > 0x07FF) && (ch <= 0xFFFF));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004940 *p++ = (wchar_t)ch;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004941 break;
4942
4943 case 4:
4944 if ((s[1] & 0xc0) != 0x80 ||
4945 (s[2] & 0xc0) != 0x80 ||
4946 (s[3] & 0xc0) != 0x80 ||
4947 ((unsigned char)s[0] == 0xF0 &&
4948 (unsigned char)s[1] < 0x90) ||
4949 ((unsigned char)s[0] == 0xF4 &&
4950 (unsigned char)s[1] > 0x8F)) {
4951 goto surrogateescape;
4952 }
4953 ch = ((s[0] & 0x7) << 18) + ((s[1] & 0x3f) << 12) +
4954 ((s[2] & 0x3f) << 6) + (s[3] & 0x3f);
Victor Stinner8faf8212011-12-08 22:14:11 +01004955 assert ((ch > 0xFFFF) && (ch <= MAX_UNICODE));
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004956
4957#if SIZEOF_WCHAR_T == 4
4958 *p++ = (wchar_t)ch;
4959#else
4960 /* compute and append the two surrogates: */
Victor Stinner551ac952011-11-29 22:58:13 +01004961 *p++ = (wchar_t)Py_UNICODE_HIGH_SURROGATE(ch);
4962 *p++ = (wchar_t)Py_UNICODE_LOW_SURROGATE(ch);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004963#endif
4964 break;
4965 }
4966 s += n;
4967 continue;
4968
4969 surrogateescape:
4970 *p++ = 0xDC00 + ch;
4971 s++;
4972 }
4973 *p = L'\0';
4974 return unicode;
4975}
4976
4977#endif /* __APPLE__ */
Antoine Pitrouab868312009-01-10 15:40:25 +00004978
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004979/* Primary internal function which creates utf8 encoded bytes objects.
4980
4981 Allocation strategy: if the string is short, convert into a stack buffer
Tim Peters602f7402002-04-27 18:03:26 +00004982 and allocate exactly as much space needed at the end. Else allocate the
4983 maximum possible needed (4 result bytes per Unicode character), and return
4984 the excess memory at the end.
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004985*/
Tim Peters7e3d9612002-04-21 03:26:37 +00004986PyObject *
Victor Stinner7931d9a2011-11-04 00:22:48 +01004987_PyUnicode_AsUTF8String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004988{
Victor Stinner6099a032011-12-18 14:22:26 +01004989 enum PyUnicode_Kind kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004990 void *data;
4991 Py_ssize_t size;
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00004992
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004993 if (!PyUnicode_Check(unicode)) {
4994 PyErr_BadArgument();
4995 return NULL;
4996 }
4997
4998 if (PyUnicode_READY(unicode) == -1)
4999 return NULL;
5000
Victor Stinnere90fe6a2011-10-01 16:48:13 +02005001 if (PyUnicode_UTF8(unicode))
5002 return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode),
5003 PyUnicode_UTF8_LENGTH(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005004
5005 kind = PyUnicode_KIND(unicode);
5006 data = PyUnicode_DATA(unicode);
5007 size = PyUnicode_GET_LENGTH(unicode);
5008
Benjamin Petersonead6b532011-12-20 17:23:42 -06005009 switch (kind) {
Victor Stinner6099a032011-12-18 14:22:26 +01005010 default:
5011 assert(0);
5012 case PyUnicode_1BYTE_KIND:
5013 /* the string cannot be ASCII, or PyUnicode_UTF8() would be set */
5014 assert(!PyUnicode_IS_ASCII(unicode));
5015 return ucs1lib_utf8_encoder(unicode, data, size, errors);
5016 case PyUnicode_2BYTE_KIND:
5017 return ucs2lib_utf8_encoder(unicode, data, size, errors);
5018 case PyUnicode_4BYTE_KIND:
5019 return ucs4lib_utf8_encoder(unicode, data, size, errors);
Tim Peters602f7402002-04-27 18:03:26 +00005020 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005021}
5022
Alexander Belopolsky40018472011-02-26 01:02:56 +00005023PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005024PyUnicode_EncodeUTF8(const Py_UNICODE *s,
5025 Py_ssize_t size,
5026 const char *errors)
5027{
5028 PyObject *v, *unicode;
5029
5030 unicode = PyUnicode_FromUnicode(s, size);
5031 if (unicode == NULL)
5032 return NULL;
5033 v = _PyUnicode_AsUTF8String(unicode, errors);
5034 Py_DECREF(unicode);
5035 return v;
5036}
5037
5038PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005039PyUnicode_AsUTF8String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005040{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005041 return _PyUnicode_AsUTF8String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005042}
5043
Walter Dörwald41980ca2007-08-16 21:55:45 +00005044/* --- UTF-32 Codec ------------------------------------------------------- */
5045
5046PyObject *
5047PyUnicode_DecodeUTF32(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005048 Py_ssize_t size,
5049 const char *errors,
5050 int *byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005051{
5052 return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
5053}
5054
5055PyObject *
5056PyUnicode_DecodeUTF32Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005057 Py_ssize_t size,
5058 const char *errors,
5059 int *byteorder,
5060 Py_ssize_t *consumed)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005061{
5062 const char *starts = s;
5063 Py_ssize_t startinpos;
5064 Py_ssize_t endinpos;
5065 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01005066 PyObject *unicode;
Mark Dickinson7db923c2010-06-12 09:10:14 +00005067 const unsigned char *q, *e;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005068 int bo = 0; /* assume native ordering by default */
5069 const char *errmsg = "";
Walter Dörwald41980ca2007-08-16 21:55:45 +00005070 /* Offsets from q for retrieving bytes in the right order. */
5071#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5072 int iorder[] = {0, 1, 2, 3};
5073#else
5074 int iorder[] = {3, 2, 1, 0};
5075#endif
5076 PyObject *errorHandler = NULL;
5077 PyObject *exc = NULL;
Victor Stinner313a1202010-06-11 23:56:51 +00005078
Walter Dörwald41980ca2007-08-16 21:55:45 +00005079 q = (unsigned char *)s;
5080 e = q + size;
5081
5082 if (byteorder)
5083 bo = *byteorder;
5084
5085 /* Check for BOM marks (U+FEFF) in the input and adjust current
5086 byte order setting accordingly. In native mode, the leading BOM
5087 mark is skipped, in all other modes, it is copied to the output
5088 stream as-is (giving a ZWNBSP character). */
5089 if (bo == 0) {
5090 if (size >= 4) {
5091 const Py_UCS4 bom = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
Benjamin Peterson29060642009-01-31 22:14:21 +00005092 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00005093#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Benjamin Peterson29060642009-01-31 22:14:21 +00005094 if (bom == 0x0000FEFF) {
5095 q += 4;
5096 bo = -1;
5097 }
5098 else if (bom == 0xFFFE0000) {
5099 q += 4;
5100 bo = 1;
5101 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00005102#else
Benjamin Peterson29060642009-01-31 22:14:21 +00005103 if (bom == 0x0000FEFF) {
5104 q += 4;
5105 bo = 1;
5106 }
5107 else if (bom == 0xFFFE0000) {
5108 q += 4;
5109 bo = -1;
5110 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00005111#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00005112 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00005113 }
5114
5115 if (bo == -1) {
5116 /* force LE */
5117 iorder[0] = 0;
5118 iorder[1] = 1;
5119 iorder[2] = 2;
5120 iorder[3] = 3;
5121 }
5122 else if (bo == 1) {
5123 /* force BE */
5124 iorder[0] = 3;
5125 iorder[1] = 2;
5126 iorder[2] = 1;
5127 iorder[3] = 0;
5128 }
5129
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005130 /* This might be one to much, because of a BOM */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005131 unicode = PyUnicode_New((size+3)/4, 127);
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005132 if (!unicode)
5133 return NULL;
5134 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01005135 return unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005136 outpos = 0;
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005137
Walter Dörwald41980ca2007-08-16 21:55:45 +00005138 while (q < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005139 Py_UCS4 ch;
5140 /* remaining bytes at the end? (size should be divisible by 4) */
5141 if (e-q<4) {
5142 if (consumed)
5143 break;
5144 errmsg = "truncated data";
5145 startinpos = ((const char *)q)-starts;
5146 endinpos = ((const char *)e)-starts;
5147 goto utf32Error;
5148 /* The remaining input chars are ignored if the callback
5149 chooses to skip the input */
5150 }
5151 ch = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
5152 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00005153
Benjamin Peterson29060642009-01-31 22:14:21 +00005154 if (ch >= 0x110000)
5155 {
5156 errmsg = "codepoint not in range(0x110000)";
5157 startinpos = ((const char *)q)-starts;
5158 endinpos = startinpos+4;
5159 goto utf32Error;
5160 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005161 if (unicode_putchar(&unicode, &outpos, ch) < 0)
5162 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005163 q += 4;
5164 continue;
5165 utf32Error:
Benjamin Peterson29060642009-01-31 22:14:21 +00005166 if (unicode_decode_call_errorhandler(
5167 errors, &errorHandler,
5168 "utf32", errmsg,
5169 &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005170 &unicode, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00005171 goto onError;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005172 }
5173
5174 if (byteorder)
5175 *byteorder = bo;
5176
5177 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005178 *consumed = (const char *)q-starts;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005179
5180 /* Adjust length */
Victor Stinner16e6a802011-12-12 13:24:15 +01005181 if (unicode_resize(&unicode, outpos) < 0)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005182 goto onError;
5183
5184 Py_XDECREF(errorHandler);
5185 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01005186 return unicode_result(unicode);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005187
Benjamin Peterson29060642009-01-31 22:14:21 +00005188 onError:
Walter Dörwald41980ca2007-08-16 21:55:45 +00005189 Py_DECREF(unicode);
5190 Py_XDECREF(errorHandler);
5191 Py_XDECREF(exc);
5192 return NULL;
5193}
5194
5195PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005196_PyUnicode_EncodeUTF32(PyObject *str,
5197 const char *errors,
5198 int byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005199{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005200 int kind;
5201 void *data;
5202 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005203 PyObject *v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005204 unsigned char *p;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005205 Py_ssize_t nsize, bytesize, i;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005206 /* Offsets from p for storing byte pairs in the right order. */
5207#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5208 int iorder[] = {0, 1, 2, 3};
5209#else
5210 int iorder[] = {3, 2, 1, 0};
5211#endif
5212
Benjamin Peterson29060642009-01-31 22:14:21 +00005213#define STORECHAR(CH) \
5214 do { \
5215 p[iorder[3]] = ((CH) >> 24) & 0xff; \
5216 p[iorder[2]] = ((CH) >> 16) & 0xff; \
5217 p[iorder[1]] = ((CH) >> 8) & 0xff; \
5218 p[iorder[0]] = (CH) & 0xff; \
5219 p += 4; \
Walter Dörwald41980ca2007-08-16 21:55:45 +00005220 } while(0)
5221
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005222 if (!PyUnicode_Check(str)) {
5223 PyErr_BadArgument();
5224 return NULL;
5225 }
5226 if (PyUnicode_READY(str) < 0)
5227 return NULL;
5228 kind = PyUnicode_KIND(str);
5229 data = PyUnicode_DATA(str);
5230 len = PyUnicode_GET_LENGTH(str);
5231
5232 nsize = len + (byteorder == 0);
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005233 bytesize = nsize * 4;
5234 if (bytesize / 4 != nsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005235 return PyErr_NoMemory();
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005236 v = PyBytes_FromStringAndSize(NULL, bytesize);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005237 if (v == NULL)
5238 return NULL;
5239
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005240 p = (unsigned char *)PyBytes_AS_STRING(v);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005241 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005242 STORECHAR(0xFEFF);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005243 if (len == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005244 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005245
5246 if (byteorder == -1) {
5247 /* force LE */
5248 iorder[0] = 0;
5249 iorder[1] = 1;
5250 iorder[2] = 2;
5251 iorder[3] = 3;
5252 }
5253 else if (byteorder == 1) {
5254 /* force BE */
5255 iorder[0] = 3;
5256 iorder[1] = 2;
5257 iorder[2] = 1;
5258 iorder[3] = 0;
5259 }
5260
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005261 for (i = 0; i < len; i++)
5262 STORECHAR(PyUnicode_READ(kind, data, i));
Guido van Rossum98297ee2007-11-06 21:34:58 +00005263
5264 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005265 return v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005266#undef STORECHAR
5267}
5268
Alexander Belopolsky40018472011-02-26 01:02:56 +00005269PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005270PyUnicode_EncodeUTF32(const Py_UNICODE *s,
5271 Py_ssize_t size,
5272 const char *errors,
5273 int byteorder)
5274{
5275 PyObject *result;
5276 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5277 if (tmp == NULL)
5278 return NULL;
5279 result = _PyUnicode_EncodeUTF32(tmp, errors, byteorder);
5280 Py_DECREF(tmp);
5281 return result;
5282}
5283
5284PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005285PyUnicode_AsUTF32String(PyObject *unicode)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005286{
Victor Stinnerb960b342011-11-20 19:12:52 +01005287 return _PyUnicode_EncodeUTF32(unicode, NULL, 0);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005288}
5289
Guido van Rossumd57fd912000-03-10 22:53:23 +00005290/* --- UTF-16 Codec ------------------------------------------------------- */
5291
Tim Peters772747b2001-08-09 22:21:55 +00005292PyObject *
5293PyUnicode_DecodeUTF16(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005294 Py_ssize_t size,
5295 const char *errors,
5296 int *byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005297{
Walter Dörwald69652032004-09-07 20:24:22 +00005298 return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
5299}
5300
Antoine Pitrouab868312009-01-10 15:40:25 +00005301/* Two masks for fast checking of whether a C 'long' may contain
5302 UTF16-encoded surrogate characters. This is an efficient heuristic,
5303 assuming that non-surrogate characters with a code point >= 0x8000 are
5304 rare in most input.
5305 FAST_CHAR_MASK is used when the input is in native byte ordering,
5306 SWAPPED_FAST_CHAR_MASK when the input is in byteswapped ordering.
Benjamin Peterson29060642009-01-31 22:14:21 +00005307*/
Antoine Pitrouab868312009-01-10 15:40:25 +00005308#if (SIZEOF_LONG == 8)
5309# define FAST_CHAR_MASK 0x8000800080008000L
5310# define SWAPPED_FAST_CHAR_MASK 0x0080008000800080L
5311#elif (SIZEOF_LONG == 4)
5312# define FAST_CHAR_MASK 0x80008000L
5313# define SWAPPED_FAST_CHAR_MASK 0x00800080L
5314#else
5315# error C 'long' size should be either 4 or 8!
5316#endif
5317
Walter Dörwald69652032004-09-07 20:24:22 +00005318PyObject *
5319PyUnicode_DecodeUTF16Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005320 Py_ssize_t size,
5321 const char *errors,
5322 int *byteorder,
5323 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00005324{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005325 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005326 Py_ssize_t startinpos;
5327 Py_ssize_t endinpos;
5328 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01005329 PyObject *unicode;
Antoine Pitrouab868312009-01-10 15:40:25 +00005330 const unsigned char *q, *e, *aligned_end;
Tim Peters772747b2001-08-09 22:21:55 +00005331 int bo = 0; /* assume native ordering by default */
Antoine Pitrouab868312009-01-10 15:40:25 +00005332 int native_ordering = 0;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00005333 const char *errmsg = "";
Tim Peters772747b2001-08-09 22:21:55 +00005334 /* Offsets from q for retrieving byte pairs in the right order. */
5335#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5336 int ihi = 1, ilo = 0;
5337#else
5338 int ihi = 0, ilo = 1;
5339#endif
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005340 PyObject *errorHandler = NULL;
5341 PyObject *exc = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005342
5343 /* Note: size will always be longer than the resulting Unicode
5344 character count */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005345 unicode = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005346 if (!unicode)
5347 return NULL;
5348 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01005349 return unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005350 outpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005351
Tim Peters772747b2001-08-09 22:21:55 +00005352 q = (unsigned char *)s;
Antoine Pitrouab868312009-01-10 15:40:25 +00005353 e = q + size - 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005354
5355 if (byteorder)
Tim Peters772747b2001-08-09 22:21:55 +00005356 bo = *byteorder;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005357
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005358 /* Check for BOM marks (U+FEFF) in the input and adjust current
5359 byte order setting accordingly. In native mode, the leading BOM
5360 mark is skipped, in all other modes, it is copied to the output
5361 stream as-is (giving a ZWNBSP character). */
5362 if (bo == 0) {
Walter Dörwald69652032004-09-07 20:24:22 +00005363 if (size >= 2) {
Victor Stinner24729f32011-11-10 20:31:37 +01005364 const Py_UCS4 bom = (q[ihi] << 8) | q[ilo];
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005365#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Benjamin Peterson29060642009-01-31 22:14:21 +00005366 if (bom == 0xFEFF) {
5367 q += 2;
5368 bo = -1;
5369 }
5370 else if (bom == 0xFFFE) {
5371 q += 2;
5372 bo = 1;
5373 }
Tim Petersced69f82003-09-16 20:30:58 +00005374#else
Benjamin Peterson29060642009-01-31 22:14:21 +00005375 if (bom == 0xFEFF) {
5376 q += 2;
5377 bo = 1;
5378 }
5379 else if (bom == 0xFFFE) {
5380 q += 2;
5381 bo = -1;
5382 }
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005383#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00005384 }
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005385 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005386
Tim Peters772747b2001-08-09 22:21:55 +00005387 if (bo == -1) {
5388 /* force LE */
5389 ihi = 1;
5390 ilo = 0;
5391 }
5392 else if (bo == 1) {
5393 /* force BE */
5394 ihi = 0;
5395 ilo = 1;
5396 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005397#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5398 native_ordering = ilo < ihi;
5399#else
5400 native_ordering = ilo > ihi;
5401#endif
Tim Peters772747b2001-08-09 22:21:55 +00005402
Antoine Pitrouab868312009-01-10 15:40:25 +00005403 aligned_end = (const unsigned char *) ((size_t) e & ~LONG_PTR_MASK);
Tim Peters772747b2001-08-09 22:21:55 +00005404 while (q < e) {
Victor Stinner24729f32011-11-10 20:31:37 +01005405 Py_UCS4 ch;
Antoine Pitrouab868312009-01-10 15:40:25 +00005406 /* First check for possible aligned read of a C 'long'. Unaligned
5407 reads are more expensive, better to defer to another iteration. */
5408 if (!((size_t) q & LONG_PTR_MASK)) {
5409 /* Fast path for runs of non-surrogate chars. */
5410 register const unsigned char *_q = q;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005411 int kind = PyUnicode_KIND(unicode);
5412 void *data = PyUnicode_DATA(unicode);
5413 while (_q < aligned_end) {
5414 unsigned long block = * (unsigned long *) _q;
5415 unsigned short *pblock = (unsigned short*)&block;
5416 Py_UCS4 maxch;
5417 if (native_ordering) {
5418 /* Can use buffer directly */
5419 if (block & FAST_CHAR_MASK)
Antoine Pitrouab868312009-01-10 15:40:25 +00005420 break;
Antoine Pitrouab868312009-01-10 15:40:25 +00005421 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005422 else {
5423 /* Need to byte-swap */
5424 unsigned char *_p = (unsigned char*)pblock;
5425 if (block & SWAPPED_FAST_CHAR_MASK)
Antoine Pitrouab868312009-01-10 15:40:25 +00005426 break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005427 _p[0] = _q[1];
5428 _p[1] = _q[0];
5429 _p[2] = _q[3];
5430 _p[3] = _q[2];
Antoine Pitrouab868312009-01-10 15:40:25 +00005431#if (SIZEOF_LONG == 8)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005432 _p[4] = _q[5];
5433 _p[5] = _q[4];
5434 _p[6] = _q[7];
5435 _p[7] = _q[6];
Antoine Pitrouab868312009-01-10 15:40:25 +00005436#endif
Antoine Pitrouab868312009-01-10 15:40:25 +00005437 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005438 maxch = Py_MAX(pblock[0], pblock[1]);
5439#if SIZEOF_LONG == 8
5440 maxch = Py_MAX(maxch, Py_MAX(pblock[2], pblock[3]));
5441#endif
5442 if (maxch > PyUnicode_MAX_CHAR_VALUE(unicode)) {
5443 if (unicode_widen(&unicode, maxch) < 0)
5444 goto onError;
5445 kind = PyUnicode_KIND(unicode);
5446 data = PyUnicode_DATA(unicode);
5447 }
5448 PyUnicode_WRITE(kind, data, outpos++, pblock[0]);
5449 PyUnicode_WRITE(kind, data, outpos++, pblock[1]);
5450#if SIZEOF_LONG == 8
5451 PyUnicode_WRITE(kind, data, outpos++, pblock[2]);
5452 PyUnicode_WRITE(kind, data, outpos++, pblock[3]);
5453#endif
5454 _q += SIZEOF_LONG;
Antoine Pitrouab868312009-01-10 15:40:25 +00005455 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005456 q = _q;
5457 if (q >= e)
5458 break;
5459 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005460 ch = (q[ihi] << 8) | q[ilo];
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005461
Benjamin Peterson14339b62009-01-31 16:36:08 +00005462 q += 2;
Benjamin Peterson29060642009-01-31 22:14:21 +00005463
Victor Stinner551ac952011-11-29 22:58:13 +01005464 if (!Py_UNICODE_IS_SURROGATE(ch)) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005465 if (unicode_putchar(&unicode, &outpos, ch) < 0)
5466 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005467 continue;
5468 }
5469
5470 /* UTF-16 code pair: */
5471 if (q > e) {
5472 errmsg = "unexpected end of data";
5473 startinpos = (((const char *)q) - 2) - starts;
5474 endinpos = ((const char *)e) + 1 - starts;
5475 goto utf16Error;
5476 }
Victor Stinner2e9cfad2011-11-20 18:40:27 +01005477 if (Py_UNICODE_IS_HIGH_SURROGATE(ch)) {
5478 Py_UCS4 ch2 = (q[ihi] << 8) | q[ilo];
Benjamin Peterson29060642009-01-31 22:14:21 +00005479 q += 2;
Victor Stinner2e9cfad2011-11-20 18:40:27 +01005480 if (Py_UNICODE_IS_LOW_SURROGATE(ch2)) {
Victor Stinner62aa4d02011-11-09 00:03:45 +01005481 if (unicode_putchar(&unicode, &outpos,
Victor Stinner2e9cfad2011-11-20 18:40:27 +01005482 Py_UNICODE_JOIN_SURROGATES(ch, ch2)) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005483 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005484 continue;
5485 }
5486 else {
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005487 errmsg = "illegal UTF-16 surrogate";
Benjamin Peterson29060642009-01-31 22:14:21 +00005488 startinpos = (((const char *)q)-4)-starts;
5489 endinpos = startinpos+2;
5490 goto utf16Error;
5491 }
5492
Benjamin Peterson14339b62009-01-31 16:36:08 +00005493 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005494 errmsg = "illegal encoding";
5495 startinpos = (((const char *)q)-2)-starts;
5496 endinpos = startinpos+2;
5497 /* Fall through to report the error */
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005498
Benjamin Peterson29060642009-01-31 22:14:21 +00005499 utf16Error:
Benjamin Peterson29060642009-01-31 22:14:21 +00005500 if (unicode_decode_call_errorhandler(
Antoine Pitrouab868312009-01-10 15:40:25 +00005501 errors,
5502 &errorHandler,
5503 "utf16", errmsg,
5504 &starts,
5505 (const char **)&e,
5506 &startinpos,
5507 &endinpos,
5508 &exc,
5509 (const char **)&q,
5510 &unicode,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005511 &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00005512 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005513 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005514 /* remaining byte at the end? (size should be even) */
5515 if (e == q) {
5516 if (!consumed) {
5517 errmsg = "truncated data";
5518 startinpos = ((const char *)q) - starts;
5519 endinpos = ((const char *)e) + 1 - starts;
Antoine Pitrouab868312009-01-10 15:40:25 +00005520 if (unicode_decode_call_errorhandler(
5521 errors,
5522 &errorHandler,
5523 "utf16", errmsg,
5524 &starts,
5525 (const char **)&e,
5526 &startinpos,
5527 &endinpos,
5528 &exc,
5529 (const char **)&q,
5530 &unicode,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005531 &outpos))
Antoine Pitrouab868312009-01-10 15:40:25 +00005532 goto onError;
5533 /* The remaining input chars are ignored if the callback
5534 chooses to skip the input */
5535 }
5536 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005537
5538 if (byteorder)
5539 *byteorder = bo;
5540
Walter Dörwald69652032004-09-07 20:24:22 +00005541 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005542 *consumed = (const char *)q-starts;
Walter Dörwald69652032004-09-07 20:24:22 +00005543
Guido van Rossumd57fd912000-03-10 22:53:23 +00005544 /* Adjust length */
Victor Stinner16e6a802011-12-12 13:24:15 +01005545 if (unicode_resize(&unicode, outpos) < 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005546 goto onError;
5547
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005548 Py_XDECREF(errorHandler);
5549 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01005550 return unicode_result(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005551
Benjamin Peterson29060642009-01-31 22:14:21 +00005552 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00005553 Py_DECREF(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005554 Py_XDECREF(errorHandler);
5555 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005556 return NULL;
5557}
5558
Antoine Pitrouab868312009-01-10 15:40:25 +00005559#undef FAST_CHAR_MASK
5560#undef SWAPPED_FAST_CHAR_MASK
5561
Tim Peters772747b2001-08-09 22:21:55 +00005562PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005563_PyUnicode_EncodeUTF16(PyObject *str,
5564 const char *errors,
5565 int byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005566{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005567 int kind;
5568 void *data;
5569 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005570 PyObject *v;
Tim Peters772747b2001-08-09 22:21:55 +00005571 unsigned char *p;
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005572 Py_ssize_t nsize, bytesize;
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005573 Py_ssize_t i, pairs;
Tim Peters772747b2001-08-09 22:21:55 +00005574 /* Offsets from p for storing byte pairs in the right order. */
5575#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5576 int ihi = 1, ilo = 0;
5577#else
5578 int ihi = 0, ilo = 1;
5579#endif
5580
Benjamin Peterson29060642009-01-31 22:14:21 +00005581#define STORECHAR(CH) \
5582 do { \
5583 p[ihi] = ((CH) >> 8) & 0xff; \
5584 p[ilo] = (CH) & 0xff; \
5585 p += 2; \
Tim Peters772747b2001-08-09 22:21:55 +00005586 } while(0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005587
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005588 if (!PyUnicode_Check(str)) {
5589 PyErr_BadArgument();
5590 return NULL;
5591 }
5592 if (PyUnicode_READY(str) < 0)
5593 return NULL;
5594 kind = PyUnicode_KIND(str);
5595 data = PyUnicode_DATA(str);
5596 len = PyUnicode_GET_LENGTH(str);
Victor Stinner0e368262011-11-10 20:12:49 +01005597
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005598 pairs = 0;
5599 if (kind == PyUnicode_4BYTE_KIND)
5600 for (i = 0; i < len; i++)
5601 if (PyUnicode_READ(kind, data, i) >= 0x10000)
5602 pairs++;
5603 /* 2 * (len + pairs + (byteorder == 0)) */
5604 if (len > PY_SSIZE_T_MAX - pairs - (byteorder == 0))
Benjamin Peterson29060642009-01-31 22:14:21 +00005605 return PyErr_NoMemory();
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005606 nsize = len + pairs + (byteorder == 0);
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005607 bytesize = nsize * 2;
5608 if (bytesize / 2 != nsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005609 return PyErr_NoMemory();
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005610 v = PyBytes_FromStringAndSize(NULL, bytesize);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005611 if (v == NULL)
5612 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005613
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005614 p = (unsigned char *)PyBytes_AS_STRING(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005615 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005616 STORECHAR(0xFEFF);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005617 if (len == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005618 goto done;
Tim Peters772747b2001-08-09 22:21:55 +00005619
5620 if (byteorder == -1) {
5621 /* force LE */
5622 ihi = 1;
5623 ilo = 0;
5624 }
5625 else if (byteorder == 1) {
5626 /* force BE */
5627 ihi = 0;
5628 ilo = 1;
5629 }
5630
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005631 for (i = 0; i < len; i++) {
5632 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
5633 Py_UCS4 ch2 = 0;
Benjamin Peterson29060642009-01-31 22:14:21 +00005634 if (ch >= 0x10000) {
Victor Stinner551ac952011-11-29 22:58:13 +01005635 ch2 = Py_UNICODE_LOW_SURROGATE(ch);
5636 ch = Py_UNICODE_HIGH_SURROGATE(ch);
Benjamin Peterson29060642009-01-31 22:14:21 +00005637 }
Tim Peters772747b2001-08-09 22:21:55 +00005638 STORECHAR(ch);
5639 if (ch2)
5640 STORECHAR(ch2);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005641 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005642
5643 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005644 return v;
Tim Peters772747b2001-08-09 22:21:55 +00005645#undef STORECHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00005646}
5647
Alexander Belopolsky40018472011-02-26 01:02:56 +00005648PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005649PyUnicode_EncodeUTF16(const Py_UNICODE *s,
5650 Py_ssize_t size,
5651 const char *errors,
5652 int byteorder)
5653{
5654 PyObject *result;
5655 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5656 if (tmp == NULL)
5657 return NULL;
5658 result = _PyUnicode_EncodeUTF16(tmp, errors, byteorder);
5659 Py_DECREF(tmp);
5660 return result;
5661}
5662
5663PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005664PyUnicode_AsUTF16String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005665{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005666 return _PyUnicode_EncodeUTF16(unicode, NULL, 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005667}
5668
5669/* --- Unicode Escape Codec ----------------------------------------------- */
5670
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005671/* Helper function for PyUnicode_DecodeUnicodeEscape, determines
5672 if all the escapes in the string make it still a valid ASCII string.
5673 Returns -1 if any escapes were found which cause the string to
5674 pop out of ASCII range. Otherwise returns the length of the
5675 required buffer to hold the string.
5676 */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02005677static Py_ssize_t
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005678length_of_escaped_ascii_string(const char *s, Py_ssize_t size)
5679{
5680 const unsigned char *p = (const unsigned char *)s;
5681 const unsigned char *end = p + size;
5682 Py_ssize_t length = 0;
5683
5684 if (size < 0)
5685 return -1;
5686
5687 for (; p < end; ++p) {
5688 if (*p > 127) {
5689 /* Non-ASCII */
5690 return -1;
5691 }
5692 else if (*p != '\\') {
5693 /* Normal character */
5694 ++length;
5695 }
5696 else {
5697 /* Backslash-escape, check next char */
5698 ++p;
5699 /* Escape sequence reaches till end of string or
5700 non-ASCII follow-up. */
5701 if (p >= end || *p > 127)
5702 return -1;
5703 switch (*p) {
5704 case '\n':
5705 /* backslash + \n result in zero characters */
5706 break;
5707 case '\\': case '\'': case '\"':
5708 case 'b': case 'f': case 't':
5709 case 'n': case 'r': case 'v': case 'a':
5710 ++length;
5711 break;
5712 case '0': case '1': case '2': case '3':
5713 case '4': case '5': case '6': case '7':
5714 case 'x': case 'u': case 'U': case 'N':
5715 /* these do not guarantee ASCII characters */
5716 return -1;
5717 default:
5718 /* count the backslash + the other character */
5719 length += 2;
5720 }
5721 }
5722 }
5723 return length;
5724}
5725
Fredrik Lundh06d12682001-01-24 07:59:11 +00005726static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
Marc-André Lemburg0f774e32000-06-28 16:43:35 +00005727
Alexander Belopolsky40018472011-02-26 01:02:56 +00005728PyObject *
5729PyUnicode_DecodeUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005730 Py_ssize_t size,
Victor Stinnerc17f5402011-09-29 00:16:58 +02005731 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005732{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005733 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005734 Py_ssize_t startinpos;
5735 Py_ssize_t endinpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005736 int j;
Victor Stinner7931d9a2011-11-04 00:22:48 +01005737 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005738 const char *end;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005739 char* message;
5740 Py_UCS4 chr = 0xffffffff; /* in case 'getcode' messes up */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005741 PyObject *errorHandler = NULL;
5742 PyObject *exc = NULL;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005743 Py_ssize_t len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005744 Py_ssize_t i;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005745
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005746 len = length_of_escaped_ascii_string(s, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005747
5748 /* After length_of_escaped_ascii_string() there are two alternatives,
5749 either the string is pure ASCII with named escapes like \n, etc.
5750 and we determined it's exact size (common case)
5751 or it contains \x, \u, ... escape sequences. then we create a
5752 legacy wchar string and resize it at the end of this function. */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005753 if (len >= 0) {
5754 v = PyUnicode_New(len, 127);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005755 if (!v)
5756 goto onError;
5757 assert(PyUnicode_KIND(v) == PyUnicode_1BYTE_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005758 }
5759 else {
5760 /* Escaped strings will always be longer than the resulting
5761 Unicode string, so we start with size here and then reduce the
5762 length after conversion to the true value.
5763 (but if the error callback returns a long replacement string
5764 we'll have to allocate more space) */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005765 v = PyUnicode_New(size, 127);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005766 if (!v)
5767 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005768 len = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005769 }
5770
Guido van Rossumd57fd912000-03-10 22:53:23 +00005771 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01005772 return v;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005773 i = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005774 end = s + size;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005775
Guido van Rossumd57fd912000-03-10 22:53:23 +00005776 while (s < end) {
5777 unsigned char c;
Victor Stinner24729f32011-11-10 20:31:37 +01005778 Py_UCS4 x;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005779 int digits;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005780
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005781 /* The only case in which i == ascii_length is a backslash
5782 followed by a newline. */
5783 assert(i <= len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005784
Guido van Rossumd57fd912000-03-10 22:53:23 +00005785 /* Non-escape characters are interpreted as Unicode ordinals */
5786 if (*s != '\\') {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005787 if (unicode_putchar(&v, &i, (unsigned char) *s++) < 0)
5788 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005789 continue;
5790 }
5791
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005792 startinpos = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005793 /* \ - Escapes */
5794 s++;
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005795 c = *s++;
5796 if (s > end)
5797 c = '\0'; /* Invalid after \ */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005798
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005799 /* The only case in which i == ascii_length is a backslash
5800 followed by a newline. */
5801 assert(i < len || (i == len && c == '\n'));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005802
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005803 switch (c) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005804
Benjamin Peterson29060642009-01-31 22:14:21 +00005805 /* \x escapes */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005806#define WRITECHAR(ch) \
5807 do { \
5808 if (unicode_putchar(&v, &i, ch) < 0) \
5809 goto onError; \
5810 }while(0)
5811
Guido van Rossumd57fd912000-03-10 22:53:23 +00005812 case '\n': break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005813 case '\\': WRITECHAR('\\'); break;
5814 case '\'': WRITECHAR('\''); break;
5815 case '\"': WRITECHAR('\"'); break;
5816 case 'b': WRITECHAR('\b'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005817 /* FF */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005818 case 'f': WRITECHAR('\014'); break;
5819 case 't': WRITECHAR('\t'); break;
5820 case 'n': WRITECHAR('\n'); break;
5821 case 'r': WRITECHAR('\r'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005822 /* VT */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005823 case 'v': WRITECHAR('\013'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005824 /* BEL, not classic C */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005825 case 'a': WRITECHAR('\007'); break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005826
Benjamin Peterson29060642009-01-31 22:14:21 +00005827 /* \OOO (octal) escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005828 case '0': case '1': case '2': case '3':
5829 case '4': case '5': case '6': case '7':
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005830 x = s[-1] - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005831 if (s < end && '0' <= *s && *s <= '7') {
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005832 x = (x<<3) + *s++ - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005833 if (s < end && '0' <= *s && *s <= '7')
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005834 x = (x<<3) + *s++ - '0';
Guido van Rossumd57fd912000-03-10 22:53:23 +00005835 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005836 WRITECHAR(x);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005837 break;
5838
Benjamin Peterson29060642009-01-31 22:14:21 +00005839 /* hex escapes */
5840 /* \xXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005841 case 'x':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005842 digits = 2;
5843 message = "truncated \\xXX escape";
5844 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005845
Benjamin Peterson29060642009-01-31 22:14:21 +00005846 /* \uXXXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005847 case 'u':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005848 digits = 4;
5849 message = "truncated \\uXXXX escape";
5850 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005851
Benjamin Peterson29060642009-01-31 22:14:21 +00005852 /* \UXXXXXXXX */
Fredrik Lundhdf846752000-09-03 11:29:49 +00005853 case 'U':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005854 digits = 8;
5855 message = "truncated \\UXXXXXXXX escape";
5856 hexescape:
5857 chr = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005858 if (s+digits>end) {
5859 endinpos = size;
5860 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005861 errors, &errorHandler,
5862 "unicodeescape", "end of string in escape sequence",
5863 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005864 &v, &i))
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005865 goto onError;
5866 goto nextByte;
5867 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005868 for (j = 0; j < digits; ++j) {
5869 c = (unsigned char) s[j];
David Malcolm96960882010-11-05 17:23:41 +00005870 if (!Py_ISXDIGIT(c)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005871 endinpos = (s+j+1)-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005872 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005873 errors, &errorHandler,
5874 "unicodeescape", message,
5875 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005876 &v, &i))
Fredrik Lundhdf846752000-09-03 11:29:49 +00005877 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005878 len = PyUnicode_GET_LENGTH(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005879 goto nextByte;
Fredrik Lundhdf846752000-09-03 11:29:49 +00005880 }
5881 chr = (chr<<4) & ~0xF;
5882 if (c >= '0' && c <= '9')
5883 chr += c - '0';
5884 else if (c >= 'a' && c <= 'f')
5885 chr += 10 + c - 'a';
5886 else
5887 chr += 10 + c - 'A';
5888 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005889 s += j;
Jeremy Hylton504de6b2003-10-06 05:08:26 +00005890 if (chr == 0xffffffff && PyErr_Occurred())
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005891 /* _decoding_error will have already written into the
5892 target buffer. */
5893 break;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005894 store:
Fredrik Lundhdf846752000-09-03 11:29:49 +00005895 /* when we get here, chr is a 32-bit unicode character */
Victor Stinner8faf8212011-12-08 22:14:11 +01005896 if (chr <= MAX_UNICODE) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005897 WRITECHAR(chr);
Fredrik Lundhdf846752000-09-03 11:29:49 +00005898 } else {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005899 endinpos = s-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005900 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005901 errors, &errorHandler,
5902 "unicodeescape", "illegal Unicode character",
5903 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005904 &v, &i))
Fredrik Lundhdf846752000-09-03 11:29:49 +00005905 goto onError;
5906 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00005907 break;
5908
Benjamin Peterson29060642009-01-31 22:14:21 +00005909 /* \N{name} */
Fredrik Lundhccc74732001-02-18 22:13:49 +00005910 case 'N':
5911 message = "malformed \\N character escape";
5912 if (ucnhash_CAPI == NULL) {
5913 /* load the unicode data module */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005914 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
5915 PyUnicodeData_CAPSULE_NAME, 1);
Fredrik Lundhccc74732001-02-18 22:13:49 +00005916 if (ucnhash_CAPI == NULL)
5917 goto ucnhashError;
5918 }
5919 if (*s == '{') {
5920 const char *start = s+1;
5921 /* look for the closing brace */
5922 while (*s != '}' && s < end)
5923 s++;
5924 if (s > start && s < end && *s == '}') {
5925 /* found a name. look it up in the unicode database */
5926 message = "unknown Unicode character name";
5927 s++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005928 if (ucnhash_CAPI->getcode(NULL, start, (int)(s-start-1),
Ezio Melotti931b8aa2011-10-21 21:57:36 +03005929 &chr, 0))
Fredrik Lundhccc74732001-02-18 22:13:49 +00005930 goto store;
5931 }
5932 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005933 endinpos = s-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005934 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005935 errors, &errorHandler,
5936 "unicodeescape", message,
5937 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005938 &v, &i))
Fredrik Lundhccc74732001-02-18 22:13:49 +00005939 goto onError;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005940 break;
5941
5942 default:
Walter Dörwald8c077222002-03-25 11:16:18 +00005943 if (s > end) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005944 message = "\\ at end of string";
5945 s--;
5946 endinpos = s-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005947 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005948 errors, &errorHandler,
5949 "unicodeescape", message,
5950 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005951 &v, &i))
Walter Dörwald8c077222002-03-25 11:16:18 +00005952 goto onError;
5953 }
5954 else {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005955 WRITECHAR('\\');
5956 WRITECHAR(s[-1]);
Walter Dörwald8c077222002-03-25 11:16:18 +00005957 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00005958 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005959 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005960 nextByte:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005961 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005962 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005963#undef WRITECHAR
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005964
Victor Stinner16e6a802011-12-12 13:24:15 +01005965 if (unicode_resize(&v, i) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005966 goto onError;
Walter Dörwaldd4ade082003-08-15 15:00:26 +00005967 Py_XDECREF(errorHandler);
5968 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01005969 return unicode_result(v);
Walter Dörwald8c077222002-03-25 11:16:18 +00005970
Benjamin Peterson29060642009-01-31 22:14:21 +00005971 ucnhashError:
Fredrik Lundh06d12682001-01-24 07:59:11 +00005972 PyErr_SetString(
5973 PyExc_UnicodeError,
5974 "\\N escapes not supported (can't load unicodedata module)"
5975 );
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00005976 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005977 Py_XDECREF(errorHandler);
5978 Py_XDECREF(exc);
Fredrik Lundhf6056062001-01-20 11:15:25 +00005979 return NULL;
5980
Benjamin Peterson29060642009-01-31 22:14:21 +00005981 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00005982 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005983 Py_XDECREF(errorHandler);
5984 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005985 return NULL;
5986}
5987
5988/* Return a Unicode-Escape string version of the Unicode object.
5989
5990 If quotes is true, the string is enclosed in u"" or u'' quotes as
5991 appropriate.
5992
5993*/
5994
Alexander Belopolsky40018472011-02-26 01:02:56 +00005995PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005996PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005997{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005998 Py_ssize_t i, len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005999 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006000 char *p;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006001 int kind;
6002 void *data;
6003 Py_ssize_t expandsize = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006004
Thomas Wouters89f507f2006-12-13 04:49:30 +00006005 /* Initial allocation is based on the longest-possible unichr
6006 escape.
6007
6008 In wide (UTF-32) builds '\U00xxxxxx' is 10 chars per source
6009 unichr, so in this case it's the longest unichr escape. In
6010 narrow (UTF-16) builds this is five chars per source unichr
6011 since there are two unichrs in the surrogate pair, so in narrow
6012 (UTF-16) builds it's not the longest unichr escape.
6013
6014 In wide or narrow builds '\uxxxx' is 6 chars per source unichr,
6015 so in the narrow (UTF-16) build case it's the longest unichr
6016 escape.
6017 */
6018
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006019 if (!PyUnicode_Check(unicode)) {
6020 PyErr_BadArgument();
6021 return NULL;
6022 }
6023 if (PyUnicode_READY(unicode) < 0)
6024 return NULL;
6025 len = PyUnicode_GET_LENGTH(unicode);
6026 kind = PyUnicode_KIND(unicode);
6027 data = PyUnicode_DATA(unicode);
Benjamin Petersonead6b532011-12-20 17:23:42 -06006028 switch (kind) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006029 case PyUnicode_1BYTE_KIND: expandsize = 4; break;
6030 case PyUnicode_2BYTE_KIND: expandsize = 6; break;
6031 case PyUnicode_4BYTE_KIND: expandsize = 10; break;
6032 }
6033
6034 if (len == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006035 return PyBytes_FromStringAndSize(NULL, 0);
6036
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006037 if (len > (PY_SSIZE_T_MAX - 2 - 1) / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00006038 return PyErr_NoMemory();
Neal Norwitz3ce5d922008-08-24 07:08:55 +00006039
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006040 repr = PyBytes_FromStringAndSize(NULL,
Benjamin Peterson29060642009-01-31 22:14:21 +00006041 2
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006042 + expandsize*len
Benjamin Peterson29060642009-01-31 22:14:21 +00006043 + 1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006044 if (repr == NULL)
6045 return NULL;
6046
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006047 p = PyBytes_AS_STRING(repr);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006048
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006049 for (i = 0; i < len; i++) {
Victor Stinner3326cb62011-11-10 20:15:25 +01006050 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006051
Walter Dörwald79e913e2007-05-12 11:08:06 +00006052 /* Escape backslashes */
6053 if (ch == '\\') {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006054 *p++ = '\\';
6055 *p++ = (char) ch;
Walter Dörwald79e913e2007-05-12 11:08:06 +00006056 continue;
Tim Petersced69f82003-09-16 20:30:58 +00006057 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006058
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00006059 /* Map 21-bit characters to '\U00xxxxxx' */
6060 else if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01006061 assert(ch <= MAX_UNICODE);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00006062 *p++ = '\\';
6063 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006064 *p++ = Py_hexdigits[(ch >> 28) & 0x0000000F];
6065 *p++ = Py_hexdigits[(ch >> 24) & 0x0000000F];
6066 *p++ = Py_hexdigits[(ch >> 20) & 0x0000000F];
6067 *p++ = Py_hexdigits[(ch >> 16) & 0x0000000F];
6068 *p++ = Py_hexdigits[(ch >> 12) & 0x0000000F];
6069 *p++ = Py_hexdigits[(ch >> 8) & 0x0000000F];
6070 *p++ = Py_hexdigits[(ch >> 4) & 0x0000000F];
6071 *p++ = Py_hexdigits[ch & 0x0000000F];
Benjamin Peterson29060642009-01-31 22:14:21 +00006072 continue;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00006073 }
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00006074
Guido van Rossumd57fd912000-03-10 22:53:23 +00006075 /* Map 16-bit characters to '\uxxxx' */
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00006076 if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006077 *p++ = '\\';
6078 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006079 *p++ = Py_hexdigits[(ch >> 12) & 0x000F];
6080 *p++ = Py_hexdigits[(ch >> 8) & 0x000F];
6081 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6082 *p++ = Py_hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006083 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006084
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006085 /* Map special whitespace to '\t', \n', '\r' */
6086 else if (ch == '\t') {
6087 *p++ = '\\';
6088 *p++ = 't';
6089 }
6090 else if (ch == '\n') {
6091 *p++ = '\\';
6092 *p++ = 'n';
6093 }
6094 else if (ch == '\r') {
6095 *p++ = '\\';
6096 *p++ = 'r';
6097 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006098
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006099 /* Map non-printable US ASCII to '\xhh' */
Marc-André Lemburg11326de2001-11-28 12:56:20 +00006100 else if (ch < ' ' || ch >= 0x7F) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006101 *p++ = '\\';
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006102 *p++ = 'x';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006103 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6104 *p++ = Py_hexdigits[ch & 0x000F];
Tim Petersced69f82003-09-16 20:30:58 +00006105 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006106
Guido van Rossumd57fd912000-03-10 22:53:23 +00006107 /* Copy everything else as-is */
6108 else
6109 *p++ = (char) ch;
6110 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006111
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006112 assert(p - PyBytes_AS_STRING(repr) > 0);
6113 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0)
6114 return NULL;
6115 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006116}
6117
Alexander Belopolsky40018472011-02-26 01:02:56 +00006118PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006119PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
6120 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006121{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006122 PyObject *result;
6123 PyObject *tmp = PyUnicode_FromUnicode(s, size);
6124 if (tmp == NULL)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006125 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006126 result = PyUnicode_AsUnicodeEscapeString(tmp);
6127 Py_DECREF(tmp);
6128 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006129}
6130
6131/* --- Raw Unicode Escape Codec ------------------------------------------- */
6132
Alexander Belopolsky40018472011-02-26 01:02:56 +00006133PyObject *
6134PyUnicode_DecodeRawUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006135 Py_ssize_t size,
6136 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006137{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006138 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006139 Py_ssize_t startinpos;
6140 Py_ssize_t endinpos;
6141 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01006142 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006143 const char *end;
6144 const char *bs;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006145 PyObject *errorHandler = NULL;
6146 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006147
Guido van Rossumd57fd912000-03-10 22:53:23 +00006148 /* Escaped strings will always be longer than the resulting
6149 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006150 length after conversion to the true value. (But decoding error
6151 handler might have to resize the string) */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006152 v = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006153 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006154 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006155 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01006156 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006157 outpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006158 end = s + size;
6159 while (s < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006160 unsigned char c;
6161 Py_UCS4 x;
6162 int i;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006163 int count;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006164
Benjamin Peterson29060642009-01-31 22:14:21 +00006165 /* Non-escape characters are interpreted as Unicode ordinals */
6166 if (*s != '\\') {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006167 if (unicode_putchar(&v, &outpos, (unsigned char)*s++) < 0)
6168 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00006169 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006170 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006171 startinpos = s-starts;
6172
6173 /* \u-escapes are only interpreted iff the number of leading
6174 backslashes if odd */
6175 bs = s;
6176 for (;s < end;) {
6177 if (*s != '\\')
6178 break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006179 if (unicode_putchar(&v, &outpos, (unsigned char)*s++) < 0)
6180 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00006181 }
6182 if (((s - bs) & 1) == 0 ||
6183 s >= end ||
6184 (*s != 'u' && *s != 'U')) {
6185 continue;
6186 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006187 outpos--;
Benjamin Peterson29060642009-01-31 22:14:21 +00006188 count = *s=='u' ? 4 : 8;
6189 s++;
6190
6191 /* \uXXXX with 4 hex digits, \Uxxxxxxxx with 8 */
Benjamin Peterson29060642009-01-31 22:14:21 +00006192 for (x = 0, i = 0; i < count; ++i, ++s) {
6193 c = (unsigned char)*s;
David Malcolm96960882010-11-05 17:23:41 +00006194 if (!Py_ISXDIGIT(c)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006195 endinpos = s-starts;
6196 if (unicode_decode_call_errorhandler(
6197 errors, &errorHandler,
6198 "rawunicodeescape", "truncated \\uXXXX",
6199 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006200 &v, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00006201 goto onError;
6202 goto nextByte;
6203 }
6204 x = (x<<4) & ~0xF;
6205 if (c >= '0' && c <= '9')
6206 x += c - '0';
6207 else if (c >= 'a' && c <= 'f')
6208 x += 10 + c - 'a';
6209 else
6210 x += 10 + c - 'A';
6211 }
Victor Stinner8faf8212011-12-08 22:14:11 +01006212 if (x <= MAX_UNICODE) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006213 if (unicode_putchar(&v, &outpos, x) < 0)
6214 goto onError;
Christian Heimesfe337bf2008-03-23 21:54:12 +00006215 } else {
6216 endinpos = s-starts;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006217 if (unicode_decode_call_errorhandler(
6218 errors, &errorHandler,
6219 "rawunicodeescape", "\\Uxxxxxxxx out of range",
Benjamin Peterson29060642009-01-31 22:14:21 +00006220 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006221 &v, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00006222 goto onError;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006223 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006224 nextByte:
6225 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006226 }
Victor Stinner16e6a802011-12-12 13:24:15 +01006227 if (unicode_resize(&v, outpos) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006228 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006229 Py_XDECREF(errorHandler);
6230 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006231 return unicode_result(v);
Tim Petersced69f82003-09-16 20:30:58 +00006232
Benjamin Peterson29060642009-01-31 22:14:21 +00006233 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00006234 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006235 Py_XDECREF(errorHandler);
6236 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006237 return NULL;
6238}
6239
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006240
Alexander Belopolsky40018472011-02-26 01:02:56 +00006241PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006242PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006243{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006244 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006245 char *p;
6246 char *q;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006247 Py_ssize_t expandsize, pos;
6248 int kind;
6249 void *data;
6250 Py_ssize_t len;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006251
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006252 if (!PyUnicode_Check(unicode)) {
6253 PyErr_BadArgument();
6254 return NULL;
6255 }
6256 if (PyUnicode_READY(unicode) < 0)
6257 return NULL;
6258 kind = PyUnicode_KIND(unicode);
6259 data = PyUnicode_DATA(unicode);
6260 len = PyUnicode_GET_LENGTH(unicode);
Benjamin Peterson1518e872011-11-23 10:44:52 -06006261 /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6
6262 bytes, and 1 byte characters 4. */
6263 expandsize = kind * 2 + 2;
Victor Stinner0e368262011-11-10 20:12:49 +01006264
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006265 if (len > PY_SSIZE_T_MAX / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00006266 return PyErr_NoMemory();
Benjamin Peterson14339b62009-01-31 16:36:08 +00006267
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006268 repr = PyBytes_FromStringAndSize(NULL, expandsize * len);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006269 if (repr == NULL)
6270 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006271 if (len == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006272 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006273
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006274 p = q = PyBytes_AS_STRING(repr);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006275 for (pos = 0; pos < len; pos++) {
6276 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Benjamin Peterson29060642009-01-31 22:14:21 +00006277 /* Map 32-bit characters to '\Uxxxxxxxx' */
6278 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01006279 assert(ch <= MAX_UNICODE);
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006280 *p++ = '\\';
6281 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006282 *p++ = Py_hexdigits[(ch >> 28) & 0xf];
6283 *p++ = Py_hexdigits[(ch >> 24) & 0xf];
6284 *p++ = Py_hexdigits[(ch >> 20) & 0xf];
6285 *p++ = Py_hexdigits[(ch >> 16) & 0xf];
6286 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6287 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6288 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6289 *p++ = Py_hexdigits[ch & 15];
Tim Petersced69f82003-09-16 20:30:58 +00006290 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006291 /* Map 16-bit characters to '\uxxxx' */
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006292 else if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006293 *p++ = '\\';
6294 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006295 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6296 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6297 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6298 *p++ = Py_hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006299 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006300 /* Copy everything else as-is */
6301 else
Guido van Rossumd57fd912000-03-10 22:53:23 +00006302 *p++ = (char) ch;
6303 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00006304
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006305 assert(p > q);
6306 if (_PyBytes_Resize(&repr, p - q) < 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006307 return NULL;
6308 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006309}
6310
Alexander Belopolsky40018472011-02-26 01:02:56 +00006311PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006312PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
6313 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006314{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006315 PyObject *result;
6316 PyObject *tmp = PyUnicode_FromUnicode(s, size);
6317 if (tmp == NULL)
Walter Dörwald711005d2007-05-12 12:03:26 +00006318 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006319 result = PyUnicode_AsRawUnicodeEscapeString(tmp);
6320 Py_DECREF(tmp);
6321 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006322}
6323
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006324/* --- Unicode Internal Codec ------------------------------------------- */
6325
Alexander Belopolsky40018472011-02-26 01:02:56 +00006326PyObject *
6327_PyUnicode_DecodeUnicodeInternal(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006328 Py_ssize_t size,
6329 const char *errors)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006330{
6331 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006332 Py_ssize_t startinpos;
6333 Py_ssize_t endinpos;
6334 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01006335 PyObject *v;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006336 const char *end;
6337 const char *reason;
6338 PyObject *errorHandler = NULL;
6339 PyObject *exc = NULL;
6340
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006341 if (PyErr_WarnEx(PyExc_DeprecationWarning,
Ezio Melotti11060a42011-11-16 09:39:10 +02006342 "unicode_internal codec has been deprecated",
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006343 1))
6344 return NULL;
6345
Thomas Wouters89f507f2006-12-13 04:49:30 +00006346 /* XXX overflow detection missing */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006347 v = PyUnicode_New((size+Py_UNICODE_SIZE-1)/ Py_UNICODE_SIZE, 127);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006348 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006349 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006350 if (PyUnicode_GET_LENGTH(v) == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01006351 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006352 outpos = 0;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006353 end = s + size;
6354
6355 while (s < end) {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006356 Py_UNICODE uch;
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006357 Py_UCS4 ch;
6358 /* We copy the raw representation one byte at a time because the
6359 pointer may be unaligned (see test_codeccallbacks). */
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006360 ((char *) &uch)[0] = s[0];
6361 ((char *) &uch)[1] = s[1];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006362#ifdef Py_UNICODE_WIDE
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006363 ((char *) &uch)[2] = s[2];
6364 ((char *) &uch)[3] = s[3];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006365#endif
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006366 ch = uch;
6367
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006368 /* We have to sanity check the raw data, otherwise doom looms for
6369 some malformed UCS-4 data. */
6370 if (
Benjamin Peterson29060642009-01-31 22:14:21 +00006371#ifdef Py_UNICODE_WIDE
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006372 ch > 0x10ffff ||
Benjamin Peterson29060642009-01-31 22:14:21 +00006373#endif
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006374 end-s < Py_UNICODE_SIZE
6375 )
Benjamin Peterson29060642009-01-31 22:14:21 +00006376 {
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006377 startinpos = s - starts;
6378 if (end-s < Py_UNICODE_SIZE) {
6379 endinpos = end-starts;
6380 reason = "truncated input";
6381 }
6382 else {
6383 endinpos = s - starts + Py_UNICODE_SIZE;
6384 reason = "illegal code point (> 0x10FFFF)";
6385 }
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006386 if (unicode_decode_call_errorhandler(
6387 errors, &errorHandler,
6388 "unicode_internal", reason,
Walter Dörwalde78178e2007-07-30 13:31:40 +00006389 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006390 &v, &outpos))
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006391 goto onError;
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006392 continue;
6393 }
6394
6395 s += Py_UNICODE_SIZE;
6396#ifndef Py_UNICODE_WIDE
Victor Stinner551ac952011-11-29 22:58:13 +01006397 if (Py_UNICODE_IS_HIGH_SURROGATE(ch) && s < end)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006398 {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006399 Py_UNICODE uch2;
6400 ((char *) &uch2)[0] = s[0];
6401 ((char *) &uch2)[1] = s[1];
Victor Stinner551ac952011-11-29 22:58:13 +01006402 if (Py_UNICODE_IS_LOW_SURROGATE(uch2))
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006403 {
Victor Stinner551ac952011-11-29 22:58:13 +01006404 ch = Py_UNICODE_JOIN_SURROGATES(uch, uch2);
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006405 s += Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006406 }
6407 }
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006408#endif
6409
6410 if (unicode_putchar(&v, &outpos, ch) < 0)
6411 goto onError;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006412 }
6413
Victor Stinner16e6a802011-12-12 13:24:15 +01006414 if (unicode_resize(&v, outpos) < 0)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006415 goto onError;
6416 Py_XDECREF(errorHandler);
6417 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006418 return unicode_result(v);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006419
Benjamin Peterson29060642009-01-31 22:14:21 +00006420 onError:
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006421 Py_XDECREF(v);
6422 Py_XDECREF(errorHandler);
6423 Py_XDECREF(exc);
6424 return NULL;
6425}
6426
Guido van Rossumd57fd912000-03-10 22:53:23 +00006427/* --- Latin-1 Codec ------------------------------------------------------ */
6428
Alexander Belopolsky40018472011-02-26 01:02:56 +00006429PyObject *
6430PyUnicode_DecodeLatin1(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006431 Py_ssize_t size,
6432 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006433{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006434 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Victor Stinnere57b1c02011-09-28 22:20:48 +02006435 return _PyUnicode_FromUCS1((unsigned char*)s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006436}
6437
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006438/* create or adjust a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006439static void
6440make_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006441 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006442 PyObject *unicode,
6443 Py_ssize_t startpos, Py_ssize_t endpos,
6444 const char *reason)
6445{
6446 if (*exceptionObject == NULL) {
6447 *exceptionObject = PyObject_CallFunction(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006448 PyExc_UnicodeEncodeError, "sOnns",
Martin v. Löwis9e816682011-11-02 12:45:42 +01006449 encoding, unicode, startpos, endpos, reason);
6450 }
6451 else {
6452 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
6453 goto onError;
6454 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
6455 goto onError;
6456 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
6457 goto onError;
6458 return;
6459 onError:
6460 Py_DECREF(*exceptionObject);
6461 *exceptionObject = NULL;
6462 }
6463}
6464
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006465/* raises a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006466static void
6467raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006468 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006469 PyObject *unicode,
6470 Py_ssize_t startpos, Py_ssize_t endpos,
6471 const char *reason)
6472{
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006473 make_encode_exception(exceptionObject,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006474 encoding, unicode, startpos, endpos, reason);
6475 if (*exceptionObject != NULL)
6476 PyCodec_StrictErrors(*exceptionObject);
6477}
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006478
6479/* error handling callback helper:
6480 build arguments, call the callback and check the arguments,
6481 put the result into newpos and return the replacement string, which
6482 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006483static PyObject *
6484unicode_encode_call_errorhandler(const char *errors,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006485 PyObject **errorHandler,
6486 const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006487 PyObject *unicode, PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006488 Py_ssize_t startpos, Py_ssize_t endpos,
6489 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006490{
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006491 static char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006492 Py_ssize_t len;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006493 PyObject *restuple;
6494 PyObject *resunicode;
6495
6496 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006497 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006498 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006499 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006500 }
6501
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006502 if (PyUnicode_READY(unicode) < 0)
6503 return NULL;
6504 len = PyUnicode_GET_LENGTH(unicode);
6505
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006506 make_encode_exception(exceptionObject,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006507 encoding, unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006508 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006509 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006510
6511 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00006512 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006513 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006514 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006515 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006516 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00006517 Py_DECREF(restuple);
6518 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006519 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006520 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00006521 &resunicode, newpos)) {
6522 Py_DECREF(restuple);
6523 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006524 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006525 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
6526 PyErr_SetString(PyExc_TypeError, &argparse[3]);
6527 Py_DECREF(restuple);
6528 return NULL;
6529 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006530 if (*newpos<0)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006531 *newpos = len + *newpos;
6532 if (*newpos<0 || *newpos>len) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006533 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
6534 Py_DECREF(restuple);
6535 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00006536 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006537 Py_INCREF(resunicode);
6538 Py_DECREF(restuple);
6539 return resunicode;
6540}
6541
Alexander Belopolsky40018472011-02-26 01:02:56 +00006542static PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006543unicode_encode_ucs1(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006544 const char *errors,
Victor Stinnerfcd96532011-11-04 00:28:50 +01006545 unsigned int limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006546{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006547 /* input state */
6548 Py_ssize_t pos=0, size;
6549 int kind;
6550 void *data;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006551 /* output object */
6552 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006553 /* pointer into the output */
6554 char *str;
6555 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00006556 Py_ssize_t ressize;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006557 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
6558 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006559 PyObject *errorHandler = NULL;
6560 PyObject *exc = NULL;
6561 /* the following variable is used for caching string comparisons
6562 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
6563 int known_errorHandler = -1;
6564
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006565 if (PyUnicode_READY(unicode) < 0)
6566 return NULL;
6567 size = PyUnicode_GET_LENGTH(unicode);
6568 kind = PyUnicode_KIND(unicode);
6569 data = PyUnicode_DATA(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006570 /* allocate enough for a simple encoding without
6571 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00006572 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00006573 return PyBytes_FromStringAndSize(NULL, 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006574 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006575 if (res == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00006576 return NULL;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006577 str = PyBytes_AS_STRING(res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006578 ressize = size;
6579
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006580 while (pos < size) {
6581 Py_UCS4 c = PyUnicode_READ(kind, data, pos);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006582
Benjamin Peterson29060642009-01-31 22:14:21 +00006583 /* can we encode this? */
6584 if (c<limit) {
6585 /* no overflow check, because we know that the space is enough */
6586 *str++ = (char)c;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006587 ++pos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006588 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006589 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006590 Py_ssize_t requiredsize;
6591 PyObject *repunicode;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006592 Py_ssize_t repsize, newpos, respos, i;
Benjamin Peterson29060642009-01-31 22:14:21 +00006593 /* startpos for collecting unencodable chars */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006594 Py_ssize_t collstart = pos;
6595 Py_ssize_t collend = pos;
Benjamin Peterson29060642009-01-31 22:14:21 +00006596 /* find all unecodable characters */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006597 while ((collend < size) && (PyUnicode_READ(kind, data, collend)>=limit))
Benjamin Peterson29060642009-01-31 22:14:21 +00006598 ++collend;
6599 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
6600 if (known_errorHandler==-1) {
6601 if ((errors==NULL) || (!strcmp(errors, "strict")))
6602 known_errorHandler = 1;
6603 else if (!strcmp(errors, "replace"))
6604 known_errorHandler = 2;
6605 else if (!strcmp(errors, "ignore"))
6606 known_errorHandler = 3;
6607 else if (!strcmp(errors, "xmlcharrefreplace"))
6608 known_errorHandler = 4;
6609 else
6610 known_errorHandler = 0;
6611 }
6612 switch (known_errorHandler) {
6613 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006614 raise_encode_exception(&exc, encoding, unicode, collstart, collend, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006615 goto onError;
6616 case 2: /* replace */
6617 while (collstart++<collend)
6618 *str++ = '?'; /* fall through */
6619 case 3: /* ignore */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006620 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006621 break;
6622 case 4: /* xmlcharrefreplace */
6623 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006624 /* determine replacement size */
6625 for (i = collstart, repsize = 0; i < collend; ++i) {
6626 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
6627 if (ch < 10)
Benjamin Peterson29060642009-01-31 22:14:21 +00006628 repsize += 2+1+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006629 else if (ch < 100)
Benjamin Peterson29060642009-01-31 22:14:21 +00006630 repsize += 2+2+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006631 else if (ch < 1000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006632 repsize += 2+3+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006633 else if (ch < 10000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006634 repsize += 2+4+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006635 else if (ch < 100000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006636 repsize += 2+5+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006637 else if (ch < 1000000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006638 repsize += 2+6+1;
Victor Stinner0d3721d2011-11-22 03:27:53 +01006639 else {
Victor Stinner8faf8212011-12-08 22:14:11 +01006640 assert(ch <= MAX_UNICODE);
Benjamin Peterson29060642009-01-31 22:14:21 +00006641 repsize += 2+7+1;
Victor Stinner0d3721d2011-11-22 03:27:53 +01006642 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006643 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006644 requiredsize = respos+repsize+(size-collend);
Benjamin Peterson29060642009-01-31 22:14:21 +00006645 if (requiredsize > ressize) {
6646 if (requiredsize<2*ressize)
6647 requiredsize = 2*ressize;
6648 if (_PyBytes_Resize(&res, requiredsize))
6649 goto onError;
6650 str = PyBytes_AS_STRING(res) + respos;
6651 ressize = requiredsize;
6652 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006653 /* generate replacement */
6654 for (i = collstart; i < collend; ++i) {
6655 str += sprintf(str, "&#%d;", PyUnicode_READ(kind, data, i));
Benjamin Peterson29060642009-01-31 22:14:21 +00006656 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006657 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006658 break;
6659 default:
6660 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006661 encoding, reason, unicode, &exc,
6662 collstart, collend, &newpos);
6663 if (repunicode == NULL || (PyUnicode_Check(repunicode) &&
6664 PyUnicode_READY(repunicode) < 0))
Benjamin Peterson29060642009-01-31 22:14:21 +00006665 goto onError;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006666 if (PyBytes_Check(repunicode)) {
6667 /* Directly copy bytes result to output. */
6668 repsize = PyBytes_Size(repunicode);
6669 if (repsize > 1) {
6670 /* Make room for all additional bytes. */
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006671 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006672 if (_PyBytes_Resize(&res, ressize+repsize-1)) {
6673 Py_DECREF(repunicode);
6674 goto onError;
6675 }
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006676 str = PyBytes_AS_STRING(res) + respos;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006677 ressize += repsize-1;
6678 }
6679 memcpy(str, PyBytes_AsString(repunicode), repsize);
6680 str += repsize;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006681 pos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006682 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006683 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006684 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006685 /* need more space? (at least enough for what we
6686 have+the replacement+the rest of the string, so
6687 we won't have to check space for encodable characters) */
6688 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006689 repsize = PyUnicode_GET_LENGTH(repunicode);
6690 requiredsize = respos+repsize+(size-collend);
Benjamin Peterson29060642009-01-31 22:14:21 +00006691 if (requiredsize > ressize) {
6692 if (requiredsize<2*ressize)
6693 requiredsize = 2*ressize;
6694 if (_PyBytes_Resize(&res, requiredsize)) {
6695 Py_DECREF(repunicode);
6696 goto onError;
6697 }
6698 str = PyBytes_AS_STRING(res) + respos;
6699 ressize = requiredsize;
6700 }
6701 /* check if there is anything unencodable in the replacement
6702 and copy it to the output */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006703 for (i = 0; repsize-->0; ++i, ++str) {
6704 c = PyUnicode_READ_CHAR(repunicode, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00006705 if (c >= limit) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006706 raise_encode_exception(&exc, encoding, unicode,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006707 pos, pos+1, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006708 Py_DECREF(repunicode);
6709 goto onError;
6710 }
6711 *str = (char)c;
6712 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006713 pos = newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006714 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006715 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00006716 }
6717 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006718 /* Resize if we allocated to much */
6719 size = str - PyBytes_AS_STRING(res);
6720 if (size < ressize) { /* If this falls res will be NULL */
Alexandre Vassalottibad1b922008-12-27 09:49:09 +00006721 assert(size >= 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006722 if (_PyBytes_Resize(&res, size) < 0)
6723 goto onError;
6724 }
6725
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006726 Py_XDECREF(errorHandler);
6727 Py_XDECREF(exc);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006728 return res;
6729
6730 onError:
6731 Py_XDECREF(res);
6732 Py_XDECREF(errorHandler);
6733 Py_XDECREF(exc);
6734 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006735}
6736
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006737/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006738PyObject *
6739PyUnicode_EncodeLatin1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006740 Py_ssize_t size,
6741 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006742{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006743 PyObject *result;
6744 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6745 if (unicode == NULL)
6746 return NULL;
6747 result = unicode_encode_ucs1(unicode, errors, 256);
6748 Py_DECREF(unicode);
6749 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006750}
6751
Alexander Belopolsky40018472011-02-26 01:02:56 +00006752PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006753_PyUnicode_AsLatin1String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006754{
6755 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006756 PyErr_BadArgument();
6757 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006758 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006759 if (PyUnicode_READY(unicode) == -1)
6760 return NULL;
6761 /* Fast path: if it is a one-byte string, construct
6762 bytes object directly. */
6763 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND)
6764 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6765 PyUnicode_GET_LENGTH(unicode));
6766 /* Non-Latin-1 characters present. Defer to above function to
6767 raise the exception. */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006768 return unicode_encode_ucs1(unicode, errors, 256);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006769}
6770
6771PyObject*
6772PyUnicode_AsLatin1String(PyObject *unicode)
6773{
6774 return _PyUnicode_AsLatin1String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006775}
6776
6777/* --- 7-bit ASCII Codec -------------------------------------------------- */
6778
Alexander Belopolsky40018472011-02-26 01:02:56 +00006779PyObject *
6780PyUnicode_DecodeASCII(const char *s,
6781 Py_ssize_t size,
6782 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006783{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006784 const char *starts = s;
Victor Stinner7931d9a2011-11-04 00:22:48 +01006785 PyObject *v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006786 int kind;
6787 void *data;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006788 Py_ssize_t startinpos;
6789 Py_ssize_t endinpos;
6790 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006791 const char *e;
Victor Stinner702c7342011-10-05 13:50:52 +02006792 int has_error;
6793 const unsigned char *p = (const unsigned char *)s;
6794 const unsigned char *end = p + size;
6795 const unsigned char *aligned_end = (const unsigned char *) ((size_t) end & ~LONG_PTR_MASK);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006796 PyObject *errorHandler = NULL;
6797 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006798
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006799 if (size == 0) {
6800 Py_INCREF(unicode_empty);
6801 return unicode_empty;
6802 }
6803
Guido van Rossumd57fd912000-03-10 22:53:23 +00006804 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Victor Stinner702c7342011-10-05 13:50:52 +02006805 if (size == 1 && (unsigned char)s[0] < 128)
6806 return get_latin1_char((unsigned char)s[0]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006807
Victor Stinner702c7342011-10-05 13:50:52 +02006808 has_error = 0;
6809 while (p < end && !has_error) {
6810 /* Fast path, see below in PyUnicode_DecodeUTF8Stateful for
6811 an explanation. */
6812 if (!((size_t) p & LONG_PTR_MASK)) {
6813 /* Help register allocation */
6814 register const unsigned char *_p = p;
6815 while (_p < aligned_end) {
6816 unsigned long value = *(unsigned long *) _p;
6817 if (value & ASCII_CHAR_MASK) {
6818 has_error = 1;
6819 break;
6820 }
6821 _p += SIZEOF_LONG;
6822 }
6823 if (_p == end)
6824 break;
6825 if (has_error)
6826 break;
6827 p = _p;
6828 }
6829 if (*p & 0x80) {
6830 has_error = 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006831 break;
Victor Stinner702c7342011-10-05 13:50:52 +02006832 }
6833 else {
6834 ++p;
6835 }
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00006836 }
Victor Stinner702c7342011-10-05 13:50:52 +02006837 if (!has_error)
6838 return unicode_fromascii((const unsigned char *)s, size);
Tim Petersced69f82003-09-16 20:30:58 +00006839
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006840 v = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006841 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006842 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006843 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01006844 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006845 kind = PyUnicode_KIND(v);
6846 data = PyUnicode_DATA(v);
6847 outpos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006848 e = s + size;
6849 while (s < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006850 register unsigned char c = (unsigned char)*s;
6851 if (c < 128) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006852 PyUnicode_WRITE(kind, data, outpos++, c);
Benjamin Peterson29060642009-01-31 22:14:21 +00006853 ++s;
6854 }
6855 else {
6856 startinpos = s-starts;
6857 endinpos = startinpos + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00006858 if (unicode_decode_call_errorhandler(
6859 errors, &errorHandler,
6860 "ascii", "ordinal not in range(128)",
6861 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006862 &v, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00006863 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006864 kind = PyUnicode_KIND(v);
6865 data = PyUnicode_DATA(v);
Benjamin Peterson29060642009-01-31 22:14:21 +00006866 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006867 }
Victor Stinner16e6a802011-12-12 13:24:15 +01006868 if (unicode_resize(&v, outpos) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006869 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006870 Py_XDECREF(errorHandler);
6871 Py_XDECREF(exc);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02006872 assert(_PyUnicode_CheckConsistency(v, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01006873 return v;
Tim Petersced69f82003-09-16 20:30:58 +00006874
Benjamin Peterson29060642009-01-31 22:14:21 +00006875 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00006876 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006877 Py_XDECREF(errorHandler);
6878 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006879 return NULL;
6880}
6881
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006882/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006883PyObject *
6884PyUnicode_EncodeASCII(const Py_UNICODE *p,
6885 Py_ssize_t size,
6886 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006887{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006888 PyObject *result;
6889 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6890 if (unicode == NULL)
6891 return NULL;
6892 result = unicode_encode_ucs1(unicode, errors, 128);
6893 Py_DECREF(unicode);
6894 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006895}
6896
Alexander Belopolsky40018472011-02-26 01:02:56 +00006897PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006898_PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006899{
6900 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006901 PyErr_BadArgument();
6902 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006903 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006904 if (PyUnicode_READY(unicode) == -1)
6905 return NULL;
6906 /* Fast path: if it is an ASCII-only string, construct bytes object
6907 directly. Else defer to above function to raise the exception. */
6908 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
6909 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6910 PyUnicode_GET_LENGTH(unicode));
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006911 return unicode_encode_ucs1(unicode, errors, 128);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006912}
6913
6914PyObject *
6915PyUnicode_AsASCIIString(PyObject *unicode)
6916{
6917 return _PyUnicode_AsASCIIString(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006918}
6919
Victor Stinner99b95382011-07-04 14:23:54 +02006920#ifdef HAVE_MBCS
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006921
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006922/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006923
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00006924#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006925#define NEED_RETRY
6926#endif
6927
Victor Stinner3a50e702011-10-18 21:21:00 +02006928#ifndef WC_ERR_INVALID_CHARS
6929# define WC_ERR_INVALID_CHARS 0x0080
6930#endif
6931
6932static char*
6933code_page_name(UINT code_page, PyObject **obj)
6934{
6935 *obj = NULL;
6936 if (code_page == CP_ACP)
6937 return "mbcs";
6938 if (code_page == CP_UTF7)
6939 return "CP_UTF7";
6940 if (code_page == CP_UTF8)
6941 return "CP_UTF8";
6942
6943 *obj = PyBytes_FromFormat("cp%u", code_page);
6944 if (*obj == NULL)
6945 return NULL;
6946 return PyBytes_AS_STRING(*obj);
6947}
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006948
Alexander Belopolsky40018472011-02-26 01:02:56 +00006949static int
Victor Stinner3a50e702011-10-18 21:21:00 +02006950is_dbcs_lead_byte(UINT code_page, const char *s, int offset)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006951{
6952 const char *curr = s + offset;
Victor Stinner3a50e702011-10-18 21:21:00 +02006953 const char *prev;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006954
Victor Stinner3a50e702011-10-18 21:21:00 +02006955 if (!IsDBCSLeadByteEx(code_page, *curr))
6956 return 0;
6957
6958 prev = CharPrevExA(code_page, s, curr, 0);
6959 if (prev == curr)
6960 return 1;
6961 /* FIXME: This code is limited to "true" double-byte encodings,
6962 as it assumes an incomplete character consists of a single
6963 byte. */
6964 if (curr - prev == 2)
6965 return 1;
6966 if (!IsDBCSLeadByteEx(code_page, *prev))
6967 return 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006968 return 0;
6969}
6970
Victor Stinner3a50e702011-10-18 21:21:00 +02006971static DWORD
6972decode_code_page_flags(UINT code_page)
6973{
6974 if (code_page == CP_UTF7) {
6975 /* The CP_UTF7 decoder only supports flags=0 */
6976 return 0;
6977 }
6978 else
6979 return MB_ERR_INVALID_CHARS;
6980}
6981
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006982/*
Victor Stinner3a50e702011-10-18 21:21:00 +02006983 * Decode a byte string from a Windows code page into unicode object in strict
6984 * mode.
6985 *
6986 * Returns consumed size if succeed, returns -2 on decode error, or raise a
6987 * WindowsError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006988 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006989static int
Victor Stinner3a50e702011-10-18 21:21:00 +02006990decode_code_page_strict(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01006991 PyObject **v,
Victor Stinner3a50e702011-10-18 21:21:00 +02006992 const char *in,
6993 int insize)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006994{
Victor Stinner3a50e702011-10-18 21:21:00 +02006995 const DWORD flags = decode_code_page_flags(code_page);
Victor Stinner24729f32011-11-10 20:31:37 +01006996 wchar_t *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02006997 DWORD outsize;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006998
6999 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007000 assert(insize > 0);
7001 outsize = MultiByteToWideChar(code_page, flags, in, insize, NULL, 0);
7002 if (outsize <= 0)
7003 goto error;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007004
7005 if (*v == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007006 /* Create unicode object */
Victor Stinnerab595942011-12-17 04:59:06 +01007007 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01007008 *v = (PyObject*)_PyUnicode_New(outsize);
Benjamin Peterson29060642009-01-31 22:14:21 +00007009 if (*v == NULL)
7010 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007011 out = PyUnicode_AS_UNICODE(*v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007012 }
7013 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007014 /* Extend unicode object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007015 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
Victor Stinner16e6a802011-12-12 13:24:15 +01007016 if (unicode_resize(v, n + outsize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007017 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007018 out = PyUnicode_AS_UNICODE(*v) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007019 }
7020
7021 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007022 outsize = MultiByteToWideChar(code_page, flags, in, insize, out, outsize);
7023 if (outsize <= 0)
7024 goto error;
7025 return insize;
Victor Stinner554f3f02010-06-16 23:33:54 +00007026
Victor Stinner3a50e702011-10-18 21:21:00 +02007027error:
7028 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7029 return -2;
7030 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007031 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007032}
7033
Victor Stinner3a50e702011-10-18 21:21:00 +02007034/*
7035 * Decode a byte string from a code page into unicode object with an error
7036 * handler.
7037 *
7038 * Returns consumed size if succeed, or raise a WindowsError or
7039 * UnicodeDecodeError exception and returns -1 on error.
7040 */
7041static int
7042decode_code_page_errors(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007043 PyObject **v,
7044 const char *in, const int size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007045 const char *errors)
7046{
7047 const char *startin = in;
7048 const char *endin = in + size;
7049 const DWORD flags = decode_code_page_flags(code_page);
7050 /* Ideally, we should get reason from FormatMessage. This is the Windows
7051 2000 English version of the message. */
7052 const char *reason = "No mapping for the Unicode character exists "
7053 "in the target code page.";
7054 /* each step cannot decode more than 1 character, but a character can be
7055 represented as a surrogate pair */
7056 wchar_t buffer[2], *startout, *out;
7057 int insize, outsize;
7058 PyObject *errorHandler = NULL;
7059 PyObject *exc = NULL;
7060 PyObject *encoding_obj = NULL;
7061 char *encoding;
7062 DWORD err;
7063 int ret = -1;
7064
7065 assert(size > 0);
7066
7067 encoding = code_page_name(code_page, &encoding_obj);
7068 if (encoding == NULL)
7069 return -1;
7070
7071 if (errors == NULL || strcmp(errors, "strict") == 0) {
7072 /* The last error was ERROR_NO_UNICODE_TRANSLATION, then we raise a
7073 UnicodeDecodeError. */
7074 make_decode_exception(&exc, encoding, in, size, 0, 0, reason);
7075 if (exc != NULL) {
7076 PyCodec_StrictErrors(exc);
7077 Py_CLEAR(exc);
7078 }
7079 goto error;
7080 }
7081
7082 if (*v == NULL) {
7083 /* Create unicode object */
7084 if (size > PY_SSIZE_T_MAX / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
7085 PyErr_NoMemory();
7086 goto error;
7087 }
Victor Stinnerab595942011-12-17 04:59:06 +01007088 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01007089 *v = (PyObject*)_PyUnicode_New(size * Py_ARRAY_LENGTH(buffer));
Victor Stinner3a50e702011-10-18 21:21:00 +02007090 if (*v == NULL)
7091 goto error;
7092 startout = PyUnicode_AS_UNICODE(*v);
7093 }
7094 else {
7095 /* Extend unicode object */
7096 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
7097 if (size > (PY_SSIZE_T_MAX - n) / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
7098 PyErr_NoMemory();
7099 goto error;
7100 }
Victor Stinner16e6a802011-12-12 13:24:15 +01007101 if (unicode_resize(v, n + size * Py_ARRAY_LENGTH(buffer)) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007102 goto error;
7103 startout = PyUnicode_AS_UNICODE(*v) + n;
7104 }
7105
7106 /* Decode the byte string character per character */
7107 out = startout;
7108 while (in < endin)
7109 {
7110 /* Decode a character */
7111 insize = 1;
7112 do
7113 {
7114 outsize = MultiByteToWideChar(code_page, flags,
7115 in, insize,
7116 buffer, Py_ARRAY_LENGTH(buffer));
7117 if (outsize > 0)
7118 break;
7119 err = GetLastError();
7120 if (err != ERROR_NO_UNICODE_TRANSLATION
7121 && err != ERROR_INSUFFICIENT_BUFFER)
7122 {
7123 PyErr_SetFromWindowsErr(0);
7124 goto error;
7125 }
7126 insize++;
7127 }
7128 /* 4=maximum length of a UTF-8 sequence */
7129 while (insize <= 4 && (in + insize) <= endin);
7130
7131 if (outsize <= 0) {
7132 Py_ssize_t startinpos, endinpos, outpos;
7133
7134 startinpos = in - startin;
7135 endinpos = startinpos + 1;
7136 outpos = out - PyUnicode_AS_UNICODE(*v);
7137 if (unicode_decode_call_errorhandler(
7138 errors, &errorHandler,
7139 encoding, reason,
7140 &startin, &endin, &startinpos, &endinpos, &exc, &in,
Victor Stinner596a6c42011-11-09 00:02:18 +01007141 v, &outpos))
Victor Stinner3a50e702011-10-18 21:21:00 +02007142 {
7143 goto error;
7144 }
Victor Stinner596a6c42011-11-09 00:02:18 +01007145 out = PyUnicode_AS_UNICODE(*v) + outpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007146 }
7147 else {
7148 in += insize;
7149 memcpy(out, buffer, outsize * sizeof(wchar_t));
7150 out += outsize;
7151 }
7152 }
7153
7154 /* write a NUL character at the end */
7155 *out = 0;
7156
7157 /* Extend unicode object */
7158 outsize = out - startout;
7159 assert(outsize <= PyUnicode_WSTR_LENGTH(*v));
Victor Stinner16e6a802011-12-12 13:24:15 +01007160 if (unicode_resize(v, outsize) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007161 goto error;
Victor Stinner76a31a62011-11-04 00:05:13 +01007162 ret = size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007163
7164error:
7165 Py_XDECREF(encoding_obj);
7166 Py_XDECREF(errorHandler);
7167 Py_XDECREF(exc);
7168 return ret;
7169}
7170
Victor Stinner3a50e702011-10-18 21:21:00 +02007171static PyObject *
7172decode_code_page_stateful(int code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007173 const char *s, Py_ssize_t size,
7174 const char *errors, Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007175{
Victor Stinner76a31a62011-11-04 00:05:13 +01007176 PyObject *v = NULL;
7177 int chunk_size, final, converted, done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007178
Victor Stinner3a50e702011-10-18 21:21:00 +02007179 if (code_page < 0) {
7180 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7181 return NULL;
7182 }
7183
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007184 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00007185 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007186
Victor Stinner76a31a62011-11-04 00:05:13 +01007187 do
7188 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007189#ifdef NEED_RETRY
Victor Stinner76a31a62011-11-04 00:05:13 +01007190 if (size > INT_MAX) {
7191 chunk_size = INT_MAX;
7192 final = 0;
7193 done = 0;
7194 }
7195 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007196#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007197 {
7198 chunk_size = (int)size;
7199 final = (consumed == NULL);
7200 done = 1;
7201 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007202
Victor Stinner76a31a62011-11-04 00:05:13 +01007203 /* Skip trailing lead-byte unless 'final' is set */
7204 if (!final && is_dbcs_lead_byte(code_page, s, chunk_size - 1))
7205 --chunk_size;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007206
Victor Stinner76a31a62011-11-04 00:05:13 +01007207 if (chunk_size == 0 && done) {
7208 if (v != NULL)
7209 break;
7210 Py_INCREF(unicode_empty);
7211 return unicode_empty;
7212 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007213
Victor Stinner76a31a62011-11-04 00:05:13 +01007214
7215 converted = decode_code_page_strict(code_page, &v,
7216 s, chunk_size);
7217 if (converted == -2)
7218 converted = decode_code_page_errors(code_page, &v,
7219 s, chunk_size,
7220 errors);
7221 assert(converted != 0);
7222
7223 if (converted < 0) {
7224 Py_XDECREF(v);
7225 return NULL;
7226 }
7227
7228 if (consumed)
7229 *consumed += converted;
7230
7231 s += converted;
7232 size -= converted;
7233 } while (!done);
Victor Stinner3a50e702011-10-18 21:21:00 +02007234
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01007235 return unicode_result(v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007236}
7237
Alexander Belopolsky40018472011-02-26 01:02:56 +00007238PyObject *
Victor Stinner3a50e702011-10-18 21:21:00 +02007239PyUnicode_DecodeCodePageStateful(int code_page,
7240 const char *s,
7241 Py_ssize_t size,
7242 const char *errors,
7243 Py_ssize_t *consumed)
7244{
7245 return decode_code_page_stateful(code_page, s, size, errors, consumed);
7246}
7247
7248PyObject *
7249PyUnicode_DecodeMBCSStateful(const char *s,
7250 Py_ssize_t size,
7251 const char *errors,
7252 Py_ssize_t *consumed)
7253{
7254 return decode_code_page_stateful(CP_ACP, s, size, errors, consumed);
7255}
7256
7257PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00007258PyUnicode_DecodeMBCS(const char *s,
7259 Py_ssize_t size,
7260 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007261{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007262 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
7263}
7264
Victor Stinner3a50e702011-10-18 21:21:00 +02007265static DWORD
7266encode_code_page_flags(UINT code_page, const char *errors)
7267{
7268 if (code_page == CP_UTF8) {
7269 if (winver.dwMajorVersion >= 6)
7270 /* CP_UTF8 supports WC_ERR_INVALID_CHARS on Windows Vista
7271 and later */
7272 return WC_ERR_INVALID_CHARS;
7273 else
7274 /* CP_UTF8 only supports flags=0 on Windows older than Vista */
7275 return 0;
7276 }
7277 else if (code_page == CP_UTF7) {
7278 /* CP_UTF7 only supports flags=0 */
7279 return 0;
7280 }
7281 else {
7282 if (errors != NULL && strcmp(errors, "replace") == 0)
7283 return 0;
7284 else
7285 return WC_NO_BEST_FIT_CHARS;
7286 }
7287}
7288
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007289/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007290 * Encode a Unicode string to a Windows code page into a byte string in strict
7291 * mode.
7292 *
7293 * Returns consumed characters if succeed, returns -2 on encode error, or raise
7294 * a WindowsError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007295 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007296static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007297encode_code_page_strict(UINT code_page, PyObject **outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007298 PyObject *unicode, Py_ssize_t offset, int len,
Victor Stinner3a50e702011-10-18 21:21:00 +02007299 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007300{
Victor Stinner554f3f02010-06-16 23:33:54 +00007301 BOOL usedDefaultChar = FALSE;
Victor Stinner3a50e702011-10-18 21:21:00 +02007302 BOOL *pusedDefaultChar = &usedDefaultChar;
7303 int outsize;
Victor Stinner554f3f02010-06-16 23:33:54 +00007304 PyObject *exc = NULL;
Victor Stinner24729f32011-11-10 20:31:37 +01007305 wchar_t *p;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007306 Py_ssize_t size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007307 const DWORD flags = encode_code_page_flags(code_page, NULL);
7308 char *out;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007309 /* Create a substring so that we can get the UTF-16 representation
7310 of just the slice under consideration. */
7311 PyObject *substring;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007312
Martin v. Löwis3d325192011-11-04 18:23:06 +01007313 assert(len > 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007314
Victor Stinner3a50e702011-10-18 21:21:00 +02007315 if (code_page != CP_UTF8 && code_page != CP_UTF7)
Victor Stinner554f3f02010-06-16 23:33:54 +00007316 pusedDefaultChar = &usedDefaultChar;
Victor Stinner3a50e702011-10-18 21:21:00 +02007317 else
Victor Stinner554f3f02010-06-16 23:33:54 +00007318 pusedDefaultChar = NULL;
Victor Stinner554f3f02010-06-16 23:33:54 +00007319
Victor Stinner2fc507f2011-11-04 20:06:39 +01007320 substring = PyUnicode_Substring(unicode, offset, offset+len);
7321 if (substring == NULL)
7322 return -1;
7323 p = PyUnicode_AsUnicodeAndSize(substring, &size);
7324 if (p == NULL) {
7325 Py_DECREF(substring);
7326 return -1;
7327 }
Martin v. Löwis3d325192011-11-04 18:23:06 +01007328
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007329 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007330 outsize = WideCharToMultiByte(code_page, flags,
7331 p, size,
7332 NULL, 0,
7333 NULL, pusedDefaultChar);
7334 if (outsize <= 0)
7335 goto error;
7336 /* If we used a default char, then we failed! */
Victor Stinner2fc507f2011-11-04 20:06:39 +01007337 if (pusedDefaultChar && *pusedDefaultChar) {
7338 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007339 return -2;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007340 }
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007341
Victor Stinner3a50e702011-10-18 21:21:00 +02007342 if (*outbytes == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007343 /* Create string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007344 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007345 if (*outbytes == NULL) {
7346 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007347 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007348 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007349 out = PyBytes_AS_STRING(*outbytes);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007350 }
7351 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007352 /* Extend string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007353 const Py_ssize_t n = PyBytes_Size(*outbytes);
7354 if (outsize > PY_SSIZE_T_MAX - n) {
7355 PyErr_NoMemory();
Victor Stinner2fc507f2011-11-04 20:06:39 +01007356 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007357 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007358 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007359 if (_PyBytes_Resize(outbytes, n + outsize) < 0) {
7360 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007361 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007362 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007363 out = PyBytes_AS_STRING(*outbytes) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007364 }
7365
7366 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007367 outsize = WideCharToMultiByte(code_page, flags,
7368 p, size,
7369 out, outsize,
7370 NULL, pusedDefaultChar);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007371 Py_CLEAR(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007372 if (outsize <= 0)
7373 goto error;
7374 if (pusedDefaultChar && *pusedDefaultChar)
7375 return -2;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007376 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00007377
Victor Stinner3a50e702011-10-18 21:21:00 +02007378error:
Victor Stinner2fc507f2011-11-04 20:06:39 +01007379 Py_XDECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007380 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7381 return -2;
7382 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007383 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007384}
7385
Victor Stinner3a50e702011-10-18 21:21:00 +02007386/*
7387 * Encode a Unicode string to a Windows code page into a byte string using a
7388 * error handler.
7389 *
7390 * Returns consumed characters if succeed, or raise a WindowsError and returns
7391 * -1 on other error.
7392 */
7393static int
7394encode_code_page_errors(UINT code_page, PyObject **outbytes,
Victor Stinner7581cef2011-11-03 22:32:33 +01007395 PyObject *unicode, Py_ssize_t unicode_offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007396 Py_ssize_t insize, const char* errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007397{
Victor Stinner3a50e702011-10-18 21:21:00 +02007398 const DWORD flags = encode_code_page_flags(code_page, errors);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007399 Py_ssize_t pos = unicode_offset;
7400 Py_ssize_t endin = unicode_offset + insize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007401 /* Ideally, we should get reason from FormatMessage. This is the Windows
7402 2000 English version of the message. */
7403 const char *reason = "invalid character";
7404 /* 4=maximum length of a UTF-8 sequence */
7405 char buffer[4];
7406 BOOL usedDefaultChar = FALSE, *pusedDefaultChar;
7407 Py_ssize_t outsize;
7408 char *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007409 PyObject *errorHandler = NULL;
7410 PyObject *exc = NULL;
7411 PyObject *encoding_obj = NULL;
7412 char *encoding;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007413 Py_ssize_t newpos, newoutsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007414 PyObject *rep;
7415 int ret = -1;
7416
7417 assert(insize > 0);
7418
7419 encoding = code_page_name(code_page, &encoding_obj);
7420 if (encoding == NULL)
7421 return -1;
7422
7423 if (errors == NULL || strcmp(errors, "strict") == 0) {
7424 /* The last error was ERROR_NO_UNICODE_TRANSLATION,
7425 then we raise a UnicodeEncodeError. */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007426 make_encode_exception(&exc, encoding, unicode, 0, 0, reason);
Victor Stinner3a50e702011-10-18 21:21:00 +02007427 if (exc != NULL) {
7428 PyCodec_StrictErrors(exc);
7429 Py_DECREF(exc);
7430 }
7431 Py_XDECREF(encoding_obj);
7432 return -1;
7433 }
7434
7435 if (code_page != CP_UTF8 && code_page != CP_UTF7)
7436 pusedDefaultChar = &usedDefaultChar;
7437 else
7438 pusedDefaultChar = NULL;
7439
7440 if (Py_ARRAY_LENGTH(buffer) > PY_SSIZE_T_MAX / insize) {
7441 PyErr_NoMemory();
7442 goto error;
7443 }
7444 outsize = insize * Py_ARRAY_LENGTH(buffer);
7445
7446 if (*outbytes == NULL) {
7447 /* Create string object */
7448 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
7449 if (*outbytes == NULL)
7450 goto error;
7451 out = PyBytes_AS_STRING(*outbytes);
7452 }
7453 else {
7454 /* Extend string object */
7455 Py_ssize_t n = PyBytes_Size(*outbytes);
7456 if (n > PY_SSIZE_T_MAX - outsize) {
7457 PyErr_NoMemory();
7458 goto error;
7459 }
7460 if (_PyBytes_Resize(outbytes, n + outsize) < 0)
7461 goto error;
7462 out = PyBytes_AS_STRING(*outbytes) + n;
7463 }
7464
7465 /* Encode the string character per character */
Martin v. Löwis3d325192011-11-04 18:23:06 +01007466 while (pos < endin)
Victor Stinner3a50e702011-10-18 21:21:00 +02007467 {
Victor Stinner2fc507f2011-11-04 20:06:39 +01007468 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, pos);
7469 wchar_t chars[2];
7470 int charsize;
7471 if (ch < 0x10000) {
7472 chars[0] = (wchar_t)ch;
7473 charsize = 1;
7474 }
7475 else {
7476 ch -= 0x10000;
7477 chars[0] = 0xd800 + (ch >> 10);
7478 chars[1] = 0xdc00 + (ch & 0x3ff);
7479 charsize = 2;
7480 }
7481
Victor Stinner3a50e702011-10-18 21:21:00 +02007482 outsize = WideCharToMultiByte(code_page, flags,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007483 chars, charsize,
Victor Stinner3a50e702011-10-18 21:21:00 +02007484 buffer, Py_ARRAY_LENGTH(buffer),
7485 NULL, pusedDefaultChar);
7486 if (outsize > 0) {
7487 if (pusedDefaultChar == NULL || !(*pusedDefaultChar))
7488 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007489 pos++;
Victor Stinner3a50e702011-10-18 21:21:00 +02007490 memcpy(out, buffer, outsize);
7491 out += outsize;
7492 continue;
7493 }
7494 }
7495 else if (GetLastError() != ERROR_NO_UNICODE_TRANSLATION) {
7496 PyErr_SetFromWindowsErr(0);
7497 goto error;
7498 }
7499
Victor Stinner3a50e702011-10-18 21:21:00 +02007500 rep = unicode_encode_call_errorhandler(
7501 errors, &errorHandler, encoding, reason,
Victor Stinner7581cef2011-11-03 22:32:33 +01007502 unicode, &exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007503 pos, pos + 1, &newpos);
Victor Stinner3a50e702011-10-18 21:21:00 +02007504 if (rep == NULL)
7505 goto error;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007506 pos = newpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007507
7508 if (PyBytes_Check(rep)) {
7509 outsize = PyBytes_GET_SIZE(rep);
7510 if (outsize != 1) {
7511 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7512 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7513 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7514 Py_DECREF(rep);
7515 goto error;
7516 }
7517 out = PyBytes_AS_STRING(*outbytes) + offset;
7518 }
7519 memcpy(out, PyBytes_AS_STRING(rep), outsize);
7520 out += outsize;
7521 }
7522 else {
7523 Py_ssize_t i;
7524 enum PyUnicode_Kind kind;
7525 void *data;
7526
7527 if (PyUnicode_READY(rep) < 0) {
7528 Py_DECREF(rep);
7529 goto error;
7530 }
7531
7532 outsize = PyUnicode_GET_LENGTH(rep);
7533 if (outsize != 1) {
7534 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7535 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7536 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7537 Py_DECREF(rep);
7538 goto error;
7539 }
7540 out = PyBytes_AS_STRING(*outbytes) + offset;
7541 }
7542 kind = PyUnicode_KIND(rep);
7543 data = PyUnicode_DATA(rep);
7544 for (i=0; i < outsize; i++) {
7545 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7546 if (ch > 127) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007547 raise_encode_exception(&exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007548 encoding, unicode,
7549 pos, pos + 1,
Victor Stinner3a50e702011-10-18 21:21:00 +02007550 "unable to encode error handler result to ASCII");
7551 Py_DECREF(rep);
7552 goto error;
7553 }
7554 *out = (unsigned char)ch;
7555 out++;
7556 }
7557 }
7558 Py_DECREF(rep);
7559 }
7560 /* write a NUL byte */
7561 *out = 0;
7562 outsize = out - PyBytes_AS_STRING(*outbytes);
7563 assert(outsize <= PyBytes_GET_SIZE(*outbytes));
7564 if (_PyBytes_Resize(outbytes, outsize) < 0)
7565 goto error;
7566 ret = 0;
7567
7568error:
7569 Py_XDECREF(encoding_obj);
7570 Py_XDECREF(errorHandler);
7571 Py_XDECREF(exc);
7572 return ret;
7573}
7574
Victor Stinner3a50e702011-10-18 21:21:00 +02007575static PyObject *
7576encode_code_page(int code_page,
Victor Stinner7581cef2011-11-03 22:32:33 +01007577 PyObject *unicode,
Victor Stinner3a50e702011-10-18 21:21:00 +02007578 const char *errors)
7579{
Martin v. Löwis3d325192011-11-04 18:23:06 +01007580 Py_ssize_t len;
Victor Stinner3a50e702011-10-18 21:21:00 +02007581 PyObject *outbytes = NULL;
Victor Stinner7581cef2011-11-03 22:32:33 +01007582 Py_ssize_t offset;
Victor Stinner76a31a62011-11-04 00:05:13 +01007583 int chunk_len, ret, done;
Victor Stinner7581cef2011-11-03 22:32:33 +01007584
Victor Stinner2fc507f2011-11-04 20:06:39 +01007585 if (PyUnicode_READY(unicode) < 0)
7586 return NULL;
7587 len = PyUnicode_GET_LENGTH(unicode);
Guido van Rossum03e29f12000-05-04 15:52:20 +00007588
Victor Stinner3a50e702011-10-18 21:21:00 +02007589 if (code_page < 0) {
7590 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7591 return NULL;
7592 }
7593
Martin v. Löwis3d325192011-11-04 18:23:06 +01007594 if (len == 0)
Victor Stinner76a31a62011-11-04 00:05:13 +01007595 return PyBytes_FromStringAndSize(NULL, 0);
7596
Victor Stinner7581cef2011-11-03 22:32:33 +01007597 offset = 0;
7598 do
7599 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007600#ifdef NEED_RETRY
Victor Stinner2fc507f2011-11-04 20:06:39 +01007601 /* UTF-16 encoding may double the size, so use only INT_MAX/2
Martin v. Löwis3d325192011-11-04 18:23:06 +01007602 chunks. */
7603 if (len > INT_MAX/2) {
7604 chunk_len = INT_MAX/2;
Victor Stinner76a31a62011-11-04 00:05:13 +01007605 done = 0;
7606 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007607 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007608#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007609 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007610 chunk_len = (int)len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007611 done = 1;
7612 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007613
Victor Stinner76a31a62011-11-04 00:05:13 +01007614 ret = encode_code_page_strict(code_page, &outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007615 unicode, offset, chunk_len,
Victor Stinner76a31a62011-11-04 00:05:13 +01007616 errors);
7617 if (ret == -2)
7618 ret = encode_code_page_errors(code_page, &outbytes,
7619 unicode, offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007620 chunk_len, errors);
Victor Stinner7581cef2011-11-03 22:32:33 +01007621 if (ret < 0) {
7622 Py_XDECREF(outbytes);
7623 return NULL;
7624 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007625
Victor Stinner7581cef2011-11-03 22:32:33 +01007626 offset += chunk_len;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007627 len -= chunk_len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007628 } while (!done);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007629
Victor Stinner3a50e702011-10-18 21:21:00 +02007630 return outbytes;
7631}
7632
7633PyObject *
7634PyUnicode_EncodeMBCS(const Py_UNICODE *p,
7635 Py_ssize_t size,
7636 const char *errors)
7637{
Victor Stinner7581cef2011-11-03 22:32:33 +01007638 PyObject *unicode, *res;
7639 unicode = PyUnicode_FromUnicode(p, size);
7640 if (unicode == NULL)
7641 return NULL;
7642 res = encode_code_page(CP_ACP, unicode, errors);
7643 Py_DECREF(unicode);
7644 return res;
Victor Stinner3a50e702011-10-18 21:21:00 +02007645}
7646
7647PyObject *
7648PyUnicode_EncodeCodePage(int code_page,
7649 PyObject *unicode,
7650 const char *errors)
7651{
Victor Stinner7581cef2011-11-03 22:32:33 +01007652 return encode_code_page(code_page, unicode, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007653}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007654
Alexander Belopolsky40018472011-02-26 01:02:56 +00007655PyObject *
7656PyUnicode_AsMBCSString(PyObject *unicode)
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007657{
7658 if (!PyUnicode_Check(unicode)) {
7659 PyErr_BadArgument();
7660 return NULL;
7661 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007662 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007663}
7664
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007665#undef NEED_RETRY
7666
Victor Stinner99b95382011-07-04 14:23:54 +02007667#endif /* HAVE_MBCS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007668
Guido van Rossumd57fd912000-03-10 22:53:23 +00007669/* --- Character Mapping Codec -------------------------------------------- */
7670
Alexander Belopolsky40018472011-02-26 01:02:56 +00007671PyObject *
7672PyUnicode_DecodeCharmap(const char *s,
7673 Py_ssize_t size,
7674 PyObject *mapping,
7675 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007676{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007677 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007678 Py_ssize_t startinpos;
7679 Py_ssize_t endinpos;
7680 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007681 const char *e;
Victor Stinner7931d9a2011-11-04 00:22:48 +01007682 PyObject *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007683 Py_ssize_t extrachars = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007684 PyObject *errorHandler = NULL;
7685 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00007686
Guido van Rossumd57fd912000-03-10 22:53:23 +00007687 /* Default to Latin-1 */
7688 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007689 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007690
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007691 v = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007692 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007693 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007694 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01007695 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007696 outpos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007697 e = s + size;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007698 if (PyUnicode_CheckExact(mapping)) {
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007699 Py_ssize_t maplen;
7700 enum PyUnicode_Kind kind;
7701 void *data;
7702 Py_UCS4 x;
7703
7704 if (PyUnicode_READY(mapping) < 0)
7705 return NULL;
7706
7707 maplen = PyUnicode_GET_LENGTH(mapping);
7708 data = PyUnicode_DATA(mapping);
7709 kind = PyUnicode_KIND(mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00007710 while (s < e) {
7711 unsigned char ch = *s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007712
Benjamin Peterson29060642009-01-31 22:14:21 +00007713 if (ch < maplen)
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007714 x = PyUnicode_READ(kind, data, ch);
7715 else
7716 x = 0xfffe; /* invalid value */
Guido van Rossumd57fd912000-03-10 22:53:23 +00007717
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007718 if (x == 0xfffe)
7719 {
Benjamin Peterson29060642009-01-31 22:14:21 +00007720 /* undefined mapping */
Benjamin Peterson29060642009-01-31 22:14:21 +00007721 startinpos = s-starts;
7722 endinpos = startinpos+1;
7723 if (unicode_decode_call_errorhandler(
7724 errors, &errorHandler,
7725 "charmap", "character maps to <undefined>",
7726 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007727 &v, &outpos)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007728 goto onError;
7729 }
7730 continue;
7731 }
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007732
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007733 if (unicode_putchar(&v, &outpos, x) < 0)
7734 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00007735 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007736 }
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007737 }
7738 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007739 while (s < e) {
7740 unsigned char ch = *s;
7741 PyObject *w, *x;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007742
Benjamin Peterson29060642009-01-31 22:14:21 +00007743 /* Get mapping (char ordinal -> integer, Unicode char or None) */
7744 w = PyLong_FromLong((long)ch);
7745 if (w == NULL)
7746 goto onError;
7747 x = PyObject_GetItem(mapping, w);
7748 Py_DECREF(w);
7749 if (x == NULL) {
7750 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7751 /* No mapping found means: mapping is undefined. */
7752 PyErr_Clear();
7753 x = Py_None;
7754 Py_INCREF(x);
7755 } else
7756 goto onError;
7757 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007758
Benjamin Peterson29060642009-01-31 22:14:21 +00007759 /* Apply mapping */
7760 if (PyLong_Check(x)) {
7761 long value = PyLong_AS_LONG(x);
7762 if (value < 0 || value > 65535) {
7763 PyErr_SetString(PyExc_TypeError,
7764 "character mapping must be in range(65536)");
7765 Py_DECREF(x);
7766 goto onError;
7767 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007768 if (unicode_putchar(&v, &outpos, value) < 0)
7769 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00007770 }
7771 else if (x == Py_None) {
7772 /* undefined mapping */
Benjamin Peterson29060642009-01-31 22:14:21 +00007773 startinpos = s-starts;
7774 endinpos = startinpos+1;
7775 if (unicode_decode_call_errorhandler(
7776 errors, &errorHandler,
7777 "charmap", "character maps to <undefined>",
7778 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007779 &v, &outpos)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007780 Py_DECREF(x);
7781 goto onError;
7782 }
7783 Py_DECREF(x);
7784 continue;
7785 }
7786 else if (PyUnicode_Check(x)) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007787 Py_ssize_t targetsize;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007788
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007789 if (PyUnicode_READY(x) < 0)
7790 goto onError;
7791 targetsize = PyUnicode_GET_LENGTH(x);
7792
7793 if (targetsize == 1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007794 /* 1-1 mapping */
Victor Stinner62aa4d02011-11-09 00:03:45 +01007795 if (unicode_putchar(&v, &outpos,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007796 PyUnicode_READ_CHAR(x, 0)) < 0)
7797 goto onError;
7798 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007799 else if (targetsize > 1) {
7800 /* 1-n mapping */
7801 if (targetsize > extrachars) {
7802 /* resize first */
Benjamin Peterson29060642009-01-31 22:14:21 +00007803 Py_ssize_t needed = (targetsize - extrachars) + \
7804 (targetsize << 2);
7805 extrachars += needed;
7806 /* XXX overflow detection missing */
Victor Stinner16e6a802011-12-12 13:24:15 +01007807 if (unicode_resize(&v,
7808 PyUnicode_GET_LENGTH(v) + needed) < 0)
7809 {
Benjamin Peterson29060642009-01-31 22:14:21 +00007810 Py_DECREF(x);
7811 goto onError;
7812 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007813 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007814 if (unicode_widen(&v, PyUnicode_MAX_CHAR_VALUE(x)) < 0)
7815 goto onError;
7816 PyUnicode_CopyCharacters(v, outpos, x, 0, targetsize);
7817 outpos += targetsize;
Benjamin Peterson29060642009-01-31 22:14:21 +00007818 extrachars -= targetsize;
7819 }
7820 /* 1-0 mapping: skip the character */
7821 }
7822 else {
7823 /* wrong return value */
7824 PyErr_SetString(PyExc_TypeError,
7825 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00007826 Py_DECREF(x);
7827 goto onError;
7828 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007829 Py_DECREF(x);
7830 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007831 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00007832 }
Victor Stinner16e6a802011-12-12 13:24:15 +01007833 if (unicode_resize(&v, outpos) < 0)
Antoine Pitroua8f63c02011-11-08 18:37:16 +01007834 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007835 Py_XDECREF(errorHandler);
7836 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01007837 return unicode_result(v);
Tim Petersced69f82003-09-16 20:30:58 +00007838
Benjamin Peterson29060642009-01-31 22:14:21 +00007839 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007840 Py_XDECREF(errorHandler);
7841 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007842 Py_XDECREF(v);
7843 return NULL;
7844}
7845
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007846/* Charmap encoding: the lookup table */
7847
Alexander Belopolsky40018472011-02-26 01:02:56 +00007848struct encoding_map {
Benjamin Peterson29060642009-01-31 22:14:21 +00007849 PyObject_HEAD
7850 unsigned char level1[32];
7851 int count2, count3;
7852 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007853};
7854
7855static PyObject*
7856encoding_map_size(PyObject *obj, PyObject* args)
7857{
7858 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007859 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00007860 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007861}
7862
7863static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007864 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00007865 PyDoc_STR("Return the size (in bytes) of this object") },
7866 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007867};
7868
7869static void
7870encoding_map_dealloc(PyObject* o)
7871{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007872 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007873}
7874
7875static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007876 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007877 "EncodingMap", /*tp_name*/
7878 sizeof(struct encoding_map), /*tp_basicsize*/
7879 0, /*tp_itemsize*/
7880 /* methods */
7881 encoding_map_dealloc, /*tp_dealloc*/
7882 0, /*tp_print*/
7883 0, /*tp_getattr*/
7884 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00007885 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00007886 0, /*tp_repr*/
7887 0, /*tp_as_number*/
7888 0, /*tp_as_sequence*/
7889 0, /*tp_as_mapping*/
7890 0, /*tp_hash*/
7891 0, /*tp_call*/
7892 0, /*tp_str*/
7893 0, /*tp_getattro*/
7894 0, /*tp_setattro*/
7895 0, /*tp_as_buffer*/
7896 Py_TPFLAGS_DEFAULT, /*tp_flags*/
7897 0, /*tp_doc*/
7898 0, /*tp_traverse*/
7899 0, /*tp_clear*/
7900 0, /*tp_richcompare*/
7901 0, /*tp_weaklistoffset*/
7902 0, /*tp_iter*/
7903 0, /*tp_iternext*/
7904 encoding_map_methods, /*tp_methods*/
7905 0, /*tp_members*/
7906 0, /*tp_getset*/
7907 0, /*tp_base*/
7908 0, /*tp_dict*/
7909 0, /*tp_descr_get*/
7910 0, /*tp_descr_set*/
7911 0, /*tp_dictoffset*/
7912 0, /*tp_init*/
7913 0, /*tp_alloc*/
7914 0, /*tp_new*/
7915 0, /*tp_free*/
7916 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007917};
7918
7919PyObject*
7920PyUnicode_BuildEncodingMap(PyObject* string)
7921{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007922 PyObject *result;
7923 struct encoding_map *mresult;
7924 int i;
7925 int need_dict = 0;
7926 unsigned char level1[32];
7927 unsigned char level2[512];
7928 unsigned char *mlevel1, *mlevel2, *mlevel3;
7929 int count2 = 0, count3 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007930 int kind;
7931 void *data;
7932 Py_UCS4 ch;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007933
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007934 if (!PyUnicode_Check(string) || PyUnicode_GET_LENGTH(string) != 256) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007935 PyErr_BadArgument();
7936 return NULL;
7937 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007938 kind = PyUnicode_KIND(string);
7939 data = PyUnicode_DATA(string);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007940 memset(level1, 0xFF, sizeof level1);
7941 memset(level2, 0xFF, sizeof level2);
7942
7943 /* If there isn't a one-to-one mapping of NULL to \0,
7944 or if there are non-BMP characters, we need to use
7945 a mapping dictionary. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007946 if (PyUnicode_READ(kind, data, 0) != 0)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007947 need_dict = 1;
7948 for (i = 1; i < 256; i++) {
7949 int l1, l2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007950 ch = PyUnicode_READ(kind, data, i);
7951 if (ch == 0 || ch > 0xFFFF) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007952 need_dict = 1;
7953 break;
7954 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007955 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007956 /* unmapped character */
7957 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007958 l1 = ch >> 11;
7959 l2 = ch >> 7;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007960 if (level1[l1] == 0xFF)
7961 level1[l1] = count2++;
7962 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00007963 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007964 }
7965
7966 if (count2 >= 0xFF || count3 >= 0xFF)
7967 need_dict = 1;
7968
7969 if (need_dict) {
7970 PyObject *result = PyDict_New();
7971 PyObject *key, *value;
7972 if (!result)
7973 return NULL;
7974 for (i = 0; i < 256; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007975 key = PyLong_FromLong(PyUnicode_READ(kind, data, i));
Christian Heimes217cfd12007-12-02 14:31:20 +00007976 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007977 if (!key || !value)
7978 goto failed1;
7979 if (PyDict_SetItem(result, key, value) == -1)
7980 goto failed1;
7981 Py_DECREF(key);
7982 Py_DECREF(value);
7983 }
7984 return result;
7985 failed1:
7986 Py_XDECREF(key);
7987 Py_XDECREF(value);
7988 Py_DECREF(result);
7989 return NULL;
7990 }
7991
7992 /* Create a three-level trie */
7993 result = PyObject_MALLOC(sizeof(struct encoding_map) +
7994 16*count2 + 128*count3 - 1);
7995 if (!result)
7996 return PyErr_NoMemory();
7997 PyObject_Init(result, &EncodingMapType);
7998 mresult = (struct encoding_map*)result;
7999 mresult->count2 = count2;
8000 mresult->count3 = count3;
8001 mlevel1 = mresult->level1;
8002 mlevel2 = mresult->level23;
8003 mlevel3 = mresult->level23 + 16*count2;
8004 memcpy(mlevel1, level1, 32);
8005 memset(mlevel2, 0xFF, 16*count2);
8006 memset(mlevel3, 0, 128*count3);
8007 count3 = 0;
8008 for (i = 1; i < 256; i++) {
8009 int o1, o2, o3, i2, i3;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008010 if (PyUnicode_READ(kind, data, i) == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008011 /* unmapped character */
8012 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008013 o1 = PyUnicode_READ(kind, data, i)>>11;
8014 o2 = (PyUnicode_READ(kind, data, i)>>7) & 0xF;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008015 i2 = 16*mlevel1[o1] + o2;
8016 if (mlevel2[i2] == 0xFF)
8017 mlevel2[i2] = count3++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008018 o3 = PyUnicode_READ(kind, data, i) & 0x7F;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008019 i3 = 128*mlevel2[i2] + o3;
8020 mlevel3[i3] = i;
8021 }
8022 return result;
8023}
8024
8025static int
Victor Stinner22168992011-11-20 17:09:18 +01008026encoding_map_lookup(Py_UCS4 c, PyObject *mapping)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008027{
8028 struct encoding_map *map = (struct encoding_map*)mapping;
8029 int l1 = c>>11;
8030 int l2 = (c>>7) & 0xF;
8031 int l3 = c & 0x7F;
8032 int i;
8033
Victor Stinner22168992011-11-20 17:09:18 +01008034 if (c > 0xFFFF)
Benjamin Peterson29060642009-01-31 22:14:21 +00008035 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008036 if (c == 0)
8037 return 0;
8038 /* level 1*/
8039 i = map->level1[l1];
8040 if (i == 0xFF) {
8041 return -1;
8042 }
8043 /* level 2*/
8044 i = map->level23[16*i+l2];
8045 if (i == 0xFF) {
8046 return -1;
8047 }
8048 /* level 3 */
8049 i = map->level23[16*map->count2 + 128*i + l3];
8050 if (i == 0) {
8051 return -1;
8052 }
8053 return i;
8054}
8055
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008056/* Lookup the character ch in the mapping. If the character
8057 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00008058 error occurred). */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008059static PyObject *
Victor Stinner22168992011-11-20 17:09:18 +01008060charmapencode_lookup(Py_UCS4 c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008061{
Christian Heimes217cfd12007-12-02 14:31:20 +00008062 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008063 PyObject *x;
8064
8065 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008066 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008067 x = PyObject_GetItem(mapping, w);
8068 Py_DECREF(w);
8069 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008070 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8071 /* No mapping found means: mapping is undefined. */
8072 PyErr_Clear();
8073 x = Py_None;
8074 Py_INCREF(x);
8075 return x;
8076 } else
8077 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008078 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00008079 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008080 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00008081 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008082 long value = PyLong_AS_LONG(x);
8083 if (value < 0 || value > 255) {
8084 PyErr_SetString(PyExc_TypeError,
8085 "character mapping must be in range(256)");
8086 Py_DECREF(x);
8087 return NULL;
8088 }
8089 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008090 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008091 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008092 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008093 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008094 /* wrong return value */
8095 PyErr_Format(PyExc_TypeError,
8096 "character mapping must return integer, bytes or None, not %.400s",
8097 x->ob_type->tp_name);
8098 Py_DECREF(x);
8099 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008100 }
8101}
8102
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008103static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00008104charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008105{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008106 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
8107 /* exponentially overallocate to minimize reallocations */
8108 if (requiredsize < 2*outsize)
8109 requiredsize = 2*outsize;
8110 if (_PyBytes_Resize(outobj, requiredsize))
8111 return -1;
8112 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008113}
8114
Benjamin Peterson14339b62009-01-31 16:36:08 +00008115typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00008116 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Alexander Belopolsky40018472011-02-26 01:02:56 +00008117} charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008118/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00008119 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008120 space is available. Return a new reference to the object that
8121 was put in the output buffer, or Py_None, if the mapping was undefined
8122 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00008123 reallocation error occurred. The caller must decref the result */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008124static charmapencode_result
Victor Stinner22168992011-11-20 17:09:18 +01008125charmapencode_output(Py_UCS4 c, PyObject *mapping,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008126 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008127{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008128 PyObject *rep;
8129 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00008130 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008131
Christian Heimes90aa7642007-12-19 02:45:37 +00008132 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008133 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008134 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008135 if (res == -1)
8136 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00008137 if (outsize<requiredsize)
8138 if (charmapencode_resize(outobj, outpos, requiredsize))
8139 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00008140 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008141 outstart[(*outpos)++] = (char)res;
8142 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008143 }
8144
8145 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008146 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008147 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008148 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008149 Py_DECREF(rep);
8150 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008151 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008152 if (PyLong_Check(rep)) {
8153 Py_ssize_t requiredsize = *outpos+1;
8154 if (outsize<requiredsize)
8155 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8156 Py_DECREF(rep);
8157 return enc_EXCEPTION;
8158 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008159 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008160 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008161 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008162 else {
8163 const char *repchars = PyBytes_AS_STRING(rep);
8164 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
8165 Py_ssize_t requiredsize = *outpos+repsize;
8166 if (outsize<requiredsize)
8167 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8168 Py_DECREF(rep);
8169 return enc_EXCEPTION;
8170 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008171 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008172 memcpy(outstart + *outpos, repchars, repsize);
8173 *outpos += repsize;
8174 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008175 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008176 Py_DECREF(rep);
8177 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008178}
8179
8180/* handle an error in PyUnicode_EncodeCharmap
8181 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008182static int
8183charmap_encoding_error(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008184 PyObject *unicode, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008185 PyObject **exceptionObject,
Walter Dörwalde5402fb2003-08-14 20:25:29 +00008186 int *known_errorHandler, PyObject **errorHandler, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00008187 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008188{
8189 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008190 Py_ssize_t size, repsize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008191 Py_ssize_t newpos;
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008192 enum PyUnicode_Kind kind;
8193 void *data;
8194 Py_ssize_t index;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008195 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008196 Py_ssize_t collstartpos = *inpos;
8197 Py_ssize_t collendpos = *inpos+1;
8198 Py_ssize_t collpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008199 char *encoding = "charmap";
8200 char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008201 charmapencode_result x;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008202 Py_UCS4 ch;
Brian Curtin2787ea42011-11-02 15:09:37 -05008203 int val;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008204
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008205 if (PyUnicode_READY(unicode) < 0)
8206 return -1;
8207 size = PyUnicode_GET_LENGTH(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008208 /* find all unencodable characters */
8209 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008210 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00008211 if (Py_TYPE(mapping) == &EncodingMapType) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008212 ch = PyUnicode_READ_CHAR(unicode, collendpos);
Brian Curtin2787ea42011-11-02 15:09:37 -05008213 val = encoding_map_lookup(ch, mapping);
8214 if (val != -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008215 break;
8216 ++collendpos;
8217 continue;
8218 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008219
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008220 ch = PyUnicode_READ_CHAR(unicode, collendpos);
8221 rep = charmapencode_lookup(ch, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008222 if (rep==NULL)
8223 return -1;
8224 else if (rep!=Py_None) {
8225 Py_DECREF(rep);
8226 break;
8227 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008228 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00008229 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008230 }
8231 /* cache callback name lookup
8232 * (if not done yet, i.e. it's the first error) */
8233 if (*known_errorHandler==-1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008234 if ((errors==NULL) || (!strcmp(errors, "strict")))
8235 *known_errorHandler = 1;
8236 else if (!strcmp(errors, "replace"))
8237 *known_errorHandler = 2;
8238 else if (!strcmp(errors, "ignore"))
8239 *known_errorHandler = 3;
8240 else if (!strcmp(errors, "xmlcharrefreplace"))
8241 *known_errorHandler = 4;
8242 else
8243 *known_errorHandler = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008244 }
8245 switch (*known_errorHandler) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008246 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008247 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008248 return -1;
8249 case 2: /* replace */
8250 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008251 x = charmapencode_output('?', mapping, res, respos);
8252 if (x==enc_EXCEPTION) {
8253 return -1;
8254 }
8255 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008256 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008257 return -1;
8258 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008259 }
8260 /* fall through */
8261 case 3: /* ignore */
8262 *inpos = collendpos;
8263 break;
8264 case 4: /* xmlcharrefreplace */
8265 /* generate replacement (temporarily (mis)uses p) */
8266 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008267 char buffer[2+29+1+1];
8268 char *cp;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008269 sprintf(buffer, "&#%d;", (int)PyUnicode_READ_CHAR(unicode, collpos));
Benjamin Peterson29060642009-01-31 22:14:21 +00008270 for (cp = buffer; *cp; ++cp) {
8271 x = charmapencode_output(*cp, mapping, res, respos);
8272 if (x==enc_EXCEPTION)
8273 return -1;
8274 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008275 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008276 return -1;
8277 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008278 }
8279 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008280 *inpos = collendpos;
8281 break;
8282 default:
8283 repunicode = unicode_encode_call_errorhandler(errors, errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008284 encoding, reason, unicode, exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00008285 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008286 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008287 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00008288 if (PyBytes_Check(repunicode)) {
8289 /* Directly copy bytes result to output. */
8290 Py_ssize_t outsize = PyBytes_Size(*res);
8291 Py_ssize_t requiredsize;
8292 repsize = PyBytes_Size(repunicode);
8293 requiredsize = *respos + repsize;
8294 if (requiredsize > outsize)
8295 /* Make room for all additional bytes. */
8296 if (charmapencode_resize(res, respos, requiredsize)) {
8297 Py_DECREF(repunicode);
8298 return -1;
8299 }
8300 memcpy(PyBytes_AsString(*res) + *respos,
8301 PyBytes_AsString(repunicode), repsize);
8302 *respos += repsize;
8303 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008304 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00008305 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008306 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008307 /* generate replacement */
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008308 if (PyUnicode_READY(repunicode) < 0) {
8309 Py_DECREF(repunicode);
8310 return -1;
8311 }
Victor Stinner9e30aa52011-11-21 02:49:52 +01008312 repsize = PyUnicode_GET_LENGTH(repunicode);
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008313 data = PyUnicode_DATA(repunicode);
8314 kind = PyUnicode_KIND(repunicode);
8315 for (index = 0; index < repsize; index++) {
8316 Py_UCS4 repch = PyUnicode_READ(kind, data, index);
8317 x = charmapencode_output(repch, mapping, res, respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008318 if (x==enc_EXCEPTION) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008319 Py_DECREF(repunicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00008320 return -1;
8321 }
8322 else if (x==enc_FAILED) {
8323 Py_DECREF(repunicode);
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008324 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008325 return -1;
8326 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008327 }
8328 *inpos = newpos;
8329 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008330 }
8331 return 0;
8332}
8333
Alexander Belopolsky40018472011-02-26 01:02:56 +00008334PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008335_PyUnicode_EncodeCharmap(PyObject *unicode,
8336 PyObject *mapping,
8337 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008338{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008339 /* output object */
8340 PyObject *res = NULL;
8341 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008342 Py_ssize_t inpos = 0;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008343 Py_ssize_t size;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008344 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008345 Py_ssize_t respos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008346 PyObject *errorHandler = NULL;
8347 PyObject *exc = NULL;
8348 /* the following variable is used for caching string comparisons
8349 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8350 * 3=ignore, 4=xmlcharrefreplace */
8351 int known_errorHandler = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008352
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008353 if (PyUnicode_READY(unicode) < 0)
8354 return NULL;
8355 size = PyUnicode_GET_LENGTH(unicode);
8356
Guido van Rossumd57fd912000-03-10 22:53:23 +00008357 /* Default to Latin-1 */
8358 if (mapping == NULL)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008359 return unicode_encode_ucs1(unicode, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008360
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008361 /* allocate enough for a simple encoding without
8362 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00008363 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008364 if (res == NULL)
8365 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00008366 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008367 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008368
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008369 while (inpos<size) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008370 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, inpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008371 /* try to encode it */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008372 charmapencode_result x = charmapencode_output(ch, mapping, &res, &respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008373 if (x==enc_EXCEPTION) /* error */
8374 goto onError;
8375 if (x==enc_FAILED) { /* unencodable character */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008376 if (charmap_encoding_error(unicode, &inpos, mapping,
Benjamin Peterson29060642009-01-31 22:14:21 +00008377 &exc,
8378 &known_errorHandler, &errorHandler, errors,
8379 &res, &respos)) {
8380 goto onError;
8381 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008382 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008383 else
8384 /* done with this character => adjust input position */
8385 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008386 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008387
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008388 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00008389 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00008390 if (_PyBytes_Resize(&res, respos) < 0)
8391 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00008392
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008393 Py_XDECREF(exc);
8394 Py_XDECREF(errorHandler);
8395 return res;
8396
Benjamin Peterson29060642009-01-31 22:14:21 +00008397 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008398 Py_XDECREF(res);
8399 Py_XDECREF(exc);
8400 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008401 return NULL;
8402}
8403
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008404/* Deprecated */
8405PyObject *
8406PyUnicode_EncodeCharmap(const Py_UNICODE *p,
8407 Py_ssize_t size,
8408 PyObject *mapping,
8409 const char *errors)
8410{
8411 PyObject *result;
8412 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8413 if (unicode == NULL)
8414 return NULL;
8415 result = _PyUnicode_EncodeCharmap(unicode, mapping, errors);
8416 Py_DECREF(unicode);
Victor Stinnerfc026c92011-11-04 00:24:51 +01008417 return result;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008418}
8419
Alexander Belopolsky40018472011-02-26 01:02:56 +00008420PyObject *
8421PyUnicode_AsCharmapString(PyObject *unicode,
8422 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008423{
8424 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008425 PyErr_BadArgument();
8426 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008427 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008428 return _PyUnicode_EncodeCharmap(unicode, mapping, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008429}
8430
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008431/* create or adjust a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008432static void
8433make_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008434 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008435 Py_ssize_t startpos, Py_ssize_t endpos,
8436 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008437{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008438 if (*exceptionObject == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008439 *exceptionObject = _PyUnicodeTranslateError_Create(
8440 unicode, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008441 }
8442 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008443 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
8444 goto onError;
8445 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
8446 goto onError;
8447 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
8448 goto onError;
8449 return;
8450 onError:
8451 Py_DECREF(*exceptionObject);
8452 *exceptionObject = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008453 }
8454}
8455
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008456/* raises a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008457static void
8458raise_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008459 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008460 Py_ssize_t startpos, Py_ssize_t endpos,
8461 const char *reason)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008462{
8463 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008464 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008465 if (*exceptionObject != NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008466 PyCodec_StrictErrors(*exceptionObject);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008467}
8468
8469/* error handling callback helper:
8470 build arguments, call the callback and check the arguments,
8471 put the result into newpos and return the replacement string, which
8472 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008473static PyObject *
8474unicode_translate_call_errorhandler(const char *errors,
8475 PyObject **errorHandler,
8476 const char *reason,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008477 PyObject *unicode, PyObject **exceptionObject,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008478 Py_ssize_t startpos, Py_ssize_t endpos,
8479 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008480{
Benjamin Peterson142957c2008-07-04 19:55:29 +00008481 static char *argparse = "O!n;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008482
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008483 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008484 PyObject *restuple;
8485 PyObject *resunicode;
8486
8487 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008488 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008489 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008490 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008491 }
8492
8493 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008494 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008495 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008496 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008497
8498 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00008499 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008500 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008501 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008502 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00008503 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00008504 Py_DECREF(restuple);
8505 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008506 }
8507 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type,
Benjamin Peterson29060642009-01-31 22:14:21 +00008508 &resunicode, &i_newpos)) {
8509 Py_DECREF(restuple);
8510 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008511 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00008512 if (i_newpos<0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008513 *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008514 else
8515 *newpos = i_newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008516 if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008517 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
8518 Py_DECREF(restuple);
8519 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00008520 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008521 Py_INCREF(resunicode);
8522 Py_DECREF(restuple);
8523 return resunicode;
8524}
8525
8526/* Lookup the character ch in the mapping and put the result in result,
8527 which must be decrefed by the caller.
8528 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008529static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008530charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008531{
Christian Heimes217cfd12007-12-02 14:31:20 +00008532 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008533 PyObject *x;
8534
8535 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008536 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008537 x = PyObject_GetItem(mapping, w);
8538 Py_DECREF(w);
8539 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008540 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8541 /* No mapping found means: use 1:1 mapping. */
8542 PyErr_Clear();
8543 *result = NULL;
8544 return 0;
8545 } else
8546 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008547 }
8548 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008549 *result = x;
8550 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008551 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008552 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008553 long value = PyLong_AS_LONG(x);
8554 long max = PyUnicode_GetMax();
8555 if (value < 0 || value > max) {
8556 PyErr_Format(PyExc_TypeError,
Guido van Rossum5a2f7e602007-10-24 21:13:09 +00008557 "character mapping must be in range(0x%x)", max+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00008558 Py_DECREF(x);
8559 return -1;
8560 }
8561 *result = x;
8562 return 0;
8563 }
8564 else if (PyUnicode_Check(x)) {
8565 *result = x;
8566 return 0;
8567 }
8568 else {
8569 /* wrong return value */
8570 PyErr_SetString(PyExc_TypeError,
8571 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00008572 Py_DECREF(x);
8573 return -1;
8574 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008575}
8576/* ensure that *outobj is at least requiredsize characters long,
Benjamin Peterson29060642009-01-31 22:14:21 +00008577 if not reallocate and adjust various state variables.
8578 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008579static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008580charmaptranslate_makespace(Py_UCS4 **outobj, Py_ssize_t *psize,
Benjamin Peterson29060642009-01-31 22:14:21 +00008581 Py_ssize_t requiredsize)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008582{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008583 Py_ssize_t oldsize = *psize;
Walter Dörwald4894c302003-10-24 14:25:28 +00008584 if (requiredsize > oldsize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008585 /* exponentially overallocate to minimize reallocations */
8586 if (requiredsize < 2 * oldsize)
8587 requiredsize = 2 * oldsize;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008588 *outobj = PyMem_Realloc(*outobj, requiredsize * sizeof(Py_UCS4));
8589 if (*outobj == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008590 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008591 *psize = requiredsize;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008592 }
8593 return 0;
8594}
8595/* lookup the character, put the result in the output string and adjust
8596 various state variables. Return a new reference to the object that
8597 was put in the output buffer in *result, or Py_None, if the mapping was
8598 undefined (in which case no character was written).
8599 The called must decref result.
8600 Return 0 on success, -1 on error. */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008601static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008602charmaptranslate_output(PyObject *input, Py_ssize_t ipos,
8603 PyObject *mapping, Py_UCS4 **output,
8604 Py_ssize_t *osize, Py_ssize_t *opos,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008605 PyObject **res)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008606{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008607 Py_UCS4 curinp = PyUnicode_READ_CHAR(input, ipos);
8608 if (charmaptranslate_lookup(curinp, mapping, res))
Benjamin Peterson29060642009-01-31 22:14:21 +00008609 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008610 if (*res==NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008611 /* not found => default to 1:1 mapping */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008612 (*output)[(*opos)++] = curinp;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008613 }
8614 else if (*res==Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008615 ;
Christian Heimes217cfd12007-12-02 14:31:20 +00008616 else if (PyLong_Check(*res)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008617 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008618 (*output)[(*opos)++] = (Py_UCS4)PyLong_AS_LONG(*res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008619 }
8620 else if (PyUnicode_Check(*res)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008621 Py_ssize_t repsize;
8622 if (PyUnicode_READY(*res) == -1)
8623 return -1;
8624 repsize = PyUnicode_GET_LENGTH(*res);
Benjamin Peterson29060642009-01-31 22:14:21 +00008625 if (repsize==1) {
8626 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008627 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +00008628 }
8629 else if (repsize!=0) {
8630 /* more than one character */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008631 Py_ssize_t requiredsize = *opos +
8632 (PyUnicode_GET_LENGTH(input) - ipos) +
Benjamin Peterson29060642009-01-31 22:14:21 +00008633 repsize - 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008634 Py_ssize_t i;
8635 if (charmaptranslate_makespace(output, osize, requiredsize))
Benjamin Peterson29060642009-01-31 22:14:21 +00008636 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008637 for(i = 0; i < repsize; i++)
8638 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00008639 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008640 }
8641 else
Benjamin Peterson29060642009-01-31 22:14:21 +00008642 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008643 return 0;
8644}
8645
Alexander Belopolsky40018472011-02-26 01:02:56 +00008646PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008647_PyUnicode_TranslateCharmap(PyObject *input,
8648 PyObject *mapping,
8649 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008650{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008651 /* input object */
8652 char *idata;
8653 Py_ssize_t size, i;
8654 int kind;
8655 /* output buffer */
8656 Py_UCS4 *output = NULL;
8657 Py_ssize_t osize;
8658 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008659 /* current output position */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008660 Py_ssize_t opos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008661 char *reason = "character maps to <undefined>";
8662 PyObject *errorHandler = NULL;
8663 PyObject *exc = NULL;
8664 /* the following variable is used for caching string comparisons
8665 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8666 * 3=ignore, 4=xmlcharrefreplace */
8667 int known_errorHandler = -1;
8668
Guido van Rossumd57fd912000-03-10 22:53:23 +00008669 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008670 PyErr_BadArgument();
8671 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008672 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008673
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008674 if (PyUnicode_READY(input) == -1)
8675 return NULL;
8676 idata = (char*)PyUnicode_DATA(input);
8677 kind = PyUnicode_KIND(input);
8678 size = PyUnicode_GET_LENGTH(input);
8679 i = 0;
8680
8681 if (size == 0) {
8682 Py_INCREF(input);
8683 return input;
8684 }
8685
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008686 /* allocate enough for a simple 1:1 translation without
8687 replacements, if we need more, we'll resize */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008688 osize = size;
8689 output = PyMem_Malloc(osize * sizeof(Py_UCS4));
8690 opos = 0;
8691 if (output == NULL) {
8692 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00008693 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008694 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008695
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008696 while (i<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008697 /* try to encode it */
8698 PyObject *x = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008699 if (charmaptranslate_output(input, i, mapping,
8700 &output, &osize, &opos, &x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008701 Py_XDECREF(x);
8702 goto onError;
8703 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008704 Py_XDECREF(x);
Benjamin Peterson29060642009-01-31 22:14:21 +00008705 if (x!=Py_None) /* it worked => adjust input pointer */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008706 ++i;
Benjamin Peterson29060642009-01-31 22:14:21 +00008707 else { /* untranslatable character */
8708 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
8709 Py_ssize_t repsize;
8710 Py_ssize_t newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008711 Py_ssize_t uni2;
Benjamin Peterson29060642009-01-31 22:14:21 +00008712 /* startpos for collecting untranslatable chars */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008713 Py_ssize_t collstart = i;
8714 Py_ssize_t collend = i+1;
8715 Py_ssize_t coll;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008716
Benjamin Peterson29060642009-01-31 22:14:21 +00008717 /* find all untranslatable characters */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008718 while (collend < size) {
8719 if (charmaptranslate_lookup(PyUnicode_READ(kind,idata, collend), mapping, &x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008720 goto onError;
8721 Py_XDECREF(x);
8722 if (x!=Py_None)
8723 break;
8724 ++collend;
8725 }
8726 /* cache callback name lookup
8727 * (if not done yet, i.e. it's the first error) */
8728 if (known_errorHandler==-1) {
8729 if ((errors==NULL) || (!strcmp(errors, "strict")))
8730 known_errorHandler = 1;
8731 else if (!strcmp(errors, "replace"))
8732 known_errorHandler = 2;
8733 else if (!strcmp(errors, "ignore"))
8734 known_errorHandler = 3;
8735 else if (!strcmp(errors, "xmlcharrefreplace"))
8736 known_errorHandler = 4;
8737 else
8738 known_errorHandler = 0;
8739 }
8740 switch (known_errorHandler) {
8741 case 1: /* strict */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008742 raise_translate_exception(&exc, input, collstart,
8743 collend, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008744 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00008745 case 2: /* replace */
8746 /* No need to check for space, this is a 1:1 replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008747 for (coll = collstart; coll<collend; coll++)
8748 output[opos++] = '?';
Benjamin Peterson29060642009-01-31 22:14:21 +00008749 /* fall through */
8750 case 3: /* ignore */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008751 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008752 break;
8753 case 4: /* xmlcharrefreplace */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008754 /* generate replacement (temporarily (mis)uses i) */
8755 for (i = collstart; i < collend; ++i) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008756 char buffer[2+29+1+1];
8757 char *cp;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008758 sprintf(buffer, "&#%d;", PyUnicode_READ(kind, idata, i));
8759 if (charmaptranslate_makespace(&output, &osize,
8760 opos+strlen(buffer)+(size-collend)))
Benjamin Peterson29060642009-01-31 22:14:21 +00008761 goto onError;
8762 for (cp = buffer; *cp; ++cp)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008763 output[opos++] = *cp;
Benjamin Peterson29060642009-01-31 22:14:21 +00008764 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008765 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008766 break;
8767 default:
8768 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008769 reason, input, &exc,
8770 collstart, collend, &newpos);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008771 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008772 goto onError;
Benjamin Peterson9ca3ffa2012-01-01 16:04:29 -06008773 if (PyUnicode_READY(repunicode) == -1) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008774 Py_DECREF(repunicode);
8775 goto onError;
8776 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008777 /* generate replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008778 repsize = PyUnicode_GET_LENGTH(repunicode);
8779 if (charmaptranslate_makespace(&output, &osize,
8780 opos+repsize+(size-collend))) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008781 Py_DECREF(repunicode);
8782 goto onError;
8783 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008784 for (uni2 = 0; repsize-->0; ++uni2)
8785 output[opos++] = PyUnicode_READ_CHAR(repunicode, uni2);
8786 i = newpos;
Benjamin Peterson29060642009-01-31 22:14:21 +00008787 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008788 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008789 }
8790 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008791 res = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND, output, opos);
8792 if (!res)
8793 goto onError;
8794 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008795 Py_XDECREF(exc);
8796 Py_XDECREF(errorHandler);
8797 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008798
Benjamin Peterson29060642009-01-31 22:14:21 +00008799 onError:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008800 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008801 Py_XDECREF(exc);
8802 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008803 return NULL;
8804}
8805
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008806/* Deprecated. Use PyUnicode_Translate instead. */
8807PyObject *
8808PyUnicode_TranslateCharmap(const Py_UNICODE *p,
8809 Py_ssize_t size,
8810 PyObject *mapping,
8811 const char *errors)
8812{
8813 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8814 if (!unicode)
8815 return NULL;
8816 return _PyUnicode_TranslateCharmap(unicode, mapping, errors);
8817}
8818
Alexander Belopolsky40018472011-02-26 01:02:56 +00008819PyObject *
8820PyUnicode_Translate(PyObject *str,
8821 PyObject *mapping,
8822 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008823{
8824 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +00008825
Guido van Rossumd57fd912000-03-10 22:53:23 +00008826 str = PyUnicode_FromObject(str);
8827 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008828 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008829 result = _PyUnicode_TranslateCharmap(str, mapping, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008830 Py_DECREF(str);
8831 return result;
Tim Petersced69f82003-09-16 20:30:58 +00008832
Benjamin Peterson29060642009-01-31 22:14:21 +00008833 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00008834 Py_XDECREF(str);
8835 return NULL;
8836}
Tim Petersced69f82003-09-16 20:30:58 +00008837
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008838static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02008839fix_decimal_and_space_to_ascii(PyObject *self)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008840{
8841 /* No need to call PyUnicode_READY(self) because this function is only
8842 called as a callback from fixup() which does it already. */
8843 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
8844 const int kind = PyUnicode_KIND(self);
8845 void *data = PyUnicode_DATA(self);
8846 Py_UCS4 maxchar = 0, ch, fixed;
8847 Py_ssize_t i;
8848
8849 for (i = 0; i < len; ++i) {
8850 ch = PyUnicode_READ(kind, data, i);
8851 fixed = 0;
8852 if (ch > 127) {
8853 if (Py_UNICODE_ISSPACE(ch))
8854 fixed = ' ';
8855 else {
8856 const int decimal = Py_UNICODE_TODECIMAL(ch);
8857 if (decimal >= 0)
8858 fixed = '0' + decimal;
8859 }
8860 if (fixed != 0) {
8861 if (fixed > maxchar)
8862 maxchar = fixed;
8863 PyUnicode_WRITE(kind, data, i, fixed);
8864 }
8865 else if (ch > maxchar)
8866 maxchar = ch;
8867 }
8868 else if (ch > maxchar)
8869 maxchar = ch;
8870 }
8871
8872 return maxchar;
8873}
8874
8875PyObject *
8876_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
8877{
8878 if (!PyUnicode_Check(unicode)) {
8879 PyErr_BadInternalCall();
8880 return NULL;
8881 }
8882 if (PyUnicode_READY(unicode) == -1)
8883 return NULL;
8884 if (PyUnicode_MAX_CHAR_VALUE(unicode) <= 127) {
8885 /* If the string is already ASCII, just return the same string */
8886 Py_INCREF(unicode);
8887 return unicode;
8888 }
Victor Stinner9310abb2011-10-05 00:59:23 +02008889 return fixup(unicode, fix_decimal_and_space_to_ascii);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008890}
8891
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008892PyObject *
8893PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
8894 Py_ssize_t length)
8895{
Victor Stinnerf0124502011-11-21 23:12:56 +01008896 PyObject *decimal;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008897 Py_ssize_t i;
Victor Stinnerf0124502011-11-21 23:12:56 +01008898 Py_UCS4 maxchar;
8899 enum PyUnicode_Kind kind;
8900 void *data;
8901
8902 maxchar = 0;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008903 for (i = 0; i < length; i++) {
Victor Stinnerf0124502011-11-21 23:12:56 +01008904 Py_UNICODE ch = s[i];
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008905 if (ch > 127) {
8906 int decimal = Py_UNICODE_TODECIMAL(ch);
8907 if (decimal >= 0)
Victor Stinnerf0124502011-11-21 23:12:56 +01008908 ch = '0' + decimal;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008909 }
Victor Stinnerf0124502011-11-21 23:12:56 +01008910 maxchar = Py_MAX(maxchar, ch);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008911 }
Victor Stinnerf0124502011-11-21 23:12:56 +01008912
8913 /* Copy to a new string */
8914 decimal = PyUnicode_New(length, maxchar);
8915 if (decimal == NULL)
8916 return decimal;
8917 kind = PyUnicode_KIND(decimal);
8918 data = PyUnicode_DATA(decimal);
8919 /* Iterate over code points */
8920 for (i = 0; i < length; i++) {
8921 Py_UNICODE ch = s[i];
8922 if (ch > 127) {
8923 int decimal = Py_UNICODE_TODECIMAL(ch);
8924 if (decimal >= 0)
8925 ch = '0' + decimal;
8926 }
8927 PyUnicode_WRITE(kind, data, i, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008928 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008929 return unicode_result(decimal);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008930}
Guido van Rossum9e896b32000-04-05 20:11:21 +00008931/* --- Decimal Encoder ---------------------------------------------------- */
8932
Alexander Belopolsky40018472011-02-26 01:02:56 +00008933int
8934PyUnicode_EncodeDecimal(Py_UNICODE *s,
8935 Py_ssize_t length,
8936 char *output,
8937 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00008938{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008939 PyObject *unicode;
Victor Stinner6345be92011-11-25 20:09:01 +01008940 Py_ssize_t i;
Victor Stinner42bf7752011-11-21 22:52:58 +01008941 enum PyUnicode_Kind kind;
8942 void *data;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008943
8944 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008945 PyErr_BadArgument();
8946 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008947 }
8948
Victor Stinner42bf7752011-11-21 22:52:58 +01008949 unicode = PyUnicode_FromUnicode(s, length);
8950 if (unicode == NULL)
8951 return -1;
8952
Victor Stinner6345be92011-11-25 20:09:01 +01008953 if (PyUnicode_READY(unicode) < 0) {
8954 Py_DECREF(unicode);
8955 return -1;
8956 }
Victor Stinner42bf7752011-11-21 22:52:58 +01008957 kind = PyUnicode_KIND(unicode);
8958 data = PyUnicode_DATA(unicode);
8959
Victor Stinnerb84d7232011-11-22 01:50:07 +01008960 for (i=0; i < length; ) {
Victor Stinner6345be92011-11-25 20:09:01 +01008961 PyObject *exc;
8962 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00008963 int decimal;
Victor Stinner6345be92011-11-25 20:09:01 +01008964 Py_ssize_t startpos;
8965
8966 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +00008967
Benjamin Peterson29060642009-01-31 22:14:21 +00008968 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008969 *output++ = ' ';
Victor Stinnerb84d7232011-11-22 01:50:07 +01008970 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00008971 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008972 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008973 decimal = Py_UNICODE_TODECIMAL(ch);
8974 if (decimal >= 0) {
8975 *output++ = '0' + decimal;
Victor Stinnerb84d7232011-11-22 01:50:07 +01008976 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00008977 continue;
8978 }
8979 if (0 < ch && ch < 256) {
8980 *output++ = (char)ch;
Victor Stinnerb84d7232011-11-22 01:50:07 +01008981 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00008982 continue;
8983 }
Victor Stinner6345be92011-11-25 20:09:01 +01008984
Victor Stinner42bf7752011-11-21 22:52:58 +01008985 startpos = i;
Victor Stinner6345be92011-11-25 20:09:01 +01008986 exc = NULL;
8987 raise_encode_exception(&exc, "decimal", unicode,
8988 startpos, startpos+1,
8989 "invalid decimal Unicode string");
8990 Py_XDECREF(exc);
8991 Py_DECREF(unicode);
8992 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008993 }
8994 /* 0-terminate the output string */
8995 *output++ = '\0';
Victor Stinner42bf7752011-11-21 22:52:58 +01008996 Py_DECREF(unicode);
Guido van Rossum9e896b32000-04-05 20:11:21 +00008997 return 0;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008998}
8999
Guido van Rossumd57fd912000-03-10 22:53:23 +00009000/* --- Helpers ------------------------------------------------------------ */
9001
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009002static Py_ssize_t
Victor Stinner794d5672011-10-10 03:21:36 +02009003any_find_slice(int direction, PyObject* s1, PyObject* s2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009004 Py_ssize_t start,
9005 Py_ssize_t end)
9006{
9007 int kind1, kind2, kind;
9008 void *buf1, *buf2;
9009 Py_ssize_t len1, len2, result;
9010
9011 kind1 = PyUnicode_KIND(s1);
9012 kind2 = PyUnicode_KIND(s2);
9013 kind = kind1 > kind2 ? kind1 : kind2;
9014 buf1 = PyUnicode_DATA(s1);
9015 buf2 = PyUnicode_DATA(s2);
9016 if (kind1 != kind)
9017 buf1 = _PyUnicode_AsKind(s1, kind);
9018 if (!buf1)
9019 return -2;
9020 if (kind2 != kind)
9021 buf2 = _PyUnicode_AsKind(s2, kind);
9022 if (!buf2) {
9023 if (kind1 != kind) PyMem_Free(buf1);
9024 return -2;
9025 }
9026 len1 = PyUnicode_GET_LENGTH(s1);
9027 len2 = PyUnicode_GET_LENGTH(s2);
9028
Victor Stinner794d5672011-10-10 03:21:36 +02009029 if (direction > 0) {
Benjamin Petersonead6b532011-12-20 17:23:42 -06009030 switch (kind) {
Victor Stinner794d5672011-10-10 03:21:36 +02009031 case PyUnicode_1BYTE_KIND:
9032 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9033 result = asciilib_find_slice(buf1, len1, buf2, len2, start, end);
9034 else
9035 result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end);
9036 break;
9037 case PyUnicode_2BYTE_KIND:
9038 result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end);
9039 break;
9040 case PyUnicode_4BYTE_KIND:
9041 result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end);
9042 break;
9043 default:
9044 assert(0); result = -2;
9045 }
9046 }
9047 else {
Benjamin Petersonead6b532011-12-20 17:23:42 -06009048 switch (kind) {
Victor Stinner794d5672011-10-10 03:21:36 +02009049 case PyUnicode_1BYTE_KIND:
9050 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9051 result = asciilib_rfind_slice(buf1, len1, buf2, len2, start, end);
9052 else
9053 result = ucs1lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9054 break;
9055 case PyUnicode_2BYTE_KIND:
9056 result = ucs2lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9057 break;
9058 case PyUnicode_4BYTE_KIND:
9059 result = ucs4lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9060 break;
9061 default:
9062 assert(0); result = -2;
9063 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009064 }
9065
9066 if (kind1 != kind)
9067 PyMem_Free(buf1);
9068 if (kind2 != kind)
9069 PyMem_Free(buf2);
9070
9071 return result;
9072}
9073
9074Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +02009075_PyUnicode_InsertThousandsGrouping(PyObject *unicode, int kind, void *data,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009076 Py_ssize_t n_buffer,
9077 void *digits, Py_ssize_t n_digits,
9078 Py_ssize_t min_width,
9079 const char *grouping,
9080 const char *thousands_sep)
9081{
Benjamin Petersonead6b532011-12-20 17:23:42 -06009082 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009083 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009084 if (unicode != NULL && PyUnicode_IS_ASCII(unicode))
9085 return _PyUnicode_ascii_InsertThousandsGrouping(
9086 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
9087 min_width, grouping, thousands_sep);
9088 else
9089 return _PyUnicode_ucs1_InsertThousandsGrouping(
9090 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
9091 min_width, grouping, thousands_sep);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009092 case PyUnicode_2BYTE_KIND:
9093 return _PyUnicode_ucs2_InsertThousandsGrouping(
9094 (Py_UCS2*)data, n_buffer, (Py_UCS2*)digits, n_digits,
9095 min_width, grouping, thousands_sep);
9096 case PyUnicode_4BYTE_KIND:
9097 return _PyUnicode_ucs4_InsertThousandsGrouping(
9098 (Py_UCS4*)data, n_buffer, (Py_UCS4*)digits, n_digits,
9099 min_width, grouping, thousands_sep);
9100 }
9101 assert(0);
9102 return -1;
9103}
9104
9105
Thomas Wouters477c8d52006-05-27 19:21:47 +00009106/* helper macro to fixup start/end slice values */
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009107#define ADJUST_INDICES(start, end, len) \
9108 if (end > len) \
9109 end = len; \
9110 else if (end < 0) { \
9111 end += len; \
9112 if (end < 0) \
9113 end = 0; \
9114 } \
9115 if (start < 0) { \
9116 start += len; \
9117 if (start < 0) \
9118 start = 0; \
9119 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009120
Alexander Belopolsky40018472011-02-26 01:02:56 +00009121Py_ssize_t
9122PyUnicode_Count(PyObject *str,
9123 PyObject *substr,
9124 Py_ssize_t start,
9125 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009126{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009127 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009128 PyObject* str_obj;
9129 PyObject* sub_obj;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009130 int kind1, kind2, kind;
9131 void *buf1 = NULL, *buf2 = NULL;
9132 Py_ssize_t len1, len2;
Tim Petersced69f82003-09-16 20:30:58 +00009133
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009134 str_obj = PyUnicode_FromObject(str);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009135 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +00009136 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009137 sub_obj = PyUnicode_FromObject(substr);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009138 if (!sub_obj) {
9139 Py_DECREF(str_obj);
9140 return -1;
9141 }
Benjamin Peterson4c13a4a2012-01-02 09:07:38 -06009142 if (PyUnicode_READY(sub_obj) == -1 || PyUnicode_READY(str_obj) == -1) {
Benjamin Peterson5e458f52012-01-02 10:12:13 -06009143 Py_DECREF(sub_obj);
Benjamin Peterson29060642009-01-31 22:14:21 +00009144 Py_DECREF(str_obj);
9145 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009146 }
Tim Petersced69f82003-09-16 20:30:58 +00009147
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009148 kind1 = PyUnicode_KIND(str_obj);
9149 kind2 = PyUnicode_KIND(sub_obj);
9150 kind = kind1 > kind2 ? kind1 : kind2;
9151 buf1 = PyUnicode_DATA(str_obj);
9152 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009153 buf1 = _PyUnicode_AsKind(str_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009154 if (!buf1)
9155 goto onError;
9156 buf2 = PyUnicode_DATA(sub_obj);
9157 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009158 buf2 = _PyUnicode_AsKind(sub_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009159 if (!buf2)
9160 goto onError;
9161 len1 = PyUnicode_GET_LENGTH(str_obj);
9162 len2 = PyUnicode_GET_LENGTH(sub_obj);
9163
9164 ADJUST_INDICES(start, end, len1);
Benjamin Petersonead6b532011-12-20 17:23:42 -06009165 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009166 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009167 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sub_obj))
9168 result = asciilib_count(
9169 ((Py_UCS1*)buf1) + start, end - start,
9170 buf2, len2, PY_SSIZE_T_MAX
9171 );
9172 else
9173 result = ucs1lib_count(
9174 ((Py_UCS1*)buf1) + start, end - start,
9175 buf2, len2, PY_SSIZE_T_MAX
9176 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009177 break;
9178 case PyUnicode_2BYTE_KIND:
9179 result = ucs2lib_count(
9180 ((Py_UCS2*)buf1) + start, end - start,
9181 buf2, len2, PY_SSIZE_T_MAX
9182 );
9183 break;
9184 case PyUnicode_4BYTE_KIND:
9185 result = ucs4lib_count(
9186 ((Py_UCS4*)buf1) + start, end - start,
9187 buf2, len2, PY_SSIZE_T_MAX
9188 );
9189 break;
9190 default:
9191 assert(0); result = 0;
9192 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009193
9194 Py_DECREF(sub_obj);
9195 Py_DECREF(str_obj);
9196
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009197 if (kind1 != kind)
9198 PyMem_Free(buf1);
9199 if (kind2 != kind)
9200 PyMem_Free(buf2);
9201
Guido van Rossumd57fd912000-03-10 22:53:23 +00009202 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009203 onError:
9204 Py_DECREF(sub_obj);
9205 Py_DECREF(str_obj);
9206 if (kind1 != kind && buf1)
9207 PyMem_Free(buf1);
9208 if (kind2 != kind && buf2)
9209 PyMem_Free(buf2);
9210 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009211}
9212
Alexander Belopolsky40018472011-02-26 01:02:56 +00009213Py_ssize_t
9214PyUnicode_Find(PyObject *str,
9215 PyObject *sub,
9216 Py_ssize_t start,
9217 Py_ssize_t end,
9218 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009219{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009220 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009221
Guido van Rossumd57fd912000-03-10 22:53:23 +00009222 str = PyUnicode_FromObject(str);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009223 if (!str)
Benjamin Peterson29060642009-01-31 22:14:21 +00009224 return -2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009225 sub = PyUnicode_FromObject(sub);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009226 if (!sub) {
9227 Py_DECREF(str);
9228 return -2;
9229 }
9230 if (PyUnicode_READY(sub) == -1 || PyUnicode_READY(str) == -1) {
9231 Py_DECREF(sub);
Benjamin Peterson29060642009-01-31 22:14:21 +00009232 Py_DECREF(str);
9233 return -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009234 }
Tim Petersced69f82003-09-16 20:30:58 +00009235
Victor Stinner794d5672011-10-10 03:21:36 +02009236 result = any_find_slice(direction,
9237 str, sub, start, end
9238 );
Thomas Wouters477c8d52006-05-27 19:21:47 +00009239
Guido van Rossumd57fd912000-03-10 22:53:23 +00009240 Py_DECREF(str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009241 Py_DECREF(sub);
9242
Guido van Rossumd57fd912000-03-10 22:53:23 +00009243 return result;
9244}
9245
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009246Py_ssize_t
9247PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
9248 Py_ssize_t start, Py_ssize_t end,
9249 int direction)
9250{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009251 int kind;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009252 Py_ssize_t result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009253 if (PyUnicode_READY(str) == -1)
9254 return -2;
Victor Stinner267aa242011-10-02 01:08:37 +02009255 if (start < 0 || end < 0) {
9256 PyErr_SetString(PyExc_IndexError, "string index out of range");
9257 return -2;
9258 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009259 if (end > PyUnicode_GET_LENGTH(str))
9260 end = PyUnicode_GET_LENGTH(str);
9261 kind = PyUnicode_KIND(str);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009262 result = findchar(PyUnicode_1BYTE_DATA(str) + kind*start,
9263 kind, end-start, ch, direction);
9264 if (result == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009265 return -1;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009266 else
9267 return start + result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009268}
9269
Alexander Belopolsky40018472011-02-26 01:02:56 +00009270static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009271tailmatch(PyObject *self,
9272 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009273 Py_ssize_t start,
9274 Py_ssize_t end,
9275 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009276{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009277 int kind_self;
9278 int kind_sub;
9279 void *data_self;
9280 void *data_sub;
9281 Py_ssize_t offset;
9282 Py_ssize_t i;
9283 Py_ssize_t end_sub;
9284
9285 if (PyUnicode_READY(self) == -1 ||
9286 PyUnicode_READY(substring) == -1)
9287 return 0;
9288
9289 if (PyUnicode_GET_LENGTH(substring) == 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009290 return 1;
9291
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009292 ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
9293 end -= PyUnicode_GET_LENGTH(substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009294 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00009295 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009296
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009297 kind_self = PyUnicode_KIND(self);
9298 data_self = PyUnicode_DATA(self);
9299 kind_sub = PyUnicode_KIND(substring);
9300 data_sub = PyUnicode_DATA(substring);
9301 end_sub = PyUnicode_GET_LENGTH(substring) - 1;
9302
9303 if (direction > 0)
9304 offset = end;
9305 else
9306 offset = start;
9307
9308 if (PyUnicode_READ(kind_self, data_self, offset) ==
9309 PyUnicode_READ(kind_sub, data_sub, 0) &&
9310 PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
9311 PyUnicode_READ(kind_sub, data_sub, end_sub)) {
9312 /* If both are of the same kind, memcmp is sufficient */
9313 if (kind_self == kind_sub) {
9314 return ! memcmp((char *)data_self +
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009315 (offset * PyUnicode_KIND(substring)),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009316 data_sub,
9317 PyUnicode_GET_LENGTH(substring) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009318 PyUnicode_KIND(substring));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009319 }
9320 /* otherwise we have to compare each character by first accesing it */
9321 else {
9322 /* We do not need to compare 0 and len(substring)-1 because
9323 the if statement above ensured already that they are equal
9324 when we end up here. */
9325 // TODO: honor direction and do a forward or backwards search
9326 for (i = 1; i < end_sub; ++i) {
9327 if (PyUnicode_READ(kind_self, data_self, offset + i) !=
9328 PyUnicode_READ(kind_sub, data_sub, i))
9329 return 0;
9330 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009331 return 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009332 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009333 }
9334
9335 return 0;
9336}
9337
Alexander Belopolsky40018472011-02-26 01:02:56 +00009338Py_ssize_t
9339PyUnicode_Tailmatch(PyObject *str,
9340 PyObject *substr,
9341 Py_ssize_t start,
9342 Py_ssize_t end,
9343 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009344{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009345 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009346
Guido van Rossumd57fd912000-03-10 22:53:23 +00009347 str = PyUnicode_FromObject(str);
9348 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009349 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009350 substr = PyUnicode_FromObject(substr);
9351 if (substr == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009352 Py_DECREF(str);
9353 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009354 }
Tim Petersced69f82003-09-16 20:30:58 +00009355
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009356 result = tailmatch(str, substr,
Benjamin Peterson29060642009-01-31 22:14:21 +00009357 start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009358 Py_DECREF(str);
9359 Py_DECREF(substr);
9360 return result;
9361}
9362
Guido van Rossumd57fd912000-03-10 22:53:23 +00009363/* Apply fixfct filter to the Unicode object self and return a
9364 reference to the modified object */
9365
Alexander Belopolsky40018472011-02-26 01:02:56 +00009366static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009367fixup(PyObject *self,
9368 Py_UCS4 (*fixfct)(PyObject *s))
Guido van Rossumd57fd912000-03-10 22:53:23 +00009369{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009370 PyObject *u;
9371 Py_UCS4 maxchar_old, maxchar_new = 0;
Victor Stinnereaab6042011-12-11 22:22:39 +01009372 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009373
Victor Stinnerbf6e5602011-12-12 01:53:47 +01009374 u = _PyUnicode_Copy(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009375 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009376 return NULL;
Victor Stinner87af4f22011-11-21 23:03:47 +01009377 maxchar_old = PyUnicode_MAX_CHAR_VALUE(u);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009378
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009379 /* fix functions return the new maximum character in a string,
9380 if the kind of the resulting unicode object does not change,
9381 everything is fine. Otherwise we need to change the string kind
9382 and re-run the fix function. */
Victor Stinner9310abb2011-10-05 00:59:23 +02009383 maxchar_new = fixfct(u);
Victor Stinnereaab6042011-12-11 22:22:39 +01009384
9385 if (maxchar_new == 0) {
9386 /* no changes */;
9387 if (PyUnicode_CheckExact(self)) {
9388 Py_DECREF(u);
9389 Py_INCREF(self);
9390 return self;
9391 }
9392 else
9393 return u;
9394 }
9395
9396 if (maxchar_new <= 127)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009397 maxchar_new = 127;
9398 else if (maxchar_new <= 255)
9399 maxchar_new = 255;
9400 else if (maxchar_new <= 65535)
9401 maxchar_new = 65535;
9402 else
Victor Stinner8faf8212011-12-08 22:14:11 +01009403 maxchar_new = MAX_UNICODE;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009404
Victor Stinnereaab6042011-12-11 22:22:39 +01009405 if (maxchar_new == maxchar_old)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009406 return u;
Victor Stinnereaab6042011-12-11 22:22:39 +01009407
9408 /* In case the maximum character changed, we need to
9409 convert the string to the new category. */
9410 v = PyUnicode_New(PyUnicode_GET_LENGTH(self), maxchar_new);
9411 if (v == NULL) {
9412 Py_DECREF(u);
9413 return NULL;
9414 }
9415 if (maxchar_new > maxchar_old) {
9416 /* If the maxchar increased so that the kind changed, not all
9417 characters are representable anymore and we need to fix the
9418 string again. This only happens in very few cases. */
9419 copy_characters(v, 0, self, 0, PyUnicode_GET_LENGTH(self));
9420 maxchar_old = fixfct(v);
9421 assert(maxchar_old > 0 && maxchar_old <= maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009422 }
9423 else {
Victor Stinnereaab6042011-12-11 22:22:39 +01009424 copy_characters(v, 0, u, 0, PyUnicode_GET_LENGTH(self));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009425 }
Victor Stinnereaab6042011-12-11 22:22:39 +01009426 Py_DECREF(u);
9427 assert(_PyUnicode_CheckConsistency(v, 1));
9428 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009429}
9430
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009431static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009432fixupper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009433{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009434 /* No need to call PyUnicode_READY(self) because this function is only
9435 called as a callback from fixup() which does it already. */
9436 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9437 const int kind = PyUnicode_KIND(self);
9438 void *data = PyUnicode_DATA(self);
9439 int touched = 0;
9440 Py_UCS4 maxchar = 0;
9441 Py_ssize_t i;
Tim Petersced69f82003-09-16 20:30:58 +00009442
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009443 for (i = 0; i < len; ++i) {
9444 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9445 const Py_UCS4 up = Py_UNICODE_TOUPPER(ch);
9446 if (up != ch) {
9447 if (up > maxchar)
9448 maxchar = up;
9449 PyUnicode_WRITE(kind, data, i, up);
9450 touched = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00009451 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009452 else if (ch > maxchar)
9453 maxchar = ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009454 }
9455
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009456 if (touched)
9457 return maxchar;
9458 else
9459 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009460}
9461
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009462static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009463fixlower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009464{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009465 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
9466 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9467 const int kind = PyUnicode_KIND(self);
9468 void *data = PyUnicode_DATA(self);
9469 int touched = 0;
9470 Py_UCS4 maxchar = 0;
9471 Py_ssize_t i;
Tim Petersced69f82003-09-16 20:30:58 +00009472
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009473 for(i = 0; i < len; ++i) {
9474 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9475 const Py_UCS4 lo = Py_UNICODE_TOLOWER(ch);
9476 if (lo != ch) {
9477 if (lo > maxchar)
9478 maxchar = lo;
9479 PyUnicode_WRITE(kind, data, i, lo);
9480 touched = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00009481 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009482 else if (ch > maxchar)
9483 maxchar = ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009484 }
9485
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009486 if (touched)
9487 return maxchar;
9488 else
9489 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009490}
9491
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009492static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009493fixswapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009494{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009495 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
9496 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9497 const int kind = PyUnicode_KIND(self);
9498 void *data = PyUnicode_DATA(self);
9499 int touched = 0;
9500 Py_UCS4 maxchar = 0;
9501 Py_ssize_t i;
Tim Petersced69f82003-09-16 20:30:58 +00009502
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009503 for(i = 0; i < len; ++i) {
9504 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9505 Py_UCS4 nu = 0;
9506
9507 if (Py_UNICODE_ISUPPER(ch))
9508 nu = Py_UNICODE_TOLOWER(ch);
9509 else if (Py_UNICODE_ISLOWER(ch))
9510 nu = Py_UNICODE_TOUPPER(ch);
9511
9512 if (nu != 0) {
9513 if (nu > maxchar)
9514 maxchar = nu;
9515 PyUnicode_WRITE(kind, data, i, nu);
9516 touched = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009517 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009518 else if (ch > maxchar)
9519 maxchar = ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009520 }
9521
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009522 if (touched)
9523 return maxchar;
9524 else
9525 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009526}
9527
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009528static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009529fixcapitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009530{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009531 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
9532 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9533 const int kind = PyUnicode_KIND(self);
9534 void *data = PyUnicode_DATA(self);
9535 int touched = 0;
9536 Py_UCS4 maxchar = 0;
9537 Py_ssize_t i = 0;
9538 Py_UCS4 ch;
Tim Petersced69f82003-09-16 20:30:58 +00009539
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009540 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009541 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009542
9543 ch = PyUnicode_READ(kind, data, i);
9544 if (!Py_UNICODE_ISUPPER(ch)) {
9545 maxchar = Py_UNICODE_TOUPPER(ch);
9546 PyUnicode_WRITE(kind, data, i, maxchar);
9547 touched = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009548 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009549 ++i;
9550 for(; i < len; ++i) {
9551 ch = PyUnicode_READ(kind, data, i);
9552 if (!Py_UNICODE_ISLOWER(ch)) {
9553 const Py_UCS4 lo = Py_UNICODE_TOLOWER(ch);
9554 if (lo > maxchar)
9555 maxchar = lo;
9556 PyUnicode_WRITE(kind, data, i, lo);
9557 touched = 1;
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009558 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009559 else if (ch > maxchar)
9560 maxchar = ch;
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009561 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009562
9563 if (touched)
9564 return maxchar;
9565 else
9566 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009567}
9568
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009569static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009570fixtitle(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009571{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009572 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
9573 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9574 const int kind = PyUnicode_KIND(self);
9575 void *data = PyUnicode_DATA(self);
9576 Py_UCS4 maxchar = 0;
9577 Py_ssize_t i = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009578 int previous_is_cased;
9579
9580 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009581 if (len == 1) {
9582 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9583 const Py_UCS4 ti = Py_UNICODE_TOTITLE(ch);
9584 if (ti != ch) {
9585 PyUnicode_WRITE(kind, data, i, ti);
9586 return ti;
Benjamin Peterson29060642009-01-31 22:14:21 +00009587 }
9588 else
9589 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009590 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009591 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009592 for(; i < len; ++i) {
9593 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9594 Py_UCS4 nu;
Tim Petersced69f82003-09-16 20:30:58 +00009595
Benjamin Peterson29060642009-01-31 22:14:21 +00009596 if (previous_is_cased)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009597 nu = Py_UNICODE_TOLOWER(ch);
Benjamin Peterson29060642009-01-31 22:14:21 +00009598 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009599 nu = Py_UNICODE_TOTITLE(ch);
9600
9601 if (nu > maxchar)
9602 maxchar = nu;
9603 PyUnicode_WRITE(kind, data, i, nu);
Tim Petersced69f82003-09-16 20:30:58 +00009604
Benjamin Peterson29060642009-01-31 22:14:21 +00009605 if (Py_UNICODE_ISLOWER(ch) ||
9606 Py_UNICODE_ISUPPER(ch) ||
9607 Py_UNICODE_ISTITLE(ch))
9608 previous_is_cased = 1;
9609 else
9610 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009611 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009612 return maxchar;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009613}
9614
Tim Peters8ce9f162004-08-27 01:49:32 +00009615PyObject *
9616PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009617{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009618 PyObject *sep = NULL;
Victor Stinnerdd077322011-10-07 17:02:31 +02009619 Py_ssize_t seplen;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009620 PyObject *res = NULL; /* the result */
Tim Peters05eba1f2004-08-27 21:32:02 +00009621 PyObject *fseq; /* PySequence_Fast(seq) */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009622 Py_ssize_t seqlen; /* len(fseq) -- number of items in sequence */
9623 PyObject **items;
Tim Peters8ce9f162004-08-27 01:49:32 +00009624 PyObject *item;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009625 Py_ssize_t sz, i, res_offset;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009626 Py_UCS4 maxchar;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009627 Py_UCS4 item_maxchar;
Victor Stinnerdd077322011-10-07 17:02:31 +02009628 int use_memcpy;
9629 unsigned char *res_data = NULL, *sep_data = NULL;
9630 PyObject *last_obj;
9631 unsigned int kind = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009632
Tim Peters05eba1f2004-08-27 21:32:02 +00009633 fseq = PySequence_Fast(seq, "");
9634 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009635 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00009636 }
9637
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009638 /* NOTE: the following code can't call back into Python code,
9639 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00009640 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009641
Tim Peters05eba1f2004-08-27 21:32:02 +00009642 seqlen = PySequence_Fast_GET_SIZE(fseq);
9643 /* If empty sequence, return u"". */
9644 if (seqlen == 0) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009645 Py_DECREF(fseq);
9646 Py_INCREF(unicode_empty);
9647 res = unicode_empty;
9648 return res;
Tim Peters05eba1f2004-08-27 21:32:02 +00009649 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009650
Tim Peters05eba1f2004-08-27 21:32:02 +00009651 /* If singleton sequence with an exact Unicode, return that. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009652 last_obj = NULL;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009653 items = PySequence_Fast_ITEMS(fseq);
Victor Stinneracf47b82011-10-06 12:32:37 +02009654 if (seqlen == 1) {
9655 if (PyUnicode_CheckExact(items[0])) {
9656 res = items[0];
9657 Py_INCREF(res);
9658 Py_DECREF(fseq);
9659 return res;
9660 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009661 seplen = 0;
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009662 maxchar = 0;
Tim Peters8ce9f162004-08-27 01:49:32 +00009663 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009664 else {
Victor Stinneracf47b82011-10-06 12:32:37 +02009665 /* Set up sep and seplen */
9666 if (separator == NULL) {
9667 /* fall back to a blank space separator */
9668 sep = PyUnicode_FromOrdinal(' ');
9669 if (!sep)
9670 goto onError;
Victor Stinnerdd077322011-10-07 17:02:31 +02009671 seplen = 1;
Victor Stinneracf47b82011-10-06 12:32:37 +02009672 maxchar = 32;
Tim Peters05eba1f2004-08-27 21:32:02 +00009673 }
Victor Stinneracf47b82011-10-06 12:32:37 +02009674 else {
9675 if (!PyUnicode_Check(separator)) {
9676 PyErr_Format(PyExc_TypeError,
9677 "separator: expected str instance,"
9678 " %.80s found",
9679 Py_TYPE(separator)->tp_name);
9680 goto onError;
9681 }
9682 if (PyUnicode_READY(separator))
9683 goto onError;
9684 sep = separator;
9685 seplen = PyUnicode_GET_LENGTH(separator);
9686 maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
9687 /* inc refcount to keep this code path symmetric with the
9688 above case of a blank separator */
9689 Py_INCREF(sep);
9690 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009691 last_obj = sep;
Tim Peters05eba1f2004-08-27 21:32:02 +00009692 }
9693
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009694 /* There are at least two things to join, or else we have a subclass
9695 * of str in the sequence.
9696 * Do a pre-pass to figure out the total amount of space we'll
9697 * need (sz), and see whether all argument are strings.
9698 */
9699 sz = 0;
Victor Stinnerdd077322011-10-07 17:02:31 +02009700#ifdef Py_DEBUG
9701 use_memcpy = 0;
9702#else
9703 use_memcpy = 1;
9704#endif
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009705 for (i = 0; i < seqlen; i++) {
9706 const Py_ssize_t old_sz = sz;
9707 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009708 if (!PyUnicode_Check(item)) {
9709 PyErr_Format(PyExc_TypeError,
9710 "sequence item %zd: expected str instance,"
9711 " %.80s found",
9712 i, Py_TYPE(item)->tp_name);
9713 goto onError;
9714 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009715 if (PyUnicode_READY(item) == -1)
9716 goto onError;
9717 sz += PyUnicode_GET_LENGTH(item);
9718 item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009719 maxchar = Py_MAX(maxchar, item_maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009720 if (i != 0)
9721 sz += seplen;
9722 if (sz < old_sz || sz > PY_SSIZE_T_MAX) {
9723 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009724 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009725 goto onError;
9726 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009727 if (use_memcpy && last_obj != NULL) {
9728 if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
9729 use_memcpy = 0;
9730 }
9731 last_obj = item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009732 }
Tim Petersced69f82003-09-16 20:30:58 +00009733
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009734 res = PyUnicode_New(sz, maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009735 if (res == NULL)
9736 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +00009737
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009738 /* Catenate everything. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009739#ifdef Py_DEBUG
9740 use_memcpy = 0;
9741#else
9742 if (use_memcpy) {
9743 res_data = PyUnicode_1BYTE_DATA(res);
9744 kind = PyUnicode_KIND(res);
9745 if (seplen != 0)
9746 sep_data = PyUnicode_1BYTE_DATA(sep);
9747 }
9748#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009749 for (i = 0, res_offset = 0; i < seqlen; ++i) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009750 Py_ssize_t itemlen;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009751 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009752 /* Copy item, and maybe the separator. */
Victor Stinner9ce5a832011-10-03 23:36:02 +02009753 if (i && seplen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009754 if (use_memcpy) {
9755 Py_MEMCPY(res_data,
9756 sep_data,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009757 kind * seplen);
9758 res_data += kind * seplen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009759 }
9760 else {
9761 copy_characters(res, res_offset, sep, 0, seplen);
9762 res_offset += seplen;
9763 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009764 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009765 itemlen = PyUnicode_GET_LENGTH(item);
9766 if (itemlen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009767 if (use_memcpy) {
9768 Py_MEMCPY(res_data,
9769 PyUnicode_DATA(item),
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009770 kind * itemlen);
9771 res_data += kind * itemlen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009772 }
9773 else {
9774 copy_characters(res, res_offset, item, 0, itemlen);
9775 res_offset += itemlen;
9776 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009777 }
Tim Peters05eba1f2004-08-27 21:32:02 +00009778 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009779 if (use_memcpy)
9780 assert(res_data == PyUnicode_1BYTE_DATA(res)
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009781 + kind * PyUnicode_GET_LENGTH(res));
Victor Stinnerdd077322011-10-07 17:02:31 +02009782 else
9783 assert(res_offset == PyUnicode_GET_LENGTH(res));
Tim Peters8ce9f162004-08-27 01:49:32 +00009784
Tim Peters05eba1f2004-08-27 21:32:02 +00009785 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009786 Py_XDECREF(sep);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009787 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009788 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009789
Benjamin Peterson29060642009-01-31 22:14:21 +00009790 onError:
Tim Peters05eba1f2004-08-27 21:32:02 +00009791 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009792 Py_XDECREF(sep);
Tim Peters8ce9f162004-08-27 01:49:32 +00009793 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009794 return NULL;
9795}
9796
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009797#define FILL(kind, data, value, start, length) \
9798 do { \
9799 Py_ssize_t i_ = 0; \
9800 assert(kind != PyUnicode_WCHAR_KIND); \
9801 switch ((kind)) { \
9802 case PyUnicode_1BYTE_KIND: { \
9803 unsigned char * to_ = (unsigned char *)((data)) + (start); \
9804 memset(to_, (unsigned char)value, length); \
9805 break; \
9806 } \
9807 case PyUnicode_2BYTE_KIND: { \
9808 Py_UCS2 * to_ = (Py_UCS2 *)((data)) + (start); \
9809 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9810 break; \
9811 } \
Benjamin Petersone157cf12012-01-01 15:56:20 -06009812 case PyUnicode_4BYTE_KIND: { \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009813 Py_UCS4 * to_ = (Py_UCS4 *)((data)) + (start); \
9814 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9815 break; \
Benjamin Petersone157cf12012-01-01 15:56:20 -06009816 default: assert(0); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009817 } \
9818 } \
9819 } while (0)
9820
Victor Stinner3fe55312012-01-04 00:33:50 +01009821Py_ssize_t
9822PyUnicode_Fill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
9823 Py_UCS4 fill_char)
9824{
9825 Py_ssize_t maxlen;
9826 enum PyUnicode_Kind kind;
9827 void *data;
9828
9829 if (!PyUnicode_Check(unicode)) {
9830 PyErr_BadInternalCall();
9831 return -1;
9832 }
9833 if (PyUnicode_READY(unicode) == -1)
9834 return -1;
9835 if (unicode_check_modifiable(unicode))
9836 return -1;
9837
9838 if (fill_char > PyUnicode_MAX_CHAR_VALUE(unicode)) {
9839 PyErr_SetString(PyExc_ValueError,
9840 "fill character is bigger than "
9841 "the string maximum character");
9842 return -1;
9843 }
9844
9845 maxlen = PyUnicode_GET_LENGTH(unicode) - start;
9846 length = Py_MIN(maxlen, length);
9847 if (length <= 0)
9848 return 0;
9849
9850 kind = PyUnicode_KIND(unicode);
9851 data = PyUnicode_DATA(unicode);
9852 FILL(kind, data, fill_char, start, length);
9853 return length;
9854}
9855
Victor Stinner9310abb2011-10-05 00:59:23 +02009856static PyObject *
9857pad(PyObject *self,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009858 Py_ssize_t left,
9859 Py_ssize_t right,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009860 Py_UCS4 fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009861{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009862 PyObject *u;
9863 Py_UCS4 maxchar;
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009864 int kind;
9865 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009866
9867 if (left < 0)
9868 left = 0;
9869 if (right < 0)
9870 right = 0;
9871
Victor Stinnerc4b49542011-12-11 22:44:26 +01009872 if (left == 0 && right == 0)
9873 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009874
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009875 if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
9876 right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +00009877 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
9878 return NULL;
9879 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009880 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
9881 if (fill > maxchar)
9882 maxchar = fill;
9883 u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009884 if (!u)
9885 return NULL;
9886
9887 kind = PyUnicode_KIND(u);
9888 data = PyUnicode_DATA(u);
9889 if (left)
9890 FILL(kind, data, fill, 0, left);
9891 if (right)
9892 FILL(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009893 copy_characters(u, left, self, 0, _PyUnicode_LENGTH(self));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009894 assert(_PyUnicode_CheckConsistency(u, 1));
9895 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009896}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009897#undef FILL
Guido van Rossumd57fd912000-03-10 22:53:23 +00009898
Alexander Belopolsky40018472011-02-26 01:02:56 +00009899PyObject *
9900PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009901{
Guido van Rossumd57fd912000-03-10 22:53:23 +00009902 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009903
9904 string = PyUnicode_FromObject(string);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009905 if (string == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009906 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -06009907 if (PyUnicode_READY(string) == -1) {
9908 Py_DECREF(string);
9909 return NULL;
9910 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009911
Benjamin Petersonead6b532011-12-20 17:23:42 -06009912 switch (PyUnicode_KIND(string)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009913 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009914 if (PyUnicode_IS_ASCII(string))
9915 list = asciilib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009916 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009917 PyUnicode_GET_LENGTH(string), keepends);
9918 else
9919 list = ucs1lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009920 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009921 PyUnicode_GET_LENGTH(string), keepends);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009922 break;
9923 case PyUnicode_2BYTE_KIND:
9924 list = ucs2lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009925 string, PyUnicode_2BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009926 PyUnicode_GET_LENGTH(string), keepends);
9927 break;
9928 case PyUnicode_4BYTE_KIND:
9929 list = ucs4lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009930 string, PyUnicode_4BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009931 PyUnicode_GET_LENGTH(string), keepends);
9932 break;
9933 default:
9934 assert(0);
9935 list = 0;
9936 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009937 Py_DECREF(string);
9938 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009939}
9940
Alexander Belopolsky40018472011-02-26 01:02:56 +00009941static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009942split(PyObject *self,
9943 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009944 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009945{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009946 int kind1, kind2, kind;
9947 void *buf1, *buf2;
9948 Py_ssize_t len1, len2;
9949 PyObject* out;
9950
Guido van Rossumd57fd912000-03-10 22:53:23 +00009951 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00009952 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009953
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009954 if (PyUnicode_READY(self) == -1)
9955 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009956
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009957 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -06009958 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009959 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009960 if (PyUnicode_IS_ASCII(self))
9961 return asciilib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009962 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009963 PyUnicode_GET_LENGTH(self), maxcount
9964 );
9965 else
9966 return ucs1lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009967 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009968 PyUnicode_GET_LENGTH(self), maxcount
9969 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009970 case PyUnicode_2BYTE_KIND:
9971 return ucs2lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009972 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009973 PyUnicode_GET_LENGTH(self), maxcount
9974 );
9975 case PyUnicode_4BYTE_KIND:
9976 return ucs4lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009977 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009978 PyUnicode_GET_LENGTH(self), maxcount
9979 );
9980 default:
9981 assert(0);
9982 return NULL;
9983 }
9984
9985 if (PyUnicode_READY(substring) == -1)
9986 return NULL;
9987
9988 kind1 = PyUnicode_KIND(self);
9989 kind2 = PyUnicode_KIND(substring);
9990 kind = kind1 > kind2 ? kind1 : kind2;
9991 buf1 = PyUnicode_DATA(self);
9992 buf2 = PyUnicode_DATA(substring);
9993 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009994 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009995 if (!buf1)
9996 return NULL;
9997 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009998 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009999 if (!buf2) {
10000 if (kind1 != kind) PyMem_Free(buf1);
10001 return NULL;
10002 }
10003 len1 = PyUnicode_GET_LENGTH(self);
10004 len2 = PyUnicode_GET_LENGTH(substring);
10005
Benjamin Petersonead6b532011-12-20 17:23:42 -060010006 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010007 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010008 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10009 out = asciilib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010010 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010011 else
10012 out = ucs1lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010013 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010014 break;
10015 case PyUnicode_2BYTE_KIND:
10016 out = ucs2lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010017 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010018 break;
10019 case PyUnicode_4BYTE_KIND:
10020 out = ucs4lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010021 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010022 break;
10023 default:
10024 out = NULL;
10025 }
10026 if (kind1 != kind)
10027 PyMem_Free(buf1);
10028 if (kind2 != kind)
10029 PyMem_Free(buf2);
10030 return out;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010031}
10032
Alexander Belopolsky40018472011-02-26 01:02:56 +000010033static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010034rsplit(PyObject *self,
10035 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010036 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010037{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010038 int kind1, kind2, kind;
10039 void *buf1, *buf2;
10040 Py_ssize_t len1, len2;
10041 PyObject* out;
10042
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010043 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010044 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010045
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010046 if (PyUnicode_READY(self) == -1)
10047 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010048
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010049 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010050 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010051 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010052 if (PyUnicode_IS_ASCII(self))
10053 return asciilib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010054 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010055 PyUnicode_GET_LENGTH(self), maxcount
10056 );
10057 else
10058 return ucs1lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010059 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010060 PyUnicode_GET_LENGTH(self), maxcount
10061 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010062 case PyUnicode_2BYTE_KIND:
10063 return ucs2lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010064 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010065 PyUnicode_GET_LENGTH(self), maxcount
10066 );
10067 case PyUnicode_4BYTE_KIND:
10068 return ucs4lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010069 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010070 PyUnicode_GET_LENGTH(self), maxcount
10071 );
10072 default:
10073 assert(0);
10074 return NULL;
10075 }
10076
10077 if (PyUnicode_READY(substring) == -1)
10078 return NULL;
10079
10080 kind1 = PyUnicode_KIND(self);
10081 kind2 = PyUnicode_KIND(substring);
10082 kind = kind1 > kind2 ? kind1 : kind2;
10083 buf1 = PyUnicode_DATA(self);
10084 buf2 = PyUnicode_DATA(substring);
10085 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010086 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010087 if (!buf1)
10088 return NULL;
10089 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010090 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010091 if (!buf2) {
10092 if (kind1 != kind) PyMem_Free(buf1);
10093 return NULL;
10094 }
10095 len1 = PyUnicode_GET_LENGTH(self);
10096 len2 = PyUnicode_GET_LENGTH(substring);
10097
Benjamin Petersonead6b532011-12-20 17:23:42 -060010098 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010099 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010100 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10101 out = asciilib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010102 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010103 else
10104 out = ucs1lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010105 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010106 break;
10107 case PyUnicode_2BYTE_KIND:
10108 out = ucs2lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010109 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010110 break;
10111 case PyUnicode_4BYTE_KIND:
10112 out = ucs4lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010113 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010114 break;
10115 default:
10116 out = NULL;
10117 }
10118 if (kind1 != kind)
10119 PyMem_Free(buf1);
10120 if (kind2 != kind)
10121 PyMem_Free(buf2);
10122 return out;
10123}
10124
10125static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010126anylib_find(int kind, PyObject *str1, void *buf1, Py_ssize_t len1,
10127 PyObject *str2, void *buf2, Py_ssize_t len2, Py_ssize_t offset)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010128{
Benjamin Petersonead6b532011-12-20 17:23:42 -060010129 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010130 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010131 if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
10132 return asciilib_find(buf1, len1, buf2, len2, offset);
10133 else
10134 return ucs1lib_find(buf1, len1, buf2, len2, offset);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010135 case PyUnicode_2BYTE_KIND:
10136 return ucs2lib_find(buf1, len1, buf2, len2, offset);
10137 case PyUnicode_4BYTE_KIND:
10138 return ucs4lib_find(buf1, len1, buf2, len2, offset);
10139 }
10140 assert(0);
10141 return -1;
10142}
10143
10144static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010145anylib_count(int kind, PyObject *sstr, void* sbuf, Py_ssize_t slen,
10146 PyObject *str1, void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010147{
Benjamin Petersonc0b95d12011-12-20 17:24:05 -060010148 switch (kind) {
10149 case PyUnicode_1BYTE_KIND:
10150 if (PyUnicode_IS_ASCII(sstr) && PyUnicode_IS_ASCII(str1))
10151 return asciilib_count(sbuf, slen, buf1, len1, maxcount);
10152 else
10153 return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
10154 case PyUnicode_2BYTE_KIND:
10155 return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
10156 case PyUnicode_4BYTE_KIND:
10157 return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
10158 }
10159 assert(0);
10160 return 0;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010161}
10162
Alexander Belopolsky40018472011-02-26 01:02:56 +000010163static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010164replace(PyObject *self, PyObject *str1,
10165 PyObject *str2, Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010166{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010167 PyObject *u;
10168 char *sbuf = PyUnicode_DATA(self);
10169 char *buf1 = PyUnicode_DATA(str1);
10170 char *buf2 = PyUnicode_DATA(str2);
10171 int srelease = 0, release1 = 0, release2 = 0;
10172 int skind = PyUnicode_KIND(self);
10173 int kind1 = PyUnicode_KIND(str1);
10174 int kind2 = PyUnicode_KIND(str2);
10175 Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
10176 Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
10177 Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010178 int mayshrink;
10179 Py_UCS4 maxchar, maxchar_str2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010180
10181 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010182 maxcount = PY_SSIZE_T_MAX;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010183 else if (maxcount == 0 || slen == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010184 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010185
Victor Stinner59de0ee2011-10-07 10:01:28 +020010186 if (str1 == str2)
10187 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010188 if (skind < kind1)
10189 /* substring too wide to be present */
10190 goto nothing;
10191
Victor Stinner49a0a212011-10-12 23:46:10 +020010192 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
10193 maxchar_str2 = PyUnicode_MAX_CHAR_VALUE(str2);
10194 /* Replacing str1 with str2 may cause a maxchar reduction in the
10195 result string. */
10196 mayshrink = (maxchar_str2 < maxchar);
10197 maxchar = Py_MAX(maxchar, maxchar_str2);
10198
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010199 if (len1 == len2) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010200 /* same length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010201 if (len1 == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010202 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010203 if (len1 == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010204 /* replace characters */
Victor Stinner49a0a212011-10-12 23:46:10 +020010205 Py_UCS4 u1, u2;
10206 int rkind;
Victor Stinnerf6441102011-12-18 02:43:08 +010010207 Py_ssize_t index, pos;
10208 char *src;
10209
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010210 u1 = PyUnicode_READ_CHAR(str1, 0);
Victor Stinnerf6441102011-12-18 02:43:08 +010010211 pos = findchar(sbuf, PyUnicode_KIND(self), slen, u1, 1);
10212 if (pos < 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010213 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010214 u2 = PyUnicode_READ_CHAR(str2, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010215 u = PyUnicode_New(slen, maxchar);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010216 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010217 goto error;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020010218 copy_characters(u, 0, self, 0, slen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010219 rkind = PyUnicode_KIND(u);
Victor Stinnerf6441102011-12-18 02:43:08 +010010220
10221 PyUnicode_WRITE(rkind, PyUnicode_DATA(u), pos, u2);
10222 index = 0;
10223 src = sbuf;
10224 while (--maxcount)
10225 {
10226 pos++;
10227 src += pos * PyUnicode_KIND(self);
10228 slen -= pos;
10229 index += pos;
10230 pos = findchar(src, PyUnicode_KIND(self), slen, u1, 1);
10231 if (pos < 0)
10232 break;
10233 PyUnicode_WRITE(rkind, PyUnicode_DATA(u), index + pos, u2);
10234 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010235 }
10236 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010237 int rkind = skind;
10238 char *res;
Victor Stinnerf6441102011-12-18 02:43:08 +010010239 Py_ssize_t i;
Victor Stinner25a4b292011-10-06 12:31:55 +020010240
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010241 if (kind1 < rkind) {
10242 /* widen substring */
10243 buf1 = _PyUnicode_AsKind(str1, rkind);
10244 if (!buf1) goto error;
10245 release1 = 1;
10246 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010247 i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010248 if (i < 0)
10249 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010250 if (rkind > kind2) {
10251 /* widen replacement */
10252 buf2 = _PyUnicode_AsKind(str2, rkind);
10253 if (!buf2) goto error;
10254 release2 = 1;
10255 }
10256 else if (rkind < kind2) {
10257 /* widen self and buf1 */
10258 rkind = kind2;
10259 if (release1) PyMem_Free(buf1);
10260 sbuf = _PyUnicode_AsKind(self, rkind);
10261 if (!sbuf) goto error;
10262 srelease = 1;
10263 buf1 = _PyUnicode_AsKind(str1, rkind);
10264 if (!buf1) goto error;
10265 release1 = 1;
10266 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010267 u = PyUnicode_New(slen, maxchar);
10268 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010269 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010270 assert(PyUnicode_KIND(u) == rkind);
10271 res = PyUnicode_DATA(u);
Victor Stinner25a4b292011-10-06 12:31:55 +020010272
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010273 memcpy(res, sbuf, rkind * slen);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010274 /* change everything in-place, starting with this one */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010275 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010276 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010277 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010278 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010279
10280 while ( --maxcount > 0) {
Victor Stinnerc3cec782011-10-05 21:24:08 +020010281 i = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010282 sbuf+rkind*i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010283 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010284 if (i == -1)
10285 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010286 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010287 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010288 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010289 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010290 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010291 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010292 }
10293 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010294 Py_ssize_t n, i, j, ires;
10295 Py_ssize_t product, new_size;
10296 int rkind = skind;
10297 char *res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010298
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010299 if (kind1 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010300 /* widen substring */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010301 buf1 = _PyUnicode_AsKind(str1, rkind);
10302 if (!buf1) goto error;
10303 release1 = 1;
10304 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010305 n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010306 if (n == 0)
10307 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010308 if (kind2 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010309 /* widen replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010310 buf2 = _PyUnicode_AsKind(str2, rkind);
10311 if (!buf2) goto error;
10312 release2 = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010313 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010314 else if (kind2 > rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010315 /* widen self and buf1 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010316 rkind = kind2;
10317 sbuf = _PyUnicode_AsKind(self, rkind);
10318 if (!sbuf) goto error;
10319 srelease = 1;
10320 if (release1) PyMem_Free(buf1);
10321 buf1 = _PyUnicode_AsKind(str1, rkind);
10322 if (!buf1) goto error;
10323 release1 = 1;
10324 }
10325 /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
10326 PyUnicode_GET_LENGTH(str1))); */
10327 product = n * (len2-len1);
10328 if ((product / (len2-len1)) != n) {
10329 PyErr_SetString(PyExc_OverflowError,
10330 "replace string is too long");
10331 goto error;
10332 }
10333 new_size = slen + product;
Victor Stinner49a0a212011-10-12 23:46:10 +020010334 if (new_size == 0) {
10335 Py_INCREF(unicode_empty);
10336 u = unicode_empty;
10337 goto done;
10338 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010339 if (new_size < 0 || new_size > (PY_SSIZE_T_MAX >> (rkind-1))) {
10340 PyErr_SetString(PyExc_OverflowError,
10341 "replace string is too long");
10342 goto error;
10343 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010344 u = PyUnicode_New(new_size, maxchar);
10345 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010346 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010347 assert(PyUnicode_KIND(u) == rkind);
10348 res = PyUnicode_DATA(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010349 ires = i = 0;
10350 if (len1 > 0) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010351 while (n-- > 0) {
10352 /* look for next match */
Victor Stinnerc3cec782011-10-05 21:24:08 +020010353 j = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010354 sbuf + rkind * i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010355 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010356 if (j == -1)
10357 break;
10358 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010359 /* copy unchanged part [i:j] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010360 memcpy(res + rkind * ires,
10361 sbuf + rkind * i,
10362 rkind * (j-i));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010363 ires += j - i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010364 }
10365 /* copy substitution string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010366 if (len2 > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010367 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010368 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010369 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010370 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010371 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010372 i = j + len1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010373 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010374 if (i < slen)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010375 /* copy tail [i:] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010376 memcpy(res + rkind * ires,
10377 sbuf + rkind * i,
10378 rkind * (slen-i));
Victor Stinner49a0a212011-10-12 23:46:10 +020010379 }
10380 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010381 /* interleave */
10382 while (n > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010383 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010384 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010385 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010386 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010387 if (--n <= 0)
10388 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010389 memcpy(res + rkind * ires,
10390 sbuf + rkind * i,
10391 rkind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010392 ires++;
10393 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010394 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010395 memcpy(res + rkind * ires,
10396 sbuf + rkind * i,
10397 rkind * (slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +000010398 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010399 }
10400
10401 if (mayshrink) {
Victor Stinner25a4b292011-10-06 12:31:55 +020010402 unicode_adjust_maxchar(&u);
10403 if (u == NULL)
10404 goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010405 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010406
10407 done:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010408 if (srelease)
10409 PyMem_FREE(sbuf);
10410 if (release1)
10411 PyMem_FREE(buf1);
10412 if (release2)
10413 PyMem_FREE(buf2);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010414 assert(_PyUnicode_CheckConsistency(u, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010415 return u;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010416
Benjamin Peterson29060642009-01-31 22:14:21 +000010417 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +000010418 /* nothing to replace; return original string (when possible) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010419 if (srelease)
10420 PyMem_FREE(sbuf);
10421 if (release1)
10422 PyMem_FREE(buf1);
10423 if (release2)
10424 PyMem_FREE(buf2);
Victor Stinnerc4b49542011-12-11 22:44:26 +010010425 return unicode_result_unchanged(self);
10426
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010427 error:
10428 if (srelease && sbuf)
10429 PyMem_FREE(sbuf);
10430 if (release1 && buf1)
10431 PyMem_FREE(buf1);
10432 if (release2 && buf2)
10433 PyMem_FREE(buf2);
10434 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010435}
10436
10437/* --- Unicode Object Methods --------------------------------------------- */
10438
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010439PyDoc_STRVAR(title__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010440 "S.title() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010441\n\
10442Return a titlecased version of S, i.e. words start with title case\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010443characters, all remaining cased characters have lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010444
10445static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010446unicode_title(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010447{
Guido van Rossumd57fd912000-03-10 22:53:23 +000010448 return fixup(self, fixtitle);
10449}
10450
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010451PyDoc_STRVAR(capitalize__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010452 "S.capitalize() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010453\n\
10454Return a capitalized version of S, i.e. make the first character\n\
Senthil Kumarane51ee8a2010-07-05 12:00:56 +000010455have upper case and the rest lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010456
10457static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010458unicode_capitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010459{
Guido van Rossumd57fd912000-03-10 22:53:23 +000010460 return fixup(self, fixcapitalize);
10461}
10462
10463#if 0
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010464PyDoc_STRVAR(capwords__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010465 "S.capwords() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010466\n\
10467Apply .capitalize() to all words in S and return the result with\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010468normalized whitespace (all whitespace strings are replaced by ' ').");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010469
10470static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010471unicode_capwords(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010472{
10473 PyObject *list;
10474 PyObject *item;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010475 Py_ssize_t i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010476
Guido van Rossumd57fd912000-03-10 22:53:23 +000010477 /* Split into words */
10478 list = split(self, NULL, -1);
10479 if (!list)
10480 return NULL;
10481
10482 /* Capitalize each word */
10483 for (i = 0; i < PyList_GET_SIZE(list); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010484 item = fixup(PyList_GET_ITEM(list, i),
Benjamin Peterson29060642009-01-31 22:14:21 +000010485 fixcapitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010486 if (item == NULL)
10487 goto onError;
10488 Py_DECREF(PyList_GET_ITEM(list, i));
10489 PyList_SET_ITEM(list, i, item);
10490 }
10491
10492 /* Join the words to form a new string */
10493 item = PyUnicode_Join(NULL, list);
10494
Benjamin Peterson29060642009-01-31 22:14:21 +000010495 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000010496 Py_DECREF(list);
Victor Stinner7931d9a2011-11-04 00:22:48 +010010497 return item;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010498}
10499#endif
10500
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010501/* Argument converter. Coerces to a single unicode character */
10502
10503static int
10504convert_uc(PyObject *obj, void *addr)
10505{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010506 Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010507 PyObject *uniobj;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010508
Benjamin Peterson14339b62009-01-31 16:36:08 +000010509 uniobj = PyUnicode_FromObject(obj);
10510 if (uniobj == NULL) {
10511 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010512 "The fill character cannot be converted to Unicode");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010513 return 0;
10514 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010515 if (PyUnicode_GET_LENGTH(uniobj) != 1) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010516 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010517 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010518 Py_DECREF(uniobj);
10519 return 0;
10520 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010521 *fillcharloc = PyUnicode_READ_CHAR(uniobj, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010522 Py_DECREF(uniobj);
10523 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010524}
10525
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010526PyDoc_STRVAR(center__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010527 "S.center(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010528\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010529Return S centered in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010530done using the specified fill character (default is a space)");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010531
10532static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010533unicode_center(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010534{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010535 Py_ssize_t marg, left;
10536 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010537 Py_UCS4 fillchar = ' ';
10538
Victor Stinnere9a29352011-10-01 02:14:59 +020010539 if (!PyArg_ParseTuple(args, "n|O&:center", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010540 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010541
Victor Stinnerc4b49542011-12-11 22:44:26 +010010542 if (PyUnicode_READY(self) < 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010543 return NULL;
10544
Victor Stinnerc4b49542011-12-11 22:44:26 +010010545 if (PyUnicode_GET_LENGTH(self) >= width)
10546 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010547
Victor Stinnerc4b49542011-12-11 22:44:26 +010010548 marg = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010549 left = marg / 2 + (marg & width & 1);
10550
Victor Stinner9310abb2011-10-05 00:59:23 +020010551 return pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010552}
10553
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010554/* This function assumes that str1 and str2 are readied by the caller. */
10555
Marc-André Lemburge5034372000-08-08 08:04:29 +000010556static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010557unicode_compare(PyObject *str1, PyObject *str2)
Marc-André Lemburge5034372000-08-08 08:04:29 +000010558{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010559 int kind1, kind2;
10560 void *data1, *data2;
10561 Py_ssize_t len1, len2, i;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010562
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010563 kind1 = PyUnicode_KIND(str1);
10564 kind2 = PyUnicode_KIND(str2);
10565 data1 = PyUnicode_DATA(str1);
10566 data2 = PyUnicode_DATA(str2);
10567 len1 = PyUnicode_GET_LENGTH(str1);
10568 len2 = PyUnicode_GET_LENGTH(str2);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010569
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010570 for (i = 0; i < len1 && i < len2; ++i) {
10571 Py_UCS4 c1, c2;
10572 c1 = PyUnicode_READ(kind1, data1, i);
10573 c2 = PyUnicode_READ(kind2, data2, i);
Fredrik Lundh45714e92001-06-26 16:39:36 +000010574
10575 if (c1 != c2)
10576 return (c1 < c2) ? -1 : 1;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010577 }
10578
10579 return (len1 < len2) ? -1 : (len1 != len2);
10580}
10581
Alexander Belopolsky40018472011-02-26 01:02:56 +000010582int
10583PyUnicode_Compare(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010584{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010585 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10586 if (PyUnicode_READY(left) == -1 ||
10587 PyUnicode_READY(right) == -1)
10588 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010589 return unicode_compare(left, right);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010590 }
Guido van Rossum09dc34f2007-05-04 04:17:33 +000010591 PyErr_Format(PyExc_TypeError,
10592 "Can't compare %.100s and %.100s",
10593 left->ob_type->tp_name,
10594 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010595 return -1;
10596}
10597
Martin v. Löwis5b222132007-06-10 09:51:05 +000010598int
10599PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
10600{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010601 Py_ssize_t i;
10602 int kind;
10603 void *data;
10604 Py_UCS4 chr;
10605
Victor Stinner910337b2011-10-03 03:20:16 +020010606 assert(_PyUnicode_CHECK(uni));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010607 if (PyUnicode_READY(uni) == -1)
10608 return -1;
10609 kind = PyUnicode_KIND(uni);
10610 data = PyUnicode_DATA(uni);
Martin v. Löwis5b222132007-06-10 09:51:05 +000010611 /* Compare Unicode string and source character set string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010612 for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
10613 if (chr != str[i])
10614 return (chr < (unsigned char)(str[i])) ? -1 : 1;
Benjamin Peterson8667a9b2010-01-09 21:45:28 +000010615 /* This check keeps Python strings that end in '\0' from comparing equal
10616 to C strings identical up to that point. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010617 if (PyUnicode_GET_LENGTH(uni) != i || chr)
Benjamin Peterson29060642009-01-31 22:14:21 +000010618 return 1; /* uni is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010619 if (str[i])
Benjamin Peterson29060642009-01-31 22:14:21 +000010620 return -1; /* str is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010621 return 0;
10622}
10623
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010624
Benjamin Peterson29060642009-01-31 22:14:21 +000010625#define TEST_COND(cond) \
Benjamin Peterson14339b62009-01-31 16:36:08 +000010626 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010627
Alexander Belopolsky40018472011-02-26 01:02:56 +000010628PyObject *
10629PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010630{
10631 int result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010632
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010633 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10634 PyObject *v;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010635 if (PyUnicode_READY(left) == -1 ||
10636 PyUnicode_READY(right) == -1)
10637 return NULL;
10638 if (PyUnicode_GET_LENGTH(left) != PyUnicode_GET_LENGTH(right) ||
10639 PyUnicode_KIND(left) != PyUnicode_KIND(right)) {
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010640 if (op == Py_EQ) {
10641 Py_INCREF(Py_False);
10642 return Py_False;
10643 }
10644 if (op == Py_NE) {
10645 Py_INCREF(Py_True);
10646 return Py_True;
10647 }
10648 }
10649 if (left == right)
10650 result = 0;
10651 else
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010652 result = unicode_compare(left, right);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010653
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010654 /* Convert the return value to a Boolean */
10655 switch (op) {
10656 case Py_EQ:
10657 v = TEST_COND(result == 0);
10658 break;
10659 case Py_NE:
10660 v = TEST_COND(result != 0);
10661 break;
10662 case Py_LE:
10663 v = TEST_COND(result <= 0);
10664 break;
10665 case Py_GE:
10666 v = TEST_COND(result >= 0);
10667 break;
10668 case Py_LT:
10669 v = TEST_COND(result == -1);
10670 break;
10671 case Py_GT:
10672 v = TEST_COND(result == 1);
10673 break;
10674 default:
10675 PyErr_BadArgument();
10676 return NULL;
10677 }
10678 Py_INCREF(v);
10679 return v;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010680 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000010681
Brian Curtindfc80e32011-08-10 20:28:54 -050010682 Py_RETURN_NOTIMPLEMENTED;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010683}
10684
Alexander Belopolsky40018472011-02-26 01:02:56 +000010685int
10686PyUnicode_Contains(PyObject *container, PyObject *element)
Guido van Rossum403d68b2000-03-13 15:55:09 +000010687{
Thomas Wouters477c8d52006-05-27 19:21:47 +000010688 PyObject *str, *sub;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010689 int kind1, kind2, kind;
10690 void *buf1, *buf2;
10691 Py_ssize_t len1, len2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010692 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010693
10694 /* Coerce the two arguments */
Thomas Wouters477c8d52006-05-27 19:21:47 +000010695 sub = PyUnicode_FromObject(element);
10696 if (!sub) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010697 PyErr_Format(PyExc_TypeError,
10698 "'in <string>' requires string as left operand, not %s",
10699 element->ob_type->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010700 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010701 }
10702
Thomas Wouters477c8d52006-05-27 19:21:47 +000010703 str = PyUnicode_FromObject(container);
Benjamin Peterson22a29702012-01-02 09:00:30 -060010704 if (!str) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010705 Py_DECREF(sub);
10706 return -1;
10707 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060010708 if (PyUnicode_READY(sub) == -1 || PyUnicode_READY(str) == -1) {
10709 Py_DECREF(sub);
10710 Py_DECREF(str);
10711 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000010712
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010713 kind1 = PyUnicode_KIND(str);
10714 kind2 = PyUnicode_KIND(sub);
10715 kind = kind1 > kind2 ? kind1 : kind2;
10716 buf1 = PyUnicode_DATA(str);
10717 buf2 = PyUnicode_DATA(sub);
10718 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010719 buf1 = _PyUnicode_AsKind(str, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010720 if (!buf1) {
10721 Py_DECREF(sub);
10722 return -1;
10723 }
10724 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010725 buf2 = _PyUnicode_AsKind(sub, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010726 if (!buf2) {
10727 Py_DECREF(sub);
10728 if (kind1 != kind) PyMem_Free(buf1);
10729 return -1;
10730 }
10731 len1 = PyUnicode_GET_LENGTH(str);
10732 len2 = PyUnicode_GET_LENGTH(sub);
10733
Benjamin Petersonead6b532011-12-20 17:23:42 -060010734 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010735 case PyUnicode_1BYTE_KIND:
10736 result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
10737 break;
10738 case PyUnicode_2BYTE_KIND:
10739 result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
10740 break;
10741 case PyUnicode_4BYTE_KIND:
10742 result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
10743 break;
10744 default:
10745 result = -1;
10746 assert(0);
10747 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000010748
10749 Py_DECREF(str);
10750 Py_DECREF(sub);
10751
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010752 if (kind1 != kind)
10753 PyMem_Free(buf1);
10754 if (kind2 != kind)
10755 PyMem_Free(buf2);
10756
Guido van Rossum403d68b2000-03-13 15:55:09 +000010757 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010758}
10759
Guido van Rossumd57fd912000-03-10 22:53:23 +000010760/* Concat to string or Unicode object giving a new Unicode object. */
10761
Alexander Belopolsky40018472011-02-26 01:02:56 +000010762PyObject *
10763PyUnicode_Concat(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010764{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010765 PyObject *u = NULL, *v = NULL, *w;
Victor Stinner127226b2011-10-13 01:12:34 +020010766 Py_UCS4 maxchar, maxchar2;
Victor Stinner488fa492011-12-12 00:01:39 +010010767 Py_ssize_t u_len, v_len, new_len;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010768
10769 /* Coerce the two arguments */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010770 u = PyUnicode_FromObject(left);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010771 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010772 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010773 v = PyUnicode_FromObject(right);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010774 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010775 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010776
10777 /* Shortcuts */
Victor Stinnera464fc12011-10-02 20:39:30 +020010778 if (v == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010779 Py_DECREF(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010780 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010781 }
Victor Stinnera464fc12011-10-02 20:39:30 +020010782 if (u == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010783 Py_DECREF(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010784 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010785 }
10786
Victor Stinner488fa492011-12-12 00:01:39 +010010787 u_len = PyUnicode_GET_LENGTH(u);
10788 v_len = PyUnicode_GET_LENGTH(v);
10789 if (u_len > PY_SSIZE_T_MAX - v_len) {
10790 PyErr_SetString(PyExc_OverflowError,
10791 "strings are too large to concat");
10792 goto onError;
10793 }
10794 new_len = u_len + v_len;
10795
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010796 maxchar = PyUnicode_MAX_CHAR_VALUE(u);
Victor Stinner127226b2011-10-13 01:12:34 +020010797 maxchar2 = PyUnicode_MAX_CHAR_VALUE(v);
10798 maxchar = Py_MAX(maxchar, maxchar2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010799
Guido van Rossumd57fd912000-03-10 22:53:23 +000010800 /* Concat the two Unicode strings */
Victor Stinner488fa492011-12-12 00:01:39 +010010801 w = PyUnicode_New(new_len, maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010802 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010803 goto onError;
Victor Stinner488fa492011-12-12 00:01:39 +010010804 copy_characters(w, 0, u, 0, u_len);
10805 copy_characters(w, u_len, v, 0, v_len);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010806 Py_DECREF(u);
10807 Py_DECREF(v);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010808 assert(_PyUnicode_CheckConsistency(w, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010809 return w;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010810
Benjamin Peterson29060642009-01-31 22:14:21 +000010811 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000010812 Py_XDECREF(u);
10813 Py_XDECREF(v);
10814 return NULL;
10815}
10816
Walter Dörwald1ab83302007-05-18 17:15:44 +000010817void
Victor Stinner23e56682011-10-03 03:54:37 +020010818PyUnicode_Append(PyObject **p_left, PyObject *right)
Walter Dörwald1ab83302007-05-18 17:15:44 +000010819{
Victor Stinner23e56682011-10-03 03:54:37 +020010820 PyObject *left, *res;
Victor Stinner488fa492011-12-12 00:01:39 +010010821 Py_UCS4 maxchar, maxchar2;
10822 Py_ssize_t left_len, right_len, new_len;
Victor Stinner23e56682011-10-03 03:54:37 +020010823
10824 if (p_left == NULL) {
10825 if (!PyErr_Occurred())
10826 PyErr_BadInternalCall();
Benjamin Peterson14339b62009-01-31 16:36:08 +000010827 return;
10828 }
Victor Stinner23e56682011-10-03 03:54:37 +020010829 left = *p_left;
10830 if (right == NULL || !PyUnicode_Check(left)) {
10831 if (!PyErr_Occurred())
10832 PyErr_BadInternalCall();
10833 goto error;
10834 }
10835
Victor Stinnere1335c72011-10-04 20:53:03 +020010836 if (PyUnicode_READY(left))
10837 goto error;
10838 if (PyUnicode_READY(right))
10839 goto error;
10840
Victor Stinner488fa492011-12-12 00:01:39 +010010841 /* Shortcuts */
10842 if (left == unicode_empty) {
10843 Py_DECREF(left);
10844 Py_INCREF(right);
10845 *p_left = right;
10846 return;
10847 }
10848 if (right == unicode_empty)
10849 return;
10850
10851 left_len = PyUnicode_GET_LENGTH(left);
10852 right_len = PyUnicode_GET_LENGTH(right);
10853 if (left_len > PY_SSIZE_T_MAX - right_len) {
10854 PyErr_SetString(PyExc_OverflowError,
10855 "strings are too large to concat");
10856 goto error;
10857 }
10858 new_len = left_len + right_len;
10859
10860 if (unicode_modifiable(left)
10861 && PyUnicode_CheckExact(right)
10862 && PyUnicode_KIND(right) <= PyUnicode_KIND(left)
Victor Stinnerb0923652011-10-04 01:17:31 +020010863 /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
10864 to change the structure size, but characters are stored just after
Georg Brandl7597add2011-10-05 16:36:47 +020010865 the structure, and so it requires to move all characters which is
Victor Stinnerb0923652011-10-04 01:17:31 +020010866 not so different than duplicating the string. */
Victor Stinner488fa492011-12-12 00:01:39 +010010867 && !(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
10868 {
10869 /* append inplace */
10870 if (unicode_resize(p_left, new_len) != 0) {
10871 /* XXX if _PyUnicode_Resize() fails, 'left' has been
10872 * deallocated so it cannot be put back into
10873 * 'variable'. The MemoryError is raised when there
10874 * is no value in 'variable', which might (very
10875 * remotely) be a cause of incompatibilities.
10876 */
10877 goto error;
Victor Stinner23e56682011-10-03 03:54:37 +020010878 }
Victor Stinner488fa492011-12-12 00:01:39 +010010879 /* copy 'right' into the newly allocated area of 'left' */
10880 copy_characters(*p_left, left_len, right, 0, right_len);
Victor Stinner23e56682011-10-03 03:54:37 +020010881 }
Victor Stinner488fa492011-12-12 00:01:39 +010010882 else {
10883 maxchar = PyUnicode_MAX_CHAR_VALUE(left);
10884 maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
10885 maxchar = Py_MAX(maxchar, maxchar2);
Victor Stinner23e56682011-10-03 03:54:37 +020010886
Victor Stinner488fa492011-12-12 00:01:39 +010010887 /* Concat the two Unicode strings */
10888 res = PyUnicode_New(new_len, maxchar);
10889 if (res == NULL)
10890 goto error;
10891 copy_characters(res, 0, left, 0, left_len);
10892 copy_characters(res, left_len, right, 0, right_len);
10893 Py_DECREF(left);
10894 *p_left = res;
10895 }
10896 assert(_PyUnicode_CheckConsistency(*p_left, 1));
Victor Stinner23e56682011-10-03 03:54:37 +020010897 return;
10898
10899error:
Victor Stinner488fa492011-12-12 00:01:39 +010010900 Py_CLEAR(*p_left);
Walter Dörwald1ab83302007-05-18 17:15:44 +000010901}
10902
10903void
10904PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
10905{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010906 PyUnicode_Append(pleft, right);
10907 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +000010908}
10909
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010910PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010911 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010912\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000010913Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010914string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010915interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010916
10917static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010918unicode_count(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010919{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010920 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010921 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010922 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010923 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010924 int kind1, kind2, kind;
10925 void *buf1, *buf2;
10926 Py_ssize_t len1, len2, iresult;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010927
Jesus Ceaac451502011-04-20 17:09:23 +020010928 if (!stringlib_parse_args_finds_unicode("count", args, &substring,
10929 &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000010930 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000010931
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010932 kind1 = PyUnicode_KIND(self);
10933 kind2 = PyUnicode_KIND(substring);
10934 kind = kind1 > kind2 ? kind1 : kind2;
10935 buf1 = PyUnicode_DATA(self);
10936 buf2 = PyUnicode_DATA(substring);
10937 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010938 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010939 if (!buf1) {
10940 Py_DECREF(substring);
10941 return NULL;
10942 }
10943 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010944 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010945 if (!buf2) {
10946 Py_DECREF(substring);
10947 if (kind1 != kind) PyMem_Free(buf1);
10948 return NULL;
10949 }
10950 len1 = PyUnicode_GET_LENGTH(self);
10951 len2 = PyUnicode_GET_LENGTH(substring);
10952
10953 ADJUST_INDICES(start, end, len1);
Benjamin Petersonead6b532011-12-20 17:23:42 -060010954 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010955 case PyUnicode_1BYTE_KIND:
10956 iresult = ucs1lib_count(
10957 ((Py_UCS1*)buf1) + start, end - start,
10958 buf2, len2, PY_SSIZE_T_MAX
10959 );
10960 break;
10961 case PyUnicode_2BYTE_KIND:
10962 iresult = ucs2lib_count(
10963 ((Py_UCS2*)buf1) + start, end - start,
10964 buf2, len2, PY_SSIZE_T_MAX
10965 );
10966 break;
10967 case PyUnicode_4BYTE_KIND:
10968 iresult = ucs4lib_count(
10969 ((Py_UCS4*)buf1) + start, end - start,
10970 buf2, len2, PY_SSIZE_T_MAX
10971 );
10972 break;
10973 default:
10974 assert(0); iresult = 0;
10975 }
10976
10977 result = PyLong_FromSsize_t(iresult);
10978
10979 if (kind1 != kind)
10980 PyMem_Free(buf1);
10981 if (kind2 != kind)
10982 PyMem_Free(buf2);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010983
10984 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010985
Guido van Rossumd57fd912000-03-10 22:53:23 +000010986 return result;
10987}
10988
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010989PyDoc_STRVAR(encode__doc__,
Victor Stinnerc911bbf2010-11-07 19:04:46 +000010990 "S.encode(encoding='utf-8', errors='strict') -> bytes\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010991\n\
Victor Stinnere14e2122010-11-07 18:41:46 +000010992Encode S using the codec registered for encoding. Default encoding\n\
10993is 'utf-8'. errors may be given to set a different error\n\
Fred Drakee4315f52000-05-09 19:53:39 +000010994handling scheme. Default is 'strict' meaning that encoding errors raise\n\
Walter Dörwald3aeb6322002-09-02 13:14:32 +000010995a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
10996'xmlcharrefreplace' as well as any other name registered with\n\
10997codecs.register_error that can handle UnicodeEncodeErrors.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010998
10999static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011000unicode_encode(PyObject *self, PyObject *args, PyObject *kwargs)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011001{
Benjamin Peterson308d6372009-09-18 21:42:35 +000011002 static char *kwlist[] = {"encoding", "errors", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000011003 char *encoding = NULL;
11004 char *errors = NULL;
Guido van Rossum35d94282007-08-27 18:20:11 +000011005
Benjamin Peterson308d6372009-09-18 21:42:35 +000011006 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:encode",
11007 kwlist, &encoding, &errors))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011008 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011009 return PyUnicode_AsEncodedString(self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +000011010}
11011
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011012PyDoc_STRVAR(expandtabs__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011013 "S.expandtabs([tabsize]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011014\n\
11015Return a copy of S where all tab characters are expanded using spaces.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011016If tabsize is not given, a tab size of 8 characters is assumed.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011017
11018static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011019unicode_expandtabs(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011020{
Antoine Pitroue71d5742011-10-04 15:55:09 +020011021 Py_ssize_t i, j, line_pos, src_len, incr;
11022 Py_UCS4 ch;
11023 PyObject *u;
11024 void *src_data, *dest_data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011025 int tabsize = 8;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011026 int kind;
Antoine Pitroue19aa382011-10-04 16:04:01 +020011027 int found;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011028
11029 if (!PyArg_ParseTuple(args, "|i:expandtabs", &tabsize))
Benjamin Peterson29060642009-01-31 22:14:21 +000011030 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011031
Antoine Pitrou22425222011-10-04 19:10:51 +020011032 if (PyUnicode_READY(self) == -1)
11033 return NULL;
11034
Thomas Wouters7e474022000-07-16 12:04:32 +000011035 /* First pass: determine size of output string */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011036 src_len = PyUnicode_GET_LENGTH(self);
11037 i = j = line_pos = 0;
11038 kind = PyUnicode_KIND(self);
11039 src_data = PyUnicode_DATA(self);
Antoine Pitroue19aa382011-10-04 16:04:01 +020011040 found = 0;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011041 for (; i < src_len; i++) {
11042 ch = PyUnicode_READ(kind, src_data, i);
11043 if (ch == '\t') {
Antoine Pitroue19aa382011-10-04 16:04:01 +020011044 found = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000011045 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011046 incr = tabsize - (line_pos % tabsize); /* cannot overflow */
Benjamin Peterson29060642009-01-31 22:14:21 +000011047 if (j > PY_SSIZE_T_MAX - incr)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011048 goto overflow;
11049 line_pos += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011050 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011051 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011052 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011053 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000011054 if (j > PY_SSIZE_T_MAX - 1)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011055 goto overflow;
11056 line_pos++;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011057 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011058 if (ch == '\n' || ch == '\r')
11059 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011060 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011061 }
Victor Stinnerc4b49542011-12-11 22:44:26 +010011062 if (!found)
11063 return unicode_result_unchanged(self);
Guido van Rossumcd16bf62007-06-13 18:07:49 +000011064
Guido van Rossumd57fd912000-03-10 22:53:23 +000011065 /* Second pass: create output string and fill it */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011066 u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011067 if (!u)
11068 return NULL;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011069 dest_data = PyUnicode_DATA(u);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011070
Antoine Pitroue71d5742011-10-04 15:55:09 +020011071 i = j = line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011072
Antoine Pitroue71d5742011-10-04 15:55:09 +020011073 for (; i < src_len; i++) {
11074 ch = PyUnicode_READ(kind, src_data, i);
11075 if (ch == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +000011076 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011077 incr = tabsize - (line_pos % tabsize);
11078 line_pos += incr;
11079 while (incr--) {
11080 PyUnicode_WRITE(kind, dest_data, j, ' ');
11081 j++;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011082 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011083 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011084 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011085 else {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011086 line_pos++;
11087 PyUnicode_WRITE(kind, dest_data, j, ch);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011088 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011089 if (ch == '\n' || ch == '\r')
11090 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011091 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011092 }
11093 assert (j == PyUnicode_GET_LENGTH(u));
Victor Stinnerd3df8ab2011-11-22 01:22:34 +010011094 return unicode_result(u);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011095
Antoine Pitroue71d5742011-10-04 15:55:09 +020011096 overflow:
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011097 PyErr_SetString(PyExc_OverflowError, "new string is too long");
11098 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011099}
11100
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011101PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011102 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011103\n\
11104Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080011105such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011106arguments start and end are interpreted as in slice notation.\n\
11107\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011108Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011109
11110static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011111unicode_find(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011112{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011113 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011114 Py_ssize_t start;
11115 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011116 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011117
Jesus Ceaac451502011-04-20 17:09:23 +020011118 if (!stringlib_parse_args_finds_unicode("find", 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
Christian Heimes217cfd12007-12-02 14:31:20 +000011134 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011135}
11136
11137static PyObject *
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011138unicode_getitem(PyObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011139{
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011140 Py_UCS4 ch = PyUnicode_ReadChar(self, index);
11141 if (ch == (Py_UCS4)-1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011142 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011143 return PyUnicode_FromOrdinal(ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011144}
11145
Guido van Rossumc2504932007-09-18 19:42:40 +000011146/* Believe it or not, this produces the same value for ASCII strings
Mark Dickinson57e683e2011-09-24 18:18:40 +010011147 as bytes_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +000011148static Py_hash_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011149unicode_hash(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011150{
Guido van Rossumc2504932007-09-18 19:42:40 +000011151 Py_ssize_t len;
Mark Dickinson57e683e2011-09-24 18:18:40 +010011152 Py_uhash_t x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011153
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011154 if (_PyUnicode_HASH(self) != -1)
11155 return _PyUnicode_HASH(self);
11156 if (PyUnicode_READY(self) == -1)
11157 return -1;
11158 len = PyUnicode_GET_LENGTH(self);
11159
11160 /* The hash function as a macro, gets expanded three times below. */
11161#define HASH(P) \
11162 x = (Py_uhash_t)*P << 7; \
11163 while (--len >= 0) \
11164 x = (1000003*x) ^ (Py_uhash_t)*P++;
11165
11166 switch (PyUnicode_KIND(self)) {
11167 case PyUnicode_1BYTE_KIND: {
11168 const unsigned char *c = PyUnicode_1BYTE_DATA(self);
11169 HASH(c);
11170 break;
11171 }
11172 case PyUnicode_2BYTE_KIND: {
11173 const Py_UCS2 *s = PyUnicode_2BYTE_DATA(self);
11174 HASH(s);
11175 break;
11176 }
11177 default: {
11178 Py_UCS4 *l;
11179 assert(PyUnicode_KIND(self) == PyUnicode_4BYTE_KIND &&
11180 "Impossible switch case in unicode_hash");
11181 l = PyUnicode_4BYTE_DATA(self);
11182 HASH(l);
11183 break;
11184 }
11185 }
11186 x ^= (Py_uhash_t)PyUnicode_GET_LENGTH(self);
11187
Guido van Rossumc2504932007-09-18 19:42:40 +000011188 if (x == -1)
11189 x = -2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011190 _PyUnicode_HASH(self) = x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011191 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011192}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011193#undef HASH
Guido van Rossumd57fd912000-03-10 22:53:23 +000011194
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011195PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011196 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011197\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011198Like S.find() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011199
11200static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011201unicode_index(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011202{
Martin v. Löwis18e16552006-02-15 17:27:45 +000011203 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011204 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011205 Py_ssize_t start;
11206 Py_ssize_t end;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011207
Jesus Ceaac451502011-04-20 17:09:23 +020011208 if (!stringlib_parse_args_finds_unicode("index", args, &substring,
11209 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011210 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011211
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011212 if (PyUnicode_READY(self) == -1)
11213 return NULL;
11214 if (PyUnicode_READY(substring) == -1)
11215 return NULL;
11216
Victor Stinner7931d9a2011-11-04 00:22:48 +010011217 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011218
11219 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011220
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011221 if (result == -2)
11222 return NULL;
11223
Guido van Rossumd57fd912000-03-10 22:53:23 +000011224 if (result < 0) {
11225 PyErr_SetString(PyExc_ValueError, "substring not found");
11226 return NULL;
11227 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011228
Christian Heimes217cfd12007-12-02 14:31:20 +000011229 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011230}
11231
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011232PyDoc_STRVAR(islower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011233 "S.islower() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011234\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011235Return True if all cased characters in S are lowercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011236at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011237
11238static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011239unicode_islower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011240{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011241 Py_ssize_t i, length;
11242 int kind;
11243 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011244 int cased;
11245
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011246 if (PyUnicode_READY(self) == -1)
11247 return NULL;
11248 length = PyUnicode_GET_LENGTH(self);
11249 kind = PyUnicode_KIND(self);
11250 data = PyUnicode_DATA(self);
11251
Guido van Rossumd57fd912000-03-10 22:53:23 +000011252 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011253 if (length == 1)
11254 return PyBool_FromLong(
11255 Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011256
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011257 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011258 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011259 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011260
Guido van Rossumd57fd912000-03-10 22:53:23 +000011261 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011262 for (i = 0; i < length; i++) {
11263 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011264
Benjamin Peterson29060642009-01-31 22:14:21 +000011265 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
11266 return PyBool_FromLong(0);
11267 else if (!cased && Py_UNICODE_ISLOWER(ch))
11268 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011269 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011270 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011271}
11272
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011273PyDoc_STRVAR(isupper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011274 "S.isupper() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011275\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011276Return True if all cased characters in S are uppercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011277at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011278
11279static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011280unicode_isupper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011281{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011282 Py_ssize_t i, length;
11283 int kind;
11284 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011285 int cased;
11286
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011287 if (PyUnicode_READY(self) == -1)
11288 return NULL;
11289 length = PyUnicode_GET_LENGTH(self);
11290 kind = PyUnicode_KIND(self);
11291 data = PyUnicode_DATA(self);
11292
Guido van Rossumd57fd912000-03-10 22:53:23 +000011293 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011294 if (length == 1)
11295 return PyBool_FromLong(
11296 Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011297
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011298 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011299 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011300 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011301
Guido van Rossumd57fd912000-03-10 22:53:23 +000011302 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011303 for (i = 0; i < length; i++) {
11304 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011305
Benjamin Peterson29060642009-01-31 22:14:21 +000011306 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
11307 return PyBool_FromLong(0);
11308 else if (!cased && Py_UNICODE_ISUPPER(ch))
11309 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011310 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011311 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011312}
11313
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011314PyDoc_STRVAR(istitle__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011315 "S.istitle() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011316\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011317Return True if S is a titlecased string and there is at least one\n\
11318character in S, i.e. upper- and titlecase characters may only\n\
11319follow uncased characters and lowercase characters only cased ones.\n\
11320Return False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011321
11322static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011323unicode_istitle(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011324{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011325 Py_ssize_t i, length;
11326 int kind;
11327 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011328 int cased, previous_is_cased;
11329
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011330 if (PyUnicode_READY(self) == -1)
11331 return NULL;
11332 length = PyUnicode_GET_LENGTH(self);
11333 kind = PyUnicode_KIND(self);
11334 data = PyUnicode_DATA(self);
11335
Guido van Rossumd57fd912000-03-10 22:53:23 +000011336 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011337 if (length == 1) {
11338 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11339 return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
11340 (Py_UNICODE_ISUPPER(ch) != 0));
11341 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011342
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011343 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011344 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011345 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011346
Guido van Rossumd57fd912000-03-10 22:53:23 +000011347 cased = 0;
11348 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011349 for (i = 0; i < length; i++) {
11350 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011351
Benjamin Peterson29060642009-01-31 22:14:21 +000011352 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
11353 if (previous_is_cased)
11354 return PyBool_FromLong(0);
11355 previous_is_cased = 1;
11356 cased = 1;
11357 }
11358 else if (Py_UNICODE_ISLOWER(ch)) {
11359 if (!previous_is_cased)
11360 return PyBool_FromLong(0);
11361 previous_is_cased = 1;
11362 cased = 1;
11363 }
11364 else
11365 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011366 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011367 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011368}
11369
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011370PyDoc_STRVAR(isspace__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011371 "S.isspace() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011372\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011373Return True if all characters in S are whitespace\n\
11374and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011375
11376static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011377unicode_isspace(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011378{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011379 Py_ssize_t i, length;
11380 int kind;
11381 void *data;
11382
11383 if (PyUnicode_READY(self) == -1)
11384 return NULL;
11385 length = PyUnicode_GET_LENGTH(self);
11386 kind = PyUnicode_KIND(self);
11387 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011388
Guido van Rossumd57fd912000-03-10 22:53:23 +000011389 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011390 if (length == 1)
11391 return PyBool_FromLong(
11392 Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011393
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011394 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011395 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011396 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011397
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011398 for (i = 0; i < length; i++) {
11399 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011400 if (!Py_UNICODE_ISSPACE(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011401 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011402 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011403 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011404}
11405
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011406PyDoc_STRVAR(isalpha__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011407 "S.isalpha() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011408\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011409Return True if all characters in S are alphabetic\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011410and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011411
11412static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011413unicode_isalpha(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011414{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011415 Py_ssize_t i, length;
11416 int kind;
11417 void *data;
11418
11419 if (PyUnicode_READY(self) == -1)
11420 return NULL;
11421 length = PyUnicode_GET_LENGTH(self);
11422 kind = PyUnicode_KIND(self);
11423 data = PyUnicode_DATA(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011424
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011425 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011426 if (length == 1)
11427 return PyBool_FromLong(
11428 Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011429
11430 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011431 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011432 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011433
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011434 for (i = 0; i < length; i++) {
11435 if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011436 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011437 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011438 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011439}
11440
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011441PyDoc_STRVAR(isalnum__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011442 "S.isalnum() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011443\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011444Return True if all characters in S are alphanumeric\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011445and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011446
11447static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011448unicode_isalnum(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011449{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011450 int kind;
11451 void *data;
11452 Py_ssize_t len, i;
11453
11454 if (PyUnicode_READY(self) == -1)
11455 return NULL;
11456
11457 kind = PyUnicode_KIND(self);
11458 data = PyUnicode_DATA(self);
11459 len = PyUnicode_GET_LENGTH(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011460
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011461 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011462 if (len == 1) {
11463 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11464 return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
11465 }
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011466
11467 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011468 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011469 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011470
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011471 for (i = 0; i < len; i++) {
11472 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011473 if (!Py_UNICODE_ISALNUM(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011474 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011475 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011476 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011477}
11478
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011479PyDoc_STRVAR(isdecimal__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011480 "S.isdecimal() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011481\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011482Return True if there are only decimal characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011483False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011484
11485static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011486unicode_isdecimal(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011487{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011488 Py_ssize_t i, length;
11489 int kind;
11490 void *data;
11491
11492 if (PyUnicode_READY(self) == -1)
11493 return NULL;
11494 length = PyUnicode_GET_LENGTH(self);
11495 kind = PyUnicode_KIND(self);
11496 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011497
Guido van Rossumd57fd912000-03-10 22:53:23 +000011498 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011499 if (length == 1)
11500 return PyBool_FromLong(
11501 Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011502
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011503 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011504 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011505 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011506
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011507 for (i = 0; i < length; i++) {
11508 if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011509 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011510 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011511 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011512}
11513
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011514PyDoc_STRVAR(isdigit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011515 "S.isdigit() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011516\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011517Return True if all characters in S are digits\n\
11518and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011519
11520static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011521unicode_isdigit(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011522{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011523 Py_ssize_t i, length;
11524 int kind;
11525 void *data;
11526
11527 if (PyUnicode_READY(self) == -1)
11528 return NULL;
11529 length = PyUnicode_GET_LENGTH(self);
11530 kind = PyUnicode_KIND(self);
11531 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011532
Guido van Rossumd57fd912000-03-10 22:53:23 +000011533 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011534 if (length == 1) {
11535 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11536 return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
11537 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011538
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011539 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011540 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011541 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011542
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011543 for (i = 0; i < length; i++) {
11544 if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011545 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011546 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011547 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011548}
11549
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011550PyDoc_STRVAR(isnumeric__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011551 "S.isnumeric() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011552\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011553Return True if there are only numeric characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011554False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011555
11556static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011557unicode_isnumeric(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011558{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011559 Py_ssize_t i, length;
11560 int kind;
11561 void *data;
11562
11563 if (PyUnicode_READY(self) == -1)
11564 return NULL;
11565 length = PyUnicode_GET_LENGTH(self);
11566 kind = PyUnicode_KIND(self);
11567 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011568
Guido van Rossumd57fd912000-03-10 22:53:23 +000011569 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011570 if (length == 1)
11571 return PyBool_FromLong(
11572 Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011573
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011574 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011575 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011576 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011577
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011578 for (i = 0; i < length; i++) {
11579 if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011580 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011581 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011582 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011583}
11584
Martin v. Löwis47383402007-08-15 07:32:56 +000011585int
11586PyUnicode_IsIdentifier(PyObject *self)
11587{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011588 int kind;
11589 void *data;
11590 Py_ssize_t i;
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011591 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +000011592
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011593 if (PyUnicode_READY(self) == -1) {
11594 Py_FatalError("identifier not ready");
Benjamin Peterson29060642009-01-31 22:14:21 +000011595 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011596 }
11597
11598 /* Special case for empty strings */
11599 if (PyUnicode_GET_LENGTH(self) == 0)
11600 return 0;
11601 kind = PyUnicode_KIND(self);
11602 data = PyUnicode_DATA(self);
Martin v. Löwis47383402007-08-15 07:32:56 +000011603
11604 /* PEP 3131 says that the first character must be in
11605 XID_Start and subsequent characters in XID_Continue,
11606 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +000011607 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +000011608 letters, digits, underscore). However, given the current
11609 definition of XID_Start and XID_Continue, it is sufficient
11610 to check just for these, except that _ must be allowed
11611 as starting an identifier. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011612 first = PyUnicode_READ(kind, data, 0);
Benjamin Petersonf413b802011-08-12 22:17:18 -050011613 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +000011614 return 0;
11615
Benjamin Peterson9c6e6a02011-09-28 08:09:05 -040011616 for (i = 1; i < PyUnicode_GET_LENGTH(self); i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011617 if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011618 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +000011619 return 1;
11620}
11621
11622PyDoc_STRVAR(isidentifier__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011623 "S.isidentifier() -> bool\n\
Martin v. Löwis47383402007-08-15 07:32:56 +000011624\n\
11625Return True if S is a valid identifier according\n\
11626to the language definition.");
11627
11628static PyObject*
11629unicode_isidentifier(PyObject *self)
11630{
11631 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
11632}
11633
Georg Brandl559e5d72008-06-11 18:37:52 +000011634PyDoc_STRVAR(isprintable__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011635 "S.isprintable() -> bool\n\
Georg Brandl559e5d72008-06-11 18:37:52 +000011636\n\
11637Return True if all characters in S are considered\n\
11638printable in repr() or S is empty, False otherwise.");
11639
11640static PyObject*
11641unicode_isprintable(PyObject *self)
11642{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011643 Py_ssize_t i, length;
11644 int kind;
11645 void *data;
11646
11647 if (PyUnicode_READY(self) == -1)
11648 return NULL;
11649 length = PyUnicode_GET_LENGTH(self);
11650 kind = PyUnicode_KIND(self);
11651 data = PyUnicode_DATA(self);
Georg Brandl559e5d72008-06-11 18:37:52 +000011652
11653 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011654 if (length == 1)
11655 return PyBool_FromLong(
11656 Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
Georg Brandl559e5d72008-06-11 18:37:52 +000011657
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011658 for (i = 0; i < length; i++) {
11659 if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
Georg Brandl559e5d72008-06-11 18:37:52 +000011660 Py_RETURN_FALSE;
11661 }
11662 }
11663 Py_RETURN_TRUE;
11664}
11665
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011666PyDoc_STRVAR(join__doc__,
Georg Brandl495f7b52009-10-27 15:28:25 +000011667 "S.join(iterable) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011668\n\
11669Return a string which is the concatenation of the strings in the\n\
Georg Brandl495f7b52009-10-27 15:28:25 +000011670iterable. The separator between elements is S.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011671
11672static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011673unicode_join(PyObject *self, PyObject *data)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011674{
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011675 return PyUnicode_Join(self, data);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011676}
11677
Martin v. Löwis18e16552006-02-15 17:27:45 +000011678static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011679unicode_length(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011680{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011681 if (PyUnicode_READY(self) == -1)
11682 return -1;
11683 return PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011684}
11685
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011686PyDoc_STRVAR(ljust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011687 "S.ljust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011688\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000011689Return S left-justified in a Unicode string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011690done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011691
11692static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020011693unicode_ljust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011694{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011695 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011696 Py_UCS4 fillchar = ' ';
11697
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011698 if (!PyArg_ParseTuple(args, "n|O&:ljust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011699 return NULL;
11700
Victor Stinnerc4b49542011-12-11 22:44:26 +010011701 if (PyUnicode_READY(self) < 0)
11702 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011703
Victor Stinnerc4b49542011-12-11 22:44:26 +010011704 if (PyUnicode_GET_LENGTH(self) >= width)
11705 return unicode_result_unchanged(self);
11706
11707 return pad(self, 0, width - PyUnicode_GET_LENGTH(self), fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011708}
11709
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011710PyDoc_STRVAR(lower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011711 "S.lower() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011712\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011713Return a copy of the string S converted to lowercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011714
11715static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020011716unicode_lower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011717{
Guido van Rossumd57fd912000-03-10 22:53:23 +000011718 return fixup(self, fixlower);
11719}
11720
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011721#define LEFTSTRIP 0
11722#define RIGHTSTRIP 1
11723#define BOTHSTRIP 2
11724
11725/* Arrays indexed by above */
11726static const char *stripformat[] = {"|O:lstrip", "|O:rstrip", "|O:strip"};
11727
11728#define STRIPNAME(i) (stripformat[i]+3)
11729
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011730/* externally visible for str.strip(unicode) */
11731PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011732_PyUnicode_XStrip(PyObject *self, int striptype, PyObject *sepobj)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011733{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011734 void *data;
11735 int kind;
11736 Py_ssize_t i, j, len;
11737 BLOOM_MASK sepmask;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011738
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011739 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
11740 return NULL;
11741
11742 kind = PyUnicode_KIND(self);
11743 data = PyUnicode_DATA(self);
11744 len = PyUnicode_GET_LENGTH(self);
11745 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
11746 PyUnicode_DATA(sepobj),
11747 PyUnicode_GET_LENGTH(sepobj));
Thomas Wouters477c8d52006-05-27 19:21:47 +000011748
Benjamin Peterson14339b62009-01-31 16:36:08 +000011749 i = 0;
11750 if (striptype != RIGHTSTRIP) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011751 while (i < len &&
11752 BLOOM_MEMBER(sepmask, PyUnicode_READ(kind, data, i), sepobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011753 i++;
11754 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011755 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011756
Benjamin Peterson14339b62009-01-31 16:36:08 +000011757 j = len;
11758 if (striptype != LEFTSTRIP) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011759 do {
11760 j--;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011761 } while (j >= i &&
11762 BLOOM_MEMBER(sepmask, PyUnicode_READ(kind, data, j), sepobj));
Benjamin Peterson29060642009-01-31 22:14:21 +000011763 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011764 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011765
Victor Stinner7931d9a2011-11-04 00:22:48 +010011766 return PyUnicode_Substring(self, i, j);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011767}
11768
11769PyObject*
11770PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
11771{
11772 unsigned char *data;
11773 int kind;
Victor Stinner12bab6d2011-10-01 01:53:49 +020011774 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011775
Victor Stinnerde636f32011-10-01 03:55:54 +020011776 if (PyUnicode_READY(self) == -1)
11777 return NULL;
11778
11779 end = Py_MIN(end, PyUnicode_GET_LENGTH(self));
11780
Victor Stinner12bab6d2011-10-01 01:53:49 +020011781 if (start == 0 && end == PyUnicode_GET_LENGTH(self))
Victor Stinnerc4b49542011-12-11 22:44:26 +010011782 return unicode_result_unchanged(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011783
Victor Stinner12bab6d2011-10-01 01:53:49 +020011784 length = end - start;
11785 if (length == 1)
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011786 return unicode_getitem(self, start);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011787
Victor Stinnerde636f32011-10-01 03:55:54 +020011788 if (start < 0 || end < 0) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020011789 PyErr_SetString(PyExc_IndexError, "string index out of range");
11790 return NULL;
11791 }
11792
Victor Stinnerb9275c12011-10-05 14:01:42 +020011793 if (PyUnicode_IS_ASCII(self)) {
11794 kind = PyUnicode_KIND(self);
11795 data = PyUnicode_1BYTE_DATA(self);
11796 return unicode_fromascii(data + start, length);
11797 }
11798 else {
11799 kind = PyUnicode_KIND(self);
11800 data = PyUnicode_1BYTE_DATA(self);
11801 return PyUnicode_FromKindAndData(kind,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020011802 data + kind * start,
Victor Stinnerb9275c12011-10-05 14:01:42 +020011803 length);
11804 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011805}
Guido van Rossumd57fd912000-03-10 22:53:23 +000011806
11807static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011808do_strip(PyObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011809{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011810 int kind;
11811 void *data;
11812 Py_ssize_t len, i, j;
11813
11814 if (PyUnicode_READY(self) == -1)
11815 return NULL;
11816
11817 kind = PyUnicode_KIND(self);
11818 data = PyUnicode_DATA(self);
11819 len = PyUnicode_GET_LENGTH(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011820
Benjamin Peterson14339b62009-01-31 16:36:08 +000011821 i = 0;
11822 if (striptype != RIGHTSTRIP) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011823 while (i < len && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, i))) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000011824 i++;
11825 }
11826 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011827
Benjamin Peterson14339b62009-01-31 16:36:08 +000011828 j = len;
11829 if (striptype != LEFTSTRIP) {
11830 do {
11831 j--;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011832 } while (j >= i && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, j)));
Benjamin Peterson14339b62009-01-31 16:36:08 +000011833 j++;
11834 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011835
Victor Stinner7931d9a2011-11-04 00:22:48 +010011836 return PyUnicode_Substring(self, i, j);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011837}
11838
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011839
11840static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011841do_argstrip(PyObject *self, int striptype, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011842{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011843 PyObject *sep = NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011844
Benjamin Peterson14339b62009-01-31 16:36:08 +000011845 if (!PyArg_ParseTuple(args, (char *)stripformat[striptype], &sep))
11846 return NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011847
Benjamin Peterson14339b62009-01-31 16:36:08 +000011848 if (sep != NULL && sep != Py_None) {
11849 if (PyUnicode_Check(sep))
11850 return _PyUnicode_XStrip(self, striptype, sep);
11851 else {
11852 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000011853 "%s arg must be None or str",
11854 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +000011855 return NULL;
11856 }
11857 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011858
Benjamin Peterson14339b62009-01-31 16:36:08 +000011859 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011860}
11861
11862
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011863PyDoc_STRVAR(strip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011864 "S.strip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011865\n\
11866Return a copy of the string S with leading and trailing\n\
11867whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011868If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011869
11870static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011871unicode_strip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011872{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011873 if (PyTuple_GET_SIZE(args) == 0)
11874 return do_strip(self, BOTHSTRIP); /* Common case */
11875 else
11876 return do_argstrip(self, BOTHSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011877}
11878
11879
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011880PyDoc_STRVAR(lstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011881 "S.lstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011882\n\
11883Return a copy of the string S with leading whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011884If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011885
11886static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011887unicode_lstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011888{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011889 if (PyTuple_GET_SIZE(args) == 0)
11890 return do_strip(self, LEFTSTRIP); /* Common case */
11891 else
11892 return do_argstrip(self, LEFTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011893}
11894
11895
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011896PyDoc_STRVAR(rstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011897 "S.rstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011898\n\
11899Return a copy of the string S with trailing whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011900If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011901
11902static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011903unicode_rstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011904{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011905 if (PyTuple_GET_SIZE(args) == 0)
11906 return do_strip(self, RIGHTSTRIP); /* Common case */
11907 else
11908 return do_argstrip(self, RIGHTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011909}
11910
11911
Guido van Rossumd57fd912000-03-10 22:53:23 +000011912static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011913unicode_repeat(PyObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011914{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011915 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011916 Py_ssize_t nchars, n;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011917
Georg Brandl222de0f2009-04-12 12:01:50 +000011918 if (len < 1) {
11919 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +020011920 return unicode_empty;
Georg Brandl222de0f2009-04-12 12:01:50 +000011921 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011922
Victor Stinnerc4b49542011-12-11 22:44:26 +010011923 /* no repeat, return original string */
11924 if (len == 1)
11925 return unicode_result_unchanged(str);
Tim Peters8f422462000-09-09 06:13:41 +000011926
Victor Stinnerc4b49542011-12-11 22:44:26 +010011927 if (PyUnicode_READY(str) < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011928 return NULL;
11929
Victor Stinnerc759f3e2011-10-01 03:09:58 +020011930 if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
Victor Stinner67ca64c2011-10-01 02:47:29 +020011931 PyErr_SetString(PyExc_OverflowError,
11932 "repeated string is too long");
11933 return NULL;
11934 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011935 nchars = len * PyUnicode_GET_LENGTH(str);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011936
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011937 u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011938 if (!u)
11939 return NULL;
Victor Stinner67ca64c2011-10-01 02:47:29 +020011940 assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011941
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011942 if (PyUnicode_GET_LENGTH(str) == 1) {
11943 const int kind = PyUnicode_KIND(str);
11944 const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
Victor Stinner73f53b52011-12-18 03:26:31 +010011945 if (kind == PyUnicode_1BYTE_KIND) {
11946 void *to = PyUnicode_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011947 memset(to, (unsigned char)fill_char, len);
Victor Stinner73f53b52011-12-18 03:26:31 +010011948 }
11949 else if (kind == PyUnicode_2BYTE_KIND) {
11950 Py_UCS2 *ucs2 = PyUnicode_2BYTE_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011951 for (n = 0; n < len; ++n)
Victor Stinner73f53b52011-12-18 03:26:31 +010011952 ucs2[n] = fill_char;
11953 } else {
11954 Py_UCS4 *ucs4 = PyUnicode_4BYTE_DATA(u);
11955 assert(kind == PyUnicode_4BYTE_KIND);
11956 for (n = 0; n < len; ++n)
11957 ucs4[n] = fill_char;
Victor Stinner67ca64c2011-10-01 02:47:29 +020011958 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011959 }
11960 else {
11961 /* number of characters copied this far */
11962 Py_ssize_t done = PyUnicode_GET_LENGTH(str);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020011963 const Py_ssize_t char_size = PyUnicode_KIND(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011964 char *to = (char *) PyUnicode_DATA(u);
11965 Py_MEMCPY(to, PyUnicode_DATA(str),
11966 PyUnicode_GET_LENGTH(str) * char_size);
Benjamin Peterson29060642009-01-31 22:14:21 +000011967 while (done < nchars) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011968 n = (done <= nchars-done) ? done : nchars-done;
11969 Py_MEMCPY(to + (done * char_size), to, n * char_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011970 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +000011971 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011972 }
11973
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020011974 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011975 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011976}
11977
Alexander Belopolsky40018472011-02-26 01:02:56 +000011978PyObject *
11979PyUnicode_Replace(PyObject *obj,
11980 PyObject *subobj,
11981 PyObject *replobj,
11982 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011983{
11984 PyObject *self;
11985 PyObject *str1;
11986 PyObject *str2;
11987 PyObject *result;
11988
11989 self = PyUnicode_FromObject(obj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060011990 if (self == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000011991 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011992 str1 = PyUnicode_FromObject(subobj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060011993 if (str1 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011994 Py_DECREF(self);
11995 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011996 }
11997 str2 = PyUnicode_FromObject(replobj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060011998 if (str2 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011999 Py_DECREF(self);
12000 Py_DECREF(str1);
12001 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012002 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060012003 if (PyUnicode_READY(self) == -1 ||
12004 PyUnicode_READY(str1) == -1 ||
12005 PyUnicode_READY(str2) == -1)
12006 result = NULL;
12007 else
12008 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012009 Py_DECREF(self);
12010 Py_DECREF(str1);
12011 Py_DECREF(str2);
12012 return result;
12013}
12014
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012015PyDoc_STRVAR(replace__doc__,
Ezio Melottic1897e72010-06-26 18:50:39 +000012016 "S.replace(old, new[, count]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012017\n\
12018Return a copy of S with all occurrences of substring\n\
Georg Brandlf08a9dd2008-06-10 16:57:31 +000012019old replaced by new. If the optional argument count is\n\
12020given, only the first count occurrences are replaced.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012021
12022static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012023unicode_replace(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012024{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012025 PyObject *str1;
12026 PyObject *str2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012027 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012028 PyObject *result;
12029
Martin v. Löwis18e16552006-02-15 17:27:45 +000012030 if (!PyArg_ParseTuple(args, "OO|n:replace", &str1, &str2, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012031 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060012032 if (PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000012033 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012034 str1 = PyUnicode_FromObject(str1);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012035 if (str1 == NULL)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012036 return NULL;
12037 str2 = PyUnicode_FromObject(str2);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012038 if (str2 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012039 Py_DECREF(str1);
12040 return NULL;
Walter Dörwaldf6b56ae2003-02-09 23:42:56 +000012041 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060012042 if (PyUnicode_READY(str1) == -1 || PyUnicode_READY(str2) == -1)
12043 result = NULL;
12044 else
12045 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012046
12047 Py_DECREF(str1);
12048 Py_DECREF(str2);
12049 return result;
12050}
12051
Alexander Belopolsky40018472011-02-26 01:02:56 +000012052static PyObject *
12053unicode_repr(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012054{
Walter Dörwald79e913e2007-05-12 11:08:06 +000012055 PyObject *repr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012056 Py_ssize_t isize;
12057 Py_ssize_t osize, squote, dquote, i, o;
12058 Py_UCS4 max, quote;
12059 int ikind, okind;
12060 void *idata, *odata;
Walter Dörwald79e913e2007-05-12 11:08:06 +000012061
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012062 if (PyUnicode_READY(unicode) == -1)
Walter Dörwald79e913e2007-05-12 11:08:06 +000012063 return NULL;
12064
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012065 isize = PyUnicode_GET_LENGTH(unicode);
12066 idata = PyUnicode_DATA(unicode);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012067
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012068 /* Compute length of output, quote characters, and
12069 maximum character */
12070 osize = 2; /* quotes */
12071 max = 127;
12072 squote = dquote = 0;
12073 ikind = PyUnicode_KIND(unicode);
12074 for (i = 0; i < isize; i++) {
12075 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
12076 switch (ch) {
12077 case '\'': squote++; osize++; break;
12078 case '"': dquote++; osize++; break;
12079 case '\\': case '\t': case '\r': case '\n':
12080 osize += 2; break;
12081 default:
12082 /* Fast-path ASCII */
12083 if (ch < ' ' || ch == 0x7f)
12084 osize += 4; /* \xHH */
12085 else if (ch < 0x7f)
12086 osize++;
12087 else if (Py_UNICODE_ISPRINTABLE(ch)) {
12088 osize++;
12089 max = ch > max ? ch : max;
12090 }
12091 else if (ch < 0x100)
12092 osize += 4; /* \xHH */
12093 else if (ch < 0x10000)
12094 osize += 6; /* \uHHHH */
12095 else
12096 osize += 10; /* \uHHHHHHHH */
12097 }
12098 }
12099
12100 quote = '\'';
12101 if (squote) {
12102 if (dquote)
12103 /* Both squote and dquote present. Use squote,
12104 and escape them */
12105 osize += squote;
12106 else
12107 quote = '"';
12108 }
12109
12110 repr = PyUnicode_New(osize, max);
12111 if (repr == NULL)
12112 return NULL;
12113 okind = PyUnicode_KIND(repr);
12114 odata = PyUnicode_DATA(repr);
12115
12116 PyUnicode_WRITE(okind, odata, 0, quote);
12117 PyUnicode_WRITE(okind, odata, osize-1, quote);
12118
12119 for (i = 0, o = 1; i < isize; i++) {
12120 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012121
12122 /* Escape quotes and backslashes */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012123 if ((ch == quote) || (ch == '\\')) {
12124 PyUnicode_WRITE(okind, odata, o++, '\\');
12125 PyUnicode_WRITE(okind, odata, o++, ch);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012126 continue;
12127 }
12128
Benjamin Peterson29060642009-01-31 22:14:21 +000012129 /* Map special whitespace to '\t', \n', '\r' */
Georg Brandl559e5d72008-06-11 18:37:52 +000012130 if (ch == '\t') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012131 PyUnicode_WRITE(okind, odata, o++, '\\');
12132 PyUnicode_WRITE(okind, odata, o++, 't');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012133 }
12134 else if (ch == '\n') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012135 PyUnicode_WRITE(okind, odata, o++, '\\');
12136 PyUnicode_WRITE(okind, odata, o++, 'n');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012137 }
12138 else if (ch == '\r') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012139 PyUnicode_WRITE(okind, odata, o++, '\\');
12140 PyUnicode_WRITE(okind, odata, o++, 'r');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012141 }
12142
12143 /* Map non-printable US ASCII to '\xhh' */
Georg Brandl559e5d72008-06-11 18:37:52 +000012144 else if (ch < ' ' || ch == 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012145 PyUnicode_WRITE(okind, odata, o++, '\\');
12146 PyUnicode_WRITE(okind, odata, o++, 'x');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012147 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12148 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012149 }
12150
Georg Brandl559e5d72008-06-11 18:37:52 +000012151 /* Copy ASCII characters as-is */
12152 else if (ch < 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012153 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000012154 }
12155
Benjamin Peterson29060642009-01-31 22:14:21 +000012156 /* Non-ASCII characters */
Georg Brandl559e5d72008-06-11 18:37:52 +000012157 else {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012158 /* Map Unicode whitespace and control characters
Georg Brandl559e5d72008-06-11 18:37:52 +000012159 (categories Z* and C* except ASCII space)
12160 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012161 if (!Py_UNICODE_ISPRINTABLE(ch)) {
Georg Brandl559e5d72008-06-11 18:37:52 +000012162 /* Map 8-bit characters to '\xhh' */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012163 if (ch <= 0xff) {
12164 PyUnicode_WRITE(okind, odata, o++, '\\');
12165 PyUnicode_WRITE(okind, odata, o++, 'x');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012166 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12167 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012168 }
12169 /* Map 21-bit characters to '\U00xxxxxx' */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012170 else if (ch >= 0x10000) {
12171 PyUnicode_WRITE(okind, odata, o++, '\\');
12172 PyUnicode_WRITE(okind, odata, o++, 'U');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012173 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 28) & 0xF]);
12174 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 24) & 0xF]);
12175 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 20) & 0xF]);
12176 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 16) & 0xF]);
12177 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12178 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12179 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12180 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012181 }
12182 /* Map 16-bit characters to '\uxxxx' */
12183 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012184 PyUnicode_WRITE(okind, odata, o++, '\\');
12185 PyUnicode_WRITE(okind, odata, o++, 'u');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012186 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12187 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12188 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12189 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012190 }
12191 }
12192 /* Copy characters as-is */
12193 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012194 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000012195 }
12196 }
Walter Dörwald79e913e2007-05-12 11:08:06 +000012197 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012198 /* Closing quote already added at the beginning */
Victor Stinner05d11892011-10-06 01:13:58 +020012199 assert(_PyUnicode_CheckConsistency(repr, 1));
Walter Dörwald79e913e2007-05-12 11:08:06 +000012200 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012201}
12202
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012203PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012204 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012205\n\
12206Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080012207such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012208arguments start and end are interpreted as in slice notation.\n\
12209\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012210Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012211
12212static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012213unicode_rfind(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012214{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012215 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012216 Py_ssize_t start;
12217 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012218 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012219
Jesus Ceaac451502011-04-20 17:09:23 +020012220 if (!stringlib_parse_args_finds_unicode("rfind", args, &substring,
12221 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012222 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012223
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012224 if (PyUnicode_READY(self) == -1)
12225 return NULL;
12226 if (PyUnicode_READY(substring) == -1)
12227 return NULL;
12228
Victor Stinner7931d9a2011-11-04 00:22:48 +010012229 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012230
12231 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012232
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012233 if (result == -2)
12234 return NULL;
12235
Christian Heimes217cfd12007-12-02 14:31:20 +000012236 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012237}
12238
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012239PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012240 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012241\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012242Like S.rfind() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012243
12244static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012245unicode_rindex(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012246{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012247 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012248 Py_ssize_t start;
12249 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012250 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012251
Jesus Ceaac451502011-04-20 17:09:23 +020012252 if (!stringlib_parse_args_finds_unicode("rindex", args, &substring,
12253 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012254 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012255
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012256 if (PyUnicode_READY(self) == -1)
12257 return NULL;
12258 if (PyUnicode_READY(substring) == -1)
12259 return NULL;
12260
Victor Stinner7931d9a2011-11-04 00:22:48 +010012261 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012262
12263 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012264
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012265 if (result == -2)
12266 return NULL;
12267
Guido van Rossumd57fd912000-03-10 22:53:23 +000012268 if (result < 0) {
12269 PyErr_SetString(PyExc_ValueError, "substring not found");
12270 return NULL;
12271 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012272
Christian Heimes217cfd12007-12-02 14:31:20 +000012273 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012274}
12275
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012276PyDoc_STRVAR(rjust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012277 "S.rjust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012278\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012279Return S right-justified in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012280done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012281
12282static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012283unicode_rjust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012284{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012285 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012286 Py_UCS4 fillchar = ' ';
12287
Victor Stinnere9a29352011-10-01 02:14:59 +020012288 if (!PyArg_ParseTuple(args, "n|O&:rjust", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012289 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012290
Victor Stinnerc4b49542011-12-11 22:44:26 +010012291 if (PyUnicode_READY(self) < 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012292 return NULL;
12293
Victor Stinnerc4b49542011-12-11 22:44:26 +010012294 if (PyUnicode_GET_LENGTH(self) >= width)
12295 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012296
Victor Stinnerc4b49542011-12-11 22:44:26 +010012297 return pad(self, width - PyUnicode_GET_LENGTH(self), 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012298}
12299
Alexander Belopolsky40018472011-02-26 01:02:56 +000012300PyObject *
12301PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012302{
12303 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +000012304
Guido van Rossumd57fd912000-03-10 22:53:23 +000012305 s = PyUnicode_FromObject(s);
12306 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012307 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012308 if (sep != NULL) {
12309 sep = PyUnicode_FromObject(sep);
12310 if (sep == NULL) {
12311 Py_DECREF(s);
12312 return NULL;
12313 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012314 }
12315
Victor Stinner9310abb2011-10-05 00:59:23 +020012316 result = split(s, sep, maxsplit);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012317
12318 Py_DECREF(s);
12319 Py_XDECREF(sep);
12320 return result;
12321}
12322
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012323PyDoc_STRVAR(split__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012324 "S.split([sep[, maxsplit]]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012325\n\
12326Return a list of the words in S, using sep as the\n\
12327delimiter string. If maxsplit is given, at most maxsplit\n\
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000012328splits are done. If sep is not specified or is None, any\n\
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +000012329whitespace string is a separator and empty strings are\n\
12330removed from the result.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012331
12332static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012333unicode_split(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012334{
12335 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012336 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012337
Martin v. Löwis18e16552006-02-15 17:27:45 +000012338 if (!PyArg_ParseTuple(args, "|On:split", &substring, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012339 return NULL;
12340
12341 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012342 return split(self, NULL, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012343 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012344 return split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012345 else
Victor Stinner7931d9a2011-11-04 00:22:48 +010012346 return PyUnicode_Split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012347}
12348
Thomas Wouters477c8d52006-05-27 19:21:47 +000012349PyObject *
12350PyUnicode_Partition(PyObject *str_in, PyObject *sep_in)
12351{
12352 PyObject* str_obj;
12353 PyObject* sep_obj;
12354 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012355 int kind1, kind2, kind;
12356 void *buf1 = NULL, *buf2 = NULL;
12357 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012358
12359 str_obj = PyUnicode_FromObject(str_in);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012360 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012361 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012362 sep_obj = PyUnicode_FromObject(sep_in);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012363 if (!sep_obj) {
12364 Py_DECREF(str_obj);
12365 return NULL;
12366 }
12367 if (PyUnicode_READY(sep_obj) == -1 || PyUnicode_READY(str_obj) == -1) {
12368 Py_DECREF(sep_obj);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012369 Py_DECREF(str_obj);
12370 return NULL;
12371 }
12372
Victor Stinner14f8f022011-10-05 20:58:25 +020012373 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012374 kind2 = PyUnicode_KIND(sep_obj);
Victor Stinner14f8f022011-10-05 20:58:25 +020012375 kind = Py_MAX(kind1, kind2);
12376 buf1 = PyUnicode_DATA(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012377 if (kind1 != kind)
Victor Stinner14f8f022011-10-05 20:58:25 +020012378 buf1 = _PyUnicode_AsKind(str_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012379 if (!buf1)
12380 goto onError;
12381 buf2 = PyUnicode_DATA(sep_obj);
12382 if (kind2 != kind)
12383 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12384 if (!buf2)
12385 goto onError;
12386 len1 = PyUnicode_GET_LENGTH(str_obj);
12387 len2 = PyUnicode_GET_LENGTH(sep_obj);
12388
Benjamin Petersonead6b532011-12-20 17:23:42 -060012389 switch (PyUnicode_KIND(str_obj)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012390 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012391 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12392 out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12393 else
12394 out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012395 break;
12396 case PyUnicode_2BYTE_KIND:
12397 out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12398 break;
12399 case PyUnicode_4BYTE_KIND:
12400 out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12401 break;
12402 default:
12403 assert(0);
12404 out = 0;
12405 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012406
12407 Py_DECREF(sep_obj);
12408 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012409 if (kind1 != kind)
12410 PyMem_Free(buf1);
12411 if (kind2 != kind)
12412 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012413
12414 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012415 onError:
12416 Py_DECREF(sep_obj);
12417 Py_DECREF(str_obj);
12418 if (kind1 != kind && buf1)
12419 PyMem_Free(buf1);
12420 if (kind2 != kind && buf2)
12421 PyMem_Free(buf2);
12422 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012423}
12424
12425
12426PyObject *
12427PyUnicode_RPartition(PyObject *str_in, PyObject *sep_in)
12428{
12429 PyObject* str_obj;
12430 PyObject* sep_obj;
12431 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012432 int kind1, kind2, kind;
12433 void *buf1 = NULL, *buf2 = NULL;
12434 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012435
12436 str_obj = PyUnicode_FromObject(str_in);
12437 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012438 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012439 sep_obj = PyUnicode_FromObject(sep_in);
12440 if (!sep_obj) {
12441 Py_DECREF(str_obj);
12442 return NULL;
12443 }
12444
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012445 kind1 = PyUnicode_KIND(str_in);
12446 kind2 = PyUnicode_KIND(sep_obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +020012447 kind = Py_MAX(kind1, kind2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012448 buf1 = PyUnicode_DATA(str_in);
12449 if (kind1 != kind)
12450 buf1 = _PyUnicode_AsKind(str_in, kind);
12451 if (!buf1)
12452 goto onError;
12453 buf2 = PyUnicode_DATA(sep_obj);
12454 if (kind2 != kind)
12455 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12456 if (!buf2)
12457 goto onError;
12458 len1 = PyUnicode_GET_LENGTH(str_obj);
12459 len2 = PyUnicode_GET_LENGTH(sep_obj);
12460
Benjamin Petersonead6b532011-12-20 17:23:42 -060012461 switch (PyUnicode_KIND(str_in)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012462 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012463 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12464 out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12465 else
12466 out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012467 break;
12468 case PyUnicode_2BYTE_KIND:
12469 out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12470 break;
12471 case PyUnicode_4BYTE_KIND:
12472 out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12473 break;
12474 default:
12475 assert(0);
12476 out = 0;
12477 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012478
12479 Py_DECREF(sep_obj);
12480 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012481 if (kind1 != kind)
12482 PyMem_Free(buf1);
12483 if (kind2 != kind)
12484 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012485
12486 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012487 onError:
12488 Py_DECREF(sep_obj);
12489 Py_DECREF(str_obj);
12490 if (kind1 != kind && buf1)
12491 PyMem_Free(buf1);
12492 if (kind2 != kind && buf2)
12493 PyMem_Free(buf2);
12494 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012495}
12496
12497PyDoc_STRVAR(partition__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012498 "S.partition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012499\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012500Search for the separator sep in S, and return the part before it,\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012501the separator itself, and the part after it. If the separator is not\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012502found, return S and two empty strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012503
12504static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012505unicode_partition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012506{
Victor Stinner9310abb2011-10-05 00:59:23 +020012507 return PyUnicode_Partition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012508}
12509
12510PyDoc_STRVAR(rpartition__doc__,
Ezio Melotti5b2b2422010-01-25 11:58:28 +000012511 "S.rpartition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012512\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012513Search for the separator sep in S, starting at the end of S, and return\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012514the part before it, the separator itself, and the part after it. If the\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012515separator is not found, return two empty strings and S.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012516
12517static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012518unicode_rpartition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012519{
Victor Stinner9310abb2011-10-05 00:59:23 +020012520 return PyUnicode_RPartition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012521}
12522
Alexander Belopolsky40018472011-02-26 01:02:56 +000012523PyObject *
12524PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012525{
12526 PyObject *result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012527
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012528 s = PyUnicode_FromObject(s);
12529 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012530 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012531 if (sep != NULL) {
12532 sep = PyUnicode_FromObject(sep);
12533 if (sep == NULL) {
12534 Py_DECREF(s);
12535 return NULL;
12536 }
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012537 }
12538
Victor Stinner9310abb2011-10-05 00:59:23 +020012539 result = rsplit(s, sep, maxsplit);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012540
12541 Py_DECREF(s);
12542 Py_XDECREF(sep);
12543 return result;
12544}
12545
12546PyDoc_STRVAR(rsplit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012547 "S.rsplit([sep[, maxsplit]]) -> list of strings\n\
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012548\n\
12549Return a list of the words in S, using sep as the\n\
12550delimiter string, starting at the end of the string and\n\
12551working to the front. If maxsplit is given, at most maxsplit\n\
12552splits are done. If sep is not specified, any whitespace string\n\
12553is a separator.");
12554
12555static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012556unicode_rsplit(PyObject *self, PyObject *args)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012557{
12558 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012559 Py_ssize_t maxcount = -1;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012560
Martin v. Löwis18e16552006-02-15 17:27:45 +000012561 if (!PyArg_ParseTuple(args, "|On:rsplit", &substring, &maxcount))
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012562 return NULL;
12563
12564 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012565 return rsplit(self, NULL, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012566 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012567 return rsplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012568 else
Victor Stinner9310abb2011-10-05 00:59:23 +020012569 return PyUnicode_RSplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012570}
12571
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012572PyDoc_STRVAR(splitlines__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012573 "S.splitlines([keepends]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012574\n\
12575Return a list of the lines in S, breaking at line boundaries.\n\
Guido van Rossum86662912000-04-11 15:38:46 +000012576Line breaks are not included in the resulting list unless keepends\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012577is given and true.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012578
12579static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012580unicode_splitlines(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012581{
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012582 static char *kwlist[] = {"keepends", 0};
Guido van Rossum86662912000-04-11 15:38:46 +000012583 int keepends = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012584
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012585 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:splitlines",
12586 kwlist, &keepends))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012587 return NULL;
12588
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012589 return PyUnicode_Splitlines(self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012590}
12591
12592static
Guido van Rossumf15a29f2007-05-04 00:41:39 +000012593PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012594{
Victor Stinnerc4b49542011-12-11 22:44:26 +010012595 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012596}
12597
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012598PyDoc_STRVAR(swapcase__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012599 "S.swapcase() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012600\n\
12601Return a copy of S with uppercase characters converted to lowercase\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012602and vice versa.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012603
12604static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012605unicode_swapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012606{
Guido van Rossumd57fd912000-03-10 22:53:23 +000012607 return fixup(self, fixswapcase);
12608}
12609
Georg Brandlceee0772007-11-27 23:48:05 +000012610PyDoc_STRVAR(maketrans__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012611 "str.maketrans(x[, y[, z]]) -> dict (static method)\n\
Georg Brandlceee0772007-11-27 23:48:05 +000012612\n\
12613Return a translation table usable for str.translate().\n\
12614If there is only one argument, it must be a dictionary mapping Unicode\n\
12615ordinals (integers) or characters to Unicode ordinals, strings or None.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012616Character keys will be then converted to ordinals.\n\
Georg Brandlceee0772007-11-27 23:48:05 +000012617If there are two arguments, they must be strings of equal length, and\n\
12618in the resulting dictionary, each character in x will be mapped to the\n\
12619character at the same position in y. If there is a third argument, it\n\
12620must be a string, whose characters will be mapped to None in the result.");
12621
12622static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012623unicode_maketrans(PyObject *null, PyObject *args)
Georg Brandlceee0772007-11-27 23:48:05 +000012624{
12625 PyObject *x, *y = NULL, *z = NULL;
12626 PyObject *new = NULL, *key, *value;
12627 Py_ssize_t i = 0;
12628 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012629
Georg Brandlceee0772007-11-27 23:48:05 +000012630 if (!PyArg_ParseTuple(args, "O|UU:maketrans", &x, &y, &z))
12631 return NULL;
12632 new = PyDict_New();
12633 if (!new)
12634 return NULL;
12635 if (y != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012636 int x_kind, y_kind, z_kind;
12637 void *x_data, *y_data, *z_data;
12638
Georg Brandlceee0772007-11-27 23:48:05 +000012639 /* x must be a string too, of equal length */
Georg Brandlceee0772007-11-27 23:48:05 +000012640 if (!PyUnicode_Check(x)) {
12641 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
12642 "be a string if there is a second argument");
12643 goto err;
12644 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012645 if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012646 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
12647 "arguments must have equal length");
12648 goto err;
12649 }
12650 /* create entries for translating chars in x to those in y */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012651 x_kind = PyUnicode_KIND(x);
12652 y_kind = PyUnicode_KIND(y);
12653 x_data = PyUnicode_DATA(x);
12654 y_data = PyUnicode_DATA(y);
12655 for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
12656 key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060012657 if (!key)
Georg Brandlceee0772007-11-27 23:48:05 +000012658 goto err;
Benjamin Peterson822c7902011-12-20 13:32:50 -060012659 value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060012660 if (!value) {
12661 Py_DECREF(key);
12662 goto err;
12663 }
Georg Brandlceee0772007-11-27 23:48:05 +000012664 res = PyDict_SetItem(new, key, value);
12665 Py_DECREF(key);
12666 Py_DECREF(value);
12667 if (res < 0)
12668 goto err;
12669 }
12670 /* create entries for deleting chars in z */
12671 if (z != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012672 z_kind = PyUnicode_KIND(z);
12673 z_data = PyUnicode_DATA(z);
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012674 for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012675 key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000012676 if (!key)
12677 goto err;
12678 res = PyDict_SetItem(new, key, Py_None);
12679 Py_DECREF(key);
12680 if (res < 0)
12681 goto err;
12682 }
12683 }
12684 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012685 int kind;
12686 void *data;
12687
Georg Brandlceee0772007-11-27 23:48:05 +000012688 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +000012689 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012690 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
12691 "to maketrans it must be a dict");
12692 goto err;
12693 }
12694 /* copy entries into the new dict, converting string keys to int keys */
12695 while (PyDict_Next(x, &i, &key, &value)) {
12696 if (PyUnicode_Check(key)) {
12697 /* convert string keys to integer keys */
12698 PyObject *newkey;
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012699 if (PyUnicode_GET_LENGTH(key) != 1) {
Georg Brandlceee0772007-11-27 23:48:05 +000012700 PyErr_SetString(PyExc_ValueError, "string keys in translate "
12701 "table must be of length 1");
12702 goto err;
12703 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012704 kind = PyUnicode_KIND(key);
12705 data = PyUnicode_DATA(key);
12706 newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
Georg Brandlceee0772007-11-27 23:48:05 +000012707 if (!newkey)
12708 goto err;
12709 res = PyDict_SetItem(new, newkey, value);
12710 Py_DECREF(newkey);
12711 if (res < 0)
12712 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +000012713 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012714 /* just keep integer keys */
12715 if (PyDict_SetItem(new, key, value) < 0)
12716 goto err;
12717 } else {
12718 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
12719 "be strings or integers");
12720 goto err;
12721 }
12722 }
12723 }
12724 return new;
12725 err:
12726 Py_DECREF(new);
12727 return NULL;
12728}
12729
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012730PyDoc_STRVAR(translate__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012731 "S.translate(table) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012732\n\
12733Return a copy of the string S, where all characters have been mapped\n\
12734through the given translation table, which must be a mapping of\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012735Unicode ordinals to Unicode ordinals, strings, or None.\n\
Walter Dörwald5c1ee172002-09-04 20:31:32 +000012736Unmapped characters are left untouched. Characters mapped to None\n\
12737are deleted.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012738
12739static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012740unicode_translate(PyObject *self, PyObject *table)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012741{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012742 return _PyUnicode_TranslateCharmap(self, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012743}
12744
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012745PyDoc_STRVAR(upper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012746 "S.upper() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012747\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012748Return a copy of S converted to uppercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012749
12750static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012751unicode_upper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012752{
Guido van Rossumd57fd912000-03-10 22:53:23 +000012753 return fixup(self, fixupper);
12754}
12755
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012756PyDoc_STRVAR(zfill__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012757 "S.zfill(width) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012758\n\
Benjamin Peterson9aa42992008-09-10 21:57:34 +000012759Pad a numeric string S with zeros on the left, to fill a field\n\
12760of the specified width. The string S is never truncated.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012761
12762static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012763unicode_zfill(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012764{
Martin v. Löwis18e16552006-02-15 17:27:45 +000012765 Py_ssize_t fill;
Victor Stinner9310abb2011-10-05 00:59:23 +020012766 PyObject *u;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012767 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012768 int kind;
12769 void *data;
12770 Py_UCS4 chr;
12771
Martin v. Löwis18e16552006-02-15 17:27:45 +000012772 if (!PyArg_ParseTuple(args, "n:zfill", &width))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012773 return NULL;
12774
Victor Stinnerc4b49542011-12-11 22:44:26 +010012775 if (PyUnicode_READY(self) < 0)
12776 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012777
Victor Stinnerc4b49542011-12-11 22:44:26 +010012778 if (PyUnicode_GET_LENGTH(self) >= width)
12779 return unicode_result_unchanged(self);
12780
12781 fill = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012782
12783 u = pad(self, fill, 0, '0');
12784
Walter Dörwald068325e2002-04-15 13:36:47 +000012785 if (u == NULL)
12786 return NULL;
12787
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012788 kind = PyUnicode_KIND(u);
12789 data = PyUnicode_DATA(u);
12790 chr = PyUnicode_READ(kind, data, fill);
12791
12792 if (chr == '+' || chr == '-') {
Guido van Rossumd57fd912000-03-10 22:53:23 +000012793 /* move sign to beginning of string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012794 PyUnicode_WRITE(kind, data, 0, chr);
12795 PyUnicode_WRITE(kind, data, fill, '0');
Guido van Rossumd57fd912000-03-10 22:53:23 +000012796 }
12797
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012798 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +010012799 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012800}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012801
12802#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012803static PyObject *
12804unicode__decimal2ascii(PyObject *self)
12805{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012806 return PyUnicode_TransformDecimalAndSpaceToASCII(self);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012807}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012808#endif
12809
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012810PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012811 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012812\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000012813Return True if S starts with the specified prefix, False otherwise.\n\
12814With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012815With optional end, stop comparing S at that position.\n\
12816prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012817
12818static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012819unicode_startswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000012820 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012821{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012822 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012823 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012824 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012825 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012826 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012827
Jesus Ceaac451502011-04-20 17:09:23 +020012828 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000012829 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012830 if (PyTuple_Check(subobj)) {
12831 Py_ssize_t i;
12832 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012833 substring = PyUnicode_FromObject(PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012834 if (substring == NULL)
12835 return NULL;
12836 result = tailmatch(self, substring, start, end, -1);
12837 Py_DECREF(substring);
12838 if (result) {
12839 Py_RETURN_TRUE;
12840 }
12841 }
12842 /* nothing matched */
12843 Py_RETURN_FALSE;
12844 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012845 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030012846 if (substring == NULL) {
12847 if (PyErr_ExceptionMatches(PyExc_TypeError))
12848 PyErr_Format(PyExc_TypeError, "startswith first arg must be str or "
12849 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000012850 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030012851 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012852 result = tailmatch(self, substring, start, end, -1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012853 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012854 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012855}
12856
12857
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012858PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012859 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012860\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000012861Return True if S ends with the specified suffix, False otherwise.\n\
12862With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012863With optional end, stop comparing S at that position.\n\
12864suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012865
12866static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012867unicode_endswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000012868 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012869{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012870 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012871 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012872 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012873 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012874 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012875
Jesus Ceaac451502011-04-20 17:09:23 +020012876 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000012877 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012878 if (PyTuple_Check(subobj)) {
12879 Py_ssize_t i;
12880 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012881 substring = PyUnicode_FromObject(
Benjamin Peterson29060642009-01-31 22:14:21 +000012882 PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012883 if (substring == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000012884 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012885 result = tailmatch(self, substring, start, end, +1);
12886 Py_DECREF(substring);
12887 if (result) {
12888 Py_RETURN_TRUE;
12889 }
12890 }
12891 Py_RETURN_FALSE;
12892 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012893 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030012894 if (substring == NULL) {
12895 if (PyErr_ExceptionMatches(PyExc_TypeError))
12896 PyErr_Format(PyExc_TypeError, "endswith first arg must be str or "
12897 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000012898 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030012899 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012900 result = tailmatch(self, substring, start, end, +1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012901 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012902 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012903}
12904
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012905#include "stringlib/unicode_format.h"
Eric Smith8c663262007-08-25 02:26:07 +000012906
12907PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012908 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000012909\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012910Return a formatted version of S, using substitutions from args and kwargs.\n\
12911The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +000012912
Eric Smith27bbca62010-11-04 17:06:58 +000012913PyDoc_STRVAR(format_map__doc__,
12914 "S.format_map(mapping) -> str\n\
12915\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012916Return a formatted version of S, using substitutions from mapping.\n\
12917The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +000012918
Eric Smith4a7d76d2008-05-30 18:10:19 +000012919static PyObject *
12920unicode__format__(PyObject* self, PyObject* args)
12921{
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012922 PyObject *format_spec, *out;
Eric Smith4a7d76d2008-05-30 18:10:19 +000012923
12924 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
12925 return NULL;
12926
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012927 out = _PyUnicode_FormatAdvanced(self, format_spec, 0,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012928 PyUnicode_GET_LENGTH(format_spec));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012929 return out;
Eric Smith4a7d76d2008-05-30 18:10:19 +000012930}
12931
Eric Smith8c663262007-08-25 02:26:07 +000012932PyDoc_STRVAR(p_format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012933 "S.__format__(format_spec) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000012934\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012935Return a formatted version of S as described by format_spec.");
Eric Smith8c663262007-08-25 02:26:07 +000012936
12937static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012938unicode__sizeof__(PyObject *v)
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012939{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012940 Py_ssize_t size;
12941
12942 /* If it's a compact object, account for base structure +
12943 character data. */
12944 if (PyUnicode_IS_COMPACT_ASCII(v))
12945 size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(v) + 1;
12946 else if (PyUnicode_IS_COMPACT(v))
12947 size = sizeof(PyCompactUnicodeObject) +
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012948 (PyUnicode_GET_LENGTH(v) + 1) * PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012949 else {
12950 /* If it is a two-block object, account for base object, and
12951 for character block if present. */
12952 size = sizeof(PyUnicodeObject);
Victor Stinnerc3c74152011-10-02 20:39:55 +020012953 if (_PyUnicode_DATA_ANY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012954 size += (PyUnicode_GET_LENGTH(v) + 1) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012955 PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012956 }
12957 /* If the wstr pointer is present, account for it unless it is shared
Victor Stinnera3be6132011-10-03 02:16:37 +020012958 with the data pointer. Check if the data is not shared. */
Victor Stinner03490912011-10-03 23:45:12 +020012959 if (_PyUnicode_HAS_WSTR_MEMORY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012960 size += (PyUnicode_WSTR_LENGTH(v) + 1) * sizeof(wchar_t);
Victor Stinner829c0ad2011-10-03 01:08:02 +020012961 if (_PyUnicode_HAS_UTF8_MEMORY(v))
Victor Stinnere90fe6a2011-10-01 16:48:13 +020012962 size += PyUnicode_UTF8_LENGTH(v) + 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012963
12964 return PyLong_FromSsize_t(size);
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012965}
12966
12967PyDoc_STRVAR(sizeof__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012968 "S.__sizeof__() -> size of S in memory, in bytes");
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012969
12970static PyObject *
Victor Stinner034f6cf2011-09-30 02:26:44 +020012971unicode_getnewargs(PyObject *v)
Guido van Rossum5d9113d2003-01-29 17:58:45 +000012972{
Victor Stinnerbf6e5602011-12-12 01:53:47 +010012973 PyObject *copy = _PyUnicode_Copy(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012974 if (!copy)
12975 return NULL;
12976 return Py_BuildValue("(N)", copy);
Guido van Rossum5d9113d2003-01-29 17:58:45 +000012977}
12978
Guido van Rossumd57fd912000-03-10 22:53:23 +000012979static PyMethodDef unicode_methods[] = {
12980
12981 /* Order is according to common usage: often used methods should
12982 appear first, since lookup is done sequentially. */
12983
Benjamin Peterson28a4dce2010-12-12 01:33:04 +000012984 {"encode", (PyCFunction) unicode_encode, METH_VARARGS | METH_KEYWORDS, encode__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012985 {"replace", (PyCFunction) unicode_replace, METH_VARARGS, replace__doc__},
12986 {"split", (PyCFunction) unicode_split, METH_VARARGS, split__doc__},
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012987 {"rsplit", (PyCFunction) unicode_rsplit, METH_VARARGS, rsplit__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012988 {"join", (PyCFunction) unicode_join, METH_O, join__doc__},
12989 {"capitalize", (PyCFunction) unicode_capitalize, METH_NOARGS, capitalize__doc__},
12990 {"title", (PyCFunction) unicode_title, METH_NOARGS, title__doc__},
12991 {"center", (PyCFunction) unicode_center, METH_VARARGS, center__doc__},
12992 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
12993 {"expandtabs", (PyCFunction) unicode_expandtabs, METH_VARARGS, expandtabs__doc__},
12994 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000012995 {"partition", (PyCFunction) unicode_partition, METH_O, partition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012996 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
12997 {"ljust", (PyCFunction) unicode_ljust, METH_VARARGS, ljust__doc__},
12998 {"lower", (PyCFunction) unicode_lower, METH_NOARGS, lower__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012999 {"lstrip", (PyCFunction) unicode_lstrip, METH_VARARGS, lstrip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013000 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
13001 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
13002 {"rjust", (PyCFunction) unicode_rjust, METH_VARARGS, rjust__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013003 {"rstrip", (PyCFunction) unicode_rstrip, METH_VARARGS, rstrip__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013004 {"rpartition", (PyCFunction) unicode_rpartition, METH_O, rpartition__doc__},
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010013005 {"splitlines", (PyCFunction) unicode_splitlines, METH_VARARGS | METH_KEYWORDS, splitlines__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013006 {"strip", (PyCFunction) unicode_strip, METH_VARARGS, strip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013007 {"swapcase", (PyCFunction) unicode_swapcase, METH_NOARGS, swapcase__doc__},
13008 {"translate", (PyCFunction) unicode_translate, METH_O, translate__doc__},
13009 {"upper", (PyCFunction) unicode_upper, METH_NOARGS, upper__doc__},
13010 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
13011 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
13012 {"islower", (PyCFunction) unicode_islower, METH_NOARGS, islower__doc__},
13013 {"isupper", (PyCFunction) unicode_isupper, METH_NOARGS, isupper__doc__},
13014 {"istitle", (PyCFunction) unicode_istitle, METH_NOARGS, istitle__doc__},
13015 {"isspace", (PyCFunction) unicode_isspace, METH_NOARGS, isspace__doc__},
13016 {"isdecimal", (PyCFunction) unicode_isdecimal, METH_NOARGS, isdecimal__doc__},
13017 {"isdigit", (PyCFunction) unicode_isdigit, METH_NOARGS, isdigit__doc__},
13018 {"isnumeric", (PyCFunction) unicode_isnumeric, METH_NOARGS, isnumeric__doc__},
13019 {"isalpha", (PyCFunction) unicode_isalpha, METH_NOARGS, isalpha__doc__},
13020 {"isalnum", (PyCFunction) unicode_isalnum, METH_NOARGS, isalnum__doc__},
Martin v. Löwis47383402007-08-15 07:32:56 +000013021 {"isidentifier", (PyCFunction) unicode_isidentifier, METH_NOARGS, isidentifier__doc__},
Georg Brandl559e5d72008-06-11 18:37:52 +000013022 {"isprintable", (PyCFunction) unicode_isprintable, METH_NOARGS, isprintable__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013023 {"zfill", (PyCFunction) unicode_zfill, METH_VARARGS, zfill__doc__},
Eric Smith9cd1e092007-08-31 18:39:38 +000013024 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +000013025 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
Eric Smith4a7d76d2008-05-30 18:10:19 +000013026 {"__format__", (PyCFunction) unicode__format__, METH_VARARGS, p_format__doc__},
Georg Brandlceee0772007-11-27 23:48:05 +000013027 {"maketrans", (PyCFunction) unicode_maketrans,
13028 METH_VARARGS | METH_STATIC, maketrans__doc__},
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013029 {"__sizeof__", (PyCFunction) unicode__sizeof__, METH_NOARGS, sizeof__doc__},
Walter Dörwald068325e2002-04-15 13:36:47 +000013030#if 0
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013031 {"capwords", (PyCFunction) unicode_capwords, METH_NOARGS, capwords__doc__},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013032#endif
13033
13034#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013035 /* These methods are just used for debugging the implementation. */
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013036 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013037#endif
13038
Benjamin Peterson14339b62009-01-31 16:36:08 +000013039 {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013040 {NULL, NULL}
13041};
13042
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013043static PyObject *
13044unicode_mod(PyObject *v, PyObject *w)
13045{
Brian Curtindfc80e32011-08-10 20:28:54 -050013046 if (!PyUnicode_Check(v))
13047 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson29060642009-01-31 22:14:21 +000013048 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013049}
13050
13051static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013052 0, /*nb_add*/
13053 0, /*nb_subtract*/
13054 0, /*nb_multiply*/
13055 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013056};
13057
Guido van Rossumd57fd912000-03-10 22:53:23 +000013058static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013059 (lenfunc) unicode_length, /* sq_length */
13060 PyUnicode_Concat, /* sq_concat */
13061 (ssizeargfunc) unicode_repeat, /* sq_repeat */
13062 (ssizeargfunc) unicode_getitem, /* sq_item */
13063 0, /* sq_slice */
13064 0, /* sq_ass_item */
13065 0, /* sq_ass_slice */
13066 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013067};
13068
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013069static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013070unicode_subscript(PyObject* self, PyObject* item)
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013071{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013072 if (PyUnicode_READY(self) == -1)
13073 return NULL;
13074
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000013075 if (PyIndex_Check(item)) {
13076 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013077 if (i == -1 && PyErr_Occurred())
13078 return NULL;
13079 if (i < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013080 i += PyUnicode_GET_LENGTH(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013081 return unicode_getitem(self, i);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013082 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000013083 Py_ssize_t start, stop, step, slicelength, cur, i;
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013084 PyObject *result;
13085 void *src_data, *dest_data;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013086 int src_kind, dest_kind;
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013087 Py_UCS4 ch, max_char, kind_limit;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013088
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013089 if (PySlice_GetIndicesEx(item, PyUnicode_GET_LENGTH(self),
Benjamin Peterson29060642009-01-31 22:14:21 +000013090 &start, &stop, &step, &slicelength) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013091 return NULL;
13092 }
13093
13094 if (slicelength <= 0) {
Victor Stinner382955f2011-12-11 21:44:00 +010013095 Py_INCREF(unicode_empty);
13096 return unicode_empty;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013097 } else if (start == 0 && step == 1 &&
Victor Stinnerc4b49542011-12-11 22:44:26 +010013098 slicelength == PyUnicode_GET_LENGTH(self)) {
13099 return unicode_result_unchanged(self);
Thomas Woutersed03b412007-08-28 21:37:11 +000013100 } else if (step == 1) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013101 return PyUnicode_Substring(self,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013102 start, start + slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013103 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013104 /* General case */
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013105 src_kind = PyUnicode_KIND(self);
13106 src_data = PyUnicode_DATA(self);
Victor Stinner55c99112011-10-13 01:17:06 +020013107 if (!PyUnicode_IS_ASCII(self)) {
13108 kind_limit = kind_maxchar_limit(src_kind);
13109 max_char = 0;
13110 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
13111 ch = PyUnicode_READ(src_kind, src_data, cur);
13112 if (ch > max_char) {
13113 max_char = ch;
13114 if (max_char >= kind_limit)
13115 break;
13116 }
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013117 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013118 }
Victor Stinner55c99112011-10-13 01:17:06 +020013119 else
13120 max_char = 127;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013121 result = PyUnicode_New(slicelength, max_char);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013122 if (result == NULL)
13123 return NULL;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013124 dest_kind = PyUnicode_KIND(result);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013125 dest_data = PyUnicode_DATA(result);
13126
13127 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013128 Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
13129 PyUnicode_WRITE(dest_kind, dest_data, i, ch);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013130 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013131 assert(_PyUnicode_CheckConsistency(result, 1));
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013132 return result;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013133 } else {
13134 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
13135 return NULL;
13136 }
13137}
13138
13139static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013140 (lenfunc)unicode_length, /* mp_length */
13141 (binaryfunc)unicode_subscript, /* mp_subscript */
13142 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013143};
13144
Guido van Rossumd57fd912000-03-10 22:53:23 +000013145
Guido van Rossumd57fd912000-03-10 22:53:23 +000013146/* Helpers for PyUnicode_Format() */
13147
13148static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +000013149getnextarg(PyObject *args, Py_ssize_t arglen, Py_ssize_t *p_argidx)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013150{
Martin v. Löwis18e16552006-02-15 17:27:45 +000013151 Py_ssize_t argidx = *p_argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013152 if (argidx < arglen) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013153 (*p_argidx)++;
13154 if (arglen < 0)
13155 return args;
13156 else
13157 return PyTuple_GetItem(args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013158 }
13159 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013160 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013161 return NULL;
13162}
13163
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013164/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013165
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013166static PyObject *
13167formatfloat(PyObject *v, int flags, int prec, int type)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013168{
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013169 char *p;
13170 PyObject *result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013171 double x;
Tim Petersced69f82003-09-16 20:30:58 +000013172
Guido van Rossumd57fd912000-03-10 22:53:23 +000013173 x = PyFloat_AsDouble(v);
13174 if (x == -1.0 && PyErr_Occurred())
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013175 return NULL;
13176
Guido van Rossumd57fd912000-03-10 22:53:23 +000013177 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000013178 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +000013179
Eric Smith0923d1d2009-04-16 20:16:10 +000013180 p = PyOS_double_to_string(x, type, prec,
13181 (flags & F_ALT) ? Py_DTSF_ALT : 0, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013182 if (p == NULL)
13183 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013184 result = PyUnicode_DecodeASCII(p, strlen(p), NULL);
Eric Smith0923d1d2009-04-16 20:16:10 +000013185 PyMem_Free(p);
13186 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013187}
13188
Tim Peters38fd5b62000-09-21 05:43:11 +000013189static PyObject*
13190formatlong(PyObject *val, int flags, int prec, int type)
13191{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013192 char *buf;
13193 int len;
13194 PyObject *str; /* temporary string object. */
13195 PyObject *result;
Tim Peters38fd5b62000-09-21 05:43:11 +000013196
Benjamin Peterson14339b62009-01-31 16:36:08 +000013197 str = _PyBytes_FormatLong(val, flags, prec, type, &buf, &len);
13198 if (!str)
13199 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013200 result = PyUnicode_DecodeASCII(buf, len, NULL);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013201 Py_DECREF(str);
13202 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +000013203}
13204
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013205static Py_UCS4
13206formatchar(PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013207{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000013208 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000013209 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013210 if (PyUnicode_GET_LENGTH(v) == 1) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013211 return PyUnicode_READ_CHAR(v, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +000013212 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013213 goto onError;
13214 }
13215 else {
13216 /* Integer input truncated to a character */
13217 long x;
13218 x = PyLong_AsLong(v);
13219 if (x == -1 && PyErr_Occurred())
13220 goto onError;
13221
Victor Stinner8faf8212011-12-08 22:14:11 +010013222 if (x < 0 || x > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013223 PyErr_SetString(PyExc_OverflowError,
13224 "%c arg not in range(0x110000)");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013225 return (Py_UCS4) -1;
Benjamin Peterson29060642009-01-31 22:14:21 +000013226 }
13227
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013228 return (Py_UCS4) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013229 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000013230
Benjamin Peterson29060642009-01-31 22:14:21 +000013231 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000013232 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013233 "%c requires int or char");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013234 return (Py_UCS4) -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013235}
13236
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013237static int
13238repeat_accumulate(_PyAccu *acc, PyObject *obj, Py_ssize_t count)
13239{
13240 int r;
13241 assert(count > 0);
13242 assert(PyUnicode_Check(obj));
13243 if (count > 5) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013244 PyObject *repeated = unicode_repeat(obj, count);
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013245 if (repeated == NULL)
13246 return -1;
13247 r = _PyAccu_Accumulate(acc, repeated);
13248 Py_DECREF(repeated);
13249 return r;
13250 }
13251 else {
13252 do {
13253 if (_PyAccu_Accumulate(acc, obj))
13254 return -1;
13255 } while (--count);
13256 return 0;
13257 }
13258}
13259
Alexander Belopolsky40018472011-02-26 01:02:56 +000013260PyObject *
13261PyUnicode_Format(PyObject *format, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013262{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013263 void *fmt;
13264 int fmtkind;
13265 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013266 int kind;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013267 int r;
13268 Py_ssize_t fmtcnt, fmtpos, arglen, argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013269 int args_owned = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013270 PyObject *dict = NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013271 PyObject *temp = NULL;
13272 PyObject *second = NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013273 PyObject *uformat;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013274 _PyAccu acc;
13275 static PyObject *plus, *minus, *blank, *zero, *percent;
13276
13277 if (!plus && !(plus = get_latin1_char('+')))
13278 return NULL;
13279 if (!minus && !(minus = get_latin1_char('-')))
13280 return NULL;
13281 if (!blank && !(blank = get_latin1_char(' ')))
13282 return NULL;
13283 if (!zero && !(zero = get_latin1_char('0')))
13284 return NULL;
13285 if (!percent && !(percent = get_latin1_char('%')))
13286 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000013287
Guido van Rossumd57fd912000-03-10 22:53:23 +000013288 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013289 PyErr_BadInternalCall();
13290 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013291 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013292 uformat = PyUnicode_FromObject(format);
Benjamin Peterson22a29702012-01-02 09:00:30 -060013293 if (uformat == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000013294 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060013295 if (PyUnicode_READY(uformat) == -1)
13296 Py_DECREF(uformat);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013297 if (_PyAccu_Init(&acc))
13298 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013299 fmt = PyUnicode_DATA(uformat);
13300 fmtkind = PyUnicode_KIND(uformat);
13301 fmtcnt = PyUnicode_GET_LENGTH(uformat);
13302 fmtpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013303
Guido van Rossumd57fd912000-03-10 22:53:23 +000013304 if (PyTuple_Check(args)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013305 arglen = PyTuple_Size(args);
13306 argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013307 }
13308 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013309 arglen = -1;
13310 argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013311 }
Christian Heimes90aa7642007-12-19 02:45:37 +000013312 if (Py_TYPE(args)->tp_as_mapping && !PyTuple_Check(args) &&
Christian Heimesf3863112007-11-22 07:46:41 +000013313 !PyUnicode_Check(args))
Benjamin Peterson29060642009-01-31 22:14:21 +000013314 dict = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013315
13316 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013317 if (PyUnicode_READ(fmtkind, fmt, fmtpos) != '%') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013318 PyObject *nonfmt;
13319 Py_ssize_t nonfmtpos;
13320 nonfmtpos = fmtpos++;
13321 while (fmtcnt >= 0 &&
13322 PyUnicode_READ(fmtkind, fmt, fmtpos) != '%') {
13323 fmtpos++;
13324 fmtcnt--;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013325 }
Victor Stinner7931d9a2011-11-04 00:22:48 +010013326 nonfmt = PyUnicode_Substring(uformat, nonfmtpos, fmtpos);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013327 if (nonfmt == NULL)
13328 goto onError;
13329 r = _PyAccu_Accumulate(&acc, nonfmt);
13330 Py_DECREF(nonfmt);
13331 if (r)
13332 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013333 }
13334 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013335 /* Got a format specifier */
13336 int flags = 0;
13337 Py_ssize_t width = -1;
13338 int prec = -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013339 Py_UCS4 c = '\0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013340 Py_UCS4 fill, sign;
Benjamin Peterson29060642009-01-31 22:14:21 +000013341 int isnumok;
13342 PyObject *v = NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013343 void *pbuf = NULL;
13344 Py_ssize_t pindex, len;
13345 PyObject *signobj = NULL, *fillobj = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013346
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013347 fmtpos++;
13348 if (PyUnicode_READ(fmtkind, fmt, fmtpos) == '(') {
13349 Py_ssize_t keystart;
Benjamin Peterson29060642009-01-31 22:14:21 +000013350 Py_ssize_t keylen;
13351 PyObject *key;
13352 int pcount = 1;
Christian Heimesa612dc02008-02-24 13:08:18 +000013353
Benjamin Peterson29060642009-01-31 22:14:21 +000013354 if (dict == NULL) {
13355 PyErr_SetString(PyExc_TypeError,
13356 "format requires a mapping");
13357 goto onError;
13358 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013359 ++fmtpos;
Benjamin Peterson29060642009-01-31 22:14:21 +000013360 --fmtcnt;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013361 keystart = fmtpos;
Benjamin Peterson29060642009-01-31 22:14:21 +000013362 /* Skip over balanced parentheses */
13363 while (pcount > 0 && --fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013364 if (PyUnicode_READ(fmtkind, fmt, fmtpos) == ')')
Benjamin Peterson29060642009-01-31 22:14:21 +000013365 --pcount;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013366 else if (PyUnicode_READ(fmtkind, fmt, fmtpos) == '(')
Benjamin Peterson29060642009-01-31 22:14:21 +000013367 ++pcount;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013368 fmtpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +000013369 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013370 keylen = fmtpos - keystart - 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000013371 if (fmtcnt < 0 || pcount > 0) {
13372 PyErr_SetString(PyExc_ValueError,
13373 "incomplete format key");
13374 goto onError;
13375 }
Victor Stinner7931d9a2011-11-04 00:22:48 +010013376 key = PyUnicode_Substring(uformat,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013377 keystart, keystart + keylen);
Benjamin Peterson29060642009-01-31 22:14:21 +000013378 if (key == NULL)
13379 goto onError;
13380 if (args_owned) {
13381 Py_DECREF(args);
13382 args_owned = 0;
13383 }
13384 args = PyObject_GetItem(dict, key);
13385 Py_DECREF(key);
13386 if (args == NULL) {
13387 goto onError;
13388 }
13389 args_owned = 1;
13390 arglen = -1;
13391 argidx = -2;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013392 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013393 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013394 switch (c = PyUnicode_READ(fmtkind, fmt, fmtpos++)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013395 case '-': flags |= F_LJUST; continue;
13396 case '+': flags |= F_SIGN; continue;
13397 case ' ': flags |= F_BLANK; continue;
13398 case '#': flags |= F_ALT; continue;
13399 case '0': flags |= F_ZERO; continue;
13400 }
13401 break;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013402 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013403 if (c == '*') {
13404 v = getnextarg(args, arglen, &argidx);
13405 if (v == NULL)
13406 goto onError;
13407 if (!PyLong_Check(v)) {
13408 PyErr_SetString(PyExc_TypeError,
13409 "* wants int");
13410 goto onError;
13411 }
13412 width = PyLong_AsLong(v);
13413 if (width == -1 && PyErr_Occurred())
13414 goto onError;
13415 if (width < 0) {
13416 flags |= F_LJUST;
13417 width = -width;
13418 }
13419 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013420 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013421 }
13422 else if (c >= '0' && c <= '9') {
13423 width = c - '0';
13424 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013425 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013426 if (c < '0' || c > '9')
13427 break;
13428 if ((width*10) / 10 != width) {
13429 PyErr_SetString(PyExc_ValueError,
13430 "width too big");
Benjamin Peterson14339b62009-01-31 16:36:08 +000013431 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +000013432 }
13433 width = width*10 + (c - '0');
13434 }
13435 }
13436 if (c == '.') {
13437 prec = 0;
13438 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013439 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013440 if (c == '*') {
13441 v = getnextarg(args, arglen, &argidx);
13442 if (v == NULL)
13443 goto onError;
13444 if (!PyLong_Check(v)) {
13445 PyErr_SetString(PyExc_TypeError,
13446 "* wants int");
13447 goto onError;
13448 }
13449 prec = PyLong_AsLong(v);
13450 if (prec == -1 && PyErr_Occurred())
13451 goto onError;
13452 if (prec < 0)
13453 prec = 0;
13454 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013455 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013456 }
13457 else if (c >= '0' && c <= '9') {
13458 prec = c - '0';
13459 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013460 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013461 if (c < '0' || c > '9')
13462 break;
13463 if ((prec*10) / 10 != prec) {
13464 PyErr_SetString(PyExc_ValueError,
13465 "prec too big");
13466 goto onError;
13467 }
13468 prec = prec*10 + (c - '0');
13469 }
13470 }
13471 } /* prec */
13472 if (fmtcnt >= 0) {
13473 if (c == 'h' || c == 'l' || c == 'L') {
13474 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013475 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013476 }
13477 }
13478 if (fmtcnt < 0) {
13479 PyErr_SetString(PyExc_ValueError,
13480 "incomplete format");
13481 goto onError;
13482 }
13483 if (c != '%') {
13484 v = getnextarg(args, arglen, &argidx);
13485 if (v == NULL)
13486 goto onError;
13487 }
13488 sign = 0;
13489 fill = ' ';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013490 fillobj = blank;
Benjamin Peterson29060642009-01-31 22:14:21 +000013491 switch (c) {
13492
13493 case '%':
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013494 _PyAccu_Accumulate(&acc, percent);
13495 continue;
Benjamin Peterson29060642009-01-31 22:14:21 +000013496
13497 case 's':
13498 case 'r':
13499 case 'a':
Victor Stinner808fc0a2010-03-22 12:50:40 +000013500 if (PyUnicode_CheckExact(v) && c == 's') {
Benjamin Peterson29060642009-01-31 22:14:21 +000013501 temp = v;
13502 Py_INCREF(temp);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013503 }
13504 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013505 if (c == 's')
13506 temp = PyObject_Str(v);
13507 else if (c == 'r')
13508 temp = PyObject_Repr(v);
13509 else
13510 temp = PyObject_ASCII(v);
13511 if (temp == NULL)
13512 goto onError;
13513 if (PyUnicode_Check(temp))
13514 /* nothing to do */;
13515 else {
13516 Py_DECREF(temp);
13517 PyErr_SetString(PyExc_TypeError,
13518 "%s argument has non-string str()");
13519 goto onError;
13520 }
13521 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013522 if (PyUnicode_READY(temp) == -1) {
13523 Py_CLEAR(temp);
13524 goto onError;
13525 }
13526 pbuf = PyUnicode_DATA(temp);
13527 kind = PyUnicode_KIND(temp);
13528 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013529 if (prec >= 0 && len > prec)
13530 len = prec;
13531 break;
13532
13533 case 'i':
13534 case 'd':
13535 case 'u':
13536 case 'o':
13537 case 'x':
13538 case 'X':
Benjamin Peterson29060642009-01-31 22:14:21 +000013539 isnumok = 0;
13540 if (PyNumber_Check(v)) {
13541 PyObject *iobj=NULL;
13542
13543 if (PyLong_Check(v)) {
13544 iobj = v;
13545 Py_INCREF(iobj);
13546 }
13547 else {
13548 iobj = PyNumber_Long(v);
13549 }
13550 if (iobj!=NULL) {
13551 if (PyLong_Check(iobj)) {
13552 isnumok = 1;
Senthil Kumaran9ebe08d2011-07-03 21:03:16 -070013553 temp = formatlong(iobj, flags, prec, (c == 'i'? 'd': c));
Benjamin Peterson29060642009-01-31 22:14:21 +000013554 Py_DECREF(iobj);
13555 if (!temp)
13556 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013557 if (PyUnicode_READY(temp) == -1) {
13558 Py_CLEAR(temp);
13559 goto onError;
13560 }
13561 pbuf = PyUnicode_DATA(temp);
13562 kind = PyUnicode_KIND(temp);
13563 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013564 sign = 1;
13565 }
13566 else {
13567 Py_DECREF(iobj);
13568 }
13569 }
13570 }
13571 if (!isnumok) {
13572 PyErr_Format(PyExc_TypeError,
13573 "%%%c format: a number is required, "
13574 "not %.200s", (char)c, Py_TYPE(v)->tp_name);
13575 goto onError;
13576 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013577 if (flags & F_ZERO) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013578 fill = '0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013579 fillobj = zero;
13580 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013581 break;
13582
13583 case 'e':
13584 case 'E':
13585 case 'f':
13586 case 'F':
13587 case 'g':
13588 case 'G':
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013589 temp = formatfloat(v, flags, prec, c);
13590 if (!temp)
Benjamin Peterson29060642009-01-31 22:14:21 +000013591 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013592 if (PyUnicode_READY(temp) == -1) {
13593 Py_CLEAR(temp);
13594 goto onError;
13595 }
13596 pbuf = PyUnicode_DATA(temp);
13597 kind = PyUnicode_KIND(temp);
13598 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013599 sign = 1;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013600 if (flags & F_ZERO) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013601 fill = '0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013602 fillobj = zero;
13603 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013604 break;
13605
13606 case 'c':
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013607 {
13608 Py_UCS4 ch = formatchar(v);
13609 if (ch == (Py_UCS4) -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000013610 goto onError;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013611 temp = _PyUnicode_FromUCS4(&ch, 1);
13612 if (temp == NULL)
13613 goto onError;
13614 pbuf = PyUnicode_DATA(temp);
13615 kind = PyUnicode_KIND(temp);
13616 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013617 break;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013618 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013619
13620 default:
13621 PyErr_Format(PyExc_ValueError,
13622 "unsupported format character '%c' (0x%x) "
13623 "at index %zd",
13624 (31<=c && c<=126) ? (char)c : '?',
13625 (int)c,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013626 fmtpos - 1);
Benjamin Peterson29060642009-01-31 22:14:21 +000013627 goto onError;
13628 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013629 /* pbuf is initialized here. */
13630 pindex = 0;
Benjamin Peterson29060642009-01-31 22:14:21 +000013631 if (sign) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013632 if (PyUnicode_READ(kind, pbuf, pindex) == '-') {
13633 signobj = minus;
Benjamin Peterson29060642009-01-31 22:14:21 +000013634 len--;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013635 pindex++;
13636 }
13637 else if (PyUnicode_READ(kind, pbuf, pindex) == '+') {
13638 signobj = plus;
13639 len--;
13640 pindex++;
Benjamin Peterson29060642009-01-31 22:14:21 +000013641 }
13642 else if (flags & F_SIGN)
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013643 signobj = plus;
Benjamin Peterson29060642009-01-31 22:14:21 +000013644 else if (flags & F_BLANK)
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013645 signobj = blank;
Benjamin Peterson29060642009-01-31 22:14:21 +000013646 else
13647 sign = 0;
13648 }
13649 if (width < len)
13650 width = len;
Benjamin Peterson29060642009-01-31 22:14:21 +000013651 if (sign) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013652 if (fill != ' ') {
13653 assert(signobj != NULL);
13654 if (_PyAccu_Accumulate(&acc, signobj))
13655 goto onError;
13656 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013657 if (width > len)
13658 width--;
13659 }
13660 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013661 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013662 assert(PyUnicode_READ(kind, pbuf, pindex + 1) == c);
Benjamin Peterson29060642009-01-31 22:14:21 +000013663 if (fill != ' ') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013664 second = get_latin1_char(
13665 PyUnicode_READ(kind, pbuf, pindex + 1));
13666 pindex += 2;
13667 if (second == NULL ||
13668 _PyAccu_Accumulate(&acc, zero) ||
13669 _PyAccu_Accumulate(&acc, second))
13670 goto onError;
13671 Py_CLEAR(second);
Benjamin Peterson29060642009-01-31 22:14:21 +000013672 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013673 width -= 2;
13674 if (width < 0)
13675 width = 0;
13676 len -= 2;
13677 }
13678 if (width > len && !(flags & F_LJUST)) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013679 assert(fillobj != NULL);
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013680 if (repeat_accumulate(&acc, fillobj, width - len))
13681 goto onError;
13682 width = len;
Benjamin Peterson29060642009-01-31 22:14:21 +000013683 }
13684 if (fill == ' ') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013685 if (sign) {
13686 assert(signobj != NULL);
13687 if (_PyAccu_Accumulate(&acc, signobj))
13688 goto onError;
13689 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013690 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013691 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
13692 assert(PyUnicode_READ(kind, pbuf, pindex+1) == c);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013693 second = get_latin1_char(
13694 PyUnicode_READ(kind, pbuf, pindex + 1));
13695 pindex += 2;
13696 if (second == NULL ||
13697 _PyAccu_Accumulate(&acc, zero) ||
13698 _PyAccu_Accumulate(&acc, second))
13699 goto onError;
13700 Py_CLEAR(second);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013701 }
13702 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013703 /* Copy all characters, preserving len */
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013704 if (temp != NULL) {
13705 assert(pbuf == PyUnicode_DATA(temp));
13706 v = PyUnicode_Substring(temp, pindex, pindex + len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013707 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013708 else {
13709 const char *p = (const char *) pbuf;
13710 assert(pbuf != NULL);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013711 p += kind * pindex;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013712 v = PyUnicode_FromKindAndData(kind, p, len);
13713 }
13714 if (v == NULL)
13715 goto onError;
13716 r = _PyAccu_Accumulate(&acc, v);
13717 Py_DECREF(v);
13718 if (r)
13719 goto onError;
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013720 if (width > len && repeat_accumulate(&acc, blank, width - len))
13721 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +000013722 if (dict && (argidx < arglen) && c != '%') {
13723 PyErr_SetString(PyExc_TypeError,
13724 "not all arguments converted during string formatting");
Benjamin Peterson29060642009-01-31 22:14:21 +000013725 goto onError;
13726 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013727 Py_CLEAR(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013728 } /* '%' */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013729 } /* until end */
13730 if (argidx < arglen && !dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013731 PyErr_SetString(PyExc_TypeError,
13732 "not all arguments converted during string formatting");
13733 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013734 }
13735
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013736 result = _PyAccu_Finish(&acc);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013737 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013738 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013739 }
13740 Py_DECREF(uformat);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013741 Py_XDECREF(temp);
13742 Py_XDECREF(second);
Victor Stinner7931d9a2011-11-04 00:22:48 +010013743 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013744
Benjamin Peterson29060642009-01-31 22:14:21 +000013745 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000013746 Py_DECREF(uformat);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013747 Py_XDECREF(temp);
13748 Py_XDECREF(second);
13749 _PyAccu_Destroy(&acc);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013750 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013751 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013752 }
13753 return NULL;
13754}
13755
Jeremy Hylton938ace62002-07-17 16:30:39 +000013756static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +000013757unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
13758
Tim Peters6d6c1a32001-08-02 04:15:00 +000013759static PyObject *
13760unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
13761{
Benjamin Peterson29060642009-01-31 22:14:21 +000013762 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013763 static char *kwlist[] = {"object", "encoding", "errors", 0};
13764 char *encoding = NULL;
13765 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000013766
Benjamin Peterson14339b62009-01-31 16:36:08 +000013767 if (type != &PyUnicode_Type)
13768 return unicode_subtype_new(type, args, kwds);
13769 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +000013770 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +000013771 return NULL;
Victor Stinner382955f2011-12-11 21:44:00 +010013772 if (x == NULL) {
13773 Py_INCREF(unicode_empty);
13774 return unicode_empty;
13775 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000013776 if (encoding == NULL && errors == NULL)
13777 return PyObject_Str(x);
13778 else
Benjamin Peterson29060642009-01-31 22:14:21 +000013779 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +000013780}
13781
Guido van Rossume023fe02001-08-30 03:12:59 +000013782static PyObject *
13783unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
13784{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013785 PyObject *unicode, *self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013786 Py_ssize_t length, char_size;
13787 int share_wstr, share_utf8;
13788 unsigned int kind;
13789 void *data;
Guido van Rossume023fe02001-08-30 03:12:59 +000013790
Benjamin Peterson14339b62009-01-31 16:36:08 +000013791 assert(PyType_IsSubtype(type, &PyUnicode_Type));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013792
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013793 unicode = unicode_new(&PyUnicode_Type, args, kwds);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013794 if (unicode == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000013795 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020013796 assert(_PyUnicode_CHECK(unicode));
Benjamin Peterson22a29702012-01-02 09:00:30 -060013797 if (PyUnicode_READY(unicode)) {
13798 Py_DECREF(unicode);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013799 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060013800 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013801
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013802 self = type->tp_alloc(type, 0);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013803 if (self == NULL) {
13804 Py_DECREF(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013805 return NULL;
13806 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013807 kind = PyUnicode_KIND(unicode);
13808 length = PyUnicode_GET_LENGTH(unicode);
13809
13810 _PyUnicode_LENGTH(self) = length;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020013811#ifdef Py_DEBUG
13812 _PyUnicode_HASH(self) = -1;
13813#else
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013814 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020013815#endif
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013816 _PyUnicode_STATE(self).interned = 0;
13817 _PyUnicode_STATE(self).kind = kind;
13818 _PyUnicode_STATE(self).compact = 0;
Victor Stinner3cf46372011-10-03 14:42:15 +020013819 _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013820 _PyUnicode_STATE(self).ready = 1;
13821 _PyUnicode_WSTR(self) = NULL;
13822 _PyUnicode_UTF8_LENGTH(self) = 0;
13823 _PyUnicode_UTF8(self) = NULL;
13824 _PyUnicode_WSTR_LENGTH(self) = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +020013825 _PyUnicode_DATA_ANY(self) = NULL;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013826
13827 share_utf8 = 0;
13828 share_wstr = 0;
13829 if (kind == PyUnicode_1BYTE_KIND) {
13830 char_size = 1;
13831 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
13832 share_utf8 = 1;
13833 }
13834 else if (kind == PyUnicode_2BYTE_KIND) {
13835 char_size = 2;
13836 if (sizeof(wchar_t) == 2)
13837 share_wstr = 1;
13838 }
13839 else {
13840 assert(kind == PyUnicode_4BYTE_KIND);
13841 char_size = 4;
13842 if (sizeof(wchar_t) == 4)
13843 share_wstr = 1;
13844 }
13845
13846 /* Ensure we won't overflow the length. */
13847 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
13848 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013849 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013850 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013851 data = PyObject_MALLOC((length + 1) * char_size);
13852 if (data == NULL) {
13853 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013854 goto onError;
13855 }
13856
Victor Stinnerc3c74152011-10-02 20:39:55 +020013857 _PyUnicode_DATA_ANY(self) = data;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013858 if (share_utf8) {
13859 _PyUnicode_UTF8_LENGTH(self) = length;
13860 _PyUnicode_UTF8(self) = data;
13861 }
13862 if (share_wstr) {
13863 _PyUnicode_WSTR_LENGTH(self) = length;
13864 _PyUnicode_WSTR(self) = (wchar_t *)data;
13865 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013866
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013867 Py_MEMCPY(data, PyUnicode_DATA(unicode),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013868 kind * (length + 1));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013869 assert(_PyUnicode_CheckConsistency(self, 1));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020013870#ifdef Py_DEBUG
13871 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
13872#endif
Victor Stinnerdd18d3a2011-10-22 11:08:10 +020013873 Py_DECREF(unicode);
Victor Stinner7931d9a2011-11-04 00:22:48 +010013874 return self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013875
13876onError:
13877 Py_DECREF(unicode);
13878 Py_DECREF(self);
13879 return NULL;
Guido van Rossume023fe02001-08-30 03:12:59 +000013880}
13881
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013882PyDoc_STRVAR(unicode_doc,
Benjamin Peterson29060642009-01-31 22:14:21 +000013883 "str(string[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +000013884\n\
Collin Winterd474ce82007-08-07 19:42:11 +000013885Create a new string object from the given encoded string.\n\
Skip Montanaro35b37a52002-07-26 16:22:46 +000013886encoding defaults to the current default string encoding.\n\
13887errors can be 'strict', 'replace' or 'ignore' and defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +000013888
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013889static PyObject *unicode_iter(PyObject *seq);
13890
Guido van Rossumd57fd912000-03-10 22:53:23 +000013891PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000013892 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Benjamin Peterson14339b62009-01-31 16:36:08 +000013893 "str", /* tp_name */
13894 sizeof(PyUnicodeObject), /* tp_size */
13895 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013896 /* Slots */
Benjamin Peterson14339b62009-01-31 16:36:08 +000013897 (destructor)unicode_dealloc, /* tp_dealloc */
13898 0, /* tp_print */
13899 0, /* tp_getattr */
13900 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000013901 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000013902 unicode_repr, /* tp_repr */
13903 &unicode_as_number, /* tp_as_number */
13904 &unicode_as_sequence, /* tp_as_sequence */
13905 &unicode_as_mapping, /* tp_as_mapping */
13906 (hashfunc) unicode_hash, /* tp_hash*/
13907 0, /* tp_call*/
13908 (reprfunc) unicode_str, /* tp_str */
13909 PyObject_GenericGetAttr, /* tp_getattro */
13910 0, /* tp_setattro */
13911 0, /* tp_as_buffer */
13912 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Benjamin Peterson29060642009-01-31 22:14:21 +000013913 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
Benjamin Peterson14339b62009-01-31 16:36:08 +000013914 unicode_doc, /* tp_doc */
13915 0, /* tp_traverse */
13916 0, /* tp_clear */
13917 PyUnicode_RichCompare, /* tp_richcompare */
13918 0, /* tp_weaklistoffset */
13919 unicode_iter, /* tp_iter */
13920 0, /* tp_iternext */
13921 unicode_methods, /* tp_methods */
13922 0, /* tp_members */
13923 0, /* tp_getset */
13924 &PyBaseObject_Type, /* tp_base */
13925 0, /* tp_dict */
13926 0, /* tp_descr_get */
13927 0, /* tp_descr_set */
13928 0, /* tp_dictoffset */
13929 0, /* tp_init */
13930 0, /* tp_alloc */
13931 unicode_new, /* tp_new */
13932 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013933};
13934
13935/* Initialize the Unicode implementation */
13936
Victor Stinner3a50e702011-10-18 21:21:00 +020013937int _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013938{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013939 int i;
13940
Thomas Wouters477c8d52006-05-27 19:21:47 +000013941 /* XXX - move this array to unicodectype.c ? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013942 Py_UCS2 linebreak[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +000013943 0x000A, /* LINE FEED */
13944 0x000D, /* CARRIAGE RETURN */
13945 0x001C, /* FILE SEPARATOR */
13946 0x001D, /* GROUP SEPARATOR */
13947 0x001E, /* RECORD SEPARATOR */
13948 0x0085, /* NEXT LINE */
13949 0x2028, /* LINE SEPARATOR */
13950 0x2029, /* PARAGRAPH SEPARATOR */
13951 };
13952
Fred Drakee4315f52000-05-09 19:53:39 +000013953 /* Init the implementation */
Victor Stinnera464fc12011-10-02 20:39:30 +020013954 unicode_empty = PyUnicode_New(0, 0);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013955 if (!unicode_empty)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013956 Py_FatalError("Can't create empty string");
Victor Stinnerd3df8ab2011-11-22 01:22:34 +010013957 assert(_PyUnicode_CheckConsistency(unicode_empty, 1));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013958
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013959 for (i = 0; i < 256; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +000013960 unicode_latin1[i] = NULL;
Guido van Rossumcacfc072002-05-24 19:01:59 +000013961 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000013962 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +000013963
13964 /* initialize the linebreak bloom filter */
13965 bloom_linebreak = make_bloom_mask(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013966 PyUnicode_2BYTE_KIND, linebreak,
Victor Stinner63941882011-09-29 00:42:28 +020013967 Py_ARRAY_LENGTH(linebreak));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013968
13969 PyType_Ready(&EncodingMapType);
Victor Stinner3a50e702011-10-18 21:21:00 +020013970
13971#ifdef HAVE_MBCS
13972 winver.dwOSVersionInfoSize = sizeof(winver);
13973 if (!GetVersionEx((OSVERSIONINFO*)&winver)) {
13974 PyErr_SetFromWindowsErr(0);
13975 return -1;
13976 }
13977#endif
13978 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013979}
13980
13981/* Finalize the Unicode implementation */
13982
Christian Heimesa156e092008-02-16 07:38:31 +000013983int
13984PyUnicode_ClearFreeList(void)
13985{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013986 return 0;
Christian Heimesa156e092008-02-16 07:38:31 +000013987}
13988
Guido van Rossumd57fd912000-03-10 22:53:23 +000013989void
Thomas Wouters78890102000-07-22 19:25:51 +000013990_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013991{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013992 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013993
Guido van Rossum4ae8ef82000-10-03 18:09:04 +000013994 Py_XDECREF(unicode_empty);
13995 unicode_empty = NULL;
Barry Warsaw5b4c2282000-10-03 20:45:26 +000013996
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013997 for (i = 0; i < 256; i++) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013998 if (unicode_latin1[i]) {
13999 Py_DECREF(unicode_latin1[i]);
14000 unicode_latin1[i] = NULL;
14001 }
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014002 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020014003 _PyUnicode_ClearStaticStrings();
Christian Heimesa156e092008-02-16 07:38:31 +000014004 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +000014005}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000014006
Walter Dörwald16807132007-05-25 13:52:07 +000014007void
14008PyUnicode_InternInPlace(PyObject **p)
14009{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014010 register PyObject *s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014011 PyObject *t;
Victor Stinner4fae54c2011-10-03 02:01:52 +020014012#ifdef Py_DEBUG
14013 assert(s != NULL);
14014 assert(_PyUnicode_CHECK(s));
14015#else
Benjamin Peterson14339b62009-01-31 16:36:08 +000014016 if (s == NULL || !PyUnicode_Check(s))
Victor Stinner4fae54c2011-10-03 02:01:52 +020014017 return;
14018#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000014019 /* If it's a subclass, we don't really know what putting
14020 it in the interned dict might do. */
14021 if (!PyUnicode_CheckExact(s))
14022 return;
14023 if (PyUnicode_CHECK_INTERNED(s))
14024 return;
14025 if (interned == NULL) {
14026 interned = PyDict_New();
14027 if (interned == NULL) {
14028 PyErr_Clear(); /* Don't leave an exception */
14029 return;
14030 }
14031 }
14032 /* It might be that the GetItem call fails even
14033 though the key is present in the dictionary,
14034 namely when this happens during a stack overflow. */
14035 Py_ALLOW_RECURSION
Victor Stinner7931d9a2011-11-04 00:22:48 +010014036 t = PyDict_GetItem(interned, s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014037 Py_END_ALLOW_RECURSION
Martin v. Löwis5b222132007-06-10 09:51:05 +000014038
Benjamin Peterson29060642009-01-31 22:14:21 +000014039 if (t) {
14040 Py_INCREF(t);
14041 Py_DECREF(*p);
14042 *p = t;
14043 return;
14044 }
Walter Dörwald16807132007-05-25 13:52:07 +000014045
Benjamin Peterson14339b62009-01-31 16:36:08 +000014046 PyThreadState_GET()->recursion_critical = 1;
Victor Stinner7931d9a2011-11-04 00:22:48 +010014047 if (PyDict_SetItem(interned, s, s) < 0) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014048 PyErr_Clear();
14049 PyThreadState_GET()->recursion_critical = 0;
14050 return;
14051 }
14052 PyThreadState_GET()->recursion_critical = 0;
14053 /* The two references in interned are not counted by refcnt.
14054 The deallocator will take care of this */
14055 Py_REFCNT(s) -= 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014056 _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000014057}
14058
14059void
14060PyUnicode_InternImmortal(PyObject **p)
14061{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014062 PyUnicode_InternInPlace(p);
14063 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
Victor Stinneraf9e4b82011-10-23 20:07:00 +020014064 _PyUnicode_STATE(*p).interned = SSTATE_INTERNED_IMMORTAL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014065 Py_INCREF(*p);
14066 }
Walter Dörwald16807132007-05-25 13:52:07 +000014067}
14068
14069PyObject *
14070PyUnicode_InternFromString(const char *cp)
14071{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014072 PyObject *s = PyUnicode_FromString(cp);
14073 if (s == NULL)
14074 return NULL;
14075 PyUnicode_InternInPlace(&s);
14076 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000014077}
14078
Alexander Belopolsky40018472011-02-26 01:02:56 +000014079void
14080_Py_ReleaseInternedUnicodeStrings(void)
Walter Dörwald16807132007-05-25 13:52:07 +000014081{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014082 PyObject *keys;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014083 PyObject *s;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014084 Py_ssize_t i, n;
14085 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000014086
Benjamin Peterson14339b62009-01-31 16:36:08 +000014087 if (interned == NULL || !PyDict_Check(interned))
14088 return;
14089 keys = PyDict_Keys(interned);
14090 if (keys == NULL || !PyList_Check(keys)) {
14091 PyErr_Clear();
14092 return;
14093 }
Walter Dörwald16807132007-05-25 13:52:07 +000014094
Benjamin Peterson14339b62009-01-31 16:36:08 +000014095 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
14096 detector, interned unicode strings are not forcibly deallocated;
14097 rather, we give them their stolen references back, and then clear
14098 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000014099
Benjamin Peterson14339b62009-01-31 16:36:08 +000014100 n = PyList_GET_SIZE(keys);
14101 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000014102 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014103 for (i = 0; i < n; i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014104 s = PyList_GET_ITEM(keys, i);
Victor Stinner6b56a7f2011-10-04 20:04:52 +020014105 if (PyUnicode_READY(s) == -1) {
14106 assert(0 && "could not ready string");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014107 fprintf(stderr, "could not ready string\n");
Victor Stinner6b56a7f2011-10-04 20:04:52 +020014108 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014109 switch (PyUnicode_CHECK_INTERNED(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014110 case SSTATE_NOT_INTERNED:
14111 /* XXX Shouldn't happen */
14112 break;
14113 case SSTATE_INTERNED_IMMORTAL:
14114 Py_REFCNT(s) += 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014115 immortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014116 break;
14117 case SSTATE_INTERNED_MORTAL:
14118 Py_REFCNT(s) += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014119 mortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014120 break;
14121 default:
14122 Py_FatalError("Inconsistent interned string state.");
14123 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014124 _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014125 }
14126 fprintf(stderr, "total size of all interned strings: "
14127 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
14128 "mortal/immortal\n", mortal_size, immortal_size);
14129 Py_DECREF(keys);
14130 PyDict_Clear(interned);
14131 Py_DECREF(interned);
14132 interned = NULL;
Walter Dörwald16807132007-05-25 13:52:07 +000014133}
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014134
14135
14136/********************* Unicode Iterator **************************/
14137
14138typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014139 PyObject_HEAD
14140 Py_ssize_t it_index;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014141 PyObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014142} unicodeiterobject;
14143
14144static void
14145unicodeiter_dealloc(unicodeiterobject *it)
14146{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014147 _PyObject_GC_UNTRACK(it);
14148 Py_XDECREF(it->it_seq);
14149 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014150}
14151
14152static int
14153unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
14154{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014155 Py_VISIT(it->it_seq);
14156 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014157}
14158
14159static PyObject *
14160unicodeiter_next(unicodeiterobject *it)
14161{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014162 PyObject *seq, *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014163
Benjamin Peterson14339b62009-01-31 16:36:08 +000014164 assert(it != NULL);
14165 seq = it->it_seq;
14166 if (seq == NULL)
14167 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020014168 assert(_PyUnicode_CHECK(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014169
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014170 if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
14171 int kind = PyUnicode_KIND(seq);
14172 void *data = PyUnicode_DATA(seq);
14173 Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
14174 item = PyUnicode_FromOrdinal(chr);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014175 if (item != NULL)
14176 ++it->it_index;
14177 return item;
14178 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014179
Benjamin Peterson14339b62009-01-31 16:36:08 +000014180 Py_DECREF(seq);
14181 it->it_seq = NULL;
14182 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014183}
14184
14185static PyObject *
14186unicodeiter_len(unicodeiterobject *it)
14187{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014188 Py_ssize_t len = 0;
14189 if (it->it_seq)
Victor Stinnerc4f281e2011-10-11 22:11:42 +020014190 len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014191 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014192}
14193
14194PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
14195
14196static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014197 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000014198 length_hint_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000014199 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014200};
14201
14202PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014203 PyVarObject_HEAD_INIT(&PyType_Type, 0)
14204 "str_iterator", /* tp_name */
14205 sizeof(unicodeiterobject), /* tp_basicsize */
14206 0, /* tp_itemsize */
14207 /* methods */
14208 (destructor)unicodeiter_dealloc, /* tp_dealloc */
14209 0, /* tp_print */
14210 0, /* tp_getattr */
14211 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000014212 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014213 0, /* tp_repr */
14214 0, /* tp_as_number */
14215 0, /* tp_as_sequence */
14216 0, /* tp_as_mapping */
14217 0, /* tp_hash */
14218 0, /* tp_call */
14219 0, /* tp_str */
14220 PyObject_GenericGetAttr, /* tp_getattro */
14221 0, /* tp_setattro */
14222 0, /* tp_as_buffer */
14223 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
14224 0, /* tp_doc */
14225 (traverseproc)unicodeiter_traverse, /* tp_traverse */
14226 0, /* tp_clear */
14227 0, /* tp_richcompare */
14228 0, /* tp_weaklistoffset */
14229 PyObject_SelfIter, /* tp_iter */
14230 (iternextfunc)unicodeiter_next, /* tp_iternext */
14231 unicodeiter_methods, /* tp_methods */
14232 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014233};
14234
14235static PyObject *
14236unicode_iter(PyObject *seq)
14237{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014238 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014239
Benjamin Peterson14339b62009-01-31 16:36:08 +000014240 if (!PyUnicode_Check(seq)) {
14241 PyErr_BadInternalCall();
14242 return NULL;
14243 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014244 if (PyUnicode_READY(seq) == -1)
14245 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014246 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
14247 if (it == NULL)
14248 return NULL;
14249 it->it_index = 0;
14250 Py_INCREF(seq);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014251 it->it_seq = seq;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014252 _PyObject_GC_TRACK(it);
14253 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014254}
14255
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010014256
14257size_t
14258Py_UNICODE_strlen(const Py_UNICODE *u)
14259{
14260 int res = 0;
14261 while(*u++)
14262 res++;
14263 return res;
14264}
14265
14266Py_UNICODE*
14267Py_UNICODE_strcpy(Py_UNICODE *s1, const Py_UNICODE *s2)
14268{
14269 Py_UNICODE *u = s1;
14270 while ((*u++ = *s2++));
14271 return s1;
14272}
14273
14274Py_UNICODE*
14275Py_UNICODE_strncpy(Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
14276{
14277 Py_UNICODE *u = s1;
14278 while ((*u++ = *s2++))
14279 if (n-- == 0)
14280 break;
14281 return s1;
14282}
14283
14284Py_UNICODE*
14285Py_UNICODE_strcat(Py_UNICODE *s1, const Py_UNICODE *s2)
14286{
14287 Py_UNICODE *u1 = s1;
14288 u1 += Py_UNICODE_strlen(u1);
14289 Py_UNICODE_strcpy(u1, s2);
14290 return s1;
14291}
14292
14293int
14294Py_UNICODE_strcmp(const Py_UNICODE *s1, const Py_UNICODE *s2)
14295{
14296 while (*s1 && *s2 && *s1 == *s2)
14297 s1++, s2++;
14298 if (*s1 && *s2)
14299 return (*s1 < *s2) ? -1 : +1;
14300 if (*s1)
14301 return 1;
14302 if (*s2)
14303 return -1;
14304 return 0;
14305}
14306
14307int
14308Py_UNICODE_strncmp(const Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
14309{
14310 register Py_UNICODE u1, u2;
14311 for (; n != 0; n--) {
14312 u1 = *s1;
14313 u2 = *s2;
14314 if (u1 != u2)
14315 return (u1 < u2) ? -1 : +1;
14316 if (u1 == '\0')
14317 return 0;
14318 s1++;
14319 s2++;
14320 }
14321 return 0;
14322}
14323
14324Py_UNICODE*
14325Py_UNICODE_strchr(const Py_UNICODE *s, Py_UNICODE c)
14326{
14327 const Py_UNICODE *p;
14328 for (p = s; *p; p++)
14329 if (*p == c)
14330 return (Py_UNICODE*)p;
14331 return NULL;
14332}
14333
14334Py_UNICODE*
14335Py_UNICODE_strrchr(const Py_UNICODE *s, Py_UNICODE c)
14336{
14337 const Py_UNICODE *p;
14338 p = s + Py_UNICODE_strlen(s);
14339 while (p != s) {
14340 p--;
14341 if (*p == c)
14342 return (Py_UNICODE*)p;
14343 }
14344 return NULL;
14345}
Victor Stinner331ea922010-08-10 16:37:20 +000014346
Victor Stinner71133ff2010-09-01 23:43:53 +000014347Py_UNICODE*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014348PyUnicode_AsUnicodeCopy(PyObject *unicode)
Victor Stinner71133ff2010-09-01 23:43:53 +000014349{
Victor Stinner577db2c2011-10-11 22:12:48 +020014350 Py_UNICODE *u, *copy;
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014351 Py_ssize_t len, size;
Victor Stinner71133ff2010-09-01 23:43:53 +000014352
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014353 if (!PyUnicode_Check(unicode)) {
14354 PyErr_BadArgument();
14355 return NULL;
14356 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014357 u = PyUnicode_AsUnicodeAndSize(unicode, &len);
Victor Stinner577db2c2011-10-11 22:12:48 +020014358 if (u == NULL)
14359 return NULL;
Victor Stinner71133ff2010-09-01 23:43:53 +000014360 /* Ensure we won't overflow the size. */
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014361 if (len > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
Victor Stinner71133ff2010-09-01 23:43:53 +000014362 PyErr_NoMemory();
14363 return NULL;
14364 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014365 size = len + 1; /* copy the null character */
Victor Stinner71133ff2010-09-01 23:43:53 +000014366 size *= sizeof(Py_UNICODE);
14367 copy = PyMem_Malloc(size);
14368 if (copy == NULL) {
14369 PyErr_NoMemory();
14370 return NULL;
14371 }
Victor Stinner577db2c2011-10-11 22:12:48 +020014372 memcpy(copy, u, size);
Victor Stinner71133ff2010-09-01 23:43:53 +000014373 return copy;
14374}
Martin v. Löwis5b222132007-06-10 09:51:05 +000014375
Georg Brandl66c221e2010-10-14 07:04:07 +000014376/* A _string module, to export formatter_parser and formatter_field_name_split
14377 to the string.Formatter class implemented in Python. */
14378
14379static PyMethodDef _string_methods[] = {
14380 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
14381 METH_O, PyDoc_STR("split the argument as a field name")},
14382 {"formatter_parser", (PyCFunction) formatter_parser,
14383 METH_O, PyDoc_STR("parse the argument as a format string")},
14384 {NULL, NULL}
14385};
14386
14387static struct PyModuleDef _string_module = {
14388 PyModuleDef_HEAD_INIT,
14389 "_string",
14390 PyDoc_STR("string helper module"),
14391 0,
14392 _string_methods,
14393 NULL,
14394 NULL,
14395 NULL,
14396 NULL
14397};
14398
14399PyMODINIT_FUNC
14400PyInit__string(void)
14401{
14402 return PyModule_Create(&_string_module);
14403}
14404
14405
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000014406#ifdef __cplusplus
14407}
14408#endif