blob: 3f70af7e379e50664f99ea789f29295f0e1dee6a [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";
874 switch(PyUnicode_KIND(unicode))
875 {
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));
890 switch(PyUnicode_KIND(unicode))
891 {
892 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200893 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200894 return "ascii";
895 else
Victor Stinnera3b334d2011-10-03 13:53:37 +0200896 return "latin1";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200897 case PyUnicode_2BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200898 return "UCS2";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200899 case PyUnicode_4BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200900 return "UCS4";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200901 default:
902 return "<invalid compact kind>";
903 }
904}
905
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200906#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +0200907static int unicode_new_new_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200908
909/* Functions wrapping macros for use in debugger */
910char *_PyUnicode_utf8(void *unicode){
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200911 return PyUnicode_UTF8(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200912}
913
914void *_PyUnicode_compact_data(void *unicode) {
915 return _PyUnicode_COMPACT_DATA(unicode);
916}
917void *_PyUnicode_data(void *unicode){
918 printf("obj %p\n", unicode);
919 printf("compact %d\n", PyUnicode_IS_COMPACT(unicode));
920 printf("compact ascii %d\n", PyUnicode_IS_COMPACT_ASCII(unicode));
921 printf("ascii op %p\n", ((void*)((PyASCIIObject*)(unicode) + 1)));
922 printf("compact op %p\n", ((void*)((PyCompactUnicodeObject*)(unicode) + 1)));
923 printf("compact data %p\n", _PyUnicode_COMPACT_DATA(unicode));
924 return PyUnicode_DATA(unicode);
925}
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200926
927void
928_PyUnicode_Dump(PyObject *op)
929{
930 PyASCIIObject *ascii = (PyASCIIObject *)op;
Victor Stinnera849a4b2011-10-03 12:12:11 +0200931 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
932 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
933 void *data;
Victor Stinner0d60e872011-10-23 19:47:19 +0200934
Victor Stinnera849a4b2011-10-03 12:12:11 +0200935 if (ascii->state.compact)
Victor Stinner0d60e872011-10-23 19:47:19 +0200936 {
937 if (ascii->state.ascii)
938 data = (ascii + 1);
939 else
940 data = (compact + 1);
941 }
Victor Stinnera849a4b2011-10-03 12:12:11 +0200942 else
943 data = unicode->data.any;
Victor Stinner0d60e872011-10-23 19:47:19 +0200944 printf("%s: len=%zu, ",unicode_kind_name(op), ascii->length);
945
Victor Stinnera849a4b2011-10-03 12:12:11 +0200946 if (ascii->wstr == data)
947 printf("shared ");
948 printf("wstr=%p", ascii->wstr);
Victor Stinner0d60e872011-10-23 19:47:19 +0200949
Victor Stinnera3b334d2011-10-03 13:53:37 +0200950 if (!(ascii->state.ascii == 1 && ascii->state.compact == 1)) {
Victor Stinnera849a4b2011-10-03 12:12:11 +0200951 printf(" (%zu), ", compact->wstr_length);
952 if (!ascii->state.compact && compact->utf8 == unicode->data.any)
953 printf("shared ");
954 printf("utf8=%p (%zu)", compact->utf8, compact->utf8_length);
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200955 }
Victor Stinnera849a4b2011-10-03 12:12:11 +0200956 printf(", data=%p\n", data);
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200957}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200958#endif
959
960PyObject *
961PyUnicode_New(Py_ssize_t size, Py_UCS4 maxchar)
962{
963 PyObject *obj;
964 PyCompactUnicodeObject *unicode;
965 void *data;
966 int kind_state;
Victor Stinner9e9d6892011-10-04 01:02:02 +0200967 int is_sharing, is_ascii;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200968 Py_ssize_t char_size;
969 Py_ssize_t struct_size;
970
971 /* Optimization for empty strings */
972 if (size == 0 && unicode_empty != NULL) {
973 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +0200974 return unicode_empty;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200975 }
976
977#ifdef Py_DEBUG
978 ++unicode_new_new_calls;
979#endif
980
Victor Stinner9e9d6892011-10-04 01:02:02 +0200981 is_ascii = 0;
982 is_sharing = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200983 struct_size = sizeof(PyCompactUnicodeObject);
984 if (maxchar < 128) {
985 kind_state = PyUnicode_1BYTE_KIND;
986 char_size = 1;
987 is_ascii = 1;
988 struct_size = sizeof(PyASCIIObject);
989 }
990 else if (maxchar < 256) {
991 kind_state = PyUnicode_1BYTE_KIND;
992 char_size = 1;
993 }
994 else if (maxchar < 65536) {
995 kind_state = PyUnicode_2BYTE_KIND;
996 char_size = 2;
997 if (sizeof(wchar_t) == 2)
998 is_sharing = 1;
999 }
1000 else {
1001 kind_state = PyUnicode_4BYTE_KIND;
1002 char_size = 4;
1003 if (sizeof(wchar_t) == 4)
1004 is_sharing = 1;
1005 }
1006
1007 /* Ensure we won't overflow the size. */
1008 if (size < 0) {
1009 PyErr_SetString(PyExc_SystemError,
1010 "Negative size passed to PyUnicode_New");
1011 return NULL;
1012 }
1013 if (size > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1))
1014 return PyErr_NoMemory();
1015
1016 /* Duplicated allocation code from _PyObject_New() instead of a call to
1017 * PyObject_New() so we are able to allocate space for the object and
1018 * it's data buffer.
1019 */
1020 obj = (PyObject *) PyObject_MALLOC(struct_size + (size + 1) * char_size);
1021 if (obj == NULL)
1022 return PyErr_NoMemory();
1023 obj = PyObject_INIT(obj, &PyUnicode_Type);
1024 if (obj == NULL)
1025 return NULL;
1026
1027 unicode = (PyCompactUnicodeObject *)obj;
1028 if (is_ascii)
1029 data = ((PyASCIIObject*)obj) + 1;
1030 else
1031 data = unicode + 1;
1032 _PyUnicode_LENGTH(unicode) = size;
1033 _PyUnicode_HASH(unicode) = -1;
1034 _PyUnicode_STATE(unicode).interned = 0;
1035 _PyUnicode_STATE(unicode).kind = kind_state;
1036 _PyUnicode_STATE(unicode).compact = 1;
1037 _PyUnicode_STATE(unicode).ready = 1;
1038 _PyUnicode_STATE(unicode).ascii = is_ascii;
1039 if (is_ascii) {
1040 ((char*)data)[size] = 0;
1041 _PyUnicode_WSTR(unicode) = NULL;
1042 }
1043 else if (kind_state == PyUnicode_1BYTE_KIND) {
1044 ((char*)data)[size] = 0;
1045 _PyUnicode_WSTR(unicode) = NULL;
1046 _PyUnicode_WSTR_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001047 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001048 unicode->utf8_length = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001049 }
1050 else {
1051 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001052 unicode->utf8_length = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001053 if (kind_state == PyUnicode_2BYTE_KIND)
1054 ((Py_UCS2*)data)[size] = 0;
1055 else /* kind_state == PyUnicode_4BYTE_KIND */
1056 ((Py_UCS4*)data)[size] = 0;
1057 if (is_sharing) {
1058 _PyUnicode_WSTR_LENGTH(unicode) = size;
1059 _PyUnicode_WSTR(unicode) = (wchar_t *)data;
1060 }
1061 else {
1062 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1063 _PyUnicode_WSTR(unicode) = NULL;
1064 }
1065 }
Victor Stinner7931d9a2011-11-04 00:22:48 +01001066 assert(_PyUnicode_CheckConsistency((PyObject*)unicode, 0));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001067 return obj;
1068}
1069
1070#if SIZEOF_WCHAR_T == 2
1071/* Helper function to convert a 16-bits wchar_t representation to UCS4, this
1072 will decode surrogate pairs, the other conversions are implemented as macros
Georg Brandl7597add2011-10-05 16:36:47 +02001073 for efficiency.
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001074
1075 This function assumes that unicode can hold one more code point than wstr
1076 characters for a terminating null character. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001077static void
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001078unicode_convert_wchar_to_ucs4(const wchar_t *begin, const wchar_t *end,
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001079 PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001080{
1081 const wchar_t *iter;
1082 Py_UCS4 *ucs4_out;
1083
Victor Stinner910337b2011-10-03 03:20:16 +02001084 assert(unicode != NULL);
1085 assert(_PyUnicode_CHECK(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001086 assert(_PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
1087 ucs4_out = PyUnicode_4BYTE_DATA(unicode);
1088
1089 for (iter = begin; iter < end; ) {
1090 assert(ucs4_out < (PyUnicode_4BYTE_DATA(unicode) +
1091 _PyUnicode_GET_LENGTH(unicode)));
Victor Stinner551ac952011-11-29 22:58:13 +01001092 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1093 && (iter+1) < end
1094 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001095 {
Victor Stinner551ac952011-11-29 22:58:13 +01001096 *ucs4_out++ = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001097 iter += 2;
1098 }
1099 else {
1100 *ucs4_out++ = *iter;
1101 iter++;
1102 }
1103 }
1104 assert(ucs4_out == (PyUnicode_4BYTE_DATA(unicode) +
1105 _PyUnicode_GET_LENGTH(unicode)));
1106
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001107}
1108#endif
1109
Victor Stinnercd9950f2011-10-02 00:34:53 +02001110static int
Victor Stinner488fa492011-12-12 00:01:39 +01001111unicode_check_modifiable(PyObject *unicode)
Victor Stinnercd9950f2011-10-02 00:34:53 +02001112{
Victor Stinner488fa492011-12-12 00:01:39 +01001113 if (!unicode_modifiable(unicode)) {
Victor Stinner01698042011-10-04 00:04:26 +02001114 PyErr_SetString(PyExc_SystemError,
Victor Stinner488fa492011-12-12 00:01:39 +01001115 "Cannot modify a string currently used");
Victor Stinnercd9950f2011-10-02 00:34:53 +02001116 return -1;
1117 }
Victor Stinnercd9950f2011-10-02 00:34:53 +02001118 return 0;
1119}
1120
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001121static int
1122_copy_characters(PyObject *to, Py_ssize_t to_start,
1123 PyObject *from, Py_ssize_t from_start,
1124 Py_ssize_t how_many, int check_maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001125{
Victor Stinnera0702ab2011-09-29 14:14:38 +02001126 unsigned int from_kind, to_kind;
1127 void *from_data, *to_data;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001128 int fast;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001129
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001130 assert(PyUnicode_Check(from));
1131 assert(PyUnicode_Check(to));
1132 assert(PyUnicode_IS_READY(from));
1133 assert(PyUnicode_IS_READY(to));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001134
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001135 assert(PyUnicode_GET_LENGTH(from) >= how_many);
1136 assert(to_start + how_many <= PyUnicode_GET_LENGTH(to));
1137 assert(0 <= how_many);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001138
Victor Stinnerf5ca1a22011-09-28 23:54:59 +02001139 if (how_many == 0)
1140 return 0;
1141
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001142 from_kind = PyUnicode_KIND(from);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001143 from_data = PyUnicode_DATA(from);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001144 to_kind = PyUnicode_KIND(to);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001145 to_data = PyUnicode_DATA(to);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001146
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001147#ifdef Py_DEBUG
1148 if (!check_maxchar
1149 && (from_kind > to_kind
1150 || (!PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to))))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001151 {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001152 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
1153 Py_UCS4 ch;
1154 Py_ssize_t i;
1155 for (i=0; i < how_many; i++) {
1156 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1157 assert(ch <= to_maxchar);
1158 }
1159 }
1160#endif
1161 fast = (from_kind == to_kind);
1162 if (check_maxchar
1163 && (!PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to)))
1164 {
1165 /* deny latin1 => ascii */
1166 fast = 0;
1167 }
1168
1169 if (fast) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +02001170 Py_MEMCPY((char*)to_data + to_kind * to_start,
1171 (char*)from_data + from_kind * from_start,
1172 to_kind * how_many);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001173 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001174 else if (from_kind == PyUnicode_1BYTE_KIND
1175 && to_kind == PyUnicode_2BYTE_KIND)
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001176 {
1177 _PyUnicode_CONVERT_BYTES(
1178 Py_UCS1, Py_UCS2,
1179 PyUnicode_1BYTE_DATA(from) + from_start,
1180 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1181 PyUnicode_2BYTE_DATA(to) + to_start
1182 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001183 }
Victor Stinner157f83f2011-09-28 21:41:31 +02001184 else if (from_kind == PyUnicode_1BYTE_KIND
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001185 && to_kind == PyUnicode_4BYTE_KIND)
1186 {
1187 _PyUnicode_CONVERT_BYTES(
1188 Py_UCS1, Py_UCS4,
1189 PyUnicode_1BYTE_DATA(from) + from_start,
1190 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1191 PyUnicode_4BYTE_DATA(to) + to_start
1192 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001193 }
1194 else if (from_kind == PyUnicode_2BYTE_KIND
1195 && to_kind == PyUnicode_4BYTE_KIND)
1196 {
1197 _PyUnicode_CONVERT_BYTES(
1198 Py_UCS2, Py_UCS4,
1199 PyUnicode_2BYTE_DATA(from) + from_start,
1200 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1201 PyUnicode_4BYTE_DATA(to) + to_start
1202 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001203 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001204 else {
Victor Stinnerf42dc442011-10-02 23:33:16 +02001205 /* check if max_char(from substring) <= max_char(to) */
1206 if (from_kind > to_kind
1207 /* latin1 => ascii */
Victor Stinnerb9275c12011-10-05 14:01:42 +02001208 || (!PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to)))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001209 {
Victor Stinnera0702ab2011-09-29 14:14:38 +02001210 /* slow path to check for character overflow */
1211 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001212 Py_UCS4 ch;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001213 Py_ssize_t i;
1214
Victor Stinner56c161a2011-10-06 02:47:11 +02001215#ifdef Py_DEBUG
Victor Stinnera0702ab2011-09-29 14:14:38 +02001216 for (i=0; i < how_many; i++) {
1217 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
Victor Stinner56c161a2011-10-06 02:47:11 +02001218 assert(ch <= to_maxchar);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001219 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1220 }
Victor Stinner56c161a2011-10-06 02:47:11 +02001221#else
1222 if (!check_maxchar) {
1223 for (i=0; i < how_many; i++) {
1224 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1225 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1226 }
1227 }
1228 else {
1229 for (i=0; i < how_many; i++) {
1230 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1231 if (ch > to_maxchar)
1232 return 1;
1233 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1234 }
1235 }
1236#endif
Victor Stinnera0702ab2011-09-29 14:14:38 +02001237 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001238 else {
Victor Stinner56c161a2011-10-06 02:47:11 +02001239 assert(0 && "inconsistent state");
1240 return 1;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001241 }
1242 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001243 return 0;
1244}
1245
1246static void
1247copy_characters(PyObject *to, Py_ssize_t to_start,
1248 PyObject *from, Py_ssize_t from_start,
1249 Py_ssize_t how_many)
1250{
1251 (void)_copy_characters(to, to_start, from, from_start, how_many, 0);
1252}
1253
1254Py_ssize_t
1255PyUnicode_CopyCharacters(PyObject *to, Py_ssize_t to_start,
1256 PyObject *from, Py_ssize_t from_start,
1257 Py_ssize_t how_many)
1258{
1259 int err;
1260
1261 if (!PyUnicode_Check(from) || !PyUnicode_Check(to)) {
1262 PyErr_BadInternalCall();
1263 return -1;
1264 }
1265
1266 if (PyUnicode_READY(from))
1267 return -1;
1268 if (PyUnicode_READY(to))
1269 return -1;
1270
1271 how_many = Py_MIN(PyUnicode_GET_LENGTH(from), how_many);
1272 if (to_start + how_many > PyUnicode_GET_LENGTH(to)) {
1273 PyErr_Format(PyExc_SystemError,
1274 "Cannot write %zi characters at %zi "
1275 "in a string of %zi characters",
1276 how_many, to_start, PyUnicode_GET_LENGTH(to));
1277 return -1;
1278 }
1279
1280 if (how_many == 0)
1281 return 0;
1282
Victor Stinner488fa492011-12-12 00:01:39 +01001283 if (unicode_check_modifiable(to))
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001284 return -1;
1285
1286 err = _copy_characters(to, to_start, from, from_start, how_many, 1);
1287 if (err) {
1288 PyErr_Format(PyExc_SystemError,
1289 "Cannot copy %s characters "
1290 "into a string of %s characters",
1291 unicode_kind_name(from),
1292 unicode_kind_name(to));
1293 return -1;
1294 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001295 return how_many;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001296}
1297
Victor Stinner17222162011-09-28 22:15:37 +02001298/* Find the maximum code point and count the number of surrogate pairs so a
1299 correct string length can be computed before converting a string to UCS4.
1300 This function counts single surrogates as a character and not as a pair.
1301
1302 Return 0 on success, or -1 on error. */
1303static int
1304find_maxchar_surrogates(const wchar_t *begin, const wchar_t *end,
1305 Py_UCS4 *maxchar, Py_ssize_t *num_surrogates)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001306{
1307 const wchar_t *iter;
Victor Stinner8faf8212011-12-08 22:14:11 +01001308 Py_UCS4 ch;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001309
Victor Stinnerc53be962011-10-02 21:33:54 +02001310 assert(num_surrogates != NULL && maxchar != NULL);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001311 *num_surrogates = 0;
1312 *maxchar = 0;
1313
1314 for (iter = begin; iter < end; ) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001315#if SIZEOF_WCHAR_T == 2
Victor Stinnerca4f2072011-11-22 03:38:40 +01001316 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1317 && (iter+1) < end
1318 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001319 {
Victor Stinner8faf8212011-12-08 22:14:11 +01001320 ch = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001321 ++(*num_surrogates);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001322 iter += 2;
1323 }
1324 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001325#endif
Victor Stinner8faf8212011-12-08 22:14:11 +01001326 {
1327 ch = *iter;
1328 iter++;
1329 }
1330 if (ch > *maxchar) {
1331 *maxchar = ch;
1332 if (*maxchar > MAX_UNICODE) {
1333 PyErr_Format(PyExc_ValueError,
1334 "character U+%x is not in range [U+0000; U+10ffff]",
1335 ch);
1336 return -1;
1337 }
1338 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001339 }
1340 return 0;
1341}
1342
1343#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +02001344static int unicode_ready_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001345#endif
1346
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001347int
1348_PyUnicode_Ready(PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001349{
1350 wchar_t *end;
1351 Py_UCS4 maxchar = 0;
1352 Py_ssize_t num_surrogates;
1353#if SIZEOF_WCHAR_T == 2
1354 Py_ssize_t length_wo_surrogates;
1355#endif
1356
Georg Brandl7597add2011-10-05 16:36:47 +02001357 /* _PyUnicode_Ready() is only intended for old-style API usage where
Victor Stinnerd8f65102011-09-29 19:43:17 +02001358 strings were created using _PyObject_New() and where no canonical
1359 representation (the str field) has been set yet aka strings
1360 which are not yet ready. */
Victor Stinner910337b2011-10-03 03:20:16 +02001361 assert(_PyUnicode_CHECK(unicode));
1362 assert(_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001363 assert(_PyUnicode_WSTR(unicode) != NULL);
Victor Stinnerc3c74152011-10-02 20:39:55 +02001364 assert(_PyUnicode_DATA_ANY(unicode) == NULL);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001365 assert(_PyUnicode_UTF8(unicode) == NULL);
Victor Stinnerd8f65102011-09-29 19:43:17 +02001366 /* Actually, it should neither be interned nor be anything else: */
1367 assert(_PyUnicode_STATE(unicode).interned == SSTATE_NOT_INTERNED);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001368
1369#ifdef Py_DEBUG
1370 ++unicode_ready_calls;
1371#endif
1372
1373 end = _PyUnicode_WSTR(unicode) + _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinner17222162011-09-28 22:15:37 +02001374 if (find_maxchar_surrogates(_PyUnicode_WSTR(unicode), end,
Victor Stinnerd8f65102011-09-29 19:43:17 +02001375 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001376 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001377
1378 if (maxchar < 256) {
Victor Stinnerc3c74152011-10-02 20:39:55 +02001379 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(_PyUnicode_WSTR_LENGTH(unicode) + 1);
1380 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001381 PyErr_NoMemory();
1382 return -1;
1383 }
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001384 _PyUnicode_CONVERT_BYTES(wchar_t, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001385 _PyUnicode_WSTR(unicode), end,
1386 PyUnicode_1BYTE_DATA(unicode));
1387 PyUnicode_1BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1388 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1389 _PyUnicode_STATE(unicode).kind = PyUnicode_1BYTE_KIND;
1390 if (maxchar < 128) {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001391 _PyUnicode_STATE(unicode).ascii = 1;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001392 _PyUnicode_UTF8(unicode) = _PyUnicode_DATA_ANY(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001393 _PyUnicode_UTF8_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001394 }
1395 else {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001396 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001397 _PyUnicode_UTF8(unicode) = NULL;
1398 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001399 }
1400 PyObject_FREE(_PyUnicode_WSTR(unicode));
1401 _PyUnicode_WSTR(unicode) = NULL;
1402 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1403 }
1404 /* In this case we might have to convert down from 4-byte native
1405 wchar_t to 2-byte unicode. */
1406 else if (maxchar < 65536) {
1407 assert(num_surrogates == 0 &&
1408 "FindMaxCharAndNumSurrogatePairs() messed up");
1409
Victor Stinner506f5922011-09-28 22:34:18 +02001410#if SIZEOF_WCHAR_T == 2
1411 /* We can share representations and are done. */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001412 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Victor Stinner506f5922011-09-28 22:34:18 +02001413 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1414 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1415 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001416 _PyUnicode_UTF8(unicode) = NULL;
1417 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001418#else
1419 /* sizeof(wchar_t) == 4 */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001420 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(
Victor Stinner506f5922011-09-28 22:34:18 +02001421 2 * (_PyUnicode_WSTR_LENGTH(unicode) + 1));
Victor Stinnerc3c74152011-10-02 20:39:55 +02001422 if (!_PyUnicode_DATA_ANY(unicode)) {
Victor Stinner506f5922011-09-28 22:34:18 +02001423 PyErr_NoMemory();
1424 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001425 }
Victor Stinner506f5922011-09-28 22:34:18 +02001426 _PyUnicode_CONVERT_BYTES(wchar_t, Py_UCS2,
1427 _PyUnicode_WSTR(unicode), end,
1428 PyUnicode_2BYTE_DATA(unicode));
1429 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1430 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1431 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001432 _PyUnicode_UTF8(unicode) = NULL;
1433 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001434 PyObject_FREE(_PyUnicode_WSTR(unicode));
1435 _PyUnicode_WSTR(unicode) = NULL;
1436 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1437#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001438 }
1439 /* maxchar exeeds 16 bit, wee need 4 bytes for unicode characters */
1440 else {
1441#if SIZEOF_WCHAR_T == 2
1442 /* in case the native representation is 2-bytes, we need to allocate a
1443 new normalized 4-byte version. */
1444 length_wo_surrogates = _PyUnicode_WSTR_LENGTH(unicode) - num_surrogates;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001445 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(4 * (length_wo_surrogates + 1));
1446 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001447 PyErr_NoMemory();
1448 return -1;
1449 }
1450 _PyUnicode_LENGTH(unicode) = length_wo_surrogates;
1451 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001452 _PyUnicode_UTF8(unicode) = NULL;
1453 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner126c5592011-10-03 04:17:10 +02001454 /* unicode_convert_wchar_to_ucs4() requires a ready string */
1455 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerc53be962011-10-02 21:33:54 +02001456 unicode_convert_wchar_to_ucs4(_PyUnicode_WSTR(unicode), end, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001457 PyObject_FREE(_PyUnicode_WSTR(unicode));
1458 _PyUnicode_WSTR(unicode) = NULL;
1459 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1460#else
1461 assert(num_surrogates == 0);
1462
Victor Stinnerc3c74152011-10-02 20:39:55 +02001463 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001464 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001465 _PyUnicode_UTF8(unicode) = NULL;
1466 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001467 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
1468#endif
1469 PyUnicode_4BYTE_DATA(unicode)[_PyUnicode_LENGTH(unicode)] = '\0';
1470 }
1471 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001472 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001473 return 0;
1474}
1475
Alexander Belopolsky40018472011-02-26 01:02:56 +00001476static void
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001477unicode_dealloc(register PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001478{
Walter Dörwald16807132007-05-25 13:52:07 +00001479 switch (PyUnicode_CHECK_INTERNED(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001480 case SSTATE_NOT_INTERNED:
1481 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001482
Benjamin Peterson29060642009-01-31 22:14:21 +00001483 case SSTATE_INTERNED_MORTAL:
1484 /* revive dead object temporarily for DelItem */
1485 Py_REFCNT(unicode) = 3;
Victor Stinner7931d9a2011-11-04 00:22:48 +01001486 if (PyDict_DelItem(interned, unicode) != 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00001487 Py_FatalError(
1488 "deletion of interned string failed");
1489 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001490
Benjamin Peterson29060642009-01-31 22:14:21 +00001491 case SSTATE_INTERNED_IMMORTAL:
1492 Py_FatalError("Immortal interned string died.");
Walter Dörwald16807132007-05-25 13:52:07 +00001493
Benjamin Peterson29060642009-01-31 22:14:21 +00001494 default:
1495 Py_FatalError("Inconsistent interned string state.");
Walter Dörwald16807132007-05-25 13:52:07 +00001496 }
1497
Victor Stinner03490912011-10-03 23:45:12 +02001498 if (_PyUnicode_HAS_WSTR_MEMORY(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001499 PyObject_DEL(_PyUnicode_WSTR(unicode));
Victor Stinner829c0ad2011-10-03 01:08:02 +02001500 if (_PyUnicode_HAS_UTF8_MEMORY(unicode))
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001501 PyObject_DEL(_PyUnicode_UTF8(unicode));
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001502 if (!PyUnicode_IS_COMPACT(unicode) && _PyUnicode_DATA_ANY(unicode))
1503 PyObject_DEL(_PyUnicode_DATA_ANY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001504
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001505 Py_TYPE(unicode)->tp_free(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001506}
1507
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001508#ifdef Py_DEBUG
1509static int
1510unicode_is_singleton(PyObject *unicode)
1511{
1512 PyASCIIObject *ascii = (PyASCIIObject *)unicode;
1513 if (unicode == unicode_empty)
1514 return 1;
1515 if (ascii->state.kind != PyUnicode_WCHAR_KIND && ascii->length == 1)
1516 {
1517 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, 0);
1518 if (ch < 256 && unicode_latin1[ch] == unicode)
1519 return 1;
1520 }
1521 return 0;
1522}
1523#endif
1524
Alexander Belopolsky40018472011-02-26 01:02:56 +00001525static int
Victor Stinner488fa492011-12-12 00:01:39 +01001526unicode_modifiable(PyObject *unicode)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001527{
Victor Stinner488fa492011-12-12 00:01:39 +01001528 assert(_PyUnicode_CHECK(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001529 if (Py_REFCNT(unicode) != 1)
1530 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001531 if (_PyUnicode_HASH(unicode) != -1)
1532 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001533 if (PyUnicode_CHECK_INTERNED(unicode))
1534 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001535 if (!PyUnicode_CheckExact(unicode))
1536 return 0;
Victor Stinner77bb47b2011-10-03 20:06:05 +02001537#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001538 /* singleton refcount is greater than 1 */
1539 assert(!unicode_is_singleton(unicode));
Victor Stinner77bb47b2011-10-03 20:06:05 +02001540#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +02001541 return 1;
1542}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001543
Victor Stinnerfe226c02011-10-03 03:52:20 +02001544static int
1545unicode_resize(PyObject **p_unicode, Py_ssize_t length)
1546{
1547 PyObject *unicode;
1548 Py_ssize_t old_length;
1549
1550 assert(p_unicode != NULL);
1551 unicode = *p_unicode;
1552
1553 assert(unicode != NULL);
1554 assert(PyUnicode_Check(unicode));
1555 assert(0 <= length);
1556
Victor Stinner910337b2011-10-03 03:20:16 +02001557 if (_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001558 old_length = PyUnicode_WSTR_LENGTH(unicode);
1559 else
1560 old_length = PyUnicode_GET_LENGTH(unicode);
1561 if (old_length == length)
1562 return 0;
1563
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001564 if (length == 0) {
1565 Py_DECREF(*p_unicode);
1566 *p_unicode = unicode_empty;
1567 Py_INCREF(*p_unicode);
1568 return 0;
1569 }
1570
Victor Stinner488fa492011-12-12 00:01:39 +01001571 if (!unicode_modifiable(unicode)) {
Victor Stinnerfe226c02011-10-03 03:52:20 +02001572 PyObject *copy = resize_copy(unicode, length);
1573 if (copy == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001574 return -1;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001575 Py_DECREF(*p_unicode);
1576 *p_unicode = copy;
Benjamin Peterson29060642009-01-31 22:14:21 +00001577 return 0;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001578 }
1579
Victor Stinnerfe226c02011-10-03 03:52:20 +02001580 if (PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001581 PyObject *new_unicode = resize_compact(unicode, length);
1582 if (new_unicode == NULL)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001583 return -1;
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001584 *p_unicode = new_unicode;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001585 assert(_PyUnicode_CheckConsistency(*p_unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001586 return 0;
Benjamin Peterson4bfce8f2011-10-03 19:35:07 -04001587 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001588 return resize_inplace(unicode, length);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001589}
1590
Alexander Belopolsky40018472011-02-26 01:02:56 +00001591int
Victor Stinnerfe226c02011-10-03 03:52:20 +02001592PyUnicode_Resize(PyObject **p_unicode, Py_ssize_t length)
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001593{
Victor Stinnerfe226c02011-10-03 03:52:20 +02001594 PyObject *unicode;
1595 if (p_unicode == NULL) {
1596 PyErr_BadInternalCall();
1597 return -1;
1598 }
1599 unicode = *p_unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001600 if (unicode == NULL || !PyUnicode_Check(unicode) || length < 0)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001601 {
1602 PyErr_BadInternalCall();
1603 return -1;
1604 }
1605 return unicode_resize(p_unicode, length);
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001606}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001607
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001608static int
Victor Stinner0a045ef2011-11-09 00:02:42 +01001609unicode_widen(PyObject **p_unicode, unsigned int maxchar)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001610{
1611 PyObject *result;
1612 assert(PyUnicode_IS_READY(*p_unicode));
1613 if (maxchar <= PyUnicode_MAX_CHAR_VALUE(*p_unicode))
1614 return 0;
1615 result = PyUnicode_New(PyUnicode_GET_LENGTH(*p_unicode),
1616 maxchar);
1617 if (result == NULL)
1618 return -1;
1619 PyUnicode_CopyCharacters(result, 0, *p_unicode, 0,
1620 PyUnicode_GET_LENGTH(*p_unicode));
1621 Py_DECREF(*p_unicode);
1622 *p_unicode = result;
1623 return 0;
1624}
1625
1626static int
1627unicode_putchar(PyObject **p_unicode, Py_ssize_t *pos,
1628 Py_UCS4 ch)
1629{
1630 if (unicode_widen(p_unicode, ch) < 0)
1631 return -1;
1632 PyUnicode_WRITE(PyUnicode_KIND(*p_unicode),
1633 PyUnicode_DATA(*p_unicode),
1634 (*pos)++, ch);
1635 return 0;
1636}
1637
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001638static PyObject*
1639get_latin1_char(unsigned char ch)
1640{
Victor Stinnera464fc12011-10-02 20:39:30 +02001641 PyObject *unicode = unicode_latin1[ch];
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001642 if (!unicode) {
Victor Stinnera464fc12011-10-02 20:39:30 +02001643 unicode = PyUnicode_New(1, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001644 if (!unicode)
1645 return NULL;
1646 PyUnicode_1BYTE_DATA(unicode)[0] = ch;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001647 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001648 unicode_latin1[ch] = unicode;
1649 }
1650 Py_INCREF(unicode);
Victor Stinnera464fc12011-10-02 20:39:30 +02001651 return unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001652}
1653
Alexander Belopolsky40018472011-02-26 01:02:56 +00001654PyObject *
1655PyUnicode_FromUnicode(const Py_UNICODE *u, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001656{
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001657 PyObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001658 Py_UCS4 maxchar = 0;
1659 Py_ssize_t num_surrogates;
1660
1661 if (u == NULL)
1662 return (PyObject*)_PyUnicode_New(size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001663
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001664 /* If the Unicode data is known at construction time, we can apply
1665 some optimizations which share commonly used objects. */
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001666
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001667 /* Optimization for empty strings */
1668 if (size == 0 && unicode_empty != NULL) {
1669 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001670 return unicode_empty;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001671 }
Tim Petersced69f82003-09-16 20:30:58 +00001672
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001673 /* Single character Unicode objects in the Latin-1 range are
1674 shared when using this constructor */
1675 if (size == 1 && *u < 256)
1676 return get_latin1_char((unsigned char)*u);
1677
1678 /* If not empty and not single character, copy the Unicode data
1679 into the new object */
Victor Stinnerd8f65102011-09-29 19:43:17 +02001680 if (find_maxchar_surrogates(u, u + size,
1681 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001682 return NULL;
1683
Victor Stinner8faf8212011-12-08 22:14:11 +01001684 unicode = PyUnicode_New(size - num_surrogates, maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001685 if (!unicode)
1686 return NULL;
1687
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001688 switch (PyUnicode_KIND(unicode)) {
1689 case PyUnicode_1BYTE_KIND:
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001690 _PyUnicode_CONVERT_BYTES(Py_UNICODE, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001691 u, u + size, PyUnicode_1BYTE_DATA(unicode));
1692 break;
1693 case PyUnicode_2BYTE_KIND:
1694#if Py_UNICODE_SIZE == 2
1695 Py_MEMCPY(PyUnicode_2BYTE_DATA(unicode), u, size * 2);
1696#else
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001697 _PyUnicode_CONVERT_BYTES(Py_UNICODE, Py_UCS2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001698 u, u + size, PyUnicode_2BYTE_DATA(unicode));
1699#endif
1700 break;
1701 case PyUnicode_4BYTE_KIND:
1702#if SIZEOF_WCHAR_T == 2
1703 /* This is the only case which has to process surrogates, thus
1704 a simple copy loop is not enough and we need a function. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001705 unicode_convert_wchar_to_ucs4(u, u + size, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001706#else
1707 assert(num_surrogates == 0);
1708 Py_MEMCPY(PyUnicode_4BYTE_DATA(unicode), u, size * 4);
1709#endif
1710 break;
1711 default:
1712 assert(0 && "Impossible state");
1713 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00001714
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001715 return unicode_result(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001716}
1717
Alexander Belopolsky40018472011-02-26 01:02:56 +00001718PyObject *
1719PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size)
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001720{
Benjamin Peterson14339b62009-01-31 16:36:08 +00001721 if (size < 0) {
1722 PyErr_SetString(PyExc_SystemError,
Benjamin Peterson29060642009-01-31 22:14:21 +00001723 "Negative size passed to PyUnicode_FromStringAndSize");
Benjamin Peterson14339b62009-01-31 16:36:08 +00001724 return NULL;
1725 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01001726 if (u != NULL)
1727 return PyUnicode_DecodeUTF8Stateful(u, size, NULL, NULL);
1728 else
1729 return (PyObject *)_PyUnicode_New(size);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001730}
1731
Alexander Belopolsky40018472011-02-26 01:02:56 +00001732PyObject *
1733PyUnicode_FromString(const char *u)
Walter Dörwaldd2034312007-05-18 16:29:38 +00001734{
1735 size_t size = strlen(u);
1736 if (size > PY_SSIZE_T_MAX) {
1737 PyErr_SetString(PyExc_OverflowError, "input too long");
1738 return NULL;
1739 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01001740 return PyUnicode_DecodeUTF8Stateful(u, (Py_ssize_t)size, NULL, NULL);
Walter Dörwaldd2034312007-05-18 16:29:38 +00001741}
1742
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001743PyObject *
1744_PyUnicode_FromId(_Py_Identifier *id)
1745{
1746 if (!id->object) {
Victor Stinnera1d12bb2011-12-11 21:53:09 +01001747 id->object = PyUnicode_DecodeUTF8Stateful(id->string,
1748 strlen(id->string),
1749 NULL, NULL);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001750 if (!id->object)
1751 return NULL;
1752 PyUnicode_InternInPlace(&id->object);
1753 assert(!id->next);
1754 id->next = static_strings;
1755 static_strings = id;
1756 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001757 return id->object;
1758}
1759
1760void
1761_PyUnicode_ClearStaticStrings()
1762{
1763 _Py_Identifier *i;
1764 for (i = static_strings; i; i = i->next) {
1765 Py_DECREF(i->object);
1766 i->object = NULL;
1767 i->next = NULL;
1768 }
1769}
1770
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001771/* Internal function, don't check maximum character */
1772
Victor Stinnere57b1c02011-09-28 22:20:48 +02001773static PyObject*
Victor Stinner0617b6e2011-10-05 23:26:01 +02001774unicode_fromascii(const unsigned char* s, Py_ssize_t size)
Victor Stinner702c7342011-10-05 13:50:52 +02001775{
Victor Stinner785938e2011-12-11 20:09:03 +01001776 PyObject *unicode;
Victor Stinnere6b2d442011-12-11 21:54:30 +01001777 if (size == 1) {
Victor Stinner0617b6e2011-10-05 23:26:01 +02001778#ifdef Py_DEBUG
Victor Stinnere6b2d442011-12-11 21:54:30 +01001779 assert(s[0] < 128);
Victor Stinner0617b6e2011-10-05 23:26:01 +02001780#endif
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001781 return get_latin1_char(s[0]);
Victor Stinnere6b2d442011-12-11 21:54:30 +01001782 }
Victor Stinner785938e2011-12-11 20:09:03 +01001783 unicode = PyUnicode_New(size, 127);
1784 if (!unicode)
Victor Stinner702c7342011-10-05 13:50:52 +02001785 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01001786 memcpy(PyUnicode_1BYTE_DATA(unicode), s, size);
1787 assert(_PyUnicode_CheckConsistency(unicode, 1));
1788 return unicode;
Victor Stinner702c7342011-10-05 13:50:52 +02001789}
1790
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001791static Py_UCS4
1792kind_maxchar_limit(unsigned int kind)
1793{
1794 switch(kind) {
1795 case PyUnicode_1BYTE_KIND:
1796 return 0x80;
1797 case PyUnicode_2BYTE_KIND:
1798 return 0x100;
1799 case PyUnicode_4BYTE_KIND:
1800 return 0x10000;
1801 default:
1802 assert(0 && "invalid kind");
Victor Stinner8faf8212011-12-08 22:14:11 +01001803 return MAX_UNICODE;
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001804 }
1805}
1806
Victor Stinner702c7342011-10-05 13:50:52 +02001807static PyObject*
Victor Stinnere57b1c02011-09-28 22:20:48 +02001808_PyUnicode_FromUCS1(const unsigned char* u, Py_ssize_t size)
Mark Dickinson081dfee2009-03-18 14:47:41 +00001809{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001810 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001811 unsigned char max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001812
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001813 if (size == 0) {
1814 Py_INCREF(unicode_empty);
1815 return unicode_empty;
1816 }
1817 assert(size > 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001818 if (size == 1)
1819 return get_latin1_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001820
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001821 max_char = ucs1lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001822 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001823 if (!res)
1824 return NULL;
1825 memcpy(PyUnicode_1BYTE_DATA(res), u, size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001826 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001827 return res;
Mark Dickinson081dfee2009-03-18 14:47:41 +00001828}
1829
Victor Stinnere57b1c02011-09-28 22:20:48 +02001830static PyObject*
1831_PyUnicode_FromUCS2(const Py_UCS2 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001832{
1833 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001834 Py_UCS2 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001835
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001836 if (size == 0) {
1837 Py_INCREF(unicode_empty);
1838 return unicode_empty;
1839 }
1840 assert(size > 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001841 if (size == 1 && u[0] < 256)
Victor Stinner4e101002011-10-11 23:27:52 +02001842 return get_latin1_char((unsigned char)u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001843
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001844 max_char = ucs2lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001845 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001846 if (!res)
1847 return NULL;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001848 if (max_char >= 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001849 memcpy(PyUnicode_2BYTE_DATA(res), u, sizeof(Py_UCS2)*size);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001850 else {
1851 _PyUnicode_CONVERT_BYTES(
1852 Py_UCS2, Py_UCS1, u, u + size, PyUnicode_1BYTE_DATA(res));
1853 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001854 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001855 return res;
1856}
1857
Victor Stinnere57b1c02011-09-28 22:20:48 +02001858static PyObject*
1859_PyUnicode_FromUCS4(const Py_UCS4 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001860{
1861 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001862 Py_UCS4 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001863
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001864 if (size == 0) {
1865 Py_INCREF(unicode_empty);
1866 return unicode_empty;
1867 }
1868 assert(size > 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001869 if (size == 1 && u[0] < 256)
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001870 return get_latin1_char((unsigned char)u[0]);
1871
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001872 max_char = ucs4lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001873 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001874 if (!res)
1875 return NULL;
Antoine Pitrou950468e2011-10-11 22:45:48 +02001876 if (max_char < 256)
1877 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, u, u + size,
1878 PyUnicode_1BYTE_DATA(res));
1879 else if (max_char < 0x10000)
1880 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, u, u + size,
1881 PyUnicode_2BYTE_DATA(res));
1882 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001883 memcpy(PyUnicode_4BYTE_DATA(res), u, sizeof(Py_UCS4)*size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001884 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001885 return res;
1886}
1887
1888PyObject*
1889PyUnicode_FromKindAndData(int kind, const void *buffer, Py_ssize_t size)
1890{
Victor Stinnercfed46e2011-11-22 01:29:14 +01001891 if (size < 0) {
1892 PyErr_SetString(PyExc_ValueError, "size must be positive");
1893 return NULL;
1894 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001895 switch(kind) {
1896 case PyUnicode_1BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02001897 return _PyUnicode_FromUCS1(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001898 case PyUnicode_2BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02001899 return _PyUnicode_FromUCS2(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001900 case PyUnicode_4BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02001901 return _PyUnicode_FromUCS4(buffer, size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001902 default:
Victor Stinnerb9275c12011-10-05 14:01:42 +02001903 PyErr_SetString(PyExc_SystemError, "invalid kind");
1904 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001905 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001906}
1907
Victor Stinner25a4b292011-10-06 12:31:55 +02001908/* Ensure that a string uses the most efficient storage, if it is not the
1909 case: create a new string with of the right kind. Write NULL into *p_unicode
1910 on error. */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02001911static void
Victor Stinner25a4b292011-10-06 12:31:55 +02001912unicode_adjust_maxchar(PyObject **p_unicode)
1913{
1914 PyObject *unicode, *copy;
1915 Py_UCS4 max_char;
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001916 Py_ssize_t len;
Victor Stinner25a4b292011-10-06 12:31:55 +02001917 unsigned int kind;
1918
1919 assert(p_unicode != NULL);
1920 unicode = *p_unicode;
1921 assert(PyUnicode_IS_READY(unicode));
1922 if (PyUnicode_IS_ASCII(unicode))
1923 return;
1924
1925 len = PyUnicode_GET_LENGTH(unicode);
1926 kind = PyUnicode_KIND(unicode);
1927 if (kind == PyUnicode_1BYTE_KIND) {
1928 const Py_UCS1 *u = PyUnicode_1BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001929 max_char = ucs1lib_find_max_char(u, u + len);
1930 if (max_char >= 128)
1931 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02001932 }
1933 else if (kind == PyUnicode_2BYTE_KIND) {
1934 const Py_UCS2 *u = PyUnicode_2BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001935 max_char = ucs2lib_find_max_char(u, u + len);
1936 if (max_char >= 256)
1937 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02001938 }
1939 else {
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001940 const Py_UCS4 *u = PyUnicode_4BYTE_DATA(unicode);
Victor Stinner25a4b292011-10-06 12:31:55 +02001941 assert(kind == PyUnicode_4BYTE_KIND);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001942 max_char = ucs4lib_find_max_char(u, u + len);
1943 if (max_char >= 0x10000)
1944 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02001945 }
Victor Stinner25a4b292011-10-06 12:31:55 +02001946 copy = PyUnicode_New(len, max_char);
1947 copy_characters(copy, 0, unicode, 0, len);
1948 Py_DECREF(unicode);
1949 *p_unicode = copy;
1950}
1951
Victor Stinner034f6cf2011-09-30 02:26:44 +02001952PyObject*
Victor Stinnerbf6e5602011-12-12 01:53:47 +01001953_PyUnicode_Copy(PyObject *unicode)
Victor Stinner034f6cf2011-09-30 02:26:44 +02001954{
Victor Stinner87af4f22011-11-21 23:03:47 +01001955 Py_ssize_t length;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02001956 PyObject *copy;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02001957
Victor Stinner034f6cf2011-09-30 02:26:44 +02001958 if (!PyUnicode_Check(unicode)) {
1959 PyErr_BadInternalCall();
1960 return NULL;
1961 }
1962 if (PyUnicode_READY(unicode))
1963 return NULL;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02001964
Victor Stinner87af4f22011-11-21 23:03:47 +01001965 length = PyUnicode_GET_LENGTH(unicode);
1966 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02001967 if (!copy)
1968 return NULL;
1969 assert(PyUnicode_KIND(copy) == PyUnicode_KIND(unicode));
1970
Victor Stinner87af4f22011-11-21 23:03:47 +01001971 Py_MEMCPY(PyUnicode_DATA(copy), PyUnicode_DATA(unicode),
1972 length * PyUnicode_KIND(unicode));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001973 assert(_PyUnicode_CheckConsistency(copy, 1));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02001974 return copy;
Victor Stinner034f6cf2011-09-30 02:26:44 +02001975}
1976
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001977
Victor Stinnerbc603d12011-10-02 01:00:40 +02001978/* Widen Unicode objects to larger buffers. Don't write terminating null
1979 character. Return NULL on error. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001980
1981void*
1982_PyUnicode_AsKind(PyObject *s, unsigned int kind)
1983{
Victor Stinnerbc603d12011-10-02 01:00:40 +02001984 Py_ssize_t len;
1985 void *result;
1986 unsigned int skind;
1987
1988 if (PyUnicode_READY(s))
1989 return NULL;
1990
1991 len = PyUnicode_GET_LENGTH(s);
1992 skind = PyUnicode_KIND(s);
1993 if (skind >= kind) {
Victor Stinner01698042011-10-04 00:04:26 +02001994 PyErr_SetString(PyExc_SystemError, "invalid widening attempt");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001995 return NULL;
1996 }
1997 switch(kind) {
Victor Stinnerbc603d12011-10-02 01:00:40 +02001998 case PyUnicode_2BYTE_KIND:
1999 result = PyMem_Malloc(len * sizeof(Py_UCS2));
2000 if (!result)
2001 return PyErr_NoMemory();
2002 assert(skind == PyUnicode_1BYTE_KIND);
2003 _PyUnicode_CONVERT_BYTES(
2004 Py_UCS1, Py_UCS2,
2005 PyUnicode_1BYTE_DATA(s),
2006 PyUnicode_1BYTE_DATA(s) + len,
2007 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002008 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002009 case PyUnicode_4BYTE_KIND:
2010 result = PyMem_Malloc(len * sizeof(Py_UCS4));
2011 if (!result)
2012 return PyErr_NoMemory();
2013 if (skind == PyUnicode_2BYTE_KIND) {
2014 _PyUnicode_CONVERT_BYTES(
2015 Py_UCS2, Py_UCS4,
2016 PyUnicode_2BYTE_DATA(s),
2017 PyUnicode_2BYTE_DATA(s) + len,
2018 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002019 }
Victor Stinnerbc603d12011-10-02 01:00:40 +02002020 else {
2021 assert(skind == PyUnicode_1BYTE_KIND);
2022 _PyUnicode_CONVERT_BYTES(
2023 Py_UCS1, Py_UCS4,
2024 PyUnicode_1BYTE_DATA(s),
2025 PyUnicode_1BYTE_DATA(s) + len,
2026 result);
2027 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002028 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002029 default:
2030 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002031 }
Victor Stinner01698042011-10-04 00:04:26 +02002032 PyErr_SetString(PyExc_SystemError, "invalid kind");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002033 return NULL;
2034}
2035
2036static Py_UCS4*
2037as_ucs4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2038 int copy_null)
2039{
2040 int kind;
2041 void *data;
2042 Py_ssize_t len, targetlen;
2043 if (PyUnicode_READY(string) == -1)
2044 return NULL;
2045 kind = PyUnicode_KIND(string);
2046 data = PyUnicode_DATA(string);
2047 len = PyUnicode_GET_LENGTH(string);
2048 targetlen = len;
2049 if (copy_null)
2050 targetlen++;
2051 if (!target) {
2052 if (PY_SSIZE_T_MAX / sizeof(Py_UCS4) < targetlen) {
2053 PyErr_NoMemory();
2054 return NULL;
2055 }
2056 target = PyMem_Malloc(targetlen * sizeof(Py_UCS4));
2057 if (!target) {
2058 PyErr_NoMemory();
2059 return NULL;
2060 }
2061 }
2062 else {
2063 if (targetsize < targetlen) {
2064 PyErr_Format(PyExc_SystemError,
2065 "string is longer than the buffer");
2066 if (copy_null && 0 < targetsize)
2067 target[0] = 0;
2068 return NULL;
2069 }
2070 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002071 if (kind == PyUnicode_1BYTE_KIND) {
2072 Py_UCS1 *start = (Py_UCS1 *) data;
2073 _PyUnicode_CONVERT_BYTES(Py_UCS1, Py_UCS4, start, start + len, target);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002074 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002075 else if (kind == PyUnicode_2BYTE_KIND) {
2076 Py_UCS2 *start = (Py_UCS2 *) data;
2077 _PyUnicode_CONVERT_BYTES(Py_UCS2, Py_UCS4, start, start + len, target);
2078 }
2079 else {
2080 assert(kind == PyUnicode_4BYTE_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002081 Py_MEMCPY(target, data, len * sizeof(Py_UCS4));
Antoine Pitrou950468e2011-10-11 22:45:48 +02002082 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002083 if (copy_null)
2084 target[len] = 0;
2085 return target;
2086}
2087
2088Py_UCS4*
2089PyUnicode_AsUCS4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2090 int copy_null)
2091{
Antoine Pitroude20b0b2011-11-10 21:47:38 +01002092 if (target == NULL || targetsize < 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002093 PyErr_BadInternalCall();
2094 return NULL;
2095 }
2096 return as_ucs4(string, target, targetsize, copy_null);
2097}
2098
2099Py_UCS4*
2100PyUnicode_AsUCS4Copy(PyObject *string)
2101{
2102 return as_ucs4(string, NULL, 0, 1);
2103}
2104
2105#ifdef HAVE_WCHAR_H
Mark Dickinson081dfee2009-03-18 14:47:41 +00002106
Alexander Belopolsky40018472011-02-26 01:02:56 +00002107PyObject *
2108PyUnicode_FromWideChar(register const wchar_t *w, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002109{
Guido van Rossumd57fd912000-03-10 22:53:23 +00002110 if (w == NULL) {
Victor Stinner382955f2011-12-11 21:44:00 +01002111 if (size == 0) {
2112 Py_INCREF(unicode_empty);
2113 return unicode_empty;
2114 }
Benjamin Peterson29060642009-01-31 22:14:21 +00002115 PyErr_BadInternalCall();
2116 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002117 }
2118
Martin v. Löwis790465f2008-04-05 20:41:37 +00002119 if (size == -1) {
2120 size = wcslen(w);
2121 }
2122
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002123 return PyUnicode_FromUnicode(w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002124}
2125
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002126#endif /* HAVE_WCHAR_H */
Mark Dickinson081dfee2009-03-18 14:47:41 +00002127
Walter Dörwald346737f2007-05-31 10:44:43 +00002128static void
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002129makefmt(char *fmt, int longflag, int longlongflag, int size_tflag,
2130 int zeropad, int width, int precision, char c)
Walter Dörwald346737f2007-05-31 10:44:43 +00002131{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002132 *fmt++ = '%';
2133 if (width) {
2134 if (zeropad)
2135 *fmt++ = '0';
2136 fmt += sprintf(fmt, "%d", width);
2137 }
2138 if (precision)
2139 fmt += sprintf(fmt, ".%d", precision);
2140 if (longflag)
2141 *fmt++ = 'l';
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002142 else if (longlongflag) {
2143 /* longlongflag should only ever be nonzero on machines with
2144 HAVE_LONG_LONG defined */
2145#ifdef HAVE_LONG_LONG
2146 char *f = PY_FORMAT_LONG_LONG;
2147 while (*f)
2148 *fmt++ = *f++;
2149#else
2150 /* we shouldn't ever get here */
2151 assert(0);
2152 *fmt++ = 'l';
2153#endif
2154 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002155 else if (size_tflag) {
2156 char *f = PY_FORMAT_SIZE_T;
2157 while (*f)
2158 *fmt++ = *f++;
2159 }
2160 *fmt++ = c;
2161 *fmt = '\0';
Walter Dörwald346737f2007-05-31 10:44:43 +00002162}
2163
Victor Stinner96865452011-03-01 23:44:09 +00002164/* helper for PyUnicode_FromFormatV() */
2165
2166static const char*
2167parse_format_flags(const char *f,
2168 int *p_width, int *p_precision,
2169 int *p_longflag, int *p_longlongflag, int *p_size_tflag)
2170{
2171 int width, precision, longflag, longlongflag, size_tflag;
2172
2173 /* parse the width.precision part, e.g. "%2.5s" => width=2, precision=5 */
2174 f++;
2175 width = 0;
2176 while (Py_ISDIGIT((unsigned)*f))
2177 width = (width*10) + *f++ - '0';
2178 precision = 0;
2179 if (*f == '.') {
2180 f++;
2181 while (Py_ISDIGIT((unsigned)*f))
2182 precision = (precision*10) + *f++ - '0';
2183 if (*f == '%') {
2184 /* "%.3%s" => f points to "3" */
2185 f--;
2186 }
2187 }
2188 if (*f == '\0') {
2189 /* bogus format "%.1" => go backward, f points to "1" */
2190 f--;
2191 }
2192 if (p_width != NULL)
2193 *p_width = width;
2194 if (p_precision != NULL)
2195 *p_precision = precision;
2196
2197 /* Handle %ld, %lu, %lld and %llu. */
2198 longflag = 0;
2199 longlongflag = 0;
Victor Stinnere7faec12011-03-02 00:01:53 +00002200 size_tflag = 0;
Victor Stinner96865452011-03-01 23:44:09 +00002201
2202 if (*f == 'l') {
Victor Stinner6d970f42011-03-02 00:04:25 +00002203 if (f[1] == 'd' || f[1] == 'u' || f[1] == 'i') {
Victor Stinner96865452011-03-01 23:44:09 +00002204 longflag = 1;
2205 ++f;
2206 }
2207#ifdef HAVE_LONG_LONG
2208 else if (f[1] == 'l' &&
Victor Stinner6d970f42011-03-02 00:04:25 +00002209 (f[2] == 'd' || f[2] == 'u' || f[2] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002210 longlongflag = 1;
2211 f += 2;
2212 }
2213#endif
2214 }
2215 /* handle the size_t flag. */
Victor Stinner6d970f42011-03-02 00:04:25 +00002216 else if (*f == 'z' && (f[1] == 'd' || f[1] == 'u' || f[1] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002217 size_tflag = 1;
2218 ++f;
2219 }
2220 if (p_longflag != NULL)
2221 *p_longflag = longflag;
2222 if (p_longlongflag != NULL)
2223 *p_longlongflag = longlongflag;
2224 if (p_size_tflag != NULL)
2225 *p_size_tflag = size_tflag;
2226 return f;
2227}
2228
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002229/* maximum number of characters required for output of %ld. 21 characters
2230 allows for 64-bit integers (in decimal) and an optional sign. */
2231#define MAX_LONG_CHARS 21
2232/* maximum number of characters required for output of %lld.
2233 We need at most ceil(log10(256)*SIZEOF_LONG_LONG) digits,
2234 plus 1 for the sign. 53/22 is an upper bound for log10(256). */
2235#define MAX_LONG_LONG_CHARS (2 + (SIZEOF_LONG_LONG*53-1) / 22)
2236
Walter Dörwaldd2034312007-05-18 16:29:38 +00002237PyObject *
2238PyUnicode_FromFormatV(const char *format, va_list vargs)
2239{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002240 va_list count;
2241 Py_ssize_t callcount = 0;
2242 PyObject **callresults = NULL;
2243 PyObject **callresult = NULL;
2244 Py_ssize_t n = 0;
2245 int width = 0;
2246 int precision = 0;
2247 int zeropad;
2248 const char* f;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002249 PyObject *string;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002250 /* used by sprintf */
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002251 char fmt[61]; /* should be enough for %0width.precisionlld */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002252 Py_UCS4 maxchar = 127; /* result is ASCII by default */
2253 Py_UCS4 argmaxchar;
2254 Py_ssize_t numbersize = 0;
2255 char *numberresults = NULL;
2256 char *numberresult = NULL;
2257 Py_ssize_t i;
2258 int kind;
2259 void *data;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002260
Victor Stinner4a2b7a12010-08-13 14:03:48 +00002261 Py_VA_COPY(count, vargs);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002262 /* step 1: count the number of %S/%R/%A/%s format specifications
2263 * (we call PyObject_Str()/PyObject_Repr()/PyObject_ASCII()/
2264 * PyUnicode_DecodeUTF8() for these objects once during step 3 and put the
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002265 * result in an array)
Georg Brandl7597add2011-10-05 16:36:47 +02002266 * also estimate a upper bound for all the number formats in the string,
2267 * numbers will be formatted in step 3 and be kept in a '\0'-separated
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002268 * buffer before putting everything together. */
Benjamin Peterson14339b62009-01-31 16:36:08 +00002269 for (f = format; *f; f++) {
2270 if (*f == '%') {
Victor Stinner96865452011-03-01 23:44:09 +00002271 int longlongflag;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002272 /* skip width or width.precision (eg. "1.2" of "%1.2f") */
2273 f = parse_format_flags(f, &width, NULL, NULL, &longlongflag, NULL);
2274 if (*f == 's' || *f=='S' || *f=='R' || *f=='A' || *f=='V')
2275 ++callcount;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002276
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002277 else if (*f == 'd' || *f=='u' || *f=='i' || *f=='x' || *f=='p') {
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002278#ifdef HAVE_LONG_LONG
2279 if (longlongflag) {
2280 if (width < MAX_LONG_LONG_CHARS)
2281 width = MAX_LONG_LONG_CHARS;
2282 }
2283 else
2284#endif
2285 /* MAX_LONG_CHARS is enough to hold a 64-bit integer,
2286 including sign. Decimal takes the most space. This
2287 isn't enough for octal. If a width is specified we
2288 need more (which we allocate later). */
2289 if (width < MAX_LONG_CHARS)
2290 width = MAX_LONG_CHARS;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002291
2292 /* account for the size + '\0' to separate numbers
2293 inside of the numberresults buffer */
2294 numbersize += (width + 1);
2295 }
2296 }
2297 else if ((unsigned char)*f > 127) {
2298 PyErr_Format(PyExc_ValueError,
2299 "PyUnicode_FromFormatV() expects an ASCII-encoded format "
2300 "string, got a non-ASCII byte: 0x%02x",
2301 (unsigned char)*f);
2302 return NULL;
2303 }
2304 }
2305 /* step 2: allocate memory for the results of
2306 * PyObject_Str()/PyObject_Repr()/PyUnicode_DecodeUTF8() calls */
2307 if (callcount) {
2308 callresults = PyObject_Malloc(sizeof(PyObject *) * callcount);
2309 if (!callresults) {
2310 PyErr_NoMemory();
2311 return NULL;
2312 }
2313 callresult = callresults;
2314 }
2315 /* step 2.5: allocate memory for the results of formating numbers */
2316 if (numbersize) {
2317 numberresults = PyObject_Malloc(numbersize);
2318 if (!numberresults) {
2319 PyErr_NoMemory();
2320 goto fail;
2321 }
2322 numberresult = numberresults;
2323 }
2324
2325 /* step 3: format numbers and figure out how large a buffer we need */
2326 for (f = format; *f; f++) {
2327 if (*f == '%') {
2328 const char* p;
2329 int longflag;
2330 int longlongflag;
2331 int size_tflag;
2332 int numprinted;
2333
2334 p = f;
2335 zeropad = (f[1] == '0');
2336 f = parse_format_flags(f, &width, &precision,
2337 &longflag, &longlongflag, &size_tflag);
2338 switch (*f) {
2339 case 'c':
2340 {
2341 Py_UCS4 ordinal = va_arg(count, int);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002342 maxchar = Py_MAX(maxchar, ordinal);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002343 n++;
2344 break;
2345 }
2346 case '%':
2347 n++;
2348 break;
2349 case 'i':
2350 case 'd':
2351 makefmt(fmt, longflag, longlongflag, size_tflag, zeropad,
2352 width, precision, *f);
2353 if (longflag)
2354 numprinted = sprintf(numberresult, fmt,
2355 va_arg(count, long));
2356#ifdef HAVE_LONG_LONG
2357 else if (longlongflag)
2358 numprinted = sprintf(numberresult, fmt,
2359 va_arg(count, PY_LONG_LONG));
2360#endif
2361 else if (size_tflag)
2362 numprinted = sprintf(numberresult, fmt,
2363 va_arg(count, Py_ssize_t));
2364 else
2365 numprinted = sprintf(numberresult, fmt,
2366 va_arg(count, int));
2367 n += numprinted;
2368 /* advance by +1 to skip over the '\0' */
2369 numberresult += (numprinted + 1);
2370 assert(*(numberresult - 1) == '\0');
2371 assert(*(numberresult - 2) != '\0');
2372 assert(numprinted >= 0);
2373 assert(numberresult <= numberresults + numbersize);
2374 break;
2375 case 'u':
2376 makefmt(fmt, longflag, longlongflag, size_tflag, zeropad,
2377 width, precision, 'u');
2378 if (longflag)
2379 numprinted = sprintf(numberresult, fmt,
2380 va_arg(count, unsigned long));
2381#ifdef HAVE_LONG_LONG
2382 else if (longlongflag)
2383 numprinted = sprintf(numberresult, fmt,
2384 va_arg(count, unsigned PY_LONG_LONG));
2385#endif
2386 else if (size_tflag)
2387 numprinted = sprintf(numberresult, fmt,
2388 va_arg(count, size_t));
2389 else
2390 numprinted = sprintf(numberresult, fmt,
2391 va_arg(count, unsigned int));
2392 n += numprinted;
2393 numberresult += (numprinted + 1);
2394 assert(*(numberresult - 1) == '\0');
2395 assert(*(numberresult - 2) != '\0');
2396 assert(numprinted >= 0);
2397 assert(numberresult <= numberresults + numbersize);
2398 break;
2399 case 'x':
2400 makefmt(fmt, 0, 0, 0, zeropad, width, precision, 'x');
2401 numprinted = sprintf(numberresult, fmt, va_arg(count, int));
2402 n += numprinted;
2403 numberresult += (numprinted + 1);
2404 assert(*(numberresult - 1) == '\0');
2405 assert(*(numberresult - 2) != '\0');
2406 assert(numprinted >= 0);
2407 assert(numberresult <= numberresults + numbersize);
2408 break;
2409 case 'p':
2410 numprinted = sprintf(numberresult, "%p", va_arg(count, void*));
2411 /* %p is ill-defined: ensure leading 0x. */
2412 if (numberresult[1] == 'X')
2413 numberresult[1] = 'x';
2414 else if (numberresult[1] != 'x') {
2415 memmove(numberresult + 2, numberresult,
2416 strlen(numberresult) + 1);
2417 numberresult[0] = '0';
2418 numberresult[1] = 'x';
2419 numprinted += 2;
2420 }
2421 n += numprinted;
2422 numberresult += (numprinted + 1);
2423 assert(*(numberresult - 1) == '\0');
2424 assert(*(numberresult - 2) != '\0');
2425 assert(numprinted >= 0);
2426 assert(numberresult <= numberresults + numbersize);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002427 break;
2428 case 's':
2429 {
2430 /* UTF-8 */
Georg Brandl780b2a62009-05-05 09:19:59 +00002431 const char *s = va_arg(count, const char*);
Victor Stinnera1d12bb2011-12-11 21:53:09 +01002432 PyObject *str = PyUnicode_DecodeUTF8Stateful(s, strlen(s), "replace", NULL);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002433 if (!str)
2434 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002435 /* since PyUnicode_DecodeUTF8 returns already flexible
2436 unicode objects, there is no need to call ready on them */
2437 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002438 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002439 n += PyUnicode_GET_LENGTH(str);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002440 /* Remember the str and switch to the next slot */
2441 *callresult++ = str;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002442 break;
2443 }
2444 case 'U':
2445 {
2446 PyObject *obj = va_arg(count, PyObject *);
Victor Stinner910337b2011-10-03 03:20:16 +02002447 assert(obj && _PyUnicode_CHECK(obj));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002448 if (PyUnicode_READY(obj) == -1)
2449 goto fail;
2450 argmaxchar = PyUnicode_MAX_CHAR_VALUE(obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002451 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002452 n += PyUnicode_GET_LENGTH(obj);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002453 break;
2454 }
2455 case 'V':
2456 {
2457 PyObject *obj = va_arg(count, PyObject *);
2458 const char *str = va_arg(count, const char *);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002459 PyObject *str_obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002460 assert(obj || str);
Victor Stinner910337b2011-10-03 03:20:16 +02002461 assert(!obj || _PyUnicode_CHECK(obj));
Victor Stinner2512a8b2011-03-01 22:46:52 +00002462 if (obj) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002463 if (PyUnicode_READY(obj) == -1)
2464 goto fail;
2465 argmaxchar = PyUnicode_MAX_CHAR_VALUE(obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002466 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002467 n += PyUnicode_GET_LENGTH(obj);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002468 *callresult++ = NULL;
2469 }
2470 else {
Victor Stinnera1d12bb2011-12-11 21:53:09 +01002471 str_obj = PyUnicode_DecodeUTF8Stateful(str, strlen(str), "replace", NULL);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002472 if (!str_obj)
2473 goto fail;
Victor Stinnere1335c72011-10-04 20:53:03 +02002474 if (PyUnicode_READY(str_obj)) {
2475 Py_DECREF(str_obj);
2476 goto fail;
2477 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002478 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str_obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002479 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002480 n += PyUnicode_GET_LENGTH(str_obj);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002481 *callresult++ = str_obj;
2482 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002483 break;
2484 }
2485 case 'S':
2486 {
2487 PyObject *obj = va_arg(count, PyObject *);
2488 PyObject *str;
2489 assert(obj);
2490 str = PyObject_Str(obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002491 if (!str || PyUnicode_READY(str) == -1)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002492 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002493 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002494 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002495 n += PyUnicode_GET_LENGTH(str);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002496 /* Remember the str and switch to the next slot */
2497 *callresult++ = str;
2498 break;
2499 }
2500 case 'R':
2501 {
2502 PyObject *obj = va_arg(count, PyObject *);
2503 PyObject *repr;
2504 assert(obj);
2505 repr = PyObject_Repr(obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002506 if (!repr || PyUnicode_READY(repr) == -1)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002507 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002508 argmaxchar = PyUnicode_MAX_CHAR_VALUE(repr);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002509 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002510 n += PyUnicode_GET_LENGTH(repr);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002511 /* Remember the repr and switch to the next slot */
2512 *callresult++ = repr;
2513 break;
2514 }
2515 case 'A':
2516 {
2517 PyObject *obj = va_arg(count, PyObject *);
2518 PyObject *ascii;
2519 assert(obj);
2520 ascii = PyObject_ASCII(obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002521 if (!ascii || PyUnicode_READY(ascii) == -1)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002522 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002523 argmaxchar = PyUnicode_MAX_CHAR_VALUE(ascii);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002524 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002525 n += PyUnicode_GET_LENGTH(ascii);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002526 /* Remember the repr and switch to the next slot */
2527 *callresult++ = ascii;
2528 break;
2529 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002530 default:
2531 /* if we stumble upon an unknown
2532 formatting code, copy the rest of
2533 the format string to the output
2534 string. (we cannot just skip the
2535 code, since there's no way to know
2536 what's in the argument list) */
2537 n += strlen(p);
2538 goto expand;
2539 }
2540 } else
2541 n++;
2542 }
Benjamin Peterson29060642009-01-31 22:14:21 +00002543 expand:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002544 /* step 4: fill the buffer */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002545 /* Since we've analyzed how much space we need,
Benjamin Peterson14339b62009-01-31 16:36:08 +00002546 we don't have to resize the string.
2547 There can be no errors beyond this point. */
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002548 string = PyUnicode_New(n, maxchar);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002549 if (!string)
2550 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002551 kind = PyUnicode_KIND(string);
2552 data = PyUnicode_DATA(string);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002553 callresult = callresults;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002554 numberresult = numberresults;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002555
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002556 for (i = 0, f = format; *f; f++) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00002557 if (*f == '%') {
Victor Stinner96865452011-03-01 23:44:09 +00002558 const char* p;
Victor Stinner96865452011-03-01 23:44:09 +00002559
2560 p = f;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002561 f = parse_format_flags(f, NULL, NULL, NULL, NULL, NULL);
2562 /* checking for == because the last argument could be a empty
2563 string, which causes i to point to end, the assert at the end of
2564 the loop */
2565 assert(i <= PyUnicode_GET_LENGTH(string));
Walter Dörwaldd2034312007-05-18 16:29:38 +00002566
Benjamin Peterson14339b62009-01-31 16:36:08 +00002567 switch (*f) {
2568 case 'c':
Victor Stinner5ed8b2c2011-02-21 21:13:44 +00002569 {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002570 const int ordinal = va_arg(vargs, int);
2571 PyUnicode_WRITE(kind, data, i++, ordinal);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002572 break;
Victor Stinner5ed8b2c2011-02-21 21:13:44 +00002573 }
Victor Stinner6d970f42011-03-02 00:04:25 +00002574 case 'i':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002575 case 'd':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002576 case 'u':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002577 case 'x':
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002578 case 'p':
2579 /* unused, since we already have the result */
2580 if (*f == 'p')
2581 (void) va_arg(vargs, void *);
2582 else
2583 (void) va_arg(vargs, int);
2584 /* extract the result from numberresults and append. */
2585 for (; *numberresult; ++i, ++numberresult)
2586 PyUnicode_WRITE(kind, data, i, *numberresult);
2587 /* skip over the separating '\0' */
2588 assert(*numberresult == '\0');
2589 numberresult++;
2590 assert(numberresult <= numberresults + numbersize);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002591 break;
2592 case 's':
2593 {
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002594 /* unused, since we already have the result */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002595 Py_ssize_t size;
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002596 (void) va_arg(vargs, char *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002597 size = PyUnicode_GET_LENGTH(*callresult);
2598 assert(PyUnicode_KIND(*callresult) <= PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002599 copy_characters(string, i, *callresult, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002600 i += size;
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002601 /* We're done with the unicode()/repr() => forget it */
2602 Py_DECREF(*callresult);
2603 /* switch to next unicode()/repr() result */
2604 ++callresult;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002605 break;
2606 }
2607 case 'U':
2608 {
2609 PyObject *obj = va_arg(vargs, PyObject *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002610 Py_ssize_t size;
2611 assert(PyUnicode_KIND(obj) <= PyUnicode_KIND(string));
2612 size = PyUnicode_GET_LENGTH(obj);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002613 copy_characters(string, i, obj, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002614 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002615 break;
2616 }
2617 case 'V':
2618 {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002619 Py_ssize_t size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002620 PyObject *obj = va_arg(vargs, PyObject *);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002621 va_arg(vargs, const char *);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002622 if (obj) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002623 size = PyUnicode_GET_LENGTH(obj);
2624 assert(PyUnicode_KIND(obj) <= PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002625 copy_characters(string, i, obj, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002626 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002627 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002628 size = PyUnicode_GET_LENGTH(*callresult);
2629 assert(PyUnicode_KIND(*callresult) <=
2630 PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002631 copy_characters(string, i, *callresult, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002632 i += size;
Victor Stinner2512a8b2011-03-01 22:46:52 +00002633 Py_DECREF(*callresult);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002634 }
Victor Stinner2512a8b2011-03-01 22:46:52 +00002635 ++callresult;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002636 break;
2637 }
2638 case 'S':
2639 case 'R':
Victor Stinner9a909002010-10-18 20:59:24 +00002640 case 'A':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002641 {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002642 Py_ssize_t size = PyUnicode_GET_LENGTH(*callresult);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002643 /* unused, since we already have the result */
2644 (void) va_arg(vargs, PyObject *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002645 assert(PyUnicode_KIND(*callresult) <= PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002646 copy_characters(string, i, *callresult, 0, size);
2647 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002648 /* We're done with the unicode()/repr() => forget it */
2649 Py_DECREF(*callresult);
2650 /* switch to next unicode()/repr() result */
2651 ++callresult;
2652 break;
2653 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002654 case '%':
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002655 PyUnicode_WRITE(kind, data, i++, '%');
Benjamin Peterson14339b62009-01-31 16:36:08 +00002656 break;
2657 default:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002658 for (; *p; ++p, ++i)
2659 PyUnicode_WRITE(kind, data, i, *p);
2660 assert(i == PyUnicode_GET_LENGTH(string));
Benjamin Peterson14339b62009-01-31 16:36:08 +00002661 goto end;
2662 }
Victor Stinner1205f272010-09-11 00:54:47 +00002663 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002664 else {
2665 assert(i < PyUnicode_GET_LENGTH(string));
2666 PyUnicode_WRITE(kind, data, i++, *f);
2667 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002668 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002669 assert(i == PyUnicode_GET_LENGTH(string));
Walter Dörwaldd2034312007-05-18 16:29:38 +00002670
Benjamin Peterson29060642009-01-31 22:14:21 +00002671 end:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002672 if (callresults)
2673 PyObject_Free(callresults);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002674 if (numberresults)
2675 PyObject_Free(numberresults);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002676 return unicode_result(string);
Benjamin Peterson29060642009-01-31 22:14:21 +00002677 fail:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002678 if (callresults) {
2679 PyObject **callresult2 = callresults;
2680 while (callresult2 < callresult) {
Victor Stinner2512a8b2011-03-01 22:46:52 +00002681 Py_XDECREF(*callresult2);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002682 ++callresult2;
2683 }
2684 PyObject_Free(callresults);
2685 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002686 if (numberresults)
2687 PyObject_Free(numberresults);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002688 return NULL;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002689}
2690
Walter Dörwaldd2034312007-05-18 16:29:38 +00002691PyObject *
2692PyUnicode_FromFormat(const char *format, ...)
2693{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002694 PyObject* ret;
2695 va_list vargs;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002696
2697#ifdef HAVE_STDARG_PROTOTYPES
Benjamin Peterson14339b62009-01-31 16:36:08 +00002698 va_start(vargs, format);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002699#else
Benjamin Peterson14339b62009-01-31 16:36:08 +00002700 va_start(vargs);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002701#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00002702 ret = PyUnicode_FromFormatV(format, vargs);
2703 va_end(vargs);
2704 return ret;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002705}
2706
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002707#ifdef HAVE_WCHAR_H
2708
Victor Stinner5593d8a2010-10-02 11:11:27 +00002709/* Helper function for PyUnicode_AsWideChar() and PyUnicode_AsWideCharString():
2710 convert a Unicode object to a wide character string.
2711
Victor Stinnerd88d9832011-09-06 02:00:05 +02002712 - If w is NULL: return the number of wide characters (including the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002713 character) required to convert the unicode object. Ignore size argument.
2714
Victor Stinnerd88d9832011-09-06 02:00:05 +02002715 - Otherwise: return the number of wide characters (excluding the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002716 character) written into w. Write at most size wide characters (including
Victor Stinnerd88d9832011-09-06 02:00:05 +02002717 the null character). */
Victor Stinner5593d8a2010-10-02 11:11:27 +00002718static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002719unicode_aswidechar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002720 wchar_t *w,
2721 Py_ssize_t size)
2722{
Victor Stinner5593d8a2010-10-02 11:11:27 +00002723 Py_ssize_t res;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002724 const wchar_t *wstr;
2725
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002726 wstr = PyUnicode_AsUnicodeAndSize(unicode, &res);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002727 if (wstr == NULL)
2728 return -1;
2729
Victor Stinner5593d8a2010-10-02 11:11:27 +00002730 if (w != NULL) {
Victor Stinner5593d8a2010-10-02 11:11:27 +00002731 if (size > res)
2732 size = res + 1;
2733 else
2734 res = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002735 Py_MEMCPY(w, wstr, size * sizeof(wchar_t));
Victor Stinner5593d8a2010-10-02 11:11:27 +00002736 return res;
2737 }
2738 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002739 return res + 1;
Victor Stinner137c34c2010-09-29 10:25:54 +00002740}
2741
2742Py_ssize_t
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002743PyUnicode_AsWideChar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002744 wchar_t *w,
2745 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002746{
2747 if (unicode == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002748 PyErr_BadInternalCall();
2749 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002750 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002751 return unicode_aswidechar(unicode, w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002752}
2753
Victor Stinner137c34c2010-09-29 10:25:54 +00002754wchar_t*
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00002755PyUnicode_AsWideCharString(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002756 Py_ssize_t *size)
2757{
2758 wchar_t* buffer;
2759 Py_ssize_t buflen;
2760
2761 if (unicode == NULL) {
2762 PyErr_BadInternalCall();
2763 return NULL;
2764 }
2765
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002766 buflen = unicode_aswidechar(unicode, NULL, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002767 if (buflen == -1)
2768 return NULL;
Victor Stinner5593d8a2010-10-02 11:11:27 +00002769 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < buflen) {
Victor Stinner137c34c2010-09-29 10:25:54 +00002770 PyErr_NoMemory();
2771 return NULL;
2772 }
2773
Victor Stinner137c34c2010-09-29 10:25:54 +00002774 buffer = PyMem_MALLOC(buflen * sizeof(wchar_t));
2775 if (buffer == NULL) {
2776 PyErr_NoMemory();
2777 return NULL;
2778 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002779 buflen = unicode_aswidechar(unicode, buffer, buflen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002780 if (buflen == -1)
2781 return NULL;
Victor Stinner5593d8a2010-10-02 11:11:27 +00002782 if (size != NULL)
2783 *size = buflen;
Victor Stinner137c34c2010-09-29 10:25:54 +00002784 return buffer;
2785}
2786
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002787#endif /* HAVE_WCHAR_H */
Guido van Rossumd57fd912000-03-10 22:53:23 +00002788
Alexander Belopolsky40018472011-02-26 01:02:56 +00002789PyObject *
2790PyUnicode_FromOrdinal(int ordinal)
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002791{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002792 PyObject *v;
Victor Stinner8faf8212011-12-08 22:14:11 +01002793 if (ordinal < 0 || ordinal > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002794 PyErr_SetString(PyExc_ValueError,
2795 "chr() arg not in range(0x110000)");
2796 return NULL;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002797 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00002798
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002799 if (ordinal < 256)
2800 return get_latin1_char(ordinal);
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002801
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002802 v = PyUnicode_New(1, ordinal);
2803 if (v == NULL)
2804 return NULL;
2805 PyUnicode_WRITE(PyUnicode_KIND(v), PyUnicode_DATA(v), 0, ordinal);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002806 assert(_PyUnicode_CheckConsistency(v, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002807 return v;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002808}
2809
Alexander Belopolsky40018472011-02-26 01:02:56 +00002810PyObject *
2811PyUnicode_FromObject(register PyObject *obj)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002812{
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002813 /* XXX Perhaps we should make this API an alias of
Benjamin Peterson29060642009-01-31 22:14:21 +00002814 PyObject_Str() instead ?! */
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002815 if (PyUnicode_CheckExact(obj)) {
Victor Stinnerd3a83d52011-10-01 03:09:33 +02002816 if (PyUnicode_READY(obj))
2817 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +00002818 Py_INCREF(obj);
2819 return obj;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002820 }
2821 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002822 /* For a Unicode subtype that's not a Unicode object,
2823 return a true Unicode object with the same data. */
Victor Stinnerbf6e5602011-12-12 01:53:47 +01002824 return _PyUnicode_Copy(obj);
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002825 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00002826 PyErr_Format(PyExc_TypeError,
2827 "Can't convert '%.100s' object to str implicitly",
Christian Heimes90aa7642007-12-19 02:45:37 +00002828 Py_TYPE(obj)->tp_name);
Guido van Rossum98297ee2007-11-06 21:34:58 +00002829 return NULL;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002830}
2831
Alexander Belopolsky40018472011-02-26 01:02:56 +00002832PyObject *
2833PyUnicode_FromEncodedObject(register PyObject *obj,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002834 const char *encoding,
2835 const char *errors)
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002836{
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002837 Py_buffer buffer;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002838 PyObject *v;
Tim Petersced69f82003-09-16 20:30:58 +00002839
Guido van Rossumd57fd912000-03-10 22:53:23 +00002840 if (obj == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002841 PyErr_BadInternalCall();
2842 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002843 }
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002844
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002845 /* Decoding bytes objects is the most common case and should be fast */
2846 if (PyBytes_Check(obj)) {
2847 if (PyBytes_GET_SIZE(obj) == 0) {
2848 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02002849 v = unicode_empty;
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002850 }
2851 else {
2852 v = PyUnicode_Decode(
2853 PyBytes_AS_STRING(obj), PyBytes_GET_SIZE(obj),
2854 encoding, errors);
2855 }
2856 return v;
2857 }
2858
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002859 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002860 PyErr_SetString(PyExc_TypeError,
2861 "decoding str is not supported");
2862 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002863 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002864
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002865 /* Retrieve a bytes buffer view through the PEP 3118 buffer interface */
2866 if (PyObject_GetBuffer(obj, &buffer, PyBUF_SIMPLE) < 0) {
2867 PyErr_Format(PyExc_TypeError,
2868 "coercing to str: need bytes, bytearray "
2869 "or buffer-like object, %.80s found",
2870 Py_TYPE(obj)->tp_name);
2871 return NULL;
Marc-André Lemburg6871f6a2001-09-20 12:53:16 +00002872 }
Tim Petersced69f82003-09-16 20:30:58 +00002873
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002874 if (buffer.len == 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002875 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02002876 v = unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002877 }
Tim Petersced69f82003-09-16 20:30:58 +00002878 else
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002879 v = PyUnicode_Decode((char*) buffer.buf, buffer.len, encoding, errors);
Marc-André Lemburgad7c98e2001-01-17 17:09:53 +00002880
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002881 PyBuffer_Release(&buffer);
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002882 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002883}
2884
Victor Stinner600d3be2010-06-10 12:00:55 +00002885/* Convert encoding to lower case and replace '_' with '-' in order to
Victor Stinner37296e82010-06-10 13:36:23 +00002886 catch e.g. UTF_8. Return 0 on error (encoding is longer than lower_len-1),
2887 1 on success. */
2888static int
2889normalize_encoding(const char *encoding,
2890 char *lower,
2891 size_t lower_len)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002892{
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002893 const char *e;
Victor Stinner600d3be2010-06-10 12:00:55 +00002894 char *l;
2895 char *l_end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002896
Benjamin Peterson7a6debe2011-10-15 09:25:28 -04002897 if (encoding == NULL) {
2898 strcpy(lower, "utf-8");
2899 return 1;
2900 }
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002901 e = encoding;
2902 l = lower;
Victor Stinner600d3be2010-06-10 12:00:55 +00002903 l_end = &lower[lower_len - 1];
Victor Stinner37296e82010-06-10 13:36:23 +00002904 while (*e) {
2905 if (l == l_end)
2906 return 0;
David Malcolm96960882010-11-05 17:23:41 +00002907 if (Py_ISUPPER(*e)) {
2908 *l++ = Py_TOLOWER(*e++);
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002909 }
2910 else if (*e == '_') {
2911 *l++ = '-';
2912 e++;
2913 }
2914 else {
2915 *l++ = *e++;
2916 }
2917 }
2918 *l = '\0';
Victor Stinner37296e82010-06-10 13:36:23 +00002919 return 1;
Victor Stinner600d3be2010-06-10 12:00:55 +00002920}
2921
Alexander Belopolsky40018472011-02-26 01:02:56 +00002922PyObject *
2923PyUnicode_Decode(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002924 Py_ssize_t size,
2925 const char *encoding,
2926 const char *errors)
Victor Stinner600d3be2010-06-10 12:00:55 +00002927{
2928 PyObject *buffer = NULL, *unicode;
2929 Py_buffer info;
2930 char lower[11]; /* Enough for any encoding shortcut */
2931
Fred Drakee4315f52000-05-09 19:53:39 +00002932 /* Shortcuts for common default encodings */
Victor Stinner37296e82010-06-10 13:36:23 +00002933 if (normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00002934 if ((strcmp(lower, "utf-8") == 0) ||
2935 (strcmp(lower, "utf8") == 0))
Victor Stinnera1d12bb2011-12-11 21:53:09 +01002936 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
Victor Stinner37296e82010-06-10 13:36:23 +00002937 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00002938 (strcmp(lower, "latin1") == 0) ||
Victor Stinner37296e82010-06-10 13:36:23 +00002939 (strcmp(lower, "iso-8859-1") == 0))
2940 return PyUnicode_DecodeLatin1(s, size, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02002941#ifdef HAVE_MBCS
Victor Stinner37296e82010-06-10 13:36:23 +00002942 else if (strcmp(lower, "mbcs") == 0)
2943 return PyUnicode_DecodeMBCS(s, size, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00002944#endif
Victor Stinner37296e82010-06-10 13:36:23 +00002945 else if (strcmp(lower, "ascii") == 0)
2946 return PyUnicode_DecodeASCII(s, size, errors);
2947 else if (strcmp(lower, "utf-16") == 0)
2948 return PyUnicode_DecodeUTF16(s, size, errors, 0);
2949 else if (strcmp(lower, "utf-32") == 0)
2950 return PyUnicode_DecodeUTF32(s, size, errors, 0);
2951 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002952
2953 /* Decode via the codec registry */
Guido van Rossumbe801ac2007-10-08 03:32:34 +00002954 buffer = NULL;
Antoine Pitrouc3b39242009-01-03 16:59:18 +00002955 if (PyBuffer_FillInfo(&info, NULL, (void *)s, size, 1, PyBUF_FULL_RO) < 0)
Guido van Rossumbe801ac2007-10-08 03:32:34 +00002956 goto onError;
Antoine Pitrouee58fa42008-08-19 18:22:14 +00002957 buffer = PyMemoryView_FromBuffer(&info);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002958 if (buffer == NULL)
2959 goto onError;
2960 unicode = PyCodec_Decode(buffer, encoding, errors);
2961 if (unicode == NULL)
2962 goto onError;
2963 if (!PyUnicode_Check(unicode)) {
2964 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00002965 "decoder did not return a str object (type=%.400s)",
Christian Heimes90aa7642007-12-19 02:45:37 +00002966 Py_TYPE(unicode)->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002967 Py_DECREF(unicode);
2968 goto onError;
2969 }
2970 Py_DECREF(buffer);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002971 return unicode_result(unicode);
Tim Petersced69f82003-09-16 20:30:58 +00002972
Benjamin Peterson29060642009-01-31 22:14:21 +00002973 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00002974 Py_XDECREF(buffer);
2975 return NULL;
2976}
2977
Alexander Belopolsky40018472011-02-26 01:02:56 +00002978PyObject *
2979PyUnicode_AsDecodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002980 const char *encoding,
2981 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002982{
2983 PyObject *v;
2984
2985 if (!PyUnicode_Check(unicode)) {
2986 PyErr_BadArgument();
2987 goto onError;
2988 }
2989
2990 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00002991 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002992
2993 /* Decode via the codec registry */
2994 v = PyCodec_Decode(unicode, encoding, errors);
2995 if (v == NULL)
2996 goto onError;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002997 return unicode_result(v);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002998
Benjamin Peterson29060642009-01-31 22:14:21 +00002999 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003000 return NULL;
3001}
3002
Alexander Belopolsky40018472011-02-26 01:02:56 +00003003PyObject *
3004PyUnicode_AsDecodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003005 const char *encoding,
3006 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003007{
3008 PyObject *v;
3009
3010 if (!PyUnicode_Check(unicode)) {
3011 PyErr_BadArgument();
3012 goto onError;
3013 }
3014
3015 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003016 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003017
3018 /* Decode via the codec registry */
3019 v = PyCodec_Decode(unicode, encoding, errors);
3020 if (v == NULL)
3021 goto onError;
3022 if (!PyUnicode_Check(v)) {
3023 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00003024 "decoder did not return a str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003025 Py_TYPE(v)->tp_name);
3026 Py_DECREF(v);
3027 goto onError;
3028 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003029 return unicode_result(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003030
Benjamin Peterson29060642009-01-31 22:14:21 +00003031 onError:
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003032 return NULL;
3033}
3034
Alexander Belopolsky40018472011-02-26 01:02:56 +00003035PyObject *
3036PyUnicode_Encode(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003037 Py_ssize_t size,
3038 const char *encoding,
3039 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003040{
3041 PyObject *v, *unicode;
Tim Petersced69f82003-09-16 20:30:58 +00003042
Guido van Rossumd57fd912000-03-10 22:53:23 +00003043 unicode = PyUnicode_FromUnicode(s, size);
3044 if (unicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003045 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003046 v = PyUnicode_AsEncodedString(unicode, encoding, errors);
3047 Py_DECREF(unicode);
3048 return v;
3049}
3050
Alexander Belopolsky40018472011-02-26 01:02:56 +00003051PyObject *
3052PyUnicode_AsEncodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003053 const char *encoding,
3054 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003055{
3056 PyObject *v;
3057
3058 if (!PyUnicode_Check(unicode)) {
3059 PyErr_BadArgument();
3060 goto onError;
3061 }
3062
3063 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003064 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003065
3066 /* Encode via the codec registry */
3067 v = PyCodec_Encode(unicode, encoding, errors);
3068 if (v == NULL)
3069 goto onError;
3070 return v;
3071
Benjamin Peterson29060642009-01-31 22:14:21 +00003072 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003073 return NULL;
3074}
3075
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003076static size_t
3077wcstombs_errorpos(const wchar_t *wstr)
3078{
3079 size_t len;
3080#if SIZEOF_WCHAR_T == 2
3081 wchar_t buf[3];
3082#else
3083 wchar_t buf[2];
3084#endif
3085 char outbuf[MB_LEN_MAX];
3086 const wchar_t *start, *previous;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003087
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003088#if SIZEOF_WCHAR_T == 2
3089 buf[2] = 0;
3090#else
3091 buf[1] = 0;
3092#endif
3093 start = wstr;
3094 while (*wstr != L'\0')
3095 {
3096 previous = wstr;
3097#if SIZEOF_WCHAR_T == 2
3098 if (Py_UNICODE_IS_HIGH_SURROGATE(wstr[0])
3099 && Py_UNICODE_IS_LOW_SURROGATE(wstr[1]))
3100 {
3101 buf[0] = wstr[0];
3102 buf[1] = wstr[1];
3103 wstr += 2;
3104 }
3105 else {
3106 buf[0] = *wstr;
3107 buf[1] = 0;
3108 wstr++;
3109 }
3110#else
3111 buf[0] = *wstr;
3112 wstr++;
3113#endif
3114 len = wcstombs(outbuf, buf, sizeof(outbuf));
Victor Stinner2f197072011-12-17 07:08:30 +01003115 if (len == (size_t)-1)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003116 return previous - start;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003117 }
3118
3119 /* failed to find the unencodable character */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003120 return 0;
3121}
3122
Victor Stinner1b579672011-12-17 05:47:23 +01003123static int
3124locale_error_handler(const char *errors, int *surrogateescape)
3125{
3126 if (errors == NULL) {
3127 *surrogateescape = 0;
3128 return 0;
3129 }
3130
3131 if (strcmp(errors, "strict") == 0) {
3132 *surrogateescape = 0;
3133 return 0;
3134 }
3135 if (strcmp(errors, "surrogateescape") == 0) {
3136 *surrogateescape = 1;
3137 return 0;
3138 }
3139 PyErr_Format(PyExc_ValueError,
3140 "only 'strict' and 'surrogateescape' error handlers "
3141 "are supported, not '%s'",
3142 errors);
3143 return -1;
3144}
3145
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003146PyObject *
Victor Stinner1b579672011-12-17 05:47:23 +01003147PyUnicode_EncodeLocale(PyObject *unicode, const char *errors)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003148{
3149 Py_ssize_t wlen, wlen2;
3150 wchar_t *wstr;
3151 PyObject *bytes = NULL;
3152 char *errmsg;
Victor Stinner1f33f2b2011-12-17 04:45:09 +01003153 PyObject *reason;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003154 PyObject *exc;
3155 size_t error_pos;
Victor Stinner1b579672011-12-17 05:47:23 +01003156 int surrogateescape;
3157
3158 if (locale_error_handler(errors, &surrogateescape) < 0)
3159 return NULL;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003160
3161 wstr = PyUnicode_AsWideCharString(unicode, &wlen);
3162 if (wstr == NULL)
3163 return NULL;
3164
3165 wlen2 = wcslen(wstr);
3166 if (wlen2 != wlen) {
3167 PyMem_Free(wstr);
3168 PyErr_SetString(PyExc_TypeError, "embedded null character");
3169 return NULL;
3170 }
3171
3172 if (surrogateescape) {
3173 /* locale encoding with surrogateescape */
3174 char *str;
3175
3176 str = _Py_wchar2char(wstr, &error_pos);
3177 if (str == NULL) {
3178 if (error_pos == (size_t)-1) {
3179 PyErr_NoMemory();
3180 PyMem_Free(wstr);
3181 return NULL;
3182 }
3183 else {
3184 goto encode_error;
3185 }
3186 }
3187 PyMem_Free(wstr);
3188
3189 bytes = PyBytes_FromString(str);
3190 PyMem_Free(str);
3191 }
3192 else {
3193 size_t len, len2;
3194
3195 len = wcstombs(NULL, wstr, 0);
3196 if (len == (size_t)-1) {
Victor Stinner2f197072011-12-17 07:08:30 +01003197 error_pos = (size_t)-1;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003198 goto encode_error;
3199 }
3200
3201 bytes = PyBytes_FromStringAndSize(NULL, len);
3202 if (bytes == NULL) {
3203 PyMem_Free(wstr);
3204 return NULL;
3205 }
3206
3207 len2 = wcstombs(PyBytes_AS_STRING(bytes), wstr, len+1);
3208 if (len2 == (size_t)-1 || len2 > len) {
Victor Stinner2f197072011-12-17 07:08:30 +01003209 error_pos = (size_t)-1;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003210 goto encode_error;
3211 }
3212 PyMem_Free(wstr);
3213 }
3214 return bytes;
3215
3216encode_error:
3217 errmsg = strerror(errno);
3218 assert(errmsg != NULL);
Victor Stinner2f197072011-12-17 07:08:30 +01003219
3220 if (error_pos == (size_t)-1)
3221 error_pos = wcstombs_errorpos(wstr);
3222
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003223 PyMem_Free(wstr);
3224 Py_XDECREF(bytes);
3225
Victor Stinner2f197072011-12-17 07:08:30 +01003226 if (errmsg != NULL) {
3227 size_t errlen;
3228 wstr = _Py_char2wchar(errmsg, &errlen);
3229 if (wstr != NULL) {
3230 reason = PyUnicode_FromWideChar(wstr, errlen);
3231 PyMem_Free(wstr);
3232 } else
3233 errmsg = NULL;
3234 }
3235 if (errmsg == NULL)
Victor Stinner1f33f2b2011-12-17 04:45:09 +01003236 reason = PyUnicode_FromString(
3237 "wcstombs() encountered an unencodable "
3238 "wide character");
3239 if (reason == NULL)
3240 return NULL;
3241
3242 exc = PyObject_CallFunction(PyExc_UnicodeEncodeError, "sOnnO",
3243 "locale", unicode,
3244 (Py_ssize_t)error_pos,
3245 (Py_ssize_t)(error_pos+1),
3246 reason);
3247 Py_DECREF(reason);
3248 if (exc != NULL) {
3249 PyCodec_StrictErrors(exc);
3250 Py_XDECREF(exc);
3251 }
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003252 return NULL;
3253}
3254
Victor Stinnerad158722010-10-27 00:25:46 +00003255PyObject *
3256PyUnicode_EncodeFSDefault(PyObject *unicode)
Victor Stinnerae6265f2010-05-15 16:27:27 +00003257{
Victor Stinner99b95382011-07-04 14:23:54 +02003258#ifdef HAVE_MBCS
Victor Stinnerac931b12011-11-20 18:27:03 +01003259 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003260#elif defined(__APPLE__)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003261 return _PyUnicode_AsUTF8String(unicode, "surrogateescape");
Victor Stinnerad158722010-10-27 00:25:46 +00003262#else
Victor Stinner793b5312011-04-27 00:24:21 +02003263 PyInterpreterState *interp = PyThreadState_GET()->interp;
3264 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3265 cannot use it to encode and decode filenames before it is loaded. Load
3266 the Python codec requires to encode at least its own filename. Use the C
3267 version of the locale codec until the codec registry is initialized and
3268 the Python codec is loaded.
3269
3270 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3271 cannot only rely on it: check also interp->fscodec_initialized for
3272 subinterpreters. */
3273 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Victor Stinnerae6265f2010-05-15 16:27:27 +00003274 return PyUnicode_AsEncodedString(unicode,
3275 Py_FileSystemDefaultEncoding,
3276 "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00003277 }
3278 else {
Victor Stinner1b579672011-12-17 05:47:23 +01003279 return PyUnicode_EncodeLocale(unicode, "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00003280 }
Victor Stinnerad158722010-10-27 00:25:46 +00003281#endif
Victor Stinnerae6265f2010-05-15 16:27:27 +00003282}
3283
Alexander Belopolsky40018472011-02-26 01:02:56 +00003284PyObject *
3285PyUnicode_AsEncodedString(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003286 const char *encoding,
3287 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003288{
3289 PyObject *v;
Victor Stinner600d3be2010-06-10 12:00:55 +00003290 char lower[11]; /* Enough for any encoding shortcut */
Tim Petersced69f82003-09-16 20:30:58 +00003291
Guido van Rossumd57fd912000-03-10 22:53:23 +00003292 if (!PyUnicode_Check(unicode)) {
3293 PyErr_BadArgument();
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003294 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003295 }
Fred Drakee4315f52000-05-09 19:53:39 +00003296
Fred Drakee4315f52000-05-09 19:53:39 +00003297 /* Shortcuts for common default encodings */
Victor Stinner37296e82010-06-10 13:36:23 +00003298 if (normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003299 if ((strcmp(lower, "utf-8") == 0) ||
3300 (strcmp(lower, "utf8") == 0))
Victor Stinnera5c68c32011-03-02 01:03:14 +00003301 {
Victor Stinner2f283c22011-03-02 01:21:46 +00003302 if (errors == NULL || strcmp(errors, "strict") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003303 return _PyUnicode_AsUTF8String(unicode, NULL);
Victor Stinner2f283c22011-03-02 01:21:46 +00003304 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003305 return _PyUnicode_AsUTF8String(unicode, errors);
Victor Stinnera5c68c32011-03-02 01:03:14 +00003306 }
Victor Stinner37296e82010-06-10 13:36:23 +00003307 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003308 (strcmp(lower, "latin1") == 0) ||
Victor Stinner37296e82010-06-10 13:36:23 +00003309 (strcmp(lower, "iso-8859-1") == 0))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003310 return _PyUnicode_AsLatin1String(unicode, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02003311#ifdef HAVE_MBCS
Victor Stinnerac931b12011-11-20 18:27:03 +01003312 else if (strcmp(lower, "mbcs") == 0)
3313 return PyUnicode_EncodeCodePage(CP_ACP, unicode, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003314#endif
Victor Stinner37296e82010-06-10 13:36:23 +00003315 else if (strcmp(lower, "ascii") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003316 return _PyUnicode_AsASCIIString(unicode, errors);
Victor Stinner37296e82010-06-10 13:36:23 +00003317 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003318
3319 /* Encode via the codec registry */
3320 v = PyCodec_Encode(unicode, encoding, errors);
3321 if (v == NULL)
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003322 return NULL;
3323
3324 /* The normal path */
3325 if (PyBytes_Check(v))
3326 return v;
3327
3328 /* If the codec returns a buffer, raise a warning and convert to bytes */
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003329 if (PyByteArray_Check(v)) {
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003330 int error;
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003331 PyObject *b;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003332
3333 error = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
3334 "encoder %s returned bytearray instead of bytes",
3335 encoding);
3336 if (error) {
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003337 Py_DECREF(v);
3338 return NULL;
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003339 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003340
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003341 b = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(v), Py_SIZE(v));
3342 Py_DECREF(v);
3343 return b;
3344 }
3345
3346 PyErr_Format(PyExc_TypeError,
3347 "encoder did not return a bytes object (type=%.400s)",
3348 Py_TYPE(v)->tp_name);
3349 Py_DECREF(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003350 return NULL;
3351}
3352
Alexander Belopolsky40018472011-02-26 01:02:56 +00003353PyObject *
3354PyUnicode_AsEncodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003355 const char *encoding,
3356 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003357{
3358 PyObject *v;
3359
3360 if (!PyUnicode_Check(unicode)) {
3361 PyErr_BadArgument();
3362 goto onError;
3363 }
3364
3365 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003366 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003367
3368 /* Encode via the codec registry */
3369 v = PyCodec_Encode(unicode, encoding, errors);
3370 if (v == NULL)
3371 goto onError;
3372 if (!PyUnicode_Check(v)) {
3373 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00003374 "encoder did not return an str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003375 Py_TYPE(v)->tp_name);
3376 Py_DECREF(v);
3377 goto onError;
3378 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003379 return v;
Tim Petersced69f82003-09-16 20:30:58 +00003380
Benjamin Peterson29060642009-01-31 22:14:21 +00003381 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003382 return NULL;
3383}
3384
Victor Stinner2f197072011-12-17 07:08:30 +01003385static size_t
3386mbstowcs_errorpos(const char *str, size_t len)
3387{
3388#ifdef HAVE_MBRTOWC
3389 const char *start = str;
3390 mbstate_t mbs;
3391 size_t converted;
3392 wchar_t ch;
3393
3394 memset(&mbs, 0, sizeof mbs);
3395 while (len)
3396 {
3397 converted = mbrtowc(&ch, (char*)str, len, &mbs);
3398 if (converted == 0)
3399 /* Reached end of string */
3400 break;
3401 if (converted == (size_t)-1 || converted == (size_t)-2) {
3402 /* Conversion error or incomplete character */
3403 return str - start;
3404 }
3405 else {
3406 str += converted;
3407 len -= converted;
3408 }
3409 }
3410 /* failed to find the undecodable byte sequence */
3411 return 0;
3412#endif
3413 return 0;
3414}
3415
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003416PyObject*
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003417PyUnicode_DecodeLocaleAndSize(const char *str, Py_ssize_t len,
Victor Stinner1b579672011-12-17 05:47:23 +01003418 const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003419{
3420 wchar_t smallbuf[256];
3421 size_t smallbuf_len = Py_ARRAY_LENGTH(smallbuf);
3422 wchar_t *wstr;
3423 size_t wlen, wlen2;
3424 PyObject *unicode;
Victor Stinner1b579672011-12-17 05:47:23 +01003425 int surrogateescape;
Victor Stinner2f197072011-12-17 07:08:30 +01003426 size_t error_pos;
3427 char *errmsg;
3428 PyObject *reason, *exc;
Victor Stinner1b579672011-12-17 05:47:23 +01003429
3430 if (locale_error_handler(errors, &surrogateescape) < 0)
3431 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003432
3433 if (str[len] != '\0' || len != strlen(str)) {
3434 PyErr_SetString(PyExc_TypeError, "embedded null character");
3435 return NULL;
3436 }
3437
3438 if (surrogateescape)
3439 {
3440 wstr = _Py_char2wchar(str, &wlen);
3441 if (wstr == NULL) {
3442 if (wlen == (size_t)-1)
3443 PyErr_NoMemory();
3444 else
3445 PyErr_SetFromErrno(PyExc_OSError);
3446 return NULL;
3447 }
3448
3449 unicode = PyUnicode_FromWideChar(wstr, wlen);
3450 PyMem_Free(wstr);
3451 }
3452 else {
3453#ifndef HAVE_BROKEN_MBSTOWCS
3454 wlen = mbstowcs(NULL, str, 0);
3455#else
3456 wlen = len;
3457#endif
Victor Stinner2f197072011-12-17 07:08:30 +01003458 if (wlen == (size_t)-1)
3459 goto decode_error;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003460 if (wlen+1 <= smallbuf_len) {
3461 wstr = smallbuf;
3462 }
3463 else {
3464 if (wlen > PY_SSIZE_T_MAX / sizeof(wchar_t) - 1)
3465 return PyErr_NoMemory();
3466
3467 wstr = PyMem_Malloc((wlen+1) * sizeof(wchar_t));
3468 if (!wstr)
3469 return PyErr_NoMemory();
3470 }
3471
3472 /* This shouldn't fail now */
3473 wlen2 = mbstowcs(wstr, str, wlen+1);
3474 if (wlen2 == (size_t)-1) {
3475 if (wstr != smallbuf)
3476 PyMem_Free(wstr);
Victor Stinner2f197072011-12-17 07:08:30 +01003477 goto decode_error;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003478 }
3479#ifdef HAVE_BROKEN_MBSTOWCS
3480 assert(wlen2 == wlen);
3481#endif
3482 unicode = PyUnicode_FromWideChar(wstr, wlen2);
3483 if (wstr != smallbuf)
3484 PyMem_Free(wstr);
3485 }
3486 return unicode;
Victor Stinner2f197072011-12-17 07:08:30 +01003487
3488decode_error:
3489 errmsg = strerror(errno);
3490 assert(errmsg != NULL);
3491
3492 error_pos = mbstowcs_errorpos(str, len);
3493 if (errmsg != NULL) {
3494 size_t errlen;
3495 wstr = _Py_char2wchar(errmsg, &errlen);
3496 if (wstr != NULL) {
3497 reason = PyUnicode_FromWideChar(wstr, errlen);
3498 PyMem_Free(wstr);
3499 } else
3500 errmsg = NULL;
3501 }
3502 if (errmsg == NULL)
3503 reason = PyUnicode_FromString(
3504 "mbstowcs() encountered an invalid multibyte sequence");
3505 if (reason == NULL)
3506 return NULL;
3507
3508 exc = PyObject_CallFunction(PyExc_UnicodeDecodeError, "sy#nnO",
3509 "locale", str, len,
3510 (Py_ssize_t)error_pos,
3511 (Py_ssize_t)(error_pos+1),
3512 reason);
3513 Py_DECREF(reason);
3514 if (exc != NULL) {
3515 PyCodec_StrictErrors(exc);
3516 Py_XDECREF(exc);
3517 }
3518 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003519}
3520
3521PyObject*
Victor Stinner1b579672011-12-17 05:47:23 +01003522PyUnicode_DecodeLocale(const char *str, const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003523{
3524 Py_ssize_t size = (Py_ssize_t)strlen(str);
Victor Stinner1b579672011-12-17 05:47:23 +01003525 return PyUnicode_DecodeLocaleAndSize(str, size, errors);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003526}
3527
3528
3529PyObject*
Christian Heimes5894ba72007-11-04 11:43:14 +00003530PyUnicode_DecodeFSDefault(const char *s) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003531 Py_ssize_t size = (Py_ssize_t)strlen(s);
Christian Heimes5894ba72007-11-04 11:43:14 +00003532 return PyUnicode_DecodeFSDefaultAndSize(s, size);
3533}
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003534
Christian Heimes5894ba72007-11-04 11:43:14 +00003535PyObject*
3536PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
3537{
Victor Stinner99b95382011-07-04 14:23:54 +02003538#ifdef HAVE_MBCS
Victor Stinnerad158722010-10-27 00:25:46 +00003539 return PyUnicode_DecodeMBCS(s, size, NULL);
3540#elif defined(__APPLE__)
Victor Stinnera1d12bb2011-12-11 21:53:09 +01003541 return PyUnicode_DecodeUTF8Stateful(s, size, "surrogateescape", NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003542#else
Victor Stinner793b5312011-04-27 00:24:21 +02003543 PyInterpreterState *interp = PyThreadState_GET()->interp;
3544 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3545 cannot use it to encode and decode filenames before it is loaded. Load
3546 the Python codec requires to encode at least its own filename. Use the C
3547 version of the locale codec until the codec registry is initialized and
3548 the Python codec is loaded.
3549
3550 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3551 cannot only rely on it: check also interp->fscodec_initialized for
3552 subinterpreters. */
3553 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003554 return PyUnicode_Decode(s, size,
3555 Py_FileSystemDefaultEncoding,
Victor Stinnerb9a20ad2010-04-30 16:37:52 +00003556 "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003557 }
3558 else {
Victor Stinner1b579672011-12-17 05:47:23 +01003559 return PyUnicode_DecodeLocaleAndSize(s, size, "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003560 }
Victor Stinnerad158722010-10-27 00:25:46 +00003561#endif
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003562}
3563
Martin v. Löwis011e8422009-05-05 04:43:17 +00003564
3565int
3566PyUnicode_FSConverter(PyObject* arg, void* addr)
3567{
3568 PyObject *output = NULL;
3569 Py_ssize_t size;
3570 void *data;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003571 if (arg == NULL) {
3572 Py_DECREF(*(PyObject**)addr);
3573 return 1;
3574 }
Victor Stinnerdcb24032010-04-22 12:08:36 +00003575 if (PyBytes_Check(arg)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00003576 output = arg;
3577 Py_INCREF(output);
3578 }
3579 else {
3580 arg = PyUnicode_FromObject(arg);
3581 if (!arg)
3582 return 0;
Victor Stinnerae6265f2010-05-15 16:27:27 +00003583 output = PyUnicode_EncodeFSDefault(arg);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003584 Py_DECREF(arg);
3585 if (!output)
3586 return 0;
3587 if (!PyBytes_Check(output)) {
3588 Py_DECREF(output);
3589 PyErr_SetString(PyExc_TypeError, "encoder failed to return bytes");
3590 return 0;
3591 }
3592 }
Victor Stinner0ea2a462010-04-30 00:22:08 +00003593 size = PyBytes_GET_SIZE(output);
3594 data = PyBytes_AS_STRING(output);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003595 if (size != strlen(data)) {
Benjamin Peterson7a6b44a2011-08-18 13:51:47 -05003596 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
Martin v. Löwis011e8422009-05-05 04:43:17 +00003597 Py_DECREF(output);
3598 return 0;
3599 }
3600 *(PyObject**)addr = output;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003601 return Py_CLEANUP_SUPPORTED;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003602}
3603
3604
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003605int
3606PyUnicode_FSDecoder(PyObject* arg, void* addr)
3607{
3608 PyObject *output = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003609 if (arg == NULL) {
3610 Py_DECREF(*(PyObject**)addr);
3611 return 1;
3612 }
3613 if (PyUnicode_Check(arg)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003614 if (PyUnicode_READY(arg))
3615 return 0;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003616 output = arg;
3617 Py_INCREF(output);
3618 }
3619 else {
3620 arg = PyBytes_FromObject(arg);
3621 if (!arg)
3622 return 0;
3623 output = PyUnicode_DecodeFSDefaultAndSize(PyBytes_AS_STRING(arg),
3624 PyBytes_GET_SIZE(arg));
3625 Py_DECREF(arg);
3626 if (!output)
3627 return 0;
3628 if (!PyUnicode_Check(output)) {
3629 Py_DECREF(output);
3630 PyErr_SetString(PyExc_TypeError, "decoder failed to return unicode");
3631 return 0;
3632 }
3633 }
Victor Stinner065836e2011-10-27 01:56:33 +02003634 if (PyUnicode_READY(output) < 0) {
3635 Py_DECREF(output);
3636 return 0;
3637 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003638 if (findchar(PyUnicode_DATA(output), PyUnicode_KIND(output),
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02003639 PyUnicode_GET_LENGTH(output), 0, 1) >= 0) {
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003640 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
3641 Py_DECREF(output);
3642 return 0;
3643 }
3644 *(PyObject**)addr = output;
3645 return Py_CLEANUP_SUPPORTED;
3646}
3647
3648
Martin v. Löwis5b222132007-06-10 09:51:05 +00003649char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003650PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *psize)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003651{
Christian Heimesf3863112007-11-22 07:46:41 +00003652 PyObject *bytes;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003653
Neal Norwitze0a0a6e2007-08-25 01:04:21 +00003654 if (!PyUnicode_Check(unicode)) {
3655 PyErr_BadArgument();
3656 return NULL;
3657 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003658 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003659 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003660
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003661 if (PyUnicode_UTF8(unicode) == NULL) {
3662 assert(!PyUnicode_IS_COMPACT_ASCII(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003663 bytes = _PyUnicode_AsUTF8String(unicode, "strict");
3664 if (bytes == NULL)
3665 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003666 _PyUnicode_UTF8(unicode) = PyObject_MALLOC(PyBytes_GET_SIZE(bytes) + 1);
3667 if (_PyUnicode_UTF8(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003668 Py_DECREF(bytes);
3669 return NULL;
3670 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003671 _PyUnicode_UTF8_LENGTH(unicode) = PyBytes_GET_SIZE(bytes);
3672 Py_MEMCPY(_PyUnicode_UTF8(unicode),
3673 PyBytes_AS_STRING(bytes),
3674 _PyUnicode_UTF8_LENGTH(unicode) + 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003675 Py_DECREF(bytes);
3676 }
3677
3678 if (psize)
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003679 *psize = PyUnicode_UTF8_LENGTH(unicode);
3680 return PyUnicode_UTF8(unicode);
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003681}
3682
3683char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003684PyUnicode_AsUTF8(PyObject *unicode)
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003685{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003686 return PyUnicode_AsUTF8AndSize(unicode, NULL);
3687}
3688
3689#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +02003690static int unicode_as_unicode_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003691#endif
3692
3693
3694Py_UNICODE *
3695PyUnicode_AsUnicodeAndSize(PyObject *unicode, Py_ssize_t *size)
3696{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003697 const unsigned char *one_byte;
3698#if SIZEOF_WCHAR_T == 4
3699 const Py_UCS2 *two_bytes;
3700#else
3701 const Py_UCS4 *four_bytes;
3702 const Py_UCS4 *ucs4_end;
3703 Py_ssize_t num_surrogates;
3704#endif
3705 wchar_t *w;
3706 wchar_t *wchar_end;
3707
3708 if (!PyUnicode_Check(unicode)) {
3709 PyErr_BadArgument();
3710 return NULL;
3711 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003712 if (_PyUnicode_WSTR(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003713 /* Non-ASCII compact unicode object */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003714 assert(_PyUnicode_KIND(unicode) != 0);
3715 assert(PyUnicode_IS_READY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003716
3717#ifdef Py_DEBUG
3718 ++unicode_as_unicode_calls;
3719#endif
3720
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003721 if (PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003722#if SIZEOF_WCHAR_T == 2
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003723 four_bytes = PyUnicode_4BYTE_DATA(unicode);
3724 ucs4_end = four_bytes + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003725 num_surrogates = 0;
3726
3727 for (; four_bytes < ucs4_end; ++four_bytes) {
3728 if (*four_bytes > 0xFFFF)
3729 ++num_surrogates;
3730 }
3731
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003732 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(
3733 sizeof(wchar_t) * (_PyUnicode_LENGTH(unicode) + 1 + num_surrogates));
3734 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003735 PyErr_NoMemory();
3736 return NULL;
3737 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003738 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode) + num_surrogates;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003739
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003740 w = _PyUnicode_WSTR(unicode);
3741 wchar_end = w + _PyUnicode_WSTR_LENGTH(unicode);
3742 four_bytes = PyUnicode_4BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003743 for (; four_bytes < ucs4_end; ++four_bytes, ++w) {
3744 if (*four_bytes > 0xFFFF) {
Victor Stinner8faf8212011-12-08 22:14:11 +01003745 assert(*four_bytes <= MAX_UNICODE);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003746 /* encode surrogate pair in this case */
Victor Stinner551ac952011-11-29 22:58:13 +01003747 *w++ = Py_UNICODE_HIGH_SURROGATE(*four_bytes);
3748 *w = Py_UNICODE_LOW_SURROGATE(*four_bytes);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003749 }
3750 else
3751 *w = *four_bytes;
3752
3753 if (w > wchar_end) {
3754 assert(0 && "Miscalculated string end");
3755 }
3756 }
3757 *w = 0;
3758#else
3759 /* sizeof(wchar_t) == 4 */
3760 Py_FatalError("Impossible unicode object state, wstr and str "
3761 "should share memory already.");
3762 return NULL;
3763#endif
3764 }
3765 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003766 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(sizeof(wchar_t) *
3767 (_PyUnicode_LENGTH(unicode) + 1));
3768 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003769 PyErr_NoMemory();
3770 return NULL;
3771 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003772 if (!PyUnicode_IS_COMPACT_ASCII(unicode))
3773 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode);
3774 w = _PyUnicode_WSTR(unicode);
3775 wchar_end = w + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003776
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003777 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND) {
3778 one_byte = PyUnicode_1BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003779 for (; w < wchar_end; ++one_byte, ++w)
3780 *w = *one_byte;
3781 /* null-terminate the wstr */
3782 *w = 0;
3783 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003784 else if (PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003785#if SIZEOF_WCHAR_T == 4
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003786 two_bytes = PyUnicode_2BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003787 for (; w < wchar_end; ++two_bytes, ++w)
3788 *w = *two_bytes;
3789 /* null-terminate the wstr */
3790 *w = 0;
3791#else
3792 /* sizeof(wchar_t) == 2 */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003793 PyObject_FREE(_PyUnicode_WSTR(unicode));
3794 _PyUnicode_WSTR(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003795 Py_FatalError("Impossible unicode object state, wstr "
3796 "and str should share memory already.");
3797 return NULL;
3798#endif
3799 }
3800 else {
3801 assert(0 && "This should never happen.");
3802 }
3803 }
3804 }
3805 if (size != NULL)
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003806 *size = PyUnicode_WSTR_LENGTH(unicode);
3807 return _PyUnicode_WSTR(unicode);
Martin v. Löwis5b222132007-06-10 09:51:05 +00003808}
3809
Alexander Belopolsky40018472011-02-26 01:02:56 +00003810Py_UNICODE *
3811PyUnicode_AsUnicode(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003812{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003813 return PyUnicode_AsUnicodeAndSize(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003814}
3815
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003816
Alexander Belopolsky40018472011-02-26 01:02:56 +00003817Py_ssize_t
3818PyUnicode_GetSize(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003819{
3820 if (!PyUnicode_Check(unicode)) {
3821 PyErr_BadArgument();
3822 goto onError;
3823 }
3824 return PyUnicode_GET_SIZE(unicode);
3825
Benjamin Peterson29060642009-01-31 22:14:21 +00003826 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003827 return -1;
3828}
3829
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003830Py_ssize_t
3831PyUnicode_GetLength(PyObject *unicode)
3832{
Victor Stinner5a706cf2011-10-02 00:36:53 +02003833 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003834 PyErr_BadArgument();
3835 return -1;
3836 }
3837
3838 return PyUnicode_GET_LENGTH(unicode);
3839}
3840
3841Py_UCS4
3842PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
3843{
Victor Stinner2fe5ced2011-10-02 00:25:40 +02003844 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
3845 PyErr_BadArgument();
3846 return (Py_UCS4)-1;
3847 }
Victor Stinnerc4b49542011-12-11 22:44:26 +01003848 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinner2fe5ced2011-10-02 00:25:40 +02003849 PyErr_SetString(PyExc_IndexError, "string index out of range");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003850 return (Py_UCS4)-1;
3851 }
3852 return PyUnicode_READ_CHAR(unicode, index);
3853}
3854
3855int
3856PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 ch)
3857{
3858 if (!PyUnicode_Check(unicode) || !PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02003859 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003860 return -1;
3861 }
Victor Stinner488fa492011-12-12 00:01:39 +01003862 assert(PyUnicode_IS_READY(unicode));
Victor Stinnerc4b49542011-12-11 22:44:26 +01003863 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02003864 PyErr_SetString(PyExc_IndexError, "string index out of range");
3865 return -1;
3866 }
Victor Stinner488fa492011-12-12 00:01:39 +01003867 if (unicode_check_modifiable(unicode))
Victor Stinnercd9950f2011-10-02 00:34:53 +02003868 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003869 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
3870 index, ch);
3871 return 0;
3872}
3873
Alexander Belopolsky40018472011-02-26 01:02:56 +00003874const char *
3875PyUnicode_GetDefaultEncoding(void)
Fred Drakee4315f52000-05-09 19:53:39 +00003876{
Victor Stinner42cb4622010-09-01 19:39:01 +00003877 return "utf-8";
Fred Drakee4315f52000-05-09 19:53:39 +00003878}
3879
Victor Stinner554f3f02010-06-16 23:33:54 +00003880/* create or adjust a UnicodeDecodeError */
3881static void
3882make_decode_exception(PyObject **exceptionObject,
3883 const char *encoding,
3884 const char *input, Py_ssize_t length,
3885 Py_ssize_t startpos, Py_ssize_t endpos,
3886 const char *reason)
3887{
3888 if (*exceptionObject == NULL) {
3889 *exceptionObject = PyUnicodeDecodeError_Create(
3890 encoding, input, length, startpos, endpos, reason);
3891 }
3892 else {
3893 if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
3894 goto onError;
3895 if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
3896 goto onError;
3897 if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
3898 goto onError;
3899 }
3900 return;
3901
3902onError:
3903 Py_DECREF(*exceptionObject);
3904 *exceptionObject = NULL;
3905}
3906
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003907/* error handling callback helper:
3908 build arguments, call the callback and check the arguments,
Fred Drakedb390c12005-10-28 14:39:47 +00003909 if no exception occurred, copy the replacement to the output
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003910 and adjust various state variables.
3911 return 0 on success, -1 on error
3912*/
3913
Alexander Belopolsky40018472011-02-26 01:02:56 +00003914static int
3915unicode_decode_call_errorhandler(const char *errors, PyObject **errorHandler,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003916 const char *encoding, const char *reason,
3917 const char **input, const char **inend, Py_ssize_t *startinpos,
3918 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003919 PyObject **output, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003920{
Benjamin Peterson142957c2008-07-04 19:55:29 +00003921 static char *argparse = "O!n;decoding error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003922
3923 PyObject *restuple = NULL;
3924 PyObject *repunicode = NULL;
Victor Stinner596a6c42011-11-09 00:02:18 +01003925 Py_ssize_t outsize;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003926 Py_ssize_t insize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003927 Py_ssize_t requiredsize;
3928 Py_ssize_t newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003929 PyObject *inputobj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003930 int res = -1;
3931
Victor Stinner596a6c42011-11-09 00:02:18 +01003932 if (_PyUnicode_KIND(*output) != PyUnicode_WCHAR_KIND)
3933 outsize = PyUnicode_GET_LENGTH(*output);
3934 else
3935 outsize = _PyUnicode_WSTR_LENGTH(*output);
3936
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003937 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003938 *errorHandler = PyCodec_LookupError(errors);
3939 if (*errorHandler == NULL)
3940 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003941 }
3942
Victor Stinner554f3f02010-06-16 23:33:54 +00003943 make_decode_exception(exceptionObject,
3944 encoding,
3945 *input, *inend - *input,
3946 *startinpos, *endinpos,
3947 reason);
3948 if (*exceptionObject == NULL)
3949 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003950
3951 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
3952 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003953 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003954 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00003955 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00003956 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003957 }
3958 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00003959 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003960 if (PyUnicode_READY(repunicode) < 0)
3961 goto onError;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003962
3963 /* Copy back the bytes variables, which might have been modified by the
3964 callback */
3965 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
3966 if (!inputobj)
3967 goto onError;
Christian Heimes72b710a2008-05-26 13:28:38 +00003968 if (!PyBytes_Check(inputobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003969 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
Walter Dörwalde78178e2007-07-30 13:31:40 +00003970 }
Christian Heimes72b710a2008-05-26 13:28:38 +00003971 *input = PyBytes_AS_STRING(inputobj);
3972 insize = PyBytes_GET_SIZE(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00003973 *inend = *input + insize;
Walter Dörwald36f938f2007-08-10 10:11:43 +00003974 /* we can DECREF safely, as the exception has another reference,
3975 so the object won't go away. */
3976 Py_DECREF(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00003977
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003978 if (newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00003979 newpos = insize+newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00003980 if (newpos<0 || newpos>insize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003981 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
3982 goto onError;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00003983 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003984
Victor Stinner596a6c42011-11-09 00:02:18 +01003985 if (_PyUnicode_KIND(*output) != PyUnicode_WCHAR_KIND) {
3986 /* need more space? (at least enough for what we
3987 have+the replacement+the rest of the string (starting
3988 at the new input position), so we won't have to check space
3989 when there are no errors in the rest of the string) */
3990 Py_ssize_t replen = PyUnicode_GET_LENGTH(repunicode);
3991 requiredsize = *outpos + replen + insize-newpos;
3992 if (requiredsize > outsize) {
3993 if (requiredsize<2*outsize)
3994 requiredsize = 2*outsize;
3995 if (unicode_resize(output, requiredsize) < 0)
3996 goto onError;
3997 }
3998 if (unicode_widen(output, PyUnicode_MAX_CHAR_VALUE(repunicode)) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00003999 goto onError;
Victor Stinner596a6c42011-11-09 00:02:18 +01004000 copy_characters(*output, *outpos, repunicode, 0, replen);
4001 *outpos += replen;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004002 }
Victor Stinner596a6c42011-11-09 00:02:18 +01004003 else {
4004 wchar_t *repwstr;
4005 Py_ssize_t repwlen;
4006 repwstr = PyUnicode_AsUnicodeAndSize(repunicode, &repwlen);
4007 if (repwstr == NULL)
4008 goto onError;
4009 /* need more space? (at least enough for what we
4010 have+the replacement+the rest of the string (starting
4011 at the new input position), so we won't have to check space
4012 when there are no errors in the rest of the string) */
4013 requiredsize = *outpos + repwlen + insize-newpos;
4014 if (requiredsize > outsize) {
4015 if (requiredsize < 2*outsize)
4016 requiredsize = 2*outsize;
4017 if (unicode_resize(output, requiredsize) < 0)
4018 goto onError;
4019 }
4020 wcsncpy(_PyUnicode_WSTR(*output) + *outpos, repwstr, repwlen);
4021 *outpos += repwlen;
4022 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004023 *endinpos = newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004024 *inptr = *input + newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004025
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004026 /* we made it! */
4027 res = 0;
4028
Benjamin Peterson29060642009-01-31 22:14:21 +00004029 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004030 Py_XDECREF(restuple);
4031 return res;
4032}
4033
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004034/* --- UTF-7 Codec -------------------------------------------------------- */
4035
Antoine Pitrou244651a2009-05-04 18:56:13 +00004036/* See RFC2152 for details. We encode conservatively and decode liberally. */
4037
4038/* Three simple macros defining base-64. */
4039
4040/* Is c a base-64 character? */
4041
4042#define IS_BASE64(c) \
4043 (((c) >= 'A' && (c) <= 'Z') || \
4044 ((c) >= 'a' && (c) <= 'z') || \
4045 ((c) >= '0' && (c) <= '9') || \
4046 (c) == '+' || (c) == '/')
4047
4048/* given that c is a base-64 character, what is its base-64 value? */
4049
4050#define FROM_BASE64(c) \
4051 (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' : \
4052 ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 : \
4053 ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 : \
4054 (c) == '+' ? 62 : 63)
4055
4056/* What is the base-64 character of the bottom 6 bits of n? */
4057
4058#define TO_BASE64(n) \
4059 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
4060
4061/* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
4062 * decoded as itself. We are permissive on decoding; the only ASCII
4063 * byte not decoding to itself is the + which begins a base64
4064 * string. */
4065
4066#define DECODE_DIRECT(c) \
4067 ((c) <= 127 && (c) != '+')
4068
4069/* The UTF-7 encoder treats ASCII characters differently according to
4070 * whether they are Set D, Set O, Whitespace, or special (i.e. none of
4071 * the above). See RFC2152. This array identifies these different
4072 * sets:
4073 * 0 : "Set D"
4074 * alphanumeric and '(),-./:?
4075 * 1 : "Set O"
4076 * !"#$%&*;<=>@[]^_`{|}
4077 * 2 : "whitespace"
4078 * ht nl cr sp
4079 * 3 : special (must be base64 encoded)
4080 * everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
4081 */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004082
Tim Petersced69f82003-09-16 20:30:58 +00004083static
Antoine Pitrou244651a2009-05-04 18:56:13 +00004084char utf7_category[128] = {
4085/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
4086 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
4087/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
4088 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
4089/* sp ! " # $ % & ' ( ) * + , - . / */
4090 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
4091/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
4092 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
4093/* @ A B C D E F G H I J K L M N O */
4094 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4095/* P Q R S T U V W X Y Z [ \ ] ^ _ */
4096 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
4097/* ` a b c d e f g h i j k l m n o */
4098 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4099/* p q r s t u v w x y z { | } ~ del */
4100 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004101};
4102
Antoine Pitrou244651a2009-05-04 18:56:13 +00004103/* ENCODE_DIRECT: this character should be encoded as itself. The
4104 * answer depends on whether we are encoding set O as itself, and also
4105 * on whether we are encoding whitespace as itself. RFC2152 makes it
4106 * clear that the answers to these questions vary between
4107 * applications, so this code needs to be flexible. */
Marc-André Lemburge115ec82005-10-19 22:33:31 +00004108
Antoine Pitrou244651a2009-05-04 18:56:13 +00004109#define ENCODE_DIRECT(c, directO, directWS) \
4110 ((c) < 128 && (c) > 0 && \
4111 ((utf7_category[(c)] == 0) || \
4112 (directWS && (utf7_category[(c)] == 2)) || \
4113 (directO && (utf7_category[(c)] == 1))))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004114
Alexander Belopolsky40018472011-02-26 01:02:56 +00004115PyObject *
4116PyUnicode_DecodeUTF7(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004117 Py_ssize_t size,
4118 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004119{
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004120 return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
4121}
4122
Antoine Pitrou244651a2009-05-04 18:56:13 +00004123/* The decoder. The only state we preserve is our read position,
4124 * i.e. how many characters we have consumed. So if we end in the
4125 * middle of a shift sequence we have to back off the read position
4126 * and the output to the beginning of the sequence, otherwise we lose
4127 * all the shift state (seen bits, number of bits seen, high
4128 * surrogate). */
4129
Alexander Belopolsky40018472011-02-26 01:02:56 +00004130PyObject *
4131PyUnicode_DecodeUTF7Stateful(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004132 Py_ssize_t size,
4133 const char *errors,
4134 Py_ssize_t *consumed)
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004135{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004136 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004137 Py_ssize_t startinpos;
4138 Py_ssize_t endinpos;
4139 Py_ssize_t outpos;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004140 const char *e;
Victor Stinner7931d9a2011-11-04 00:22:48 +01004141 PyObject *unicode;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004142 const char *errmsg = "";
4143 int inShift = 0;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004144 Py_ssize_t shiftOutStart;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004145 unsigned int base64bits = 0;
4146 unsigned long base64buffer = 0;
Victor Stinner24729f32011-11-10 20:31:37 +01004147 Py_UCS4 surrogate = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004148 PyObject *errorHandler = NULL;
4149 PyObject *exc = NULL;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004150
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004151 /* Start off assuming it's all ASCII. Widen later as necessary. */
4152 unicode = PyUnicode_New(size, 127);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004153 if (!unicode)
4154 return NULL;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004155 if (size == 0) {
4156 if (consumed)
4157 *consumed = 0;
Victor Stinner7931d9a2011-11-04 00:22:48 +01004158 return unicode;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004159 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004160
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004161 shiftOutStart = outpos = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004162 e = s + size;
4163
4164 while (s < e) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004165 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00004166 restart:
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00004167 ch = (unsigned char) *s;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004168
Antoine Pitrou244651a2009-05-04 18:56:13 +00004169 if (inShift) { /* in a base-64 section */
4170 if (IS_BASE64(ch)) { /* consume a base-64 character */
4171 base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
4172 base64bits += 6;
4173 s++;
4174 if (base64bits >= 16) {
4175 /* we have enough bits for a UTF-16 value */
Victor Stinner24729f32011-11-10 20:31:37 +01004176 Py_UCS4 outCh = (Py_UCS4)(base64buffer >> (base64bits-16));
Antoine Pitrou244651a2009-05-04 18:56:13 +00004177 base64bits -= 16;
4178 base64buffer &= (1 << base64bits) - 1; /* clear high bits */
4179 if (surrogate) {
4180 /* expecting a second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004181 if (Py_UNICODE_IS_LOW_SURROGATE(outCh)) {
4182 Py_UCS4 ch2 = Py_UNICODE_JOIN_SURROGATES(surrogate, outCh);
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004183 if (unicode_putchar(&unicode, &outpos, ch2) < 0)
4184 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004185 surrogate = 0;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01004186 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004187 }
4188 else {
Antoine Pitrou78edf752011-11-15 01:44:16 +01004189 if (unicode_putchar(&unicode, &outpos, surrogate) < 0)
4190 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004191 surrogate = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004192 }
4193 }
Victor Stinner551ac952011-11-29 22:58:13 +01004194 if (Py_UNICODE_IS_HIGH_SURROGATE(outCh)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004195 /* first surrogate */
4196 surrogate = outCh;
4197 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004198 else {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004199 if (unicode_putchar(&unicode, &outpos, outCh) < 0)
4200 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004201 }
4202 }
4203 }
4204 else { /* now leaving a base-64 section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004205 inShift = 0;
4206 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004207 if (surrogate) {
Antoine Pitrou78edf752011-11-15 01:44:16 +01004208 if (unicode_putchar(&unicode, &outpos, surrogate) < 0)
4209 goto onError;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01004210 surrogate = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004211 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004212 if (base64bits > 0) { /* left-over bits */
4213 if (base64bits >= 6) {
4214 /* We've seen at least one base-64 character */
4215 errmsg = "partial character in shift sequence";
4216 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004217 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004218 else {
4219 /* Some bits remain; they should be zero */
4220 if (base64buffer != 0) {
4221 errmsg = "non-zero padding bits in shift sequence";
4222 goto utf7Error;
4223 }
4224 }
4225 }
4226 if (ch != '-') {
4227 /* '-' is absorbed; other terminating
4228 characters are preserved */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004229 if (unicode_putchar(&unicode, &outpos, ch) < 0)
4230 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004231 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004232 }
4233 }
4234 else if ( ch == '+' ) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004235 startinpos = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004236 s++; /* consume '+' */
4237 if (s < e && *s == '-') { /* '+-' encodes '+' */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004238 s++;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004239 if (unicode_putchar(&unicode, &outpos, '+') < 0)
4240 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004241 }
4242 else { /* begin base64-encoded section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004243 inShift = 1;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004244 shiftOutStart = outpos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004245 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004246 }
4247 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004248 else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004249 if (unicode_putchar(&unicode, &outpos, ch) < 0)
4250 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004251 s++;
4252 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004253 else {
4254 startinpos = s-starts;
4255 s++;
4256 errmsg = "unexpected special character";
4257 goto utf7Error;
4258 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004259 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004260utf7Error:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004261 endinpos = s-starts;
4262 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00004263 errors, &errorHandler,
4264 "utf7", errmsg,
4265 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004266 &unicode, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00004267 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004268 }
4269
Antoine Pitrou244651a2009-05-04 18:56:13 +00004270 /* end of string */
4271
4272 if (inShift && !consumed) { /* in shift sequence, no more to follow */
4273 /* if we're in an inconsistent state, that's an error */
4274 if (surrogate ||
4275 (base64bits >= 6) ||
4276 (base64bits > 0 && base64buffer != 0)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004277 endinpos = size;
4278 if (unicode_decode_call_errorhandler(
4279 errors, &errorHandler,
4280 "utf7", "unterminated shift sequence",
4281 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004282 &unicode, &outpos))
Antoine Pitrou244651a2009-05-04 18:56:13 +00004283 goto onError;
4284 if (s < e)
4285 goto restart;
4286 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004287 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004288
4289 /* return state */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004290 if (consumed) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004291 if (inShift) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004292 outpos = shiftOutStart; /* back off output */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004293 *consumed = startinpos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004294 }
4295 else {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004296 *consumed = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004297 }
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004298 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004299
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004300 if (unicode_resize(&unicode, outpos) < 0)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004301 goto onError;
4302
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004303 Py_XDECREF(errorHandler);
4304 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01004305 return unicode_result(unicode);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004306
Benjamin Peterson29060642009-01-31 22:14:21 +00004307 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004308 Py_XDECREF(errorHandler);
4309 Py_XDECREF(exc);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004310 Py_DECREF(unicode);
4311 return NULL;
4312}
4313
4314
Alexander Belopolsky40018472011-02-26 01:02:56 +00004315PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004316_PyUnicode_EncodeUTF7(PyObject *str,
4317 int base64SetO,
4318 int base64WhiteSpace,
4319 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004320{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004321 int kind;
4322 void *data;
4323 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004324 PyObject *v;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004325 Py_ssize_t allocated;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004326 int inShift = 0;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004327 Py_ssize_t i;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004328 unsigned int base64bits = 0;
4329 unsigned long base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004330 char * out;
4331 char * start;
4332
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004333 if (PyUnicode_READY(str) < 0)
4334 return NULL;
4335 kind = PyUnicode_KIND(str);
4336 data = PyUnicode_DATA(str);
4337 len = PyUnicode_GET_LENGTH(str);
4338
4339 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004340 return PyBytes_FromStringAndSize(NULL, 0);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004341
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004342 /* It might be possible to tighten this worst case */
4343 allocated = 8 * len;
4344 if (allocated / 8 != len)
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004345 return PyErr_NoMemory();
4346
Antoine Pitrou244651a2009-05-04 18:56:13 +00004347 v = PyBytes_FromStringAndSize(NULL, allocated);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004348 if (v == NULL)
4349 return NULL;
4350
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004351 start = out = PyBytes_AS_STRING(v);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004352 for (i = 0; i < len; ++i) {
Victor Stinner0e368262011-11-10 20:12:49 +01004353 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004354
Antoine Pitrou244651a2009-05-04 18:56:13 +00004355 if (inShift) {
4356 if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4357 /* shifting out */
4358 if (base64bits) { /* output remaining bits */
4359 *out++ = TO_BASE64(base64buffer << (6-base64bits));
4360 base64buffer = 0;
4361 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004362 }
4363 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004364 /* Characters not in the BASE64 set implicitly unshift the sequence
4365 so no '-' is required, except if the character is itself a '-' */
4366 if (IS_BASE64(ch) || ch == '-') {
4367 *out++ = '-';
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004368 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004369 *out++ = (char) ch;
4370 }
4371 else {
4372 goto encode_char;
Tim Petersced69f82003-09-16 20:30:58 +00004373 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004374 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004375 else { /* not in a shift sequence */
4376 if (ch == '+') {
4377 *out++ = '+';
4378 *out++ = '-';
4379 }
4380 else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4381 *out++ = (char) ch;
4382 }
4383 else {
4384 *out++ = '+';
4385 inShift = 1;
4386 goto encode_char;
4387 }
4388 }
4389 continue;
4390encode_char:
Antoine Pitrou244651a2009-05-04 18:56:13 +00004391 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01004392 assert(ch <= MAX_UNICODE);
Victor Stinner0d3721d2011-11-22 03:27:53 +01004393
Antoine Pitrou244651a2009-05-04 18:56:13 +00004394 /* code first surrogate */
4395 base64bits += 16;
4396 base64buffer = (base64buffer << 16) | 0xd800 | ((ch-0x10000) >> 10);
4397 while (base64bits >= 6) {
4398 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4399 base64bits -= 6;
4400 }
4401 /* prepare second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004402 ch = Py_UNICODE_LOW_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004403 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004404 base64bits += 16;
4405 base64buffer = (base64buffer << 16) | ch;
4406 while (base64bits >= 6) {
4407 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4408 base64bits -= 6;
4409 }
Hye-Shik Chang1bc09b72004-01-03 19:35:43 +00004410 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004411 if (base64bits)
4412 *out++= TO_BASE64(base64buffer << (6-base64bits) );
4413 if (inShift)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004414 *out++ = '-';
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004415 if (_PyBytes_Resize(&v, out - start) < 0)
4416 return NULL;
4417 return v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004418}
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004419PyObject *
4420PyUnicode_EncodeUTF7(const Py_UNICODE *s,
4421 Py_ssize_t size,
4422 int base64SetO,
4423 int base64WhiteSpace,
4424 const char *errors)
4425{
4426 PyObject *result;
4427 PyObject *tmp = PyUnicode_FromUnicode(s, size);
4428 if (tmp == NULL)
4429 return NULL;
Victor Stinner0e368262011-11-10 20:12:49 +01004430 result = _PyUnicode_EncodeUTF7(tmp, base64SetO,
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004431 base64WhiteSpace, errors);
4432 Py_DECREF(tmp);
4433 return result;
4434}
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004435
Antoine Pitrou244651a2009-05-04 18:56:13 +00004436#undef IS_BASE64
4437#undef FROM_BASE64
4438#undef TO_BASE64
4439#undef DECODE_DIRECT
4440#undef ENCODE_DIRECT
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004441
Guido van Rossumd57fd912000-03-10 22:53:23 +00004442/* --- UTF-8 Codec -------------------------------------------------------- */
4443
Tim Petersced69f82003-09-16 20:30:58 +00004444static
Guido van Rossumd57fd912000-03-10 22:53:23 +00004445char utf8_code_length[256] = {
Ezio Melotti57221d02010-07-01 07:32:02 +00004446 /* Map UTF-8 encoded prefix byte to sequence length. Zero means
4447 illegal prefix. See RFC 3629 for details */
4448 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 00-0F */
4449 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Victor Stinner4a2b7a12010-08-13 14:03:48 +00004450 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Guido van Rossumd57fd912000-03-10 22:53:23 +00004451 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,
4454 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Ezio Melotti57221d02010-07-01 07:32:02 +00004455 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 70-7F */
4456 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 +00004457 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4458 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
Ezio Melotti57221d02010-07-01 07:32:02 +00004459 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* B0-BF */
4460 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* C0-C1 + C2-CF */
4461 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* D0-DF */
4462 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, /* E0-EF */
4463 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 +00004464};
4465
Alexander Belopolsky40018472011-02-26 01:02:56 +00004466PyObject *
4467PyUnicode_DecodeUTF8(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004468 Py_ssize_t size,
4469 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004470{
Walter Dörwald69652032004-09-07 20:24:22 +00004471 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
4472}
4473
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004474#include "stringlib/ucs1lib.h"
4475#include "stringlib/codecs.h"
4476#include "stringlib/undef.h"
4477
4478#include "stringlib/ucs2lib.h"
4479#include "stringlib/codecs.h"
4480#include "stringlib/undef.h"
4481
4482#include "stringlib/ucs4lib.h"
4483#include "stringlib/codecs.h"
4484#include "stringlib/undef.h"
4485
Antoine Pitrouab868312009-01-10 15:40:25 +00004486/* Mask to check or force alignment of a pointer to C 'long' boundaries */
4487#define LONG_PTR_MASK (size_t) (SIZEOF_LONG - 1)
4488
4489/* Mask to quickly check whether a C 'long' contains a
4490 non-ASCII, UTF8-encoded char. */
4491#if (SIZEOF_LONG == 8)
4492# define ASCII_CHAR_MASK 0x8080808080808080L
4493#elif (SIZEOF_LONG == 4)
4494# define ASCII_CHAR_MASK 0x80808080L
4495#else
4496# error C 'long' size should be either 4 or 8!
4497#endif
4498
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004499/* Scans a UTF-8 string and returns the maximum character to be expected
4500 and the size of the decoded unicode string.
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004501
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004502 This function doesn't check for errors, these checks are performed in
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004503 PyUnicode_DecodeUTF8Stateful.
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004504 */
4505static Py_UCS4
Victor Stinnera1d12bb2011-12-11 21:53:09 +01004506utf8_scanner(const unsigned char *p, Py_ssize_t string_size, Py_ssize_t *unicode_size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004507{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004508 Py_ssize_t char_count = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004509 const unsigned char *end = p + string_size;
4510 const unsigned char *aligned_end = (const unsigned char *) ((size_t) end & ~LONG_PTR_MASK);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004511
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004512 assert(unicode_size != NULL);
4513
4514 /* By having a cascade of independent loops which fallback onto each
4515 other, we minimize the amount of work done in the average loop
4516 iteration, and we also maximize the CPU's ability to predict
4517 branches correctly (because a given condition will have always the
4518 same boolean outcome except perhaps in the last iteration of the
4519 corresponding loop).
4520 In the general case this brings us rather close to decoding
4521 performance pre-PEP 393, despite the two-pass decoding.
4522
4523 Note that the pure ASCII loop is not duplicated once a non-ASCII
4524 character has been encountered. It is actually a pessimization (by
4525 a significant factor) to use this loop on text with many non-ASCII
4526 characters, and it is important to avoid bad performance on valid
4527 utf-8 data (invalid utf-8 being a different can of worms).
4528 */
4529
4530 /* ASCII */
4531 for (; p < end; ++p) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004532 /* Only check value if it's not a ASCII char... */
4533 if (*p < 0x80) {
4534 /* Fast path, see below in PyUnicode_DecodeUTF8Stateful for
4535 an explanation. */
4536 if (!((size_t) p & LONG_PTR_MASK)) {
4537 /* Help register allocation */
4538 register const unsigned char *_p = p;
4539 while (_p < aligned_end) {
4540 unsigned long value = *(unsigned long *) _p;
4541 if (value & ASCII_CHAR_MASK)
4542 break;
4543 _p += SIZEOF_LONG;
4544 char_count += SIZEOF_LONG;
4545 }
4546 p = _p;
4547 if (p == end)
4548 break;
4549 }
4550 }
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004551 if (*p < 0x80)
4552 ++char_count;
4553 else
4554 goto _ucs1loop;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004555 }
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004556 *unicode_size = char_count;
4557 return 127;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004558
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004559_ucs1loop:
4560 for (; p < end; ++p) {
4561 if (*p < 0xc4)
4562 char_count += ((*p & 0xc0) != 0x80);
4563 else
4564 goto _ucs2loop;
4565 }
4566 *unicode_size = char_count;
4567 return 255;
4568
4569_ucs2loop:
4570 for (; p < end; ++p) {
4571 if (*p < 0xf0)
4572 char_count += ((*p & 0xc0) != 0x80);
4573 else
4574 goto _ucs4loop;
4575 }
4576 *unicode_size = char_count;
4577 return 65535;
4578
4579_ucs4loop:
4580 for (; p < end; ++p) {
4581 char_count += ((*p & 0xc0) != 0x80);
4582 }
4583 *unicode_size = char_count;
4584 return 65537;
4585}
4586
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004587/* Similar to PyUnicode_WRITE but may attempt to widen and resize the string
Victor Stinner785938e2011-12-11 20:09:03 +01004588 in case of errors. Implicit parameters: unicode, kind, data, onError.
4589 Potential resizing overallocates, so the result needs to shrink at the end.
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004590*/
Victor Stinner785938e2011-12-11 20:09:03 +01004591#define WRITE_MAYBE_FAIL(index, value) \
4592 do { \
4593 Py_ssize_t pos = index; \
4594 if (pos > PyUnicode_GET_LENGTH(unicode) && \
4595 unicode_resize(&unicode, pos + pos/8) < 0) \
4596 goto onError; \
4597 if (unicode_putchar(&unicode, &pos, value) < 0) \
4598 goto onError; \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004599 } while (0)
4600
Victor Stinnerbf6e5602011-12-12 01:53:47 +01004601static PyObject *
Victor Stinner785938e2011-12-11 20:09:03 +01004602decode_utf8_errors(const char *starts,
4603 Py_ssize_t size,
4604 const char *errors,
4605 Py_ssize_t *consumed,
4606 const char *s,
4607 PyObject *unicode,
4608 Py_ssize_t i)
Walter Dörwald69652032004-09-07 20:24:22 +00004609{
Guido van Rossumd57fd912000-03-10 22:53:23 +00004610 int n;
Ezio Melotti57221d02010-07-01 07:32:02 +00004611 int k;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004612 Py_ssize_t startinpos;
4613 Py_ssize_t endinpos;
Victor Stinner785938e2011-12-11 20:09:03 +01004614 const char *e = starts + size;
4615 const char *aligned_end;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004616 const char *errmsg = "";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004617 PyObject *errorHandler = NULL;
4618 PyObject *exc = NULL;
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004619
Antoine Pitrouab868312009-01-10 15:40:25 +00004620 aligned_end = (const char *) ((size_t) e & ~LONG_PTR_MASK);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004621
4622 while (s < e) {
Marc-André Lemburge12896e2000-07-07 17:51:08 +00004623 Py_UCS4 ch = (unsigned char)*s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004624
4625 if (ch < 0x80) {
Antoine Pitrouab868312009-01-10 15:40:25 +00004626 /* Fast path for runs of ASCII characters. Given that common UTF-8
4627 input will consist of an overwhelming majority of ASCII
4628 characters, we try to optimize for this case by checking
4629 as many characters as a C 'long' can contain.
4630 First, check if we can do an aligned read, as most CPUs have
4631 a penalty for unaligned reads.
4632 */
4633 if (!((size_t) s & LONG_PTR_MASK)) {
4634 /* Help register allocation */
4635 register const char *_s = s;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004636 register Py_ssize_t _i = i;
Antoine Pitrouab868312009-01-10 15:40:25 +00004637 while (_s < aligned_end) {
4638 /* Read a whole long at a time (either 4 or 8 bytes),
4639 and do a fast unrolled copy if it only contains ASCII
4640 characters. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004641 unsigned long value = *(unsigned long *) _s;
4642 if (value & ASCII_CHAR_MASK)
Antoine Pitrouab868312009-01-10 15:40:25 +00004643 break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004644 WRITE_MAYBE_FAIL(_i+0, _s[0]);
4645 WRITE_MAYBE_FAIL(_i+1, _s[1]);
4646 WRITE_MAYBE_FAIL(_i+2, _s[2]);
4647 WRITE_MAYBE_FAIL(_i+3, _s[3]);
Antoine Pitrouab868312009-01-10 15:40:25 +00004648#if (SIZEOF_LONG == 8)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004649 WRITE_MAYBE_FAIL(_i+4, _s[4]);
4650 WRITE_MAYBE_FAIL(_i+5, _s[5]);
4651 WRITE_MAYBE_FAIL(_i+6, _s[6]);
4652 WRITE_MAYBE_FAIL(_i+7, _s[7]);
Antoine Pitrouab868312009-01-10 15:40:25 +00004653#endif
4654 _s += SIZEOF_LONG;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004655 _i += SIZEOF_LONG;
Antoine Pitrouab868312009-01-10 15:40:25 +00004656 }
4657 s = _s;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004658 i = _i;
Antoine Pitrouab868312009-01-10 15:40:25 +00004659 if (s == e)
4660 break;
4661 ch = (unsigned char)*s;
4662 }
4663 }
4664
4665 if (ch < 0x80) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004666 WRITE_MAYBE_FAIL(i++, ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004667 s++;
4668 continue;
4669 }
4670
4671 n = utf8_code_length[ch];
4672
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004673 if (s + n > e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004674 if (consumed)
4675 break;
4676 else {
4677 errmsg = "unexpected end of data";
4678 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004679 endinpos = startinpos+1;
4680 for (k=1; (k < size-startinpos) && ((s[k]&0xC0) == 0x80); k++)
4681 endinpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00004682 goto utf8Error;
4683 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00004684 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004685
4686 switch (n) {
4687
4688 case 0:
Ezio Melotti57221d02010-07-01 07:32:02 +00004689 errmsg = "invalid start byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004690 startinpos = s-starts;
4691 endinpos = startinpos+1;
4692 goto utf8Error;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004693
4694 case 1:
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004695 errmsg = "internal error";
Benjamin Peterson29060642009-01-31 22:14:21 +00004696 startinpos = s-starts;
4697 endinpos = startinpos+1;
4698 goto utf8Error;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004699
4700 case 2:
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004701 if ((s[1] & 0xc0) != 0x80) {
Ezio Melotti57221d02010-07-01 07:32:02 +00004702 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004703 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004704 endinpos = startinpos + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00004705 goto utf8Error;
4706 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004707 ch = ((s[0] & 0x1f) << 6) + (s[1] & 0x3f);
Ezio Melotti57221d02010-07-01 07:32:02 +00004708 assert ((ch > 0x007F) && (ch <= 0x07FF));
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004709 WRITE_MAYBE_FAIL(i++, ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004710 break;
4711
4712 case 3:
Ezio Melotti9bf2b3a2010-07-03 04:52:19 +00004713 /* Decoding UTF-8 sequences in range \xed\xa0\x80-\xed\xbf\xbf
4714 will result in surrogates in range d800-dfff. Surrogates are
4715 not valid UTF-8 so they are rejected.
4716 See http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf
4717 (table 3-7) and http://www.rfc-editor.org/rfc/rfc3629.txt */
Tim Petersced69f82003-09-16 20:30:58 +00004718 if ((s[1] & 0xc0) != 0x80 ||
Ezio Melotti57221d02010-07-01 07:32:02 +00004719 (s[2] & 0xc0) != 0x80 ||
4720 ((unsigned char)s[0] == 0xE0 &&
4721 (unsigned char)s[1] < 0xA0) ||
4722 ((unsigned char)s[0] == 0xED &&
4723 (unsigned char)s[1] > 0x9F)) {
4724 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004725 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004726 endinpos = startinpos + 1;
4727
4728 /* if s[1] first two bits are 1 and 0, then the invalid
4729 continuation byte is s[2], so increment endinpos by 1,
4730 if not, s[1] is invalid and endinpos doesn't need to
4731 be incremented. */
4732 if ((s[1] & 0xC0) == 0x80)
4733 endinpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00004734 goto utf8Error;
4735 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004736 ch = ((s[0] & 0x0f) << 12) + ((s[1] & 0x3f) << 6) + (s[2] & 0x3f);
Ezio Melotti57221d02010-07-01 07:32:02 +00004737 assert ((ch > 0x07FF) && (ch <= 0xFFFF));
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004738 WRITE_MAYBE_FAIL(i++, ch);
Marc-André Lemburge12896e2000-07-07 17:51:08 +00004739 break;
4740
4741 case 4:
4742 if ((s[1] & 0xc0) != 0x80 ||
4743 (s[2] & 0xc0) != 0x80 ||
Ezio Melotti57221d02010-07-01 07:32:02 +00004744 (s[3] & 0xc0) != 0x80 ||
4745 ((unsigned char)s[0] == 0xF0 &&
4746 (unsigned char)s[1] < 0x90) ||
4747 ((unsigned char)s[0] == 0xF4 &&
4748 (unsigned char)s[1] > 0x8F)) {
4749 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004750 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004751 endinpos = startinpos + 1;
4752 if ((s[1] & 0xC0) == 0x80) {
4753 endinpos++;
4754 if ((s[2] & 0xC0) == 0x80)
4755 endinpos++;
4756 }
Benjamin Peterson29060642009-01-31 22:14:21 +00004757 goto utf8Error;
4758 }
Marc-André Lemburge12896e2000-07-07 17:51:08 +00004759 ch = ((s[0] & 0x7) << 18) + ((s[1] & 0x3f) << 12) +
Ezio Melotti57221d02010-07-01 07:32:02 +00004760 ((s[2] & 0x3f) << 6) + (s[3] & 0x3f);
Victor Stinner8faf8212011-12-08 22:14:11 +01004761 assert ((ch > 0xFFFF) && (ch <= MAX_UNICODE));
Ezio Melotti57221d02010-07-01 07:32:02 +00004762
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004763 WRITE_MAYBE_FAIL(i++, ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004764 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004765 }
4766 s += n;
Benjamin Peterson29060642009-01-31 22:14:21 +00004767 continue;
Tim Petersced69f82003-09-16 20:30:58 +00004768
Benjamin Peterson29060642009-01-31 22:14:21 +00004769 utf8Error:
Benjamin Peterson29060642009-01-31 22:14:21 +00004770 if (unicode_decode_call_errorhandler(
4771 errors, &errorHandler,
4772 "utf8", errmsg,
4773 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004774 &unicode, &i))
Benjamin Peterson29060642009-01-31 22:14:21 +00004775 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004776 /* Update data because unicode_decode_call_errorhandler might have
4777 re-created or resized the unicode object. */
Benjamin Peterson29060642009-01-31 22:14:21 +00004778 aligned_end = (const char *) ((size_t) e & ~LONG_PTR_MASK);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004779 }
Walter Dörwald69652032004-09-07 20:24:22 +00004780 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00004781 *consumed = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004782
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004783 /* Adjust length and ready string when it contained errors and
4784 is of the old resizable kind. */
Victor Stinner785938e2011-12-11 20:09:03 +01004785 if (unicode_resize(&unicode, i) < 0)
4786 goto onError;
4787 unicode_adjust_maxchar(&unicode);
4788 if (unicode == NULL)
4789 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004790
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004791 Py_XDECREF(errorHandler);
4792 Py_XDECREF(exc);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02004793 assert(_PyUnicode_CheckConsistency(unicode, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01004794 return unicode;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004795
Benjamin Peterson29060642009-01-31 22:14:21 +00004796 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004797 Py_XDECREF(errorHandler);
4798 Py_XDECREF(exc);
Victor Stinner785938e2011-12-11 20:09:03 +01004799 Py_XDECREF(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004800 return NULL;
4801}
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004802#undef WRITE_MAYBE_FAIL
Antoine Pitrouab868312009-01-10 15:40:25 +00004803
Victor Stinner785938e2011-12-11 20:09:03 +01004804PyObject *
4805PyUnicode_DecodeUTF8Stateful(const char *s,
4806 Py_ssize_t size,
4807 const char *errors,
4808 Py_ssize_t *consumed)
4809{
4810 Py_UCS4 maxchar = 0;
4811 Py_ssize_t unicode_size;
4812 int has_errors = 0;
4813 PyObject *unicode;
4814 int kind;
4815 void *data;
4816 const char *starts = s;
4817 const char *e;
4818 Py_ssize_t i;
4819
4820 if (size == 0) {
4821 if (consumed)
4822 *consumed = 0;
Victor Stinner382955f2011-12-11 21:44:00 +01004823 Py_INCREF(unicode_empty);
4824 return unicode_empty;
Victor Stinner785938e2011-12-11 20:09:03 +01004825 }
4826
Victor Stinnera1d12bb2011-12-11 21:53:09 +01004827 maxchar = utf8_scanner((const unsigned char *)s, size, &unicode_size);
Victor Stinner785938e2011-12-11 20:09:03 +01004828
4829 /* When the string is ASCII only, just use memcpy and return.
4830 unicode_size may be != size if there is an incomplete UTF-8
4831 sequence at the end of the ASCII block. */
4832 if (maxchar < 128 && size == unicode_size) {
4833 if (consumed)
4834 *consumed = size;
4835 return unicode_fromascii(s, size);
4836 }
4837
4838 unicode = PyUnicode_New(unicode_size, maxchar);
4839 if (!unicode)
4840 return NULL;
4841 kind = PyUnicode_KIND(unicode);
4842 data = PyUnicode_DATA(unicode);
4843
4844 /* Unpack UTF-8 encoded data */
4845 i = 0;
4846 e = starts + size;
4847 switch (kind) {
4848 case PyUnicode_1BYTE_KIND:
4849 has_errors = ucs1lib_utf8_try_decode(s, e, (Py_UCS1 *) data, &s, &i);
4850 break;
4851 case PyUnicode_2BYTE_KIND:
4852 has_errors = ucs2lib_utf8_try_decode(s, e, (Py_UCS2 *) data, &s, &i);
4853 break;
4854 case PyUnicode_4BYTE_KIND:
4855 has_errors = ucs4lib_utf8_try_decode(s, e, (Py_UCS4 *) data, &s, &i);
4856 break;
4857 }
4858 if (!has_errors) {
4859 /* Ensure the unicode size calculation was correct */
4860 assert(i == unicode_size);
4861 assert(s == e);
4862 if (consumed)
4863 *consumed = size;
4864 return unicode;
4865 }
4866
4867 /* In case of errors, maxchar and size computation might be incorrect;
4868 code below refits and resizes as necessary. */
4869 return decode_utf8_errors(starts, size, errors, consumed, s, unicode, i);
4870}
4871
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004872#ifdef __APPLE__
4873
4874/* Simplified UTF-8 decoder using surrogateescape error handler,
4875 used to decode the command line arguments on Mac OS X. */
4876
4877wchar_t*
4878_Py_DecodeUTF8_surrogateescape(const char *s, Py_ssize_t size)
4879{
4880 int n;
4881 const char *e;
4882 wchar_t *unicode, *p;
4883
4884 /* Note: size will always be longer than the resulting Unicode
4885 character count */
4886 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < (size + 1)) {
4887 PyErr_NoMemory();
4888 return NULL;
4889 }
4890 unicode = PyMem_Malloc((size + 1) * sizeof(wchar_t));
4891 if (!unicode)
4892 return NULL;
4893
4894 /* Unpack UTF-8 encoded data */
4895 p = unicode;
4896 e = s + size;
4897 while (s < e) {
4898 Py_UCS4 ch = (unsigned char)*s;
4899
4900 if (ch < 0x80) {
4901 *p++ = (wchar_t)ch;
4902 s++;
4903 continue;
4904 }
4905
4906 n = utf8_code_length[ch];
4907 if (s + n > e) {
4908 goto surrogateescape;
4909 }
4910
4911 switch (n) {
4912 case 0:
4913 case 1:
4914 goto surrogateescape;
4915
4916 case 2:
4917 if ((s[1] & 0xc0) != 0x80)
4918 goto surrogateescape;
4919 ch = ((s[0] & 0x1f) << 6) + (s[1] & 0x3f);
4920 assert ((ch > 0x007F) && (ch <= 0x07FF));
4921 *p++ = (wchar_t)ch;
4922 break;
4923
4924 case 3:
4925 /* Decoding UTF-8 sequences in range \xed\xa0\x80-\xed\xbf\xbf
4926 will result in surrogates in range d800-dfff. Surrogates are
4927 not valid UTF-8 so they are rejected.
4928 See http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf
4929 (table 3-7) and http://www.rfc-editor.org/rfc/rfc3629.txt */
4930 if ((s[1] & 0xc0) != 0x80 ||
4931 (s[2] & 0xc0) != 0x80 ||
4932 ((unsigned char)s[0] == 0xE0 &&
4933 (unsigned char)s[1] < 0xA0) ||
4934 ((unsigned char)s[0] == 0xED &&
4935 (unsigned char)s[1] > 0x9F)) {
4936
4937 goto surrogateescape;
4938 }
4939 ch = ((s[0] & 0x0f) << 12) + ((s[1] & 0x3f) << 6) + (s[2] & 0x3f);
4940 assert ((ch > 0x07FF) && (ch <= 0xFFFF));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004941 *p++ = (wchar_t)ch;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004942 break;
4943
4944 case 4:
4945 if ((s[1] & 0xc0) != 0x80 ||
4946 (s[2] & 0xc0) != 0x80 ||
4947 (s[3] & 0xc0) != 0x80 ||
4948 ((unsigned char)s[0] == 0xF0 &&
4949 (unsigned char)s[1] < 0x90) ||
4950 ((unsigned char)s[0] == 0xF4 &&
4951 (unsigned char)s[1] > 0x8F)) {
4952 goto surrogateescape;
4953 }
4954 ch = ((s[0] & 0x7) << 18) + ((s[1] & 0x3f) << 12) +
4955 ((s[2] & 0x3f) << 6) + (s[3] & 0x3f);
Victor Stinner8faf8212011-12-08 22:14:11 +01004956 assert ((ch > 0xFFFF) && (ch <= MAX_UNICODE));
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004957
4958#if SIZEOF_WCHAR_T == 4
4959 *p++ = (wchar_t)ch;
4960#else
4961 /* compute and append the two surrogates: */
Victor Stinner551ac952011-11-29 22:58:13 +01004962 *p++ = (wchar_t)Py_UNICODE_HIGH_SURROGATE(ch);
4963 *p++ = (wchar_t)Py_UNICODE_LOW_SURROGATE(ch);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004964#endif
4965 break;
4966 }
4967 s += n;
4968 continue;
4969
4970 surrogateescape:
4971 *p++ = 0xDC00 + ch;
4972 s++;
4973 }
4974 *p = L'\0';
4975 return unicode;
4976}
4977
4978#endif /* __APPLE__ */
Antoine Pitrouab868312009-01-10 15:40:25 +00004979
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004980/* Primary internal function which creates utf8 encoded bytes objects.
4981
4982 Allocation strategy: if the string is short, convert into a stack buffer
Tim Peters602f7402002-04-27 18:03:26 +00004983 and allocate exactly as much space needed at the end. Else allocate the
4984 maximum possible needed (4 result bytes per Unicode character), and return
4985 the excess memory at the end.
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004986*/
Tim Peters7e3d9612002-04-21 03:26:37 +00004987PyObject *
Victor Stinner7931d9a2011-11-04 00:22:48 +01004988_PyUnicode_AsUTF8String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004989{
Tim Peters602f7402002-04-27 18:03:26 +00004990#define MAX_SHORT_UNICHARS 300 /* largest size we'll do on the stack */
Tim Peters0eca65c2002-04-21 17:28:06 +00004991
Guido van Rossum98297ee2007-11-06 21:34:58 +00004992 Py_ssize_t i; /* index into s of next input byte */
4993 PyObject *result; /* result string object */
4994 char *p; /* next free byte in output buffer */
4995 Py_ssize_t nallocated; /* number of result bytes allocated */
4996 Py_ssize_t nneeded; /* number of result bytes needed */
Tim Peters602f7402002-04-27 18:03:26 +00004997 char stackbuf[MAX_SHORT_UNICHARS * 4];
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004998 PyObject *errorHandler = NULL;
4999 PyObject *exc = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005000 int kind;
5001 void *data;
5002 Py_ssize_t size;
Antoine Pitrou31b92a52011-11-12 18:35:19 +01005003 PyObject *rep = NULL;
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00005004
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005005 if (!PyUnicode_Check(unicode)) {
5006 PyErr_BadArgument();
5007 return NULL;
5008 }
5009
5010 if (PyUnicode_READY(unicode) == -1)
5011 return NULL;
5012
Victor Stinnere90fe6a2011-10-01 16:48:13 +02005013 if (PyUnicode_UTF8(unicode))
5014 return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode),
5015 PyUnicode_UTF8_LENGTH(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005016
5017 kind = PyUnicode_KIND(unicode);
5018 data = PyUnicode_DATA(unicode);
5019 size = PyUnicode_GET_LENGTH(unicode);
5020
Tim Peters602f7402002-04-27 18:03:26 +00005021 assert(size >= 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005022
Tim Peters602f7402002-04-27 18:03:26 +00005023 if (size <= MAX_SHORT_UNICHARS) {
5024 /* Write into the stack buffer; nallocated can't overflow.
5025 * At the end, we'll allocate exactly as much heap space as it
5026 * turns out we need.
5027 */
5028 nallocated = Py_SAFE_DOWNCAST(sizeof(stackbuf), size_t, int);
Guido van Rossum98297ee2007-11-06 21:34:58 +00005029 result = NULL; /* will allocate after we're done */
Tim Peters602f7402002-04-27 18:03:26 +00005030 p = stackbuf;
5031 }
5032 else {
5033 /* Overallocate on the heap, and give the excess back at the end. */
5034 nallocated = size * 4;
5035 if (nallocated / 4 != size) /* overflow! */
5036 return PyErr_NoMemory();
Christian Heimes72b710a2008-05-26 13:28:38 +00005037 result = PyBytes_FromStringAndSize(NULL, nallocated);
Guido van Rossum98297ee2007-11-06 21:34:58 +00005038 if (result == NULL)
Tim Peters602f7402002-04-27 18:03:26 +00005039 return NULL;
Christian Heimes72b710a2008-05-26 13:28:38 +00005040 p = PyBytes_AS_STRING(result);
Tim Peters602f7402002-04-27 18:03:26 +00005041 }
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00005042
Tim Peters602f7402002-04-27 18:03:26 +00005043 for (i = 0; i < size;) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005044 Py_UCS4 ch = PyUnicode_READ(kind, data, i++);
Marc-André Lemburg3688a882002-02-06 18:09:02 +00005045
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00005046 if (ch < 0x80)
Tim Peters602f7402002-04-27 18:03:26 +00005047 /* Encode ASCII */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005048 *p++ = (char) ch;
Marc-André Lemburg3688a882002-02-06 18:09:02 +00005049
Guido van Rossumd57fd912000-03-10 22:53:23 +00005050 else if (ch < 0x0800) {
Tim Peters602f7402002-04-27 18:03:26 +00005051 /* Encode Latin-1 */
Marc-André Lemburgdc724d62002-02-06 18:20:19 +00005052 *p++ = (char)(0xc0 | (ch >> 6));
5053 *p++ = (char)(0x80 | (ch & 0x3f));
Victor Stinner551ac952011-11-29 22:58:13 +01005054 } else if (Py_UNICODE_IS_SURROGATE(ch)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005055 Py_ssize_t newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005056 Py_ssize_t repsize, k, startpos;
5057 startpos = i-1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005058 rep = unicode_encode_call_errorhandler(
5059 errors, &errorHandler, "utf-8", "surrogates not allowed",
Victor Stinner7931d9a2011-11-04 00:22:48 +01005060 unicode, &exc, startpos, startpos+1, &newpos);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005061 if (!rep)
5062 goto error;
Victor Stinner31be90b2010-04-22 19:38:16 +00005063
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005064 if (PyBytes_Check(rep))
5065 repsize = PyBytes_GET_SIZE(rep);
5066 else
Victor Stinner9e30aa52011-11-21 02:49:52 +01005067 repsize = PyUnicode_GET_LENGTH(rep);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005068
5069 if (repsize > 4) {
5070 Py_ssize_t offset;
5071
5072 if (result == NULL)
5073 offset = p - stackbuf;
Victor Stinner31be90b2010-04-22 19:38:16 +00005074 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005075 offset = p - PyBytes_AS_STRING(result);
Victor Stinner31be90b2010-04-22 19:38:16 +00005076
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005077 if (nallocated > PY_SSIZE_T_MAX - repsize + 4) {
5078 /* integer overflow */
5079 PyErr_NoMemory();
5080 goto error;
5081 }
5082 nallocated += repsize - 4;
5083 if (result != NULL) {
5084 if (_PyBytes_Resize(&result, nallocated) < 0)
5085 goto error;
5086 } else {
5087 result = PyBytes_FromStringAndSize(NULL, nallocated);
Victor Stinner31be90b2010-04-22 19:38:16 +00005088 if (result == NULL)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005089 goto error;
5090 Py_MEMCPY(PyBytes_AS_STRING(result), stackbuf, offset);
5091 }
5092 p = PyBytes_AS_STRING(result) + offset;
5093 }
Victor Stinner31be90b2010-04-22 19:38:16 +00005094
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005095 if (PyBytes_Check(rep)) {
5096 char *prep = PyBytes_AS_STRING(rep);
5097 for(k = repsize; k > 0; k--)
5098 *p++ = *prep++;
5099 } else /* rep is unicode */ {
Victor Stinnera98b28c2011-11-10 20:21:49 +01005100 enum PyUnicode_Kind repkind;
5101 void *repdata;
5102
Antoine Pitrou31b92a52011-11-12 18:35:19 +01005103 if (PyUnicode_READY(rep) < 0)
Victor Stinnera98b28c2011-11-10 20:21:49 +01005104 goto error;
Victor Stinnera98b28c2011-11-10 20:21:49 +01005105 repkind = PyUnicode_KIND(rep);
5106 repdata = PyUnicode_DATA(rep);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005107
5108 for(k=0; k<repsize; k++) {
Victor Stinnera98b28c2011-11-10 20:21:49 +01005109 Py_UCS4 c = PyUnicode_READ(repkind, repdata, k);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005110 if (0x80 <= c) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01005111 raise_encode_exception(&exc, "utf-8",
Victor Stinner7931d9a2011-11-04 00:22:48 +01005112 unicode,
Martin v. Löwis9e816682011-11-02 12:45:42 +01005113 i-1, i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005114 "surrogates not allowed");
Victor Stinner31be90b2010-04-22 19:38:16 +00005115 goto error;
5116 }
Victor Stinnera98b28c2011-11-10 20:21:49 +01005117 *p++ = (char)c;
Victor Stinner31be90b2010-04-22 19:38:16 +00005118 }
Victor Stinner31be90b2010-04-22 19:38:16 +00005119 }
Antoine Pitrou31b92a52011-11-12 18:35:19 +01005120 Py_CLEAR(rep);
Victor Stinner31be90b2010-04-22 19:38:16 +00005121 } else if (ch < 0x10000) {
5122 *p++ = (char)(0xe0 | (ch >> 12));
5123 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
5124 *p++ = (char)(0x80 | (ch & 0x3f));
5125 } else /* ch >= 0x10000 */ {
Victor Stinner8faf8212011-12-08 22:14:11 +01005126 assert(ch <= MAX_UNICODE);
Tim Peters602f7402002-04-27 18:03:26 +00005127 /* Encode UCS4 Unicode ordinals */
5128 *p++ = (char)(0xf0 | (ch >> 18));
5129 *p++ = (char)(0x80 | ((ch >> 12) & 0x3f));
5130 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
5131 *p++ = (char)(0x80 | (ch & 0x3f));
5132 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005133 }
Tim Peters0eca65c2002-04-21 17:28:06 +00005134
Guido van Rossum98297ee2007-11-06 21:34:58 +00005135 if (result == NULL) {
Tim Peters602f7402002-04-27 18:03:26 +00005136 /* This was stack allocated. */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005137 nneeded = p - stackbuf;
Tim Peters602f7402002-04-27 18:03:26 +00005138 assert(nneeded <= nallocated);
Christian Heimes72b710a2008-05-26 13:28:38 +00005139 result = PyBytes_FromStringAndSize(stackbuf, nneeded);
Tim Peters602f7402002-04-27 18:03:26 +00005140 }
5141 else {
Christian Heimesf3863112007-11-22 07:46:41 +00005142 /* Cut back to size actually needed. */
Christian Heimes72b710a2008-05-26 13:28:38 +00005143 nneeded = p - PyBytes_AS_STRING(result);
Tim Peters602f7402002-04-27 18:03:26 +00005144 assert(nneeded <= nallocated);
Christian Heimes72b710a2008-05-26 13:28:38 +00005145 _PyBytes_Resize(&result, nneeded);
Tim Peters602f7402002-04-27 18:03:26 +00005146 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005147
Martin v. Löwisdb12d452009-05-02 18:52:14 +00005148 Py_XDECREF(errorHandler);
5149 Py_XDECREF(exc);
Guido van Rossum98297ee2007-11-06 21:34:58 +00005150 return result;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00005151 error:
Antoine Pitrou31b92a52011-11-12 18:35:19 +01005152 Py_XDECREF(rep);
Martin v. Löwisdb12d452009-05-02 18:52:14 +00005153 Py_XDECREF(errorHandler);
5154 Py_XDECREF(exc);
5155 Py_XDECREF(result);
5156 return NULL;
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00005157
Tim Peters602f7402002-04-27 18:03:26 +00005158#undef MAX_SHORT_UNICHARS
Guido van Rossumd57fd912000-03-10 22:53:23 +00005159}
5160
Alexander Belopolsky40018472011-02-26 01:02:56 +00005161PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005162PyUnicode_EncodeUTF8(const Py_UNICODE *s,
5163 Py_ssize_t size,
5164 const char *errors)
5165{
5166 PyObject *v, *unicode;
5167
5168 unicode = PyUnicode_FromUnicode(s, size);
5169 if (unicode == NULL)
5170 return NULL;
5171 v = _PyUnicode_AsUTF8String(unicode, errors);
5172 Py_DECREF(unicode);
5173 return v;
5174}
5175
5176PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005177PyUnicode_AsUTF8String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005178{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005179 return _PyUnicode_AsUTF8String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005180}
5181
Walter Dörwald41980ca2007-08-16 21:55:45 +00005182/* --- UTF-32 Codec ------------------------------------------------------- */
5183
5184PyObject *
5185PyUnicode_DecodeUTF32(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005186 Py_ssize_t size,
5187 const char *errors,
5188 int *byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005189{
5190 return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
5191}
5192
5193PyObject *
5194PyUnicode_DecodeUTF32Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005195 Py_ssize_t size,
5196 const char *errors,
5197 int *byteorder,
5198 Py_ssize_t *consumed)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005199{
5200 const char *starts = s;
5201 Py_ssize_t startinpos;
5202 Py_ssize_t endinpos;
5203 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01005204 PyObject *unicode;
Mark Dickinson7db923c2010-06-12 09:10:14 +00005205 const unsigned char *q, *e;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005206 int bo = 0; /* assume native ordering by default */
5207 const char *errmsg = "";
Walter Dörwald41980ca2007-08-16 21:55:45 +00005208 /* Offsets from q for retrieving bytes in the right order. */
5209#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5210 int iorder[] = {0, 1, 2, 3};
5211#else
5212 int iorder[] = {3, 2, 1, 0};
5213#endif
5214 PyObject *errorHandler = NULL;
5215 PyObject *exc = NULL;
Victor Stinner313a1202010-06-11 23:56:51 +00005216
Walter Dörwald41980ca2007-08-16 21:55:45 +00005217 q = (unsigned char *)s;
5218 e = q + size;
5219
5220 if (byteorder)
5221 bo = *byteorder;
5222
5223 /* Check for BOM marks (U+FEFF) in the input and adjust current
5224 byte order setting accordingly. In native mode, the leading BOM
5225 mark is skipped, in all other modes, it is copied to the output
5226 stream as-is (giving a ZWNBSP character). */
5227 if (bo == 0) {
5228 if (size >= 4) {
5229 const Py_UCS4 bom = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
Benjamin Peterson29060642009-01-31 22:14:21 +00005230 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00005231#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Benjamin Peterson29060642009-01-31 22:14:21 +00005232 if (bom == 0x0000FEFF) {
5233 q += 4;
5234 bo = -1;
5235 }
5236 else if (bom == 0xFFFE0000) {
5237 q += 4;
5238 bo = 1;
5239 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00005240#else
Benjamin Peterson29060642009-01-31 22:14:21 +00005241 if (bom == 0x0000FEFF) {
5242 q += 4;
5243 bo = 1;
5244 }
5245 else if (bom == 0xFFFE0000) {
5246 q += 4;
5247 bo = -1;
5248 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00005249#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00005250 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00005251 }
5252
5253 if (bo == -1) {
5254 /* force LE */
5255 iorder[0] = 0;
5256 iorder[1] = 1;
5257 iorder[2] = 2;
5258 iorder[3] = 3;
5259 }
5260 else if (bo == 1) {
5261 /* force BE */
5262 iorder[0] = 3;
5263 iorder[1] = 2;
5264 iorder[2] = 1;
5265 iorder[3] = 0;
5266 }
5267
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005268 /* This might be one to much, because of a BOM */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005269 unicode = PyUnicode_New((size+3)/4, 127);
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005270 if (!unicode)
5271 return NULL;
5272 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01005273 return unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005274 outpos = 0;
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005275
Walter Dörwald41980ca2007-08-16 21:55:45 +00005276 while (q < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005277 Py_UCS4 ch;
5278 /* remaining bytes at the end? (size should be divisible by 4) */
5279 if (e-q<4) {
5280 if (consumed)
5281 break;
5282 errmsg = "truncated data";
5283 startinpos = ((const char *)q)-starts;
5284 endinpos = ((const char *)e)-starts;
5285 goto utf32Error;
5286 /* The remaining input chars are ignored if the callback
5287 chooses to skip the input */
5288 }
5289 ch = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
5290 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00005291
Benjamin Peterson29060642009-01-31 22:14:21 +00005292 if (ch >= 0x110000)
5293 {
5294 errmsg = "codepoint not in range(0x110000)";
5295 startinpos = ((const char *)q)-starts;
5296 endinpos = startinpos+4;
5297 goto utf32Error;
5298 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005299 if (unicode_putchar(&unicode, &outpos, ch) < 0)
5300 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005301 q += 4;
5302 continue;
5303 utf32Error:
Benjamin Peterson29060642009-01-31 22:14:21 +00005304 if (unicode_decode_call_errorhandler(
5305 errors, &errorHandler,
5306 "utf32", errmsg,
5307 &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005308 &unicode, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00005309 goto onError;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005310 }
5311
5312 if (byteorder)
5313 *byteorder = bo;
5314
5315 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005316 *consumed = (const char *)q-starts;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005317
5318 /* Adjust length */
Victor Stinner16e6a802011-12-12 13:24:15 +01005319 if (unicode_resize(&unicode, outpos) < 0)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005320 goto onError;
5321
5322 Py_XDECREF(errorHandler);
5323 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01005324 return unicode_result(unicode);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005325
Benjamin Peterson29060642009-01-31 22:14:21 +00005326 onError:
Walter Dörwald41980ca2007-08-16 21:55:45 +00005327 Py_DECREF(unicode);
5328 Py_XDECREF(errorHandler);
5329 Py_XDECREF(exc);
5330 return NULL;
5331}
5332
5333PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005334_PyUnicode_EncodeUTF32(PyObject *str,
5335 const char *errors,
5336 int byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005337{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005338 int kind;
5339 void *data;
5340 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005341 PyObject *v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005342 unsigned char *p;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005343 Py_ssize_t nsize, bytesize, i;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005344 /* Offsets from p for storing byte pairs in the right order. */
5345#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5346 int iorder[] = {0, 1, 2, 3};
5347#else
5348 int iorder[] = {3, 2, 1, 0};
5349#endif
5350
Benjamin Peterson29060642009-01-31 22:14:21 +00005351#define STORECHAR(CH) \
5352 do { \
5353 p[iorder[3]] = ((CH) >> 24) & 0xff; \
5354 p[iorder[2]] = ((CH) >> 16) & 0xff; \
5355 p[iorder[1]] = ((CH) >> 8) & 0xff; \
5356 p[iorder[0]] = (CH) & 0xff; \
5357 p += 4; \
Walter Dörwald41980ca2007-08-16 21:55:45 +00005358 } while(0)
5359
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005360 if (!PyUnicode_Check(str)) {
5361 PyErr_BadArgument();
5362 return NULL;
5363 }
5364 if (PyUnicode_READY(str) < 0)
5365 return NULL;
5366 kind = PyUnicode_KIND(str);
5367 data = PyUnicode_DATA(str);
5368 len = PyUnicode_GET_LENGTH(str);
5369
5370 nsize = len + (byteorder == 0);
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005371 bytesize = nsize * 4;
5372 if (bytesize / 4 != nsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005373 return PyErr_NoMemory();
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005374 v = PyBytes_FromStringAndSize(NULL, bytesize);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005375 if (v == NULL)
5376 return NULL;
5377
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005378 p = (unsigned char *)PyBytes_AS_STRING(v);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005379 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005380 STORECHAR(0xFEFF);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005381 if (len == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005382 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005383
5384 if (byteorder == -1) {
5385 /* force LE */
5386 iorder[0] = 0;
5387 iorder[1] = 1;
5388 iorder[2] = 2;
5389 iorder[3] = 3;
5390 }
5391 else if (byteorder == 1) {
5392 /* force BE */
5393 iorder[0] = 3;
5394 iorder[1] = 2;
5395 iorder[2] = 1;
5396 iorder[3] = 0;
5397 }
5398
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005399 for (i = 0; i < len; i++)
5400 STORECHAR(PyUnicode_READ(kind, data, i));
Guido van Rossum98297ee2007-11-06 21:34:58 +00005401
5402 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005403 return v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005404#undef STORECHAR
5405}
5406
Alexander Belopolsky40018472011-02-26 01:02:56 +00005407PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005408PyUnicode_EncodeUTF32(const Py_UNICODE *s,
5409 Py_ssize_t size,
5410 const char *errors,
5411 int byteorder)
5412{
5413 PyObject *result;
5414 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5415 if (tmp == NULL)
5416 return NULL;
5417 result = _PyUnicode_EncodeUTF32(tmp, errors, byteorder);
5418 Py_DECREF(tmp);
5419 return result;
5420}
5421
5422PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005423PyUnicode_AsUTF32String(PyObject *unicode)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005424{
Victor Stinnerb960b342011-11-20 19:12:52 +01005425 return _PyUnicode_EncodeUTF32(unicode, NULL, 0);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005426}
5427
Guido van Rossumd57fd912000-03-10 22:53:23 +00005428/* --- UTF-16 Codec ------------------------------------------------------- */
5429
Tim Peters772747b2001-08-09 22:21:55 +00005430PyObject *
5431PyUnicode_DecodeUTF16(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005432 Py_ssize_t size,
5433 const char *errors,
5434 int *byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005435{
Walter Dörwald69652032004-09-07 20:24:22 +00005436 return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
5437}
5438
Antoine Pitrouab868312009-01-10 15:40:25 +00005439/* Two masks for fast checking of whether a C 'long' may contain
5440 UTF16-encoded surrogate characters. This is an efficient heuristic,
5441 assuming that non-surrogate characters with a code point >= 0x8000 are
5442 rare in most input.
5443 FAST_CHAR_MASK is used when the input is in native byte ordering,
5444 SWAPPED_FAST_CHAR_MASK when the input is in byteswapped ordering.
Benjamin Peterson29060642009-01-31 22:14:21 +00005445*/
Antoine Pitrouab868312009-01-10 15:40:25 +00005446#if (SIZEOF_LONG == 8)
5447# define FAST_CHAR_MASK 0x8000800080008000L
5448# define SWAPPED_FAST_CHAR_MASK 0x0080008000800080L
5449#elif (SIZEOF_LONG == 4)
5450# define FAST_CHAR_MASK 0x80008000L
5451# define SWAPPED_FAST_CHAR_MASK 0x00800080L
5452#else
5453# error C 'long' size should be either 4 or 8!
5454#endif
5455
Walter Dörwald69652032004-09-07 20:24:22 +00005456PyObject *
5457PyUnicode_DecodeUTF16Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005458 Py_ssize_t size,
5459 const char *errors,
5460 int *byteorder,
5461 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00005462{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005463 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005464 Py_ssize_t startinpos;
5465 Py_ssize_t endinpos;
5466 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01005467 PyObject *unicode;
Antoine Pitrouab868312009-01-10 15:40:25 +00005468 const unsigned char *q, *e, *aligned_end;
Tim Peters772747b2001-08-09 22:21:55 +00005469 int bo = 0; /* assume native ordering by default */
Antoine Pitrouab868312009-01-10 15:40:25 +00005470 int native_ordering = 0;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00005471 const char *errmsg = "";
Tim Peters772747b2001-08-09 22:21:55 +00005472 /* Offsets from q for retrieving byte pairs in the right order. */
5473#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5474 int ihi = 1, ilo = 0;
5475#else
5476 int ihi = 0, ilo = 1;
5477#endif
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005478 PyObject *errorHandler = NULL;
5479 PyObject *exc = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005480
5481 /* Note: size will always be longer than the resulting Unicode
5482 character count */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005483 unicode = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005484 if (!unicode)
5485 return NULL;
5486 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01005487 return unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005488 outpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005489
Tim Peters772747b2001-08-09 22:21:55 +00005490 q = (unsigned char *)s;
Antoine Pitrouab868312009-01-10 15:40:25 +00005491 e = q + size - 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005492
5493 if (byteorder)
Tim Peters772747b2001-08-09 22:21:55 +00005494 bo = *byteorder;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005495
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005496 /* Check for BOM marks (U+FEFF) in the input and adjust current
5497 byte order setting accordingly. In native mode, the leading BOM
5498 mark is skipped, in all other modes, it is copied to the output
5499 stream as-is (giving a ZWNBSP character). */
5500 if (bo == 0) {
Walter Dörwald69652032004-09-07 20:24:22 +00005501 if (size >= 2) {
Victor Stinner24729f32011-11-10 20:31:37 +01005502 const Py_UCS4 bom = (q[ihi] << 8) | q[ilo];
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005503#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Benjamin Peterson29060642009-01-31 22:14:21 +00005504 if (bom == 0xFEFF) {
5505 q += 2;
5506 bo = -1;
5507 }
5508 else if (bom == 0xFFFE) {
5509 q += 2;
5510 bo = 1;
5511 }
Tim Petersced69f82003-09-16 20:30:58 +00005512#else
Benjamin Peterson29060642009-01-31 22:14:21 +00005513 if (bom == 0xFEFF) {
5514 q += 2;
5515 bo = 1;
5516 }
5517 else if (bom == 0xFFFE) {
5518 q += 2;
5519 bo = -1;
5520 }
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005521#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00005522 }
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005523 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005524
Tim Peters772747b2001-08-09 22:21:55 +00005525 if (bo == -1) {
5526 /* force LE */
5527 ihi = 1;
5528 ilo = 0;
5529 }
5530 else if (bo == 1) {
5531 /* force BE */
5532 ihi = 0;
5533 ilo = 1;
5534 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005535#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5536 native_ordering = ilo < ihi;
5537#else
5538 native_ordering = ilo > ihi;
5539#endif
Tim Peters772747b2001-08-09 22:21:55 +00005540
Antoine Pitrouab868312009-01-10 15:40:25 +00005541 aligned_end = (const unsigned char *) ((size_t) e & ~LONG_PTR_MASK);
Tim Peters772747b2001-08-09 22:21:55 +00005542 while (q < e) {
Victor Stinner24729f32011-11-10 20:31:37 +01005543 Py_UCS4 ch;
Antoine Pitrouab868312009-01-10 15:40:25 +00005544 /* First check for possible aligned read of a C 'long'. Unaligned
5545 reads are more expensive, better to defer to another iteration. */
5546 if (!((size_t) q & LONG_PTR_MASK)) {
5547 /* Fast path for runs of non-surrogate chars. */
5548 register const unsigned char *_q = q;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005549 int kind = PyUnicode_KIND(unicode);
5550 void *data = PyUnicode_DATA(unicode);
5551 while (_q < aligned_end) {
5552 unsigned long block = * (unsigned long *) _q;
5553 unsigned short *pblock = (unsigned short*)&block;
5554 Py_UCS4 maxch;
5555 if (native_ordering) {
5556 /* Can use buffer directly */
5557 if (block & FAST_CHAR_MASK)
Antoine Pitrouab868312009-01-10 15:40:25 +00005558 break;
Antoine Pitrouab868312009-01-10 15:40:25 +00005559 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005560 else {
5561 /* Need to byte-swap */
5562 unsigned char *_p = (unsigned char*)pblock;
5563 if (block & SWAPPED_FAST_CHAR_MASK)
Antoine Pitrouab868312009-01-10 15:40:25 +00005564 break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005565 _p[0] = _q[1];
5566 _p[1] = _q[0];
5567 _p[2] = _q[3];
5568 _p[3] = _q[2];
Antoine Pitrouab868312009-01-10 15:40:25 +00005569#if (SIZEOF_LONG == 8)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005570 _p[4] = _q[5];
5571 _p[5] = _q[4];
5572 _p[6] = _q[7];
5573 _p[7] = _q[6];
Antoine Pitrouab868312009-01-10 15:40:25 +00005574#endif
Antoine Pitrouab868312009-01-10 15:40:25 +00005575 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005576 maxch = Py_MAX(pblock[0], pblock[1]);
5577#if SIZEOF_LONG == 8
5578 maxch = Py_MAX(maxch, Py_MAX(pblock[2], pblock[3]));
5579#endif
5580 if (maxch > PyUnicode_MAX_CHAR_VALUE(unicode)) {
5581 if (unicode_widen(&unicode, maxch) < 0)
5582 goto onError;
5583 kind = PyUnicode_KIND(unicode);
5584 data = PyUnicode_DATA(unicode);
5585 }
5586 PyUnicode_WRITE(kind, data, outpos++, pblock[0]);
5587 PyUnicode_WRITE(kind, data, outpos++, pblock[1]);
5588#if SIZEOF_LONG == 8
5589 PyUnicode_WRITE(kind, data, outpos++, pblock[2]);
5590 PyUnicode_WRITE(kind, data, outpos++, pblock[3]);
5591#endif
5592 _q += SIZEOF_LONG;
Antoine Pitrouab868312009-01-10 15:40:25 +00005593 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005594 q = _q;
5595 if (q >= e)
5596 break;
5597 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005598 ch = (q[ihi] << 8) | q[ilo];
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005599
Benjamin Peterson14339b62009-01-31 16:36:08 +00005600 q += 2;
Benjamin Peterson29060642009-01-31 22:14:21 +00005601
Victor Stinner551ac952011-11-29 22:58:13 +01005602 if (!Py_UNICODE_IS_SURROGATE(ch)) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005603 if (unicode_putchar(&unicode, &outpos, ch) < 0)
5604 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005605 continue;
5606 }
5607
5608 /* UTF-16 code pair: */
5609 if (q > e) {
5610 errmsg = "unexpected end of data";
5611 startinpos = (((const char *)q) - 2) - starts;
5612 endinpos = ((const char *)e) + 1 - starts;
5613 goto utf16Error;
5614 }
Victor Stinner2e9cfad2011-11-20 18:40:27 +01005615 if (Py_UNICODE_IS_HIGH_SURROGATE(ch)) {
5616 Py_UCS4 ch2 = (q[ihi] << 8) | q[ilo];
Benjamin Peterson29060642009-01-31 22:14:21 +00005617 q += 2;
Victor Stinner2e9cfad2011-11-20 18:40:27 +01005618 if (Py_UNICODE_IS_LOW_SURROGATE(ch2)) {
Victor Stinner62aa4d02011-11-09 00:03:45 +01005619 if (unicode_putchar(&unicode, &outpos,
Victor Stinner2e9cfad2011-11-20 18:40:27 +01005620 Py_UNICODE_JOIN_SURROGATES(ch, ch2)) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005621 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005622 continue;
5623 }
5624 else {
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005625 errmsg = "illegal UTF-16 surrogate";
Benjamin Peterson29060642009-01-31 22:14:21 +00005626 startinpos = (((const char *)q)-4)-starts;
5627 endinpos = startinpos+2;
5628 goto utf16Error;
5629 }
5630
Benjamin Peterson14339b62009-01-31 16:36:08 +00005631 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005632 errmsg = "illegal encoding";
5633 startinpos = (((const char *)q)-2)-starts;
5634 endinpos = startinpos+2;
5635 /* Fall through to report the error */
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005636
Benjamin Peterson29060642009-01-31 22:14:21 +00005637 utf16Error:
Benjamin Peterson29060642009-01-31 22:14:21 +00005638 if (unicode_decode_call_errorhandler(
Antoine Pitrouab868312009-01-10 15:40:25 +00005639 errors,
5640 &errorHandler,
5641 "utf16", errmsg,
5642 &starts,
5643 (const char **)&e,
5644 &startinpos,
5645 &endinpos,
5646 &exc,
5647 (const char **)&q,
5648 &unicode,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005649 &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00005650 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005651 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005652 /* remaining byte at the end? (size should be even) */
5653 if (e == q) {
5654 if (!consumed) {
5655 errmsg = "truncated data";
5656 startinpos = ((const char *)q) - starts;
5657 endinpos = ((const char *)e) + 1 - starts;
Antoine Pitrouab868312009-01-10 15:40:25 +00005658 if (unicode_decode_call_errorhandler(
5659 errors,
5660 &errorHandler,
5661 "utf16", errmsg,
5662 &starts,
5663 (const char **)&e,
5664 &startinpos,
5665 &endinpos,
5666 &exc,
5667 (const char **)&q,
5668 &unicode,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005669 &outpos))
Antoine Pitrouab868312009-01-10 15:40:25 +00005670 goto onError;
5671 /* The remaining input chars are ignored if the callback
5672 chooses to skip the input */
5673 }
5674 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005675
5676 if (byteorder)
5677 *byteorder = bo;
5678
Walter Dörwald69652032004-09-07 20:24:22 +00005679 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005680 *consumed = (const char *)q-starts;
Walter Dörwald69652032004-09-07 20:24:22 +00005681
Guido van Rossumd57fd912000-03-10 22:53:23 +00005682 /* Adjust length */
Victor Stinner16e6a802011-12-12 13:24:15 +01005683 if (unicode_resize(&unicode, outpos) < 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005684 goto onError;
5685
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005686 Py_XDECREF(errorHandler);
5687 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01005688 return unicode_result(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005689
Benjamin Peterson29060642009-01-31 22:14:21 +00005690 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00005691 Py_DECREF(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005692 Py_XDECREF(errorHandler);
5693 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005694 return NULL;
5695}
5696
Antoine Pitrouab868312009-01-10 15:40:25 +00005697#undef FAST_CHAR_MASK
5698#undef SWAPPED_FAST_CHAR_MASK
5699
Tim Peters772747b2001-08-09 22:21:55 +00005700PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005701_PyUnicode_EncodeUTF16(PyObject *str,
5702 const char *errors,
5703 int byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005704{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005705 int kind;
5706 void *data;
5707 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005708 PyObject *v;
Tim Peters772747b2001-08-09 22:21:55 +00005709 unsigned char *p;
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005710 Py_ssize_t nsize, bytesize;
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005711 Py_ssize_t i, pairs;
Tim Peters772747b2001-08-09 22:21:55 +00005712 /* Offsets from p for storing byte pairs in the right order. */
5713#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5714 int ihi = 1, ilo = 0;
5715#else
5716 int ihi = 0, ilo = 1;
5717#endif
5718
Benjamin Peterson29060642009-01-31 22:14:21 +00005719#define STORECHAR(CH) \
5720 do { \
5721 p[ihi] = ((CH) >> 8) & 0xff; \
5722 p[ilo] = (CH) & 0xff; \
5723 p += 2; \
Tim Peters772747b2001-08-09 22:21:55 +00005724 } while(0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005725
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005726 if (!PyUnicode_Check(str)) {
5727 PyErr_BadArgument();
5728 return NULL;
5729 }
5730 if (PyUnicode_READY(str) < 0)
5731 return NULL;
5732 kind = PyUnicode_KIND(str);
5733 data = PyUnicode_DATA(str);
5734 len = PyUnicode_GET_LENGTH(str);
Victor Stinner0e368262011-11-10 20:12:49 +01005735
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005736 pairs = 0;
5737 if (kind == PyUnicode_4BYTE_KIND)
5738 for (i = 0; i < len; i++)
5739 if (PyUnicode_READ(kind, data, i) >= 0x10000)
5740 pairs++;
5741 /* 2 * (len + pairs + (byteorder == 0)) */
5742 if (len > PY_SSIZE_T_MAX - pairs - (byteorder == 0))
Benjamin Peterson29060642009-01-31 22:14:21 +00005743 return PyErr_NoMemory();
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005744 nsize = len + pairs + (byteorder == 0);
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005745 bytesize = nsize * 2;
5746 if (bytesize / 2 != nsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005747 return PyErr_NoMemory();
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005748 v = PyBytes_FromStringAndSize(NULL, bytesize);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005749 if (v == NULL)
5750 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005751
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005752 p = (unsigned char *)PyBytes_AS_STRING(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005753 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005754 STORECHAR(0xFEFF);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005755 if (len == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005756 goto done;
Tim Peters772747b2001-08-09 22:21:55 +00005757
5758 if (byteorder == -1) {
5759 /* force LE */
5760 ihi = 1;
5761 ilo = 0;
5762 }
5763 else if (byteorder == 1) {
5764 /* force BE */
5765 ihi = 0;
5766 ilo = 1;
5767 }
5768
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005769 for (i = 0; i < len; i++) {
5770 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
5771 Py_UCS4 ch2 = 0;
Benjamin Peterson29060642009-01-31 22:14:21 +00005772 if (ch >= 0x10000) {
Victor Stinner551ac952011-11-29 22:58:13 +01005773 ch2 = Py_UNICODE_LOW_SURROGATE(ch);
5774 ch = Py_UNICODE_HIGH_SURROGATE(ch);
Benjamin Peterson29060642009-01-31 22:14:21 +00005775 }
Tim Peters772747b2001-08-09 22:21:55 +00005776 STORECHAR(ch);
5777 if (ch2)
5778 STORECHAR(ch2);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005779 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005780
5781 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005782 return v;
Tim Peters772747b2001-08-09 22:21:55 +00005783#undef STORECHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00005784}
5785
Alexander Belopolsky40018472011-02-26 01:02:56 +00005786PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005787PyUnicode_EncodeUTF16(const Py_UNICODE *s,
5788 Py_ssize_t size,
5789 const char *errors,
5790 int byteorder)
5791{
5792 PyObject *result;
5793 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5794 if (tmp == NULL)
5795 return NULL;
5796 result = _PyUnicode_EncodeUTF16(tmp, errors, byteorder);
5797 Py_DECREF(tmp);
5798 return result;
5799}
5800
5801PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005802PyUnicode_AsUTF16String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005803{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005804 return _PyUnicode_EncodeUTF16(unicode, NULL, 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005805}
5806
5807/* --- Unicode Escape Codec ----------------------------------------------- */
5808
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005809/* Helper function for PyUnicode_DecodeUnicodeEscape, determines
5810 if all the escapes in the string make it still a valid ASCII string.
5811 Returns -1 if any escapes were found which cause the string to
5812 pop out of ASCII range. Otherwise returns the length of the
5813 required buffer to hold the string.
5814 */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02005815static Py_ssize_t
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005816length_of_escaped_ascii_string(const char *s, Py_ssize_t size)
5817{
5818 const unsigned char *p = (const unsigned char *)s;
5819 const unsigned char *end = p + size;
5820 Py_ssize_t length = 0;
5821
5822 if (size < 0)
5823 return -1;
5824
5825 for (; p < end; ++p) {
5826 if (*p > 127) {
5827 /* Non-ASCII */
5828 return -1;
5829 }
5830 else if (*p != '\\') {
5831 /* Normal character */
5832 ++length;
5833 }
5834 else {
5835 /* Backslash-escape, check next char */
5836 ++p;
5837 /* Escape sequence reaches till end of string or
5838 non-ASCII follow-up. */
5839 if (p >= end || *p > 127)
5840 return -1;
5841 switch (*p) {
5842 case '\n':
5843 /* backslash + \n result in zero characters */
5844 break;
5845 case '\\': case '\'': case '\"':
5846 case 'b': case 'f': case 't':
5847 case 'n': case 'r': case 'v': case 'a':
5848 ++length;
5849 break;
5850 case '0': case '1': case '2': case '3':
5851 case '4': case '5': case '6': case '7':
5852 case 'x': case 'u': case 'U': case 'N':
5853 /* these do not guarantee ASCII characters */
5854 return -1;
5855 default:
5856 /* count the backslash + the other character */
5857 length += 2;
5858 }
5859 }
5860 }
5861 return length;
5862}
5863
Fredrik Lundh06d12682001-01-24 07:59:11 +00005864static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
Marc-André Lemburg0f774e32000-06-28 16:43:35 +00005865
Alexander Belopolsky40018472011-02-26 01:02:56 +00005866PyObject *
5867PyUnicode_DecodeUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005868 Py_ssize_t size,
Victor Stinnerc17f5402011-09-29 00:16:58 +02005869 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005870{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005871 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005872 Py_ssize_t startinpos;
5873 Py_ssize_t endinpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005874 int j;
Victor Stinner7931d9a2011-11-04 00:22:48 +01005875 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005876 const char *end;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005877 char* message;
5878 Py_UCS4 chr = 0xffffffff; /* in case 'getcode' messes up */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005879 PyObject *errorHandler = NULL;
5880 PyObject *exc = NULL;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005881 Py_ssize_t len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005882 Py_ssize_t i;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005883
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005884 len = length_of_escaped_ascii_string(s, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005885
5886 /* After length_of_escaped_ascii_string() there are two alternatives,
5887 either the string is pure ASCII with named escapes like \n, etc.
5888 and we determined it's exact size (common case)
5889 or it contains \x, \u, ... escape sequences. then we create a
5890 legacy wchar string and resize it at the end of this function. */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005891 if (len >= 0) {
5892 v = PyUnicode_New(len, 127);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005893 if (!v)
5894 goto onError;
5895 assert(PyUnicode_KIND(v) == PyUnicode_1BYTE_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005896 }
5897 else {
5898 /* Escaped strings will always be longer than the resulting
5899 Unicode string, so we start with size here and then reduce the
5900 length after conversion to the true value.
5901 (but if the error callback returns a long replacement string
5902 we'll have to allocate more space) */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005903 v = PyUnicode_New(size, 127);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005904 if (!v)
5905 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005906 len = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005907 }
5908
Guido van Rossumd57fd912000-03-10 22:53:23 +00005909 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01005910 return v;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005911 i = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005912 end = s + size;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005913
Guido van Rossumd57fd912000-03-10 22:53:23 +00005914 while (s < end) {
5915 unsigned char c;
Victor Stinner24729f32011-11-10 20:31:37 +01005916 Py_UCS4 x;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005917 int digits;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005918
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005919 /* The only case in which i == ascii_length is a backslash
5920 followed by a newline. */
5921 assert(i <= len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005922
Guido van Rossumd57fd912000-03-10 22:53:23 +00005923 /* Non-escape characters are interpreted as Unicode ordinals */
5924 if (*s != '\\') {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005925 if (unicode_putchar(&v, &i, (unsigned char) *s++) < 0)
5926 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005927 continue;
5928 }
5929
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005930 startinpos = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005931 /* \ - Escapes */
5932 s++;
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005933 c = *s++;
5934 if (s > end)
5935 c = '\0'; /* Invalid after \ */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005936
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005937 /* The only case in which i == ascii_length is a backslash
5938 followed by a newline. */
5939 assert(i < len || (i == len && c == '\n'));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005940
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005941 switch (c) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005942
Benjamin Peterson29060642009-01-31 22:14:21 +00005943 /* \x escapes */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005944#define WRITECHAR(ch) \
5945 do { \
5946 if (unicode_putchar(&v, &i, ch) < 0) \
5947 goto onError; \
5948 }while(0)
5949
Guido van Rossumd57fd912000-03-10 22:53:23 +00005950 case '\n': break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005951 case '\\': WRITECHAR('\\'); break;
5952 case '\'': WRITECHAR('\''); break;
5953 case '\"': WRITECHAR('\"'); break;
5954 case 'b': WRITECHAR('\b'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005955 /* FF */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005956 case 'f': WRITECHAR('\014'); break;
5957 case 't': WRITECHAR('\t'); break;
5958 case 'n': WRITECHAR('\n'); break;
5959 case 'r': WRITECHAR('\r'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005960 /* VT */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005961 case 'v': WRITECHAR('\013'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005962 /* BEL, not classic C */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005963 case 'a': WRITECHAR('\007'); break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005964
Benjamin Peterson29060642009-01-31 22:14:21 +00005965 /* \OOO (octal) escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005966 case '0': case '1': case '2': case '3':
5967 case '4': case '5': case '6': case '7':
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005968 x = s[-1] - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005969 if (s < end && '0' <= *s && *s <= '7') {
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005970 x = (x<<3) + *s++ - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005971 if (s < end && '0' <= *s && *s <= '7')
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005972 x = (x<<3) + *s++ - '0';
Guido van Rossumd57fd912000-03-10 22:53:23 +00005973 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005974 WRITECHAR(x);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005975 break;
5976
Benjamin Peterson29060642009-01-31 22:14:21 +00005977 /* hex escapes */
5978 /* \xXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005979 case 'x':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005980 digits = 2;
5981 message = "truncated \\xXX escape";
5982 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005983
Benjamin Peterson29060642009-01-31 22:14:21 +00005984 /* \uXXXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005985 case 'u':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005986 digits = 4;
5987 message = "truncated \\uXXXX escape";
5988 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005989
Benjamin Peterson29060642009-01-31 22:14:21 +00005990 /* \UXXXXXXXX */
Fredrik Lundhdf846752000-09-03 11:29:49 +00005991 case 'U':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005992 digits = 8;
5993 message = "truncated \\UXXXXXXXX escape";
5994 hexescape:
5995 chr = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005996 if (s+digits>end) {
5997 endinpos = size;
5998 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005999 errors, &errorHandler,
6000 "unicodeescape", "end of string in escape sequence",
6001 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006002 &v, &i))
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006003 goto onError;
6004 goto nextByte;
6005 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006006 for (j = 0; j < digits; ++j) {
6007 c = (unsigned char) s[j];
David Malcolm96960882010-11-05 17:23:41 +00006008 if (!Py_ISXDIGIT(c)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006009 endinpos = (s+j+1)-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006010 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00006011 errors, &errorHandler,
6012 "unicodeescape", message,
6013 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006014 &v, &i))
Fredrik Lundhdf846752000-09-03 11:29:49 +00006015 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006016 len = PyUnicode_GET_LENGTH(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006017 goto nextByte;
Fredrik Lundhdf846752000-09-03 11:29:49 +00006018 }
6019 chr = (chr<<4) & ~0xF;
6020 if (c >= '0' && c <= '9')
6021 chr += c - '0';
6022 else if (c >= 'a' && c <= 'f')
6023 chr += 10 + c - 'a';
6024 else
6025 chr += 10 + c - 'A';
6026 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006027 s += j;
Jeremy Hylton504de6b2003-10-06 05:08:26 +00006028 if (chr == 0xffffffff && PyErr_Occurred())
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006029 /* _decoding_error will have already written into the
6030 target buffer. */
6031 break;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006032 store:
Fredrik Lundhdf846752000-09-03 11:29:49 +00006033 /* when we get here, chr is a 32-bit unicode character */
Victor Stinner8faf8212011-12-08 22:14:11 +01006034 if (chr <= MAX_UNICODE) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006035 WRITECHAR(chr);
Fredrik Lundhdf846752000-09-03 11:29:49 +00006036 } else {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006037 endinpos = s-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006038 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00006039 errors, &errorHandler,
6040 "unicodeescape", "illegal Unicode character",
6041 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006042 &v, &i))
Fredrik Lundhdf846752000-09-03 11:29:49 +00006043 goto onError;
6044 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00006045 break;
6046
Benjamin Peterson29060642009-01-31 22:14:21 +00006047 /* \N{name} */
Fredrik Lundhccc74732001-02-18 22:13:49 +00006048 case 'N':
6049 message = "malformed \\N character escape";
6050 if (ucnhash_CAPI == NULL) {
6051 /* load the unicode data module */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006052 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
6053 PyUnicodeData_CAPSULE_NAME, 1);
Fredrik Lundhccc74732001-02-18 22:13:49 +00006054 if (ucnhash_CAPI == NULL)
6055 goto ucnhashError;
6056 }
6057 if (*s == '{') {
6058 const char *start = s+1;
6059 /* look for the closing brace */
6060 while (*s != '}' && s < end)
6061 s++;
6062 if (s > start && s < end && *s == '}') {
6063 /* found a name. look it up in the unicode database */
6064 message = "unknown Unicode character name";
6065 s++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006066 if (ucnhash_CAPI->getcode(NULL, start, (int)(s-start-1),
Ezio Melotti931b8aa2011-10-21 21:57:36 +03006067 &chr, 0))
Fredrik Lundhccc74732001-02-18 22:13:49 +00006068 goto store;
6069 }
6070 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006071 endinpos = s-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006072 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00006073 errors, &errorHandler,
6074 "unicodeescape", message,
6075 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006076 &v, &i))
Fredrik Lundhccc74732001-02-18 22:13:49 +00006077 goto onError;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006078 break;
6079
6080 default:
Walter Dörwald8c077222002-03-25 11:16:18 +00006081 if (s > end) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006082 message = "\\ at end of string";
6083 s--;
6084 endinpos = s-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006085 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00006086 errors, &errorHandler,
6087 "unicodeescape", message,
6088 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006089 &v, &i))
Walter Dörwald8c077222002-03-25 11:16:18 +00006090 goto onError;
6091 }
6092 else {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006093 WRITECHAR('\\');
6094 WRITECHAR(s[-1]);
Walter Dörwald8c077222002-03-25 11:16:18 +00006095 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00006096 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006097 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006098 nextByte:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006099 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006100 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006101#undef WRITECHAR
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006102
Victor Stinner16e6a802011-12-12 13:24:15 +01006103 if (unicode_resize(&v, i) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006104 goto onError;
Walter Dörwaldd4ade082003-08-15 15:00:26 +00006105 Py_XDECREF(errorHandler);
6106 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006107 return unicode_result(v);
Walter Dörwald8c077222002-03-25 11:16:18 +00006108
Benjamin Peterson29060642009-01-31 22:14:21 +00006109 ucnhashError:
Fredrik Lundh06d12682001-01-24 07:59:11 +00006110 PyErr_SetString(
6111 PyExc_UnicodeError,
6112 "\\N escapes not supported (can't load unicodedata module)"
6113 );
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00006114 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006115 Py_XDECREF(errorHandler);
6116 Py_XDECREF(exc);
Fredrik Lundhf6056062001-01-20 11:15:25 +00006117 return NULL;
6118
Benjamin Peterson29060642009-01-31 22:14:21 +00006119 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00006120 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006121 Py_XDECREF(errorHandler);
6122 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006123 return NULL;
6124}
6125
6126/* Return a Unicode-Escape string version of the Unicode object.
6127
6128 If quotes is true, the string is enclosed in u"" or u'' quotes as
6129 appropriate.
6130
6131*/
6132
Alexander Belopolsky40018472011-02-26 01:02:56 +00006133PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006134PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006135{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006136 Py_ssize_t i, len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006137 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006138 char *p;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006139 int kind;
6140 void *data;
6141 Py_ssize_t expandsize = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006142
Thomas Wouters89f507f2006-12-13 04:49:30 +00006143 /* Initial allocation is based on the longest-possible unichr
6144 escape.
6145
6146 In wide (UTF-32) builds '\U00xxxxxx' is 10 chars per source
6147 unichr, so in this case it's the longest unichr escape. In
6148 narrow (UTF-16) builds this is five chars per source unichr
6149 since there are two unichrs in the surrogate pair, so in narrow
6150 (UTF-16) builds it's not the longest unichr escape.
6151
6152 In wide or narrow builds '\uxxxx' is 6 chars per source unichr,
6153 so in the narrow (UTF-16) build case it's the longest unichr
6154 escape.
6155 */
6156
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006157 if (!PyUnicode_Check(unicode)) {
6158 PyErr_BadArgument();
6159 return NULL;
6160 }
6161 if (PyUnicode_READY(unicode) < 0)
6162 return NULL;
6163 len = PyUnicode_GET_LENGTH(unicode);
6164 kind = PyUnicode_KIND(unicode);
6165 data = PyUnicode_DATA(unicode);
6166 switch(kind) {
6167 case PyUnicode_1BYTE_KIND: expandsize = 4; break;
6168 case PyUnicode_2BYTE_KIND: expandsize = 6; break;
6169 case PyUnicode_4BYTE_KIND: expandsize = 10; break;
6170 }
6171
6172 if (len == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006173 return PyBytes_FromStringAndSize(NULL, 0);
6174
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006175 if (len > (PY_SSIZE_T_MAX - 2 - 1) / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00006176 return PyErr_NoMemory();
Neal Norwitz3ce5d922008-08-24 07:08:55 +00006177
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006178 repr = PyBytes_FromStringAndSize(NULL,
Benjamin Peterson29060642009-01-31 22:14:21 +00006179 2
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006180 + expandsize*len
Benjamin Peterson29060642009-01-31 22:14:21 +00006181 + 1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006182 if (repr == NULL)
6183 return NULL;
6184
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006185 p = PyBytes_AS_STRING(repr);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006186
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006187 for (i = 0; i < len; i++) {
Victor Stinner3326cb62011-11-10 20:15:25 +01006188 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006189
Walter Dörwald79e913e2007-05-12 11:08:06 +00006190 /* Escape backslashes */
6191 if (ch == '\\') {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006192 *p++ = '\\';
6193 *p++ = (char) ch;
Walter Dörwald79e913e2007-05-12 11:08:06 +00006194 continue;
Tim Petersced69f82003-09-16 20:30:58 +00006195 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006196
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00006197 /* Map 21-bit characters to '\U00xxxxxx' */
6198 else if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01006199 assert(ch <= MAX_UNICODE);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00006200 *p++ = '\\';
6201 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006202 *p++ = Py_hexdigits[(ch >> 28) & 0x0000000F];
6203 *p++ = Py_hexdigits[(ch >> 24) & 0x0000000F];
6204 *p++ = Py_hexdigits[(ch >> 20) & 0x0000000F];
6205 *p++ = Py_hexdigits[(ch >> 16) & 0x0000000F];
6206 *p++ = Py_hexdigits[(ch >> 12) & 0x0000000F];
6207 *p++ = Py_hexdigits[(ch >> 8) & 0x0000000F];
6208 *p++ = Py_hexdigits[(ch >> 4) & 0x0000000F];
6209 *p++ = Py_hexdigits[ch & 0x0000000F];
Benjamin Peterson29060642009-01-31 22:14:21 +00006210 continue;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00006211 }
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00006212
Guido van Rossumd57fd912000-03-10 22:53:23 +00006213 /* Map 16-bit characters to '\uxxxx' */
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00006214 if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006215 *p++ = '\\';
6216 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006217 *p++ = Py_hexdigits[(ch >> 12) & 0x000F];
6218 *p++ = Py_hexdigits[(ch >> 8) & 0x000F];
6219 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6220 *p++ = Py_hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006221 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006222
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006223 /* Map special whitespace to '\t', \n', '\r' */
6224 else if (ch == '\t') {
6225 *p++ = '\\';
6226 *p++ = 't';
6227 }
6228 else if (ch == '\n') {
6229 *p++ = '\\';
6230 *p++ = 'n';
6231 }
6232 else if (ch == '\r') {
6233 *p++ = '\\';
6234 *p++ = 'r';
6235 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006236
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006237 /* Map non-printable US ASCII to '\xhh' */
Marc-André Lemburg11326de2001-11-28 12:56:20 +00006238 else if (ch < ' ' || ch >= 0x7F) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006239 *p++ = '\\';
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006240 *p++ = 'x';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006241 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6242 *p++ = Py_hexdigits[ch & 0x000F];
Tim Petersced69f82003-09-16 20:30:58 +00006243 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006244
Guido van Rossumd57fd912000-03-10 22:53:23 +00006245 /* Copy everything else as-is */
6246 else
6247 *p++ = (char) ch;
6248 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006249
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006250 assert(p - PyBytes_AS_STRING(repr) > 0);
6251 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0)
6252 return NULL;
6253 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006254}
6255
Alexander Belopolsky40018472011-02-26 01:02:56 +00006256PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006257PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
6258 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006259{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006260 PyObject *result;
6261 PyObject *tmp = PyUnicode_FromUnicode(s, size);
6262 if (tmp == NULL)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006263 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006264 result = PyUnicode_AsUnicodeEscapeString(tmp);
6265 Py_DECREF(tmp);
6266 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006267}
6268
6269/* --- Raw Unicode Escape Codec ------------------------------------------- */
6270
Alexander Belopolsky40018472011-02-26 01:02:56 +00006271PyObject *
6272PyUnicode_DecodeRawUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006273 Py_ssize_t size,
6274 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006275{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006276 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006277 Py_ssize_t startinpos;
6278 Py_ssize_t endinpos;
6279 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01006280 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006281 const char *end;
6282 const char *bs;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006283 PyObject *errorHandler = NULL;
6284 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006285
Guido van Rossumd57fd912000-03-10 22:53:23 +00006286 /* Escaped strings will always be longer than the resulting
6287 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006288 length after conversion to the true value. (But decoding error
6289 handler might have to resize the string) */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006290 v = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006291 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006292 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006293 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01006294 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006295 outpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006296 end = s + size;
6297 while (s < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006298 unsigned char c;
6299 Py_UCS4 x;
6300 int i;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006301 int count;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006302
Benjamin Peterson29060642009-01-31 22:14:21 +00006303 /* Non-escape characters are interpreted as Unicode ordinals */
6304 if (*s != '\\') {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006305 if (unicode_putchar(&v, &outpos, (unsigned char)*s++) < 0)
6306 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00006307 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006308 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006309 startinpos = s-starts;
6310
6311 /* \u-escapes are only interpreted iff the number of leading
6312 backslashes if odd */
6313 bs = s;
6314 for (;s < end;) {
6315 if (*s != '\\')
6316 break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006317 if (unicode_putchar(&v, &outpos, (unsigned char)*s++) < 0)
6318 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00006319 }
6320 if (((s - bs) & 1) == 0 ||
6321 s >= end ||
6322 (*s != 'u' && *s != 'U')) {
6323 continue;
6324 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006325 outpos--;
Benjamin Peterson29060642009-01-31 22:14:21 +00006326 count = *s=='u' ? 4 : 8;
6327 s++;
6328
6329 /* \uXXXX with 4 hex digits, \Uxxxxxxxx with 8 */
Benjamin Peterson29060642009-01-31 22:14:21 +00006330 for (x = 0, i = 0; i < count; ++i, ++s) {
6331 c = (unsigned char)*s;
David Malcolm96960882010-11-05 17:23:41 +00006332 if (!Py_ISXDIGIT(c)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006333 endinpos = s-starts;
6334 if (unicode_decode_call_errorhandler(
6335 errors, &errorHandler,
6336 "rawunicodeescape", "truncated \\uXXXX",
6337 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006338 &v, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00006339 goto onError;
6340 goto nextByte;
6341 }
6342 x = (x<<4) & ~0xF;
6343 if (c >= '0' && c <= '9')
6344 x += c - '0';
6345 else if (c >= 'a' && c <= 'f')
6346 x += 10 + c - 'a';
6347 else
6348 x += 10 + c - 'A';
6349 }
Victor Stinner8faf8212011-12-08 22:14:11 +01006350 if (x <= MAX_UNICODE) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006351 if (unicode_putchar(&v, &outpos, x) < 0)
6352 goto onError;
Christian Heimesfe337bf2008-03-23 21:54:12 +00006353 } else {
6354 endinpos = s-starts;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006355 if (unicode_decode_call_errorhandler(
6356 errors, &errorHandler,
6357 "rawunicodeescape", "\\Uxxxxxxxx out of range",
Benjamin Peterson29060642009-01-31 22:14:21 +00006358 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006359 &v, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00006360 goto onError;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006361 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006362 nextByte:
6363 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006364 }
Victor Stinner16e6a802011-12-12 13:24:15 +01006365 if (unicode_resize(&v, outpos) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006366 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006367 Py_XDECREF(errorHandler);
6368 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006369 return unicode_result(v);
Tim Petersced69f82003-09-16 20:30:58 +00006370
Benjamin Peterson29060642009-01-31 22:14:21 +00006371 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00006372 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006373 Py_XDECREF(errorHandler);
6374 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006375 return NULL;
6376}
6377
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006378
Alexander Belopolsky40018472011-02-26 01:02:56 +00006379PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006380PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006381{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006382 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006383 char *p;
6384 char *q;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006385 Py_ssize_t expandsize, pos;
6386 int kind;
6387 void *data;
6388 Py_ssize_t len;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006389
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006390 if (!PyUnicode_Check(unicode)) {
6391 PyErr_BadArgument();
6392 return NULL;
6393 }
6394 if (PyUnicode_READY(unicode) < 0)
6395 return NULL;
6396 kind = PyUnicode_KIND(unicode);
6397 data = PyUnicode_DATA(unicode);
6398 len = PyUnicode_GET_LENGTH(unicode);
Benjamin Peterson1518e872011-11-23 10:44:52 -06006399 /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6
6400 bytes, and 1 byte characters 4. */
6401 expandsize = kind * 2 + 2;
Victor Stinner0e368262011-11-10 20:12:49 +01006402
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006403 if (len > PY_SSIZE_T_MAX / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00006404 return PyErr_NoMemory();
Benjamin Peterson14339b62009-01-31 16:36:08 +00006405
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006406 repr = PyBytes_FromStringAndSize(NULL, expandsize * len);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006407 if (repr == NULL)
6408 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006409 if (len == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006410 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006411
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006412 p = q = PyBytes_AS_STRING(repr);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006413 for (pos = 0; pos < len; pos++) {
6414 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Benjamin Peterson29060642009-01-31 22:14:21 +00006415 /* Map 32-bit characters to '\Uxxxxxxxx' */
6416 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01006417 assert(ch <= MAX_UNICODE);
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006418 *p++ = '\\';
6419 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006420 *p++ = Py_hexdigits[(ch >> 28) & 0xf];
6421 *p++ = Py_hexdigits[(ch >> 24) & 0xf];
6422 *p++ = Py_hexdigits[(ch >> 20) & 0xf];
6423 *p++ = Py_hexdigits[(ch >> 16) & 0xf];
6424 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6425 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6426 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6427 *p++ = Py_hexdigits[ch & 15];
Tim Petersced69f82003-09-16 20:30:58 +00006428 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006429 /* Map 16-bit characters to '\uxxxx' */
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006430 else if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006431 *p++ = '\\';
6432 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006433 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6434 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6435 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6436 *p++ = Py_hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006437 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006438 /* Copy everything else as-is */
6439 else
Guido van Rossumd57fd912000-03-10 22:53:23 +00006440 *p++ = (char) ch;
6441 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00006442
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006443 assert(p > q);
6444 if (_PyBytes_Resize(&repr, p - q) < 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006445 return NULL;
6446 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006447}
6448
Alexander Belopolsky40018472011-02-26 01:02:56 +00006449PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006450PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
6451 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006452{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006453 PyObject *result;
6454 PyObject *tmp = PyUnicode_FromUnicode(s, size);
6455 if (tmp == NULL)
Walter Dörwald711005d2007-05-12 12:03:26 +00006456 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006457 result = PyUnicode_AsRawUnicodeEscapeString(tmp);
6458 Py_DECREF(tmp);
6459 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006460}
6461
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006462/* --- Unicode Internal Codec ------------------------------------------- */
6463
Alexander Belopolsky40018472011-02-26 01:02:56 +00006464PyObject *
6465_PyUnicode_DecodeUnicodeInternal(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006466 Py_ssize_t size,
6467 const char *errors)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006468{
6469 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006470 Py_ssize_t startinpos;
6471 Py_ssize_t endinpos;
6472 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01006473 PyObject *v;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006474 const char *end;
6475 const char *reason;
6476 PyObject *errorHandler = NULL;
6477 PyObject *exc = NULL;
6478
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006479 if (PyErr_WarnEx(PyExc_DeprecationWarning,
Ezio Melotti11060a42011-11-16 09:39:10 +02006480 "unicode_internal codec has been deprecated",
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006481 1))
6482 return NULL;
6483
Thomas Wouters89f507f2006-12-13 04:49:30 +00006484 /* XXX overflow detection missing */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006485 v = PyUnicode_New((size+Py_UNICODE_SIZE-1)/ Py_UNICODE_SIZE, 127);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006486 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006487 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006488 if (PyUnicode_GET_LENGTH(v) == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01006489 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006490 outpos = 0;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006491 end = s + size;
6492
6493 while (s < end) {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006494 Py_UNICODE uch;
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006495 Py_UCS4 ch;
6496 /* We copy the raw representation one byte at a time because the
6497 pointer may be unaligned (see test_codeccallbacks). */
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006498 ((char *) &uch)[0] = s[0];
6499 ((char *) &uch)[1] = s[1];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006500#ifdef Py_UNICODE_WIDE
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006501 ((char *) &uch)[2] = s[2];
6502 ((char *) &uch)[3] = s[3];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006503#endif
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006504 ch = uch;
6505
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006506 /* We have to sanity check the raw data, otherwise doom looms for
6507 some malformed UCS-4 data. */
6508 if (
Benjamin Peterson29060642009-01-31 22:14:21 +00006509#ifdef Py_UNICODE_WIDE
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006510 ch > 0x10ffff ||
Benjamin Peterson29060642009-01-31 22:14:21 +00006511#endif
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006512 end-s < Py_UNICODE_SIZE
6513 )
Benjamin Peterson29060642009-01-31 22:14:21 +00006514 {
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006515 startinpos = s - starts;
6516 if (end-s < Py_UNICODE_SIZE) {
6517 endinpos = end-starts;
6518 reason = "truncated input";
6519 }
6520 else {
6521 endinpos = s - starts + Py_UNICODE_SIZE;
6522 reason = "illegal code point (> 0x10FFFF)";
6523 }
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006524 if (unicode_decode_call_errorhandler(
6525 errors, &errorHandler,
6526 "unicode_internal", reason,
Walter Dörwalde78178e2007-07-30 13:31:40 +00006527 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006528 &v, &outpos))
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006529 goto onError;
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006530 continue;
6531 }
6532
6533 s += Py_UNICODE_SIZE;
6534#ifndef Py_UNICODE_WIDE
Victor Stinner551ac952011-11-29 22:58:13 +01006535 if (Py_UNICODE_IS_HIGH_SURROGATE(ch) && s < end)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006536 {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006537 Py_UNICODE uch2;
6538 ((char *) &uch2)[0] = s[0];
6539 ((char *) &uch2)[1] = s[1];
Victor Stinner551ac952011-11-29 22:58:13 +01006540 if (Py_UNICODE_IS_LOW_SURROGATE(uch2))
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006541 {
Victor Stinner551ac952011-11-29 22:58:13 +01006542 ch = Py_UNICODE_JOIN_SURROGATES(uch, uch2);
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006543 s += Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006544 }
6545 }
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006546#endif
6547
6548 if (unicode_putchar(&v, &outpos, ch) < 0)
6549 goto onError;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006550 }
6551
Victor Stinner16e6a802011-12-12 13:24:15 +01006552 if (unicode_resize(&v, outpos) < 0)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006553 goto onError;
6554 Py_XDECREF(errorHandler);
6555 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006556 return unicode_result(v);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006557
Benjamin Peterson29060642009-01-31 22:14:21 +00006558 onError:
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006559 Py_XDECREF(v);
6560 Py_XDECREF(errorHandler);
6561 Py_XDECREF(exc);
6562 return NULL;
6563}
6564
Guido van Rossumd57fd912000-03-10 22:53:23 +00006565/* --- Latin-1 Codec ------------------------------------------------------ */
6566
Alexander Belopolsky40018472011-02-26 01:02:56 +00006567PyObject *
6568PyUnicode_DecodeLatin1(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006569 Py_ssize_t size,
6570 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006571{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006572 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Victor Stinnere57b1c02011-09-28 22:20:48 +02006573 return _PyUnicode_FromUCS1((unsigned char*)s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006574}
6575
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006576/* create or adjust a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006577static void
6578make_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006579 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006580 PyObject *unicode,
6581 Py_ssize_t startpos, Py_ssize_t endpos,
6582 const char *reason)
6583{
6584 if (*exceptionObject == NULL) {
6585 *exceptionObject = PyObject_CallFunction(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006586 PyExc_UnicodeEncodeError, "sOnns",
Martin v. Löwis9e816682011-11-02 12:45:42 +01006587 encoding, unicode, startpos, endpos, reason);
6588 }
6589 else {
6590 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
6591 goto onError;
6592 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
6593 goto onError;
6594 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
6595 goto onError;
6596 return;
6597 onError:
6598 Py_DECREF(*exceptionObject);
6599 *exceptionObject = NULL;
6600 }
6601}
6602
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006603/* raises a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006604static void
6605raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006606 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006607 PyObject *unicode,
6608 Py_ssize_t startpos, Py_ssize_t endpos,
6609 const char *reason)
6610{
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006611 make_encode_exception(exceptionObject,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006612 encoding, unicode, startpos, endpos, reason);
6613 if (*exceptionObject != NULL)
6614 PyCodec_StrictErrors(*exceptionObject);
6615}
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006616
6617/* error handling callback helper:
6618 build arguments, call the callback and check the arguments,
6619 put the result into newpos and return the replacement string, which
6620 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006621static PyObject *
6622unicode_encode_call_errorhandler(const char *errors,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006623 PyObject **errorHandler,
6624 const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006625 PyObject *unicode, PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006626 Py_ssize_t startpos, Py_ssize_t endpos,
6627 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006628{
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006629 static char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006630 Py_ssize_t len;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006631 PyObject *restuple;
6632 PyObject *resunicode;
6633
6634 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006635 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006636 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006637 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006638 }
6639
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006640 if (PyUnicode_READY(unicode) < 0)
6641 return NULL;
6642 len = PyUnicode_GET_LENGTH(unicode);
6643
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006644 make_encode_exception(exceptionObject,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006645 encoding, unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006646 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006647 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006648
6649 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00006650 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006651 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006652 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006653 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006654 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00006655 Py_DECREF(restuple);
6656 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006657 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006658 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00006659 &resunicode, newpos)) {
6660 Py_DECREF(restuple);
6661 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006662 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006663 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
6664 PyErr_SetString(PyExc_TypeError, &argparse[3]);
6665 Py_DECREF(restuple);
6666 return NULL;
6667 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006668 if (*newpos<0)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006669 *newpos = len + *newpos;
6670 if (*newpos<0 || *newpos>len) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006671 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
6672 Py_DECREF(restuple);
6673 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00006674 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006675 Py_INCREF(resunicode);
6676 Py_DECREF(restuple);
6677 return resunicode;
6678}
6679
Alexander Belopolsky40018472011-02-26 01:02:56 +00006680static PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006681unicode_encode_ucs1(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006682 const char *errors,
Victor Stinnerfcd96532011-11-04 00:28:50 +01006683 unsigned int limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006684{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006685 /* input state */
6686 Py_ssize_t pos=0, size;
6687 int kind;
6688 void *data;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006689 /* output object */
6690 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006691 /* pointer into the output */
6692 char *str;
6693 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00006694 Py_ssize_t ressize;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006695 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
6696 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006697 PyObject *errorHandler = NULL;
6698 PyObject *exc = NULL;
6699 /* the following variable is used for caching string comparisons
6700 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
6701 int known_errorHandler = -1;
6702
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006703 if (PyUnicode_READY(unicode) < 0)
6704 return NULL;
6705 size = PyUnicode_GET_LENGTH(unicode);
6706 kind = PyUnicode_KIND(unicode);
6707 data = PyUnicode_DATA(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006708 /* allocate enough for a simple encoding without
6709 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00006710 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00006711 return PyBytes_FromStringAndSize(NULL, 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006712 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006713 if (res == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00006714 return NULL;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006715 str = PyBytes_AS_STRING(res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006716 ressize = size;
6717
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006718 while (pos < size) {
6719 Py_UCS4 c = PyUnicode_READ(kind, data, pos);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006720
Benjamin Peterson29060642009-01-31 22:14:21 +00006721 /* can we encode this? */
6722 if (c<limit) {
6723 /* no overflow check, because we know that the space is enough */
6724 *str++ = (char)c;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006725 ++pos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006726 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006727 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006728 Py_ssize_t requiredsize;
6729 PyObject *repunicode;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006730 Py_ssize_t repsize, newpos, respos, i;
Benjamin Peterson29060642009-01-31 22:14:21 +00006731 /* startpos for collecting unencodable chars */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006732 Py_ssize_t collstart = pos;
6733 Py_ssize_t collend = pos;
Benjamin Peterson29060642009-01-31 22:14:21 +00006734 /* find all unecodable characters */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006735 while ((collend < size) && (PyUnicode_READ(kind, data, collend)>=limit))
Benjamin Peterson29060642009-01-31 22:14:21 +00006736 ++collend;
6737 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
6738 if (known_errorHandler==-1) {
6739 if ((errors==NULL) || (!strcmp(errors, "strict")))
6740 known_errorHandler = 1;
6741 else if (!strcmp(errors, "replace"))
6742 known_errorHandler = 2;
6743 else if (!strcmp(errors, "ignore"))
6744 known_errorHandler = 3;
6745 else if (!strcmp(errors, "xmlcharrefreplace"))
6746 known_errorHandler = 4;
6747 else
6748 known_errorHandler = 0;
6749 }
6750 switch (known_errorHandler) {
6751 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006752 raise_encode_exception(&exc, encoding, unicode, collstart, collend, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006753 goto onError;
6754 case 2: /* replace */
6755 while (collstart++<collend)
6756 *str++ = '?'; /* fall through */
6757 case 3: /* ignore */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006758 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006759 break;
6760 case 4: /* xmlcharrefreplace */
6761 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006762 /* determine replacement size */
6763 for (i = collstart, repsize = 0; i < collend; ++i) {
6764 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
6765 if (ch < 10)
Benjamin Peterson29060642009-01-31 22:14:21 +00006766 repsize += 2+1+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006767 else if (ch < 100)
Benjamin Peterson29060642009-01-31 22:14:21 +00006768 repsize += 2+2+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006769 else if (ch < 1000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006770 repsize += 2+3+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006771 else if (ch < 10000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006772 repsize += 2+4+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006773 else if (ch < 100000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006774 repsize += 2+5+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006775 else if (ch < 1000000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006776 repsize += 2+6+1;
Victor Stinner0d3721d2011-11-22 03:27:53 +01006777 else {
Victor Stinner8faf8212011-12-08 22:14:11 +01006778 assert(ch <= MAX_UNICODE);
Benjamin Peterson29060642009-01-31 22:14:21 +00006779 repsize += 2+7+1;
Victor Stinner0d3721d2011-11-22 03:27:53 +01006780 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006781 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006782 requiredsize = respos+repsize+(size-collend);
Benjamin Peterson29060642009-01-31 22:14:21 +00006783 if (requiredsize > ressize) {
6784 if (requiredsize<2*ressize)
6785 requiredsize = 2*ressize;
6786 if (_PyBytes_Resize(&res, requiredsize))
6787 goto onError;
6788 str = PyBytes_AS_STRING(res) + respos;
6789 ressize = requiredsize;
6790 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006791 /* generate replacement */
6792 for (i = collstart; i < collend; ++i) {
6793 str += sprintf(str, "&#%d;", PyUnicode_READ(kind, data, i));
Benjamin Peterson29060642009-01-31 22:14:21 +00006794 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006795 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006796 break;
6797 default:
6798 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006799 encoding, reason, unicode, &exc,
6800 collstart, collend, &newpos);
6801 if (repunicode == NULL || (PyUnicode_Check(repunicode) &&
6802 PyUnicode_READY(repunicode) < 0))
Benjamin Peterson29060642009-01-31 22:14:21 +00006803 goto onError;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006804 if (PyBytes_Check(repunicode)) {
6805 /* Directly copy bytes result to output. */
6806 repsize = PyBytes_Size(repunicode);
6807 if (repsize > 1) {
6808 /* Make room for all additional bytes. */
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006809 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006810 if (_PyBytes_Resize(&res, ressize+repsize-1)) {
6811 Py_DECREF(repunicode);
6812 goto onError;
6813 }
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006814 str = PyBytes_AS_STRING(res) + respos;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006815 ressize += repsize-1;
6816 }
6817 memcpy(str, PyBytes_AsString(repunicode), repsize);
6818 str += repsize;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006819 pos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006820 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006821 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006822 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006823 /* need more space? (at least enough for what we
6824 have+the replacement+the rest of the string, so
6825 we won't have to check space for encodable characters) */
6826 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006827 repsize = PyUnicode_GET_LENGTH(repunicode);
6828 requiredsize = respos+repsize+(size-collend);
Benjamin Peterson29060642009-01-31 22:14:21 +00006829 if (requiredsize > ressize) {
6830 if (requiredsize<2*ressize)
6831 requiredsize = 2*ressize;
6832 if (_PyBytes_Resize(&res, requiredsize)) {
6833 Py_DECREF(repunicode);
6834 goto onError;
6835 }
6836 str = PyBytes_AS_STRING(res) + respos;
6837 ressize = requiredsize;
6838 }
6839 /* check if there is anything unencodable in the replacement
6840 and copy it to the output */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006841 for (i = 0; repsize-->0; ++i, ++str) {
6842 c = PyUnicode_READ_CHAR(repunicode, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00006843 if (c >= limit) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006844 raise_encode_exception(&exc, encoding, unicode,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006845 pos, pos+1, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006846 Py_DECREF(repunicode);
6847 goto onError;
6848 }
6849 *str = (char)c;
6850 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006851 pos = newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006852 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006853 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00006854 }
6855 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006856 /* Resize if we allocated to much */
6857 size = str - PyBytes_AS_STRING(res);
6858 if (size < ressize) { /* If this falls res will be NULL */
Alexandre Vassalottibad1b922008-12-27 09:49:09 +00006859 assert(size >= 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006860 if (_PyBytes_Resize(&res, size) < 0)
6861 goto onError;
6862 }
6863
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006864 Py_XDECREF(errorHandler);
6865 Py_XDECREF(exc);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006866 return res;
6867
6868 onError:
6869 Py_XDECREF(res);
6870 Py_XDECREF(errorHandler);
6871 Py_XDECREF(exc);
6872 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006873}
6874
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006875/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006876PyObject *
6877PyUnicode_EncodeLatin1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006878 Py_ssize_t size,
6879 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006880{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006881 PyObject *result;
6882 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6883 if (unicode == NULL)
6884 return NULL;
6885 result = unicode_encode_ucs1(unicode, errors, 256);
6886 Py_DECREF(unicode);
6887 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006888}
6889
Alexander Belopolsky40018472011-02-26 01:02:56 +00006890PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006891_PyUnicode_AsLatin1String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006892{
6893 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006894 PyErr_BadArgument();
6895 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006896 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006897 if (PyUnicode_READY(unicode) == -1)
6898 return NULL;
6899 /* Fast path: if it is a one-byte string, construct
6900 bytes object directly. */
6901 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND)
6902 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6903 PyUnicode_GET_LENGTH(unicode));
6904 /* Non-Latin-1 characters present. Defer to above function to
6905 raise the exception. */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006906 return unicode_encode_ucs1(unicode, errors, 256);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006907}
6908
6909PyObject*
6910PyUnicode_AsLatin1String(PyObject *unicode)
6911{
6912 return _PyUnicode_AsLatin1String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006913}
6914
6915/* --- 7-bit ASCII Codec -------------------------------------------------- */
6916
Alexander Belopolsky40018472011-02-26 01:02:56 +00006917PyObject *
6918PyUnicode_DecodeASCII(const char *s,
6919 Py_ssize_t size,
6920 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006921{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006922 const char *starts = s;
Victor Stinner7931d9a2011-11-04 00:22:48 +01006923 PyObject *v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006924 int kind;
6925 void *data;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006926 Py_ssize_t startinpos;
6927 Py_ssize_t endinpos;
6928 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006929 const char *e;
Victor Stinner702c7342011-10-05 13:50:52 +02006930 int has_error;
6931 const unsigned char *p = (const unsigned char *)s;
6932 const unsigned char *end = p + size;
6933 const unsigned char *aligned_end = (const unsigned char *) ((size_t) end & ~LONG_PTR_MASK);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006934 PyObject *errorHandler = NULL;
6935 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006936
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006937 if (size == 0) {
6938 Py_INCREF(unicode_empty);
6939 return unicode_empty;
6940 }
6941
Guido van Rossumd57fd912000-03-10 22:53:23 +00006942 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Victor Stinner702c7342011-10-05 13:50:52 +02006943 if (size == 1 && (unsigned char)s[0] < 128)
6944 return get_latin1_char((unsigned char)s[0]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006945
Victor Stinner702c7342011-10-05 13:50:52 +02006946 has_error = 0;
6947 while (p < end && !has_error) {
6948 /* Fast path, see below in PyUnicode_DecodeUTF8Stateful for
6949 an explanation. */
6950 if (!((size_t) p & LONG_PTR_MASK)) {
6951 /* Help register allocation */
6952 register const unsigned char *_p = p;
6953 while (_p < aligned_end) {
6954 unsigned long value = *(unsigned long *) _p;
6955 if (value & ASCII_CHAR_MASK) {
6956 has_error = 1;
6957 break;
6958 }
6959 _p += SIZEOF_LONG;
6960 }
6961 if (_p == end)
6962 break;
6963 if (has_error)
6964 break;
6965 p = _p;
6966 }
6967 if (*p & 0x80) {
6968 has_error = 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006969 break;
Victor Stinner702c7342011-10-05 13:50:52 +02006970 }
6971 else {
6972 ++p;
6973 }
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00006974 }
Victor Stinner702c7342011-10-05 13:50:52 +02006975 if (!has_error)
6976 return unicode_fromascii((const unsigned char *)s, size);
Tim Petersced69f82003-09-16 20:30:58 +00006977
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006978 v = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006979 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006980 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006981 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01006982 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006983 kind = PyUnicode_KIND(v);
6984 data = PyUnicode_DATA(v);
6985 outpos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006986 e = s + size;
6987 while (s < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006988 register unsigned char c = (unsigned char)*s;
6989 if (c < 128) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006990 PyUnicode_WRITE(kind, data, outpos++, c);
Benjamin Peterson29060642009-01-31 22:14:21 +00006991 ++s;
6992 }
6993 else {
6994 startinpos = s-starts;
6995 endinpos = startinpos + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00006996 if (unicode_decode_call_errorhandler(
6997 errors, &errorHandler,
6998 "ascii", "ordinal not in range(128)",
6999 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007000 &v, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00007001 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007002 kind = PyUnicode_KIND(v);
7003 data = PyUnicode_DATA(v);
Benjamin Peterson29060642009-01-31 22:14:21 +00007004 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00007005 }
Victor Stinner16e6a802011-12-12 13:24:15 +01007006 if (unicode_resize(&v, outpos) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007007 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007008 Py_XDECREF(errorHandler);
7009 Py_XDECREF(exc);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02007010 assert(_PyUnicode_CheckConsistency(v, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01007011 return v;
Tim Petersced69f82003-09-16 20:30:58 +00007012
Benjamin Peterson29060642009-01-31 22:14:21 +00007013 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00007014 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007015 Py_XDECREF(errorHandler);
7016 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007017 return NULL;
7018}
7019
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007020/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007021PyObject *
7022PyUnicode_EncodeASCII(const Py_UNICODE *p,
7023 Py_ssize_t size,
7024 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007025{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007026 PyObject *result;
7027 PyObject *unicode = PyUnicode_FromUnicode(p, size);
7028 if (unicode == NULL)
7029 return NULL;
7030 result = unicode_encode_ucs1(unicode, errors, 128);
7031 Py_DECREF(unicode);
7032 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007033}
7034
Alexander Belopolsky40018472011-02-26 01:02:56 +00007035PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007036_PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007037{
7038 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007039 PyErr_BadArgument();
7040 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007041 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007042 if (PyUnicode_READY(unicode) == -1)
7043 return NULL;
7044 /* Fast path: if it is an ASCII-only string, construct bytes object
7045 directly. Else defer to above function to raise the exception. */
7046 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
7047 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
7048 PyUnicode_GET_LENGTH(unicode));
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007049 return unicode_encode_ucs1(unicode, errors, 128);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007050}
7051
7052PyObject *
7053PyUnicode_AsASCIIString(PyObject *unicode)
7054{
7055 return _PyUnicode_AsASCIIString(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007056}
7057
Victor Stinner99b95382011-07-04 14:23:54 +02007058#ifdef HAVE_MBCS
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007059
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007060/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007061
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00007062#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007063#define NEED_RETRY
7064#endif
7065
Victor Stinner3a50e702011-10-18 21:21:00 +02007066#ifndef WC_ERR_INVALID_CHARS
7067# define WC_ERR_INVALID_CHARS 0x0080
7068#endif
7069
7070static char*
7071code_page_name(UINT code_page, PyObject **obj)
7072{
7073 *obj = NULL;
7074 if (code_page == CP_ACP)
7075 return "mbcs";
7076 if (code_page == CP_UTF7)
7077 return "CP_UTF7";
7078 if (code_page == CP_UTF8)
7079 return "CP_UTF8";
7080
7081 *obj = PyBytes_FromFormat("cp%u", code_page);
7082 if (*obj == NULL)
7083 return NULL;
7084 return PyBytes_AS_STRING(*obj);
7085}
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007086
Alexander Belopolsky40018472011-02-26 01:02:56 +00007087static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007088is_dbcs_lead_byte(UINT code_page, const char *s, int offset)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007089{
7090 const char *curr = s + offset;
Victor Stinner3a50e702011-10-18 21:21:00 +02007091 const char *prev;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007092
Victor Stinner3a50e702011-10-18 21:21:00 +02007093 if (!IsDBCSLeadByteEx(code_page, *curr))
7094 return 0;
7095
7096 prev = CharPrevExA(code_page, s, curr, 0);
7097 if (prev == curr)
7098 return 1;
7099 /* FIXME: This code is limited to "true" double-byte encodings,
7100 as it assumes an incomplete character consists of a single
7101 byte. */
7102 if (curr - prev == 2)
7103 return 1;
7104 if (!IsDBCSLeadByteEx(code_page, *prev))
7105 return 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007106 return 0;
7107}
7108
Victor Stinner3a50e702011-10-18 21:21:00 +02007109static DWORD
7110decode_code_page_flags(UINT code_page)
7111{
7112 if (code_page == CP_UTF7) {
7113 /* The CP_UTF7 decoder only supports flags=0 */
7114 return 0;
7115 }
7116 else
7117 return MB_ERR_INVALID_CHARS;
7118}
7119
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007120/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007121 * Decode a byte string from a Windows code page into unicode object in strict
7122 * mode.
7123 *
7124 * Returns consumed size if succeed, returns -2 on decode error, or raise a
7125 * WindowsError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007126 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007127static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007128decode_code_page_strict(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007129 PyObject **v,
Victor Stinner3a50e702011-10-18 21:21:00 +02007130 const char *in,
7131 int insize)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007132{
Victor Stinner3a50e702011-10-18 21:21:00 +02007133 const DWORD flags = decode_code_page_flags(code_page);
Victor Stinner24729f32011-11-10 20:31:37 +01007134 wchar_t *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007135 DWORD outsize;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007136
7137 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007138 assert(insize > 0);
7139 outsize = MultiByteToWideChar(code_page, flags, in, insize, NULL, 0);
7140 if (outsize <= 0)
7141 goto error;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007142
7143 if (*v == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007144 /* Create unicode object */
Victor Stinnerab595942011-12-17 04:59:06 +01007145 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01007146 *v = (PyObject*)_PyUnicode_New(outsize);
Benjamin Peterson29060642009-01-31 22:14:21 +00007147 if (*v == NULL)
7148 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007149 out = PyUnicode_AS_UNICODE(*v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007150 }
7151 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007152 /* Extend unicode object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007153 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
Victor Stinner16e6a802011-12-12 13:24:15 +01007154 if (unicode_resize(v, n + outsize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007155 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007156 out = PyUnicode_AS_UNICODE(*v) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007157 }
7158
7159 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007160 outsize = MultiByteToWideChar(code_page, flags, in, insize, out, outsize);
7161 if (outsize <= 0)
7162 goto error;
7163 return insize;
Victor Stinner554f3f02010-06-16 23:33:54 +00007164
Victor Stinner3a50e702011-10-18 21:21:00 +02007165error:
7166 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7167 return -2;
7168 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007169 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007170}
7171
Victor Stinner3a50e702011-10-18 21:21:00 +02007172/*
7173 * Decode a byte string from a code page into unicode object with an error
7174 * handler.
7175 *
7176 * Returns consumed size if succeed, or raise a WindowsError or
7177 * UnicodeDecodeError exception and returns -1 on error.
7178 */
7179static int
7180decode_code_page_errors(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007181 PyObject **v,
7182 const char *in, const int size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007183 const char *errors)
7184{
7185 const char *startin = in;
7186 const char *endin = in + size;
7187 const DWORD flags = decode_code_page_flags(code_page);
7188 /* Ideally, we should get reason from FormatMessage. This is the Windows
7189 2000 English version of the message. */
7190 const char *reason = "No mapping for the Unicode character exists "
7191 "in the target code page.";
7192 /* each step cannot decode more than 1 character, but a character can be
7193 represented as a surrogate pair */
7194 wchar_t buffer[2], *startout, *out;
7195 int insize, outsize;
7196 PyObject *errorHandler = NULL;
7197 PyObject *exc = NULL;
7198 PyObject *encoding_obj = NULL;
7199 char *encoding;
7200 DWORD err;
7201 int ret = -1;
7202
7203 assert(size > 0);
7204
7205 encoding = code_page_name(code_page, &encoding_obj);
7206 if (encoding == NULL)
7207 return -1;
7208
7209 if (errors == NULL || strcmp(errors, "strict") == 0) {
7210 /* The last error was ERROR_NO_UNICODE_TRANSLATION, then we raise a
7211 UnicodeDecodeError. */
7212 make_decode_exception(&exc, encoding, in, size, 0, 0, reason);
7213 if (exc != NULL) {
7214 PyCodec_StrictErrors(exc);
7215 Py_CLEAR(exc);
7216 }
7217 goto error;
7218 }
7219
7220 if (*v == NULL) {
7221 /* Create unicode object */
7222 if (size > PY_SSIZE_T_MAX / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
7223 PyErr_NoMemory();
7224 goto error;
7225 }
Victor Stinnerab595942011-12-17 04:59:06 +01007226 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01007227 *v = (PyObject*)_PyUnicode_New(size * Py_ARRAY_LENGTH(buffer));
Victor Stinner3a50e702011-10-18 21:21:00 +02007228 if (*v == NULL)
7229 goto error;
7230 startout = PyUnicode_AS_UNICODE(*v);
7231 }
7232 else {
7233 /* Extend unicode object */
7234 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
7235 if (size > (PY_SSIZE_T_MAX - n) / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
7236 PyErr_NoMemory();
7237 goto error;
7238 }
Victor Stinner16e6a802011-12-12 13:24:15 +01007239 if (unicode_resize(v, n + size * Py_ARRAY_LENGTH(buffer)) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007240 goto error;
7241 startout = PyUnicode_AS_UNICODE(*v) + n;
7242 }
7243
7244 /* Decode the byte string character per character */
7245 out = startout;
7246 while (in < endin)
7247 {
7248 /* Decode a character */
7249 insize = 1;
7250 do
7251 {
7252 outsize = MultiByteToWideChar(code_page, flags,
7253 in, insize,
7254 buffer, Py_ARRAY_LENGTH(buffer));
7255 if (outsize > 0)
7256 break;
7257 err = GetLastError();
7258 if (err != ERROR_NO_UNICODE_TRANSLATION
7259 && err != ERROR_INSUFFICIENT_BUFFER)
7260 {
7261 PyErr_SetFromWindowsErr(0);
7262 goto error;
7263 }
7264 insize++;
7265 }
7266 /* 4=maximum length of a UTF-8 sequence */
7267 while (insize <= 4 && (in + insize) <= endin);
7268
7269 if (outsize <= 0) {
7270 Py_ssize_t startinpos, endinpos, outpos;
7271
7272 startinpos = in - startin;
7273 endinpos = startinpos + 1;
7274 outpos = out - PyUnicode_AS_UNICODE(*v);
7275 if (unicode_decode_call_errorhandler(
7276 errors, &errorHandler,
7277 encoding, reason,
7278 &startin, &endin, &startinpos, &endinpos, &exc, &in,
Victor Stinner596a6c42011-11-09 00:02:18 +01007279 v, &outpos))
Victor Stinner3a50e702011-10-18 21:21:00 +02007280 {
7281 goto error;
7282 }
Victor Stinner596a6c42011-11-09 00:02:18 +01007283 out = PyUnicode_AS_UNICODE(*v) + outpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007284 }
7285 else {
7286 in += insize;
7287 memcpy(out, buffer, outsize * sizeof(wchar_t));
7288 out += outsize;
7289 }
7290 }
7291
7292 /* write a NUL character at the end */
7293 *out = 0;
7294
7295 /* Extend unicode object */
7296 outsize = out - startout;
7297 assert(outsize <= PyUnicode_WSTR_LENGTH(*v));
Victor Stinner16e6a802011-12-12 13:24:15 +01007298 if (unicode_resize(v, outsize) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007299 goto error;
Victor Stinner76a31a62011-11-04 00:05:13 +01007300 ret = size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007301
7302error:
7303 Py_XDECREF(encoding_obj);
7304 Py_XDECREF(errorHandler);
7305 Py_XDECREF(exc);
7306 return ret;
7307}
7308
Victor Stinner3a50e702011-10-18 21:21:00 +02007309static PyObject *
7310decode_code_page_stateful(int code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007311 const char *s, Py_ssize_t size,
7312 const char *errors, Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007313{
Victor Stinner76a31a62011-11-04 00:05:13 +01007314 PyObject *v = NULL;
7315 int chunk_size, final, converted, done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007316
Victor Stinner3a50e702011-10-18 21:21:00 +02007317 if (code_page < 0) {
7318 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7319 return NULL;
7320 }
7321
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007322 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00007323 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007324
Victor Stinner76a31a62011-11-04 00:05:13 +01007325 do
7326 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007327#ifdef NEED_RETRY
Victor Stinner76a31a62011-11-04 00:05:13 +01007328 if (size > INT_MAX) {
7329 chunk_size = INT_MAX;
7330 final = 0;
7331 done = 0;
7332 }
7333 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007334#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007335 {
7336 chunk_size = (int)size;
7337 final = (consumed == NULL);
7338 done = 1;
7339 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007340
Victor Stinner76a31a62011-11-04 00:05:13 +01007341 /* Skip trailing lead-byte unless 'final' is set */
7342 if (!final && is_dbcs_lead_byte(code_page, s, chunk_size - 1))
7343 --chunk_size;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007344
Victor Stinner76a31a62011-11-04 00:05:13 +01007345 if (chunk_size == 0 && done) {
7346 if (v != NULL)
7347 break;
7348 Py_INCREF(unicode_empty);
7349 return unicode_empty;
7350 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007351
Victor Stinner76a31a62011-11-04 00:05:13 +01007352
7353 converted = decode_code_page_strict(code_page, &v,
7354 s, chunk_size);
7355 if (converted == -2)
7356 converted = decode_code_page_errors(code_page, &v,
7357 s, chunk_size,
7358 errors);
7359 assert(converted != 0);
7360
7361 if (converted < 0) {
7362 Py_XDECREF(v);
7363 return NULL;
7364 }
7365
7366 if (consumed)
7367 *consumed += converted;
7368
7369 s += converted;
7370 size -= converted;
7371 } while (!done);
Victor Stinner3a50e702011-10-18 21:21:00 +02007372
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01007373 return unicode_result(v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007374}
7375
Alexander Belopolsky40018472011-02-26 01:02:56 +00007376PyObject *
Victor Stinner3a50e702011-10-18 21:21:00 +02007377PyUnicode_DecodeCodePageStateful(int code_page,
7378 const char *s,
7379 Py_ssize_t size,
7380 const char *errors,
7381 Py_ssize_t *consumed)
7382{
7383 return decode_code_page_stateful(code_page, s, size, errors, consumed);
7384}
7385
7386PyObject *
7387PyUnicode_DecodeMBCSStateful(const char *s,
7388 Py_ssize_t size,
7389 const char *errors,
7390 Py_ssize_t *consumed)
7391{
7392 return decode_code_page_stateful(CP_ACP, s, size, errors, consumed);
7393}
7394
7395PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00007396PyUnicode_DecodeMBCS(const char *s,
7397 Py_ssize_t size,
7398 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007399{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007400 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
7401}
7402
Victor Stinner3a50e702011-10-18 21:21:00 +02007403static DWORD
7404encode_code_page_flags(UINT code_page, const char *errors)
7405{
7406 if (code_page == CP_UTF8) {
7407 if (winver.dwMajorVersion >= 6)
7408 /* CP_UTF8 supports WC_ERR_INVALID_CHARS on Windows Vista
7409 and later */
7410 return WC_ERR_INVALID_CHARS;
7411 else
7412 /* CP_UTF8 only supports flags=0 on Windows older than Vista */
7413 return 0;
7414 }
7415 else if (code_page == CP_UTF7) {
7416 /* CP_UTF7 only supports flags=0 */
7417 return 0;
7418 }
7419 else {
7420 if (errors != NULL && strcmp(errors, "replace") == 0)
7421 return 0;
7422 else
7423 return WC_NO_BEST_FIT_CHARS;
7424 }
7425}
7426
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007427/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007428 * Encode a Unicode string to a Windows code page into a byte string in strict
7429 * mode.
7430 *
7431 * Returns consumed characters if succeed, returns -2 on encode error, or raise
7432 * a WindowsError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007433 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007434static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007435encode_code_page_strict(UINT code_page, PyObject **outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007436 PyObject *unicode, Py_ssize_t offset, int len,
Victor Stinner3a50e702011-10-18 21:21:00 +02007437 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007438{
Victor Stinner554f3f02010-06-16 23:33:54 +00007439 BOOL usedDefaultChar = FALSE;
Victor Stinner3a50e702011-10-18 21:21:00 +02007440 BOOL *pusedDefaultChar = &usedDefaultChar;
7441 int outsize;
Victor Stinner554f3f02010-06-16 23:33:54 +00007442 PyObject *exc = NULL;
Victor Stinner24729f32011-11-10 20:31:37 +01007443 wchar_t *p;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007444 Py_ssize_t size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007445 const DWORD flags = encode_code_page_flags(code_page, NULL);
7446 char *out;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007447 /* Create a substring so that we can get the UTF-16 representation
7448 of just the slice under consideration. */
7449 PyObject *substring;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007450
Martin v. Löwis3d325192011-11-04 18:23:06 +01007451 assert(len > 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007452
Victor Stinner3a50e702011-10-18 21:21:00 +02007453 if (code_page != CP_UTF8 && code_page != CP_UTF7)
Victor Stinner554f3f02010-06-16 23:33:54 +00007454 pusedDefaultChar = &usedDefaultChar;
Victor Stinner3a50e702011-10-18 21:21:00 +02007455 else
Victor Stinner554f3f02010-06-16 23:33:54 +00007456 pusedDefaultChar = NULL;
Victor Stinner554f3f02010-06-16 23:33:54 +00007457
Victor Stinner2fc507f2011-11-04 20:06:39 +01007458 substring = PyUnicode_Substring(unicode, offset, offset+len);
7459 if (substring == NULL)
7460 return -1;
7461 p = PyUnicode_AsUnicodeAndSize(substring, &size);
7462 if (p == NULL) {
7463 Py_DECREF(substring);
7464 return -1;
7465 }
Martin v. Löwis3d325192011-11-04 18:23:06 +01007466
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007467 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007468 outsize = WideCharToMultiByte(code_page, flags,
7469 p, size,
7470 NULL, 0,
7471 NULL, pusedDefaultChar);
7472 if (outsize <= 0)
7473 goto error;
7474 /* If we used a default char, then we failed! */
Victor Stinner2fc507f2011-11-04 20:06:39 +01007475 if (pusedDefaultChar && *pusedDefaultChar) {
7476 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007477 return -2;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007478 }
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007479
Victor Stinner3a50e702011-10-18 21:21:00 +02007480 if (*outbytes == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007481 /* Create string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007482 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007483 if (*outbytes == NULL) {
7484 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007485 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007486 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007487 out = PyBytes_AS_STRING(*outbytes);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007488 }
7489 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007490 /* Extend string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007491 const Py_ssize_t n = PyBytes_Size(*outbytes);
7492 if (outsize > PY_SSIZE_T_MAX - n) {
7493 PyErr_NoMemory();
Victor Stinner2fc507f2011-11-04 20:06:39 +01007494 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007495 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007496 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007497 if (_PyBytes_Resize(outbytes, n + outsize) < 0) {
7498 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007499 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007500 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007501 out = PyBytes_AS_STRING(*outbytes) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007502 }
7503
7504 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007505 outsize = WideCharToMultiByte(code_page, flags,
7506 p, size,
7507 out, outsize,
7508 NULL, pusedDefaultChar);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007509 Py_CLEAR(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007510 if (outsize <= 0)
7511 goto error;
7512 if (pusedDefaultChar && *pusedDefaultChar)
7513 return -2;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007514 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00007515
Victor Stinner3a50e702011-10-18 21:21:00 +02007516error:
Victor Stinner2fc507f2011-11-04 20:06:39 +01007517 Py_XDECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007518 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7519 return -2;
7520 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007521 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007522}
7523
Victor Stinner3a50e702011-10-18 21:21:00 +02007524/*
7525 * Encode a Unicode string to a Windows code page into a byte string using a
7526 * error handler.
7527 *
7528 * Returns consumed characters if succeed, or raise a WindowsError and returns
7529 * -1 on other error.
7530 */
7531static int
7532encode_code_page_errors(UINT code_page, PyObject **outbytes,
Victor Stinner7581cef2011-11-03 22:32:33 +01007533 PyObject *unicode, Py_ssize_t unicode_offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007534 Py_ssize_t insize, const char* errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007535{
Victor Stinner3a50e702011-10-18 21:21:00 +02007536 const DWORD flags = encode_code_page_flags(code_page, errors);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007537 Py_ssize_t pos = unicode_offset;
7538 Py_ssize_t endin = unicode_offset + insize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007539 /* Ideally, we should get reason from FormatMessage. This is the Windows
7540 2000 English version of the message. */
7541 const char *reason = "invalid character";
7542 /* 4=maximum length of a UTF-8 sequence */
7543 char buffer[4];
7544 BOOL usedDefaultChar = FALSE, *pusedDefaultChar;
7545 Py_ssize_t outsize;
7546 char *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007547 PyObject *errorHandler = NULL;
7548 PyObject *exc = NULL;
7549 PyObject *encoding_obj = NULL;
7550 char *encoding;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007551 Py_ssize_t newpos, newoutsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007552 PyObject *rep;
7553 int ret = -1;
7554
7555 assert(insize > 0);
7556
7557 encoding = code_page_name(code_page, &encoding_obj);
7558 if (encoding == NULL)
7559 return -1;
7560
7561 if (errors == NULL || strcmp(errors, "strict") == 0) {
7562 /* The last error was ERROR_NO_UNICODE_TRANSLATION,
7563 then we raise a UnicodeEncodeError. */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007564 make_encode_exception(&exc, encoding, unicode, 0, 0, reason);
Victor Stinner3a50e702011-10-18 21:21:00 +02007565 if (exc != NULL) {
7566 PyCodec_StrictErrors(exc);
7567 Py_DECREF(exc);
7568 }
7569 Py_XDECREF(encoding_obj);
7570 return -1;
7571 }
7572
7573 if (code_page != CP_UTF8 && code_page != CP_UTF7)
7574 pusedDefaultChar = &usedDefaultChar;
7575 else
7576 pusedDefaultChar = NULL;
7577
7578 if (Py_ARRAY_LENGTH(buffer) > PY_SSIZE_T_MAX / insize) {
7579 PyErr_NoMemory();
7580 goto error;
7581 }
7582 outsize = insize * Py_ARRAY_LENGTH(buffer);
7583
7584 if (*outbytes == NULL) {
7585 /* Create string object */
7586 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
7587 if (*outbytes == NULL)
7588 goto error;
7589 out = PyBytes_AS_STRING(*outbytes);
7590 }
7591 else {
7592 /* Extend string object */
7593 Py_ssize_t n = PyBytes_Size(*outbytes);
7594 if (n > PY_SSIZE_T_MAX - outsize) {
7595 PyErr_NoMemory();
7596 goto error;
7597 }
7598 if (_PyBytes_Resize(outbytes, n + outsize) < 0)
7599 goto error;
7600 out = PyBytes_AS_STRING(*outbytes) + n;
7601 }
7602
7603 /* Encode the string character per character */
Martin v. Löwis3d325192011-11-04 18:23:06 +01007604 while (pos < endin)
Victor Stinner3a50e702011-10-18 21:21:00 +02007605 {
Victor Stinner2fc507f2011-11-04 20:06:39 +01007606 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, pos);
7607 wchar_t chars[2];
7608 int charsize;
7609 if (ch < 0x10000) {
7610 chars[0] = (wchar_t)ch;
7611 charsize = 1;
7612 }
7613 else {
7614 ch -= 0x10000;
7615 chars[0] = 0xd800 + (ch >> 10);
7616 chars[1] = 0xdc00 + (ch & 0x3ff);
7617 charsize = 2;
7618 }
7619
Victor Stinner3a50e702011-10-18 21:21:00 +02007620 outsize = WideCharToMultiByte(code_page, flags,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007621 chars, charsize,
Victor Stinner3a50e702011-10-18 21:21:00 +02007622 buffer, Py_ARRAY_LENGTH(buffer),
7623 NULL, pusedDefaultChar);
7624 if (outsize > 0) {
7625 if (pusedDefaultChar == NULL || !(*pusedDefaultChar))
7626 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007627 pos++;
Victor Stinner3a50e702011-10-18 21:21:00 +02007628 memcpy(out, buffer, outsize);
7629 out += outsize;
7630 continue;
7631 }
7632 }
7633 else if (GetLastError() != ERROR_NO_UNICODE_TRANSLATION) {
7634 PyErr_SetFromWindowsErr(0);
7635 goto error;
7636 }
7637
Victor Stinner3a50e702011-10-18 21:21:00 +02007638 rep = unicode_encode_call_errorhandler(
7639 errors, &errorHandler, encoding, reason,
Victor Stinner7581cef2011-11-03 22:32:33 +01007640 unicode, &exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007641 pos, pos + 1, &newpos);
Victor Stinner3a50e702011-10-18 21:21:00 +02007642 if (rep == NULL)
7643 goto error;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007644 pos = newpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007645
7646 if (PyBytes_Check(rep)) {
7647 outsize = PyBytes_GET_SIZE(rep);
7648 if (outsize != 1) {
7649 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7650 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7651 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7652 Py_DECREF(rep);
7653 goto error;
7654 }
7655 out = PyBytes_AS_STRING(*outbytes) + offset;
7656 }
7657 memcpy(out, PyBytes_AS_STRING(rep), outsize);
7658 out += outsize;
7659 }
7660 else {
7661 Py_ssize_t i;
7662 enum PyUnicode_Kind kind;
7663 void *data;
7664
7665 if (PyUnicode_READY(rep) < 0) {
7666 Py_DECREF(rep);
7667 goto error;
7668 }
7669
7670 outsize = PyUnicode_GET_LENGTH(rep);
7671 if (outsize != 1) {
7672 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7673 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7674 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7675 Py_DECREF(rep);
7676 goto error;
7677 }
7678 out = PyBytes_AS_STRING(*outbytes) + offset;
7679 }
7680 kind = PyUnicode_KIND(rep);
7681 data = PyUnicode_DATA(rep);
7682 for (i=0; i < outsize; i++) {
7683 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7684 if (ch > 127) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007685 raise_encode_exception(&exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007686 encoding, unicode,
7687 pos, pos + 1,
Victor Stinner3a50e702011-10-18 21:21:00 +02007688 "unable to encode error handler result to ASCII");
7689 Py_DECREF(rep);
7690 goto error;
7691 }
7692 *out = (unsigned char)ch;
7693 out++;
7694 }
7695 }
7696 Py_DECREF(rep);
7697 }
7698 /* write a NUL byte */
7699 *out = 0;
7700 outsize = out - PyBytes_AS_STRING(*outbytes);
7701 assert(outsize <= PyBytes_GET_SIZE(*outbytes));
7702 if (_PyBytes_Resize(outbytes, outsize) < 0)
7703 goto error;
7704 ret = 0;
7705
7706error:
7707 Py_XDECREF(encoding_obj);
7708 Py_XDECREF(errorHandler);
7709 Py_XDECREF(exc);
7710 return ret;
7711}
7712
Victor Stinner3a50e702011-10-18 21:21:00 +02007713static PyObject *
7714encode_code_page(int code_page,
Victor Stinner7581cef2011-11-03 22:32:33 +01007715 PyObject *unicode,
Victor Stinner3a50e702011-10-18 21:21:00 +02007716 const char *errors)
7717{
Martin v. Löwis3d325192011-11-04 18:23:06 +01007718 Py_ssize_t len;
Victor Stinner3a50e702011-10-18 21:21:00 +02007719 PyObject *outbytes = NULL;
Victor Stinner7581cef2011-11-03 22:32:33 +01007720 Py_ssize_t offset;
Victor Stinner76a31a62011-11-04 00:05:13 +01007721 int chunk_len, ret, done;
Victor Stinner7581cef2011-11-03 22:32:33 +01007722
Victor Stinner2fc507f2011-11-04 20:06:39 +01007723 if (PyUnicode_READY(unicode) < 0)
7724 return NULL;
7725 len = PyUnicode_GET_LENGTH(unicode);
Guido van Rossum03e29f12000-05-04 15:52:20 +00007726
Victor Stinner3a50e702011-10-18 21:21:00 +02007727 if (code_page < 0) {
7728 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7729 return NULL;
7730 }
7731
Martin v. Löwis3d325192011-11-04 18:23:06 +01007732 if (len == 0)
Victor Stinner76a31a62011-11-04 00:05:13 +01007733 return PyBytes_FromStringAndSize(NULL, 0);
7734
Victor Stinner7581cef2011-11-03 22:32:33 +01007735 offset = 0;
7736 do
7737 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007738#ifdef NEED_RETRY
Victor Stinner2fc507f2011-11-04 20:06:39 +01007739 /* UTF-16 encoding may double the size, so use only INT_MAX/2
Martin v. Löwis3d325192011-11-04 18:23:06 +01007740 chunks. */
7741 if (len > INT_MAX/2) {
7742 chunk_len = INT_MAX/2;
Victor Stinner76a31a62011-11-04 00:05:13 +01007743 done = 0;
7744 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007745 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007746#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007747 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007748 chunk_len = (int)len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007749 done = 1;
7750 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007751
Victor Stinner76a31a62011-11-04 00:05:13 +01007752 ret = encode_code_page_strict(code_page, &outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007753 unicode, offset, chunk_len,
Victor Stinner76a31a62011-11-04 00:05:13 +01007754 errors);
7755 if (ret == -2)
7756 ret = encode_code_page_errors(code_page, &outbytes,
7757 unicode, offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007758 chunk_len, errors);
Victor Stinner7581cef2011-11-03 22:32:33 +01007759 if (ret < 0) {
7760 Py_XDECREF(outbytes);
7761 return NULL;
7762 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007763
Victor Stinner7581cef2011-11-03 22:32:33 +01007764 offset += chunk_len;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007765 len -= chunk_len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007766 } while (!done);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007767
Victor Stinner3a50e702011-10-18 21:21:00 +02007768 return outbytes;
7769}
7770
7771PyObject *
7772PyUnicode_EncodeMBCS(const Py_UNICODE *p,
7773 Py_ssize_t size,
7774 const char *errors)
7775{
Victor Stinner7581cef2011-11-03 22:32:33 +01007776 PyObject *unicode, *res;
7777 unicode = PyUnicode_FromUnicode(p, size);
7778 if (unicode == NULL)
7779 return NULL;
7780 res = encode_code_page(CP_ACP, unicode, errors);
7781 Py_DECREF(unicode);
7782 return res;
Victor Stinner3a50e702011-10-18 21:21:00 +02007783}
7784
7785PyObject *
7786PyUnicode_EncodeCodePage(int code_page,
7787 PyObject *unicode,
7788 const char *errors)
7789{
Victor Stinner7581cef2011-11-03 22:32:33 +01007790 return encode_code_page(code_page, unicode, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007791}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007792
Alexander Belopolsky40018472011-02-26 01:02:56 +00007793PyObject *
7794PyUnicode_AsMBCSString(PyObject *unicode)
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007795{
7796 if (!PyUnicode_Check(unicode)) {
7797 PyErr_BadArgument();
7798 return NULL;
7799 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007800 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007801}
7802
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007803#undef NEED_RETRY
7804
Victor Stinner99b95382011-07-04 14:23:54 +02007805#endif /* HAVE_MBCS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007806
Guido van Rossumd57fd912000-03-10 22:53:23 +00007807/* --- Character Mapping Codec -------------------------------------------- */
7808
Alexander Belopolsky40018472011-02-26 01:02:56 +00007809PyObject *
7810PyUnicode_DecodeCharmap(const char *s,
7811 Py_ssize_t size,
7812 PyObject *mapping,
7813 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007814{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007815 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007816 Py_ssize_t startinpos;
7817 Py_ssize_t endinpos;
7818 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007819 const char *e;
Victor Stinner7931d9a2011-11-04 00:22:48 +01007820 PyObject *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007821 Py_ssize_t extrachars = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007822 PyObject *errorHandler = NULL;
7823 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00007824
Guido van Rossumd57fd912000-03-10 22:53:23 +00007825 /* Default to Latin-1 */
7826 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007827 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007828
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007829 v = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007830 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007831 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007832 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01007833 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007834 outpos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007835 e = s + size;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007836 if (PyUnicode_CheckExact(mapping)) {
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007837 Py_ssize_t maplen;
7838 enum PyUnicode_Kind kind;
7839 void *data;
7840 Py_UCS4 x;
7841
7842 if (PyUnicode_READY(mapping) < 0)
7843 return NULL;
7844
7845 maplen = PyUnicode_GET_LENGTH(mapping);
7846 data = PyUnicode_DATA(mapping);
7847 kind = PyUnicode_KIND(mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00007848 while (s < e) {
7849 unsigned char ch = *s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007850
Benjamin Peterson29060642009-01-31 22:14:21 +00007851 if (ch < maplen)
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007852 x = PyUnicode_READ(kind, data, ch);
7853 else
7854 x = 0xfffe; /* invalid value */
Guido van Rossumd57fd912000-03-10 22:53:23 +00007855
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007856 if (x == 0xfffe)
7857 {
Benjamin Peterson29060642009-01-31 22:14:21 +00007858 /* undefined mapping */
Benjamin Peterson29060642009-01-31 22:14:21 +00007859 startinpos = s-starts;
7860 endinpos = startinpos+1;
7861 if (unicode_decode_call_errorhandler(
7862 errors, &errorHandler,
7863 "charmap", "character maps to <undefined>",
7864 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007865 &v, &outpos)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007866 goto onError;
7867 }
7868 continue;
7869 }
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007870
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007871 if (unicode_putchar(&v, &outpos, x) < 0)
7872 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00007873 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007874 }
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007875 }
7876 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007877 while (s < e) {
7878 unsigned char ch = *s;
7879 PyObject *w, *x;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007880
Benjamin Peterson29060642009-01-31 22:14:21 +00007881 /* Get mapping (char ordinal -> integer, Unicode char or None) */
7882 w = PyLong_FromLong((long)ch);
7883 if (w == NULL)
7884 goto onError;
7885 x = PyObject_GetItem(mapping, w);
7886 Py_DECREF(w);
7887 if (x == NULL) {
7888 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7889 /* No mapping found means: mapping is undefined. */
7890 PyErr_Clear();
7891 x = Py_None;
7892 Py_INCREF(x);
7893 } else
7894 goto onError;
7895 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007896
Benjamin Peterson29060642009-01-31 22:14:21 +00007897 /* Apply mapping */
7898 if (PyLong_Check(x)) {
7899 long value = PyLong_AS_LONG(x);
7900 if (value < 0 || value > 65535) {
7901 PyErr_SetString(PyExc_TypeError,
7902 "character mapping must be in range(65536)");
7903 Py_DECREF(x);
7904 goto onError;
7905 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007906 if (unicode_putchar(&v, &outpos, value) < 0)
7907 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00007908 }
7909 else if (x == Py_None) {
7910 /* undefined mapping */
Benjamin Peterson29060642009-01-31 22:14:21 +00007911 startinpos = s-starts;
7912 endinpos = startinpos+1;
7913 if (unicode_decode_call_errorhandler(
7914 errors, &errorHandler,
7915 "charmap", "character maps to <undefined>",
7916 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007917 &v, &outpos)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007918 Py_DECREF(x);
7919 goto onError;
7920 }
7921 Py_DECREF(x);
7922 continue;
7923 }
7924 else if (PyUnicode_Check(x)) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007925 Py_ssize_t targetsize;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007926
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007927 if (PyUnicode_READY(x) < 0)
7928 goto onError;
7929 targetsize = PyUnicode_GET_LENGTH(x);
7930
7931 if (targetsize == 1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007932 /* 1-1 mapping */
Victor Stinner62aa4d02011-11-09 00:03:45 +01007933 if (unicode_putchar(&v, &outpos,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007934 PyUnicode_READ_CHAR(x, 0)) < 0)
7935 goto onError;
7936 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007937 else if (targetsize > 1) {
7938 /* 1-n mapping */
7939 if (targetsize > extrachars) {
7940 /* resize first */
Benjamin Peterson29060642009-01-31 22:14:21 +00007941 Py_ssize_t needed = (targetsize - extrachars) + \
7942 (targetsize << 2);
7943 extrachars += needed;
7944 /* XXX overflow detection missing */
Victor Stinner16e6a802011-12-12 13:24:15 +01007945 if (unicode_resize(&v,
7946 PyUnicode_GET_LENGTH(v) + needed) < 0)
7947 {
Benjamin Peterson29060642009-01-31 22:14:21 +00007948 Py_DECREF(x);
7949 goto onError;
7950 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007951 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007952 if (unicode_widen(&v, PyUnicode_MAX_CHAR_VALUE(x)) < 0)
7953 goto onError;
7954 PyUnicode_CopyCharacters(v, outpos, x, 0, targetsize);
7955 outpos += targetsize;
Benjamin Peterson29060642009-01-31 22:14:21 +00007956 extrachars -= targetsize;
7957 }
7958 /* 1-0 mapping: skip the character */
7959 }
7960 else {
7961 /* wrong return value */
7962 PyErr_SetString(PyExc_TypeError,
7963 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00007964 Py_DECREF(x);
7965 goto onError;
7966 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007967 Py_DECREF(x);
7968 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007969 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00007970 }
Victor Stinner16e6a802011-12-12 13:24:15 +01007971 if (unicode_resize(&v, outpos) < 0)
Antoine Pitroua8f63c02011-11-08 18:37:16 +01007972 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007973 Py_XDECREF(errorHandler);
7974 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01007975 return unicode_result(v);
Tim Petersced69f82003-09-16 20:30:58 +00007976
Benjamin Peterson29060642009-01-31 22:14:21 +00007977 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007978 Py_XDECREF(errorHandler);
7979 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007980 Py_XDECREF(v);
7981 return NULL;
7982}
7983
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007984/* Charmap encoding: the lookup table */
7985
Alexander Belopolsky40018472011-02-26 01:02:56 +00007986struct encoding_map {
Benjamin Peterson29060642009-01-31 22:14:21 +00007987 PyObject_HEAD
7988 unsigned char level1[32];
7989 int count2, count3;
7990 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007991};
7992
7993static PyObject*
7994encoding_map_size(PyObject *obj, PyObject* args)
7995{
7996 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007997 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00007998 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007999}
8000
8001static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008002 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00008003 PyDoc_STR("Return the size (in bytes) of this object") },
8004 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008005};
8006
8007static void
8008encoding_map_dealloc(PyObject* o)
8009{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008010 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008011}
8012
8013static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008014 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008015 "EncodingMap", /*tp_name*/
8016 sizeof(struct encoding_map), /*tp_basicsize*/
8017 0, /*tp_itemsize*/
8018 /* methods */
8019 encoding_map_dealloc, /*tp_dealloc*/
8020 0, /*tp_print*/
8021 0, /*tp_getattr*/
8022 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00008023 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00008024 0, /*tp_repr*/
8025 0, /*tp_as_number*/
8026 0, /*tp_as_sequence*/
8027 0, /*tp_as_mapping*/
8028 0, /*tp_hash*/
8029 0, /*tp_call*/
8030 0, /*tp_str*/
8031 0, /*tp_getattro*/
8032 0, /*tp_setattro*/
8033 0, /*tp_as_buffer*/
8034 Py_TPFLAGS_DEFAULT, /*tp_flags*/
8035 0, /*tp_doc*/
8036 0, /*tp_traverse*/
8037 0, /*tp_clear*/
8038 0, /*tp_richcompare*/
8039 0, /*tp_weaklistoffset*/
8040 0, /*tp_iter*/
8041 0, /*tp_iternext*/
8042 encoding_map_methods, /*tp_methods*/
8043 0, /*tp_members*/
8044 0, /*tp_getset*/
8045 0, /*tp_base*/
8046 0, /*tp_dict*/
8047 0, /*tp_descr_get*/
8048 0, /*tp_descr_set*/
8049 0, /*tp_dictoffset*/
8050 0, /*tp_init*/
8051 0, /*tp_alloc*/
8052 0, /*tp_new*/
8053 0, /*tp_free*/
8054 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008055};
8056
8057PyObject*
8058PyUnicode_BuildEncodingMap(PyObject* string)
8059{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008060 PyObject *result;
8061 struct encoding_map *mresult;
8062 int i;
8063 int need_dict = 0;
8064 unsigned char level1[32];
8065 unsigned char level2[512];
8066 unsigned char *mlevel1, *mlevel2, *mlevel3;
8067 int count2 = 0, count3 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008068 int kind;
8069 void *data;
8070 Py_UCS4 ch;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008071
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008072 if (!PyUnicode_Check(string) || PyUnicode_GET_LENGTH(string) != 256) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008073 PyErr_BadArgument();
8074 return NULL;
8075 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008076 kind = PyUnicode_KIND(string);
8077 data = PyUnicode_DATA(string);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008078 memset(level1, 0xFF, sizeof level1);
8079 memset(level2, 0xFF, sizeof level2);
8080
8081 /* If there isn't a one-to-one mapping of NULL to \0,
8082 or if there are non-BMP characters, we need to use
8083 a mapping dictionary. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008084 if (PyUnicode_READ(kind, data, 0) != 0)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008085 need_dict = 1;
8086 for (i = 1; i < 256; i++) {
8087 int l1, l2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008088 ch = PyUnicode_READ(kind, data, i);
8089 if (ch == 0 || ch > 0xFFFF) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008090 need_dict = 1;
8091 break;
8092 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008093 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008094 /* unmapped character */
8095 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008096 l1 = ch >> 11;
8097 l2 = ch >> 7;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008098 if (level1[l1] == 0xFF)
8099 level1[l1] = count2++;
8100 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00008101 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008102 }
8103
8104 if (count2 >= 0xFF || count3 >= 0xFF)
8105 need_dict = 1;
8106
8107 if (need_dict) {
8108 PyObject *result = PyDict_New();
8109 PyObject *key, *value;
8110 if (!result)
8111 return NULL;
8112 for (i = 0; i < 256; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008113 key = PyLong_FromLong(PyUnicode_READ(kind, data, i));
Christian Heimes217cfd12007-12-02 14:31:20 +00008114 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008115 if (!key || !value)
8116 goto failed1;
8117 if (PyDict_SetItem(result, key, value) == -1)
8118 goto failed1;
8119 Py_DECREF(key);
8120 Py_DECREF(value);
8121 }
8122 return result;
8123 failed1:
8124 Py_XDECREF(key);
8125 Py_XDECREF(value);
8126 Py_DECREF(result);
8127 return NULL;
8128 }
8129
8130 /* Create a three-level trie */
8131 result = PyObject_MALLOC(sizeof(struct encoding_map) +
8132 16*count2 + 128*count3 - 1);
8133 if (!result)
8134 return PyErr_NoMemory();
8135 PyObject_Init(result, &EncodingMapType);
8136 mresult = (struct encoding_map*)result;
8137 mresult->count2 = count2;
8138 mresult->count3 = count3;
8139 mlevel1 = mresult->level1;
8140 mlevel2 = mresult->level23;
8141 mlevel3 = mresult->level23 + 16*count2;
8142 memcpy(mlevel1, level1, 32);
8143 memset(mlevel2, 0xFF, 16*count2);
8144 memset(mlevel3, 0, 128*count3);
8145 count3 = 0;
8146 for (i = 1; i < 256; i++) {
8147 int o1, o2, o3, i2, i3;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008148 if (PyUnicode_READ(kind, data, i) == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008149 /* unmapped character */
8150 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008151 o1 = PyUnicode_READ(kind, data, i)>>11;
8152 o2 = (PyUnicode_READ(kind, data, i)>>7) & 0xF;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008153 i2 = 16*mlevel1[o1] + o2;
8154 if (mlevel2[i2] == 0xFF)
8155 mlevel2[i2] = count3++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008156 o3 = PyUnicode_READ(kind, data, i) & 0x7F;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008157 i3 = 128*mlevel2[i2] + o3;
8158 mlevel3[i3] = i;
8159 }
8160 return result;
8161}
8162
8163static int
Victor Stinner22168992011-11-20 17:09:18 +01008164encoding_map_lookup(Py_UCS4 c, PyObject *mapping)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008165{
8166 struct encoding_map *map = (struct encoding_map*)mapping;
8167 int l1 = c>>11;
8168 int l2 = (c>>7) & 0xF;
8169 int l3 = c & 0x7F;
8170 int i;
8171
Victor Stinner22168992011-11-20 17:09:18 +01008172 if (c > 0xFFFF)
Benjamin Peterson29060642009-01-31 22:14:21 +00008173 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008174 if (c == 0)
8175 return 0;
8176 /* level 1*/
8177 i = map->level1[l1];
8178 if (i == 0xFF) {
8179 return -1;
8180 }
8181 /* level 2*/
8182 i = map->level23[16*i+l2];
8183 if (i == 0xFF) {
8184 return -1;
8185 }
8186 /* level 3 */
8187 i = map->level23[16*map->count2 + 128*i + l3];
8188 if (i == 0) {
8189 return -1;
8190 }
8191 return i;
8192}
8193
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008194/* Lookup the character ch in the mapping. If the character
8195 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00008196 error occurred). */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008197static PyObject *
Victor Stinner22168992011-11-20 17:09:18 +01008198charmapencode_lookup(Py_UCS4 c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008199{
Christian Heimes217cfd12007-12-02 14:31:20 +00008200 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008201 PyObject *x;
8202
8203 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008204 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008205 x = PyObject_GetItem(mapping, w);
8206 Py_DECREF(w);
8207 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008208 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8209 /* No mapping found means: mapping is undefined. */
8210 PyErr_Clear();
8211 x = Py_None;
8212 Py_INCREF(x);
8213 return x;
8214 } else
8215 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008216 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00008217 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008218 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00008219 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008220 long value = PyLong_AS_LONG(x);
8221 if (value < 0 || value > 255) {
8222 PyErr_SetString(PyExc_TypeError,
8223 "character mapping must be in range(256)");
8224 Py_DECREF(x);
8225 return NULL;
8226 }
8227 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008228 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008229 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008230 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008231 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008232 /* wrong return value */
8233 PyErr_Format(PyExc_TypeError,
8234 "character mapping must return integer, bytes or None, not %.400s",
8235 x->ob_type->tp_name);
8236 Py_DECREF(x);
8237 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008238 }
8239}
8240
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008241static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00008242charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008243{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008244 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
8245 /* exponentially overallocate to minimize reallocations */
8246 if (requiredsize < 2*outsize)
8247 requiredsize = 2*outsize;
8248 if (_PyBytes_Resize(outobj, requiredsize))
8249 return -1;
8250 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008251}
8252
Benjamin Peterson14339b62009-01-31 16:36:08 +00008253typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00008254 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Alexander Belopolsky40018472011-02-26 01:02:56 +00008255} charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008256/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00008257 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008258 space is available. Return a new reference to the object that
8259 was put in the output buffer, or Py_None, if the mapping was undefined
8260 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00008261 reallocation error occurred. The caller must decref the result */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008262static charmapencode_result
Victor Stinner22168992011-11-20 17:09:18 +01008263charmapencode_output(Py_UCS4 c, PyObject *mapping,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008264 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008265{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008266 PyObject *rep;
8267 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00008268 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008269
Christian Heimes90aa7642007-12-19 02:45:37 +00008270 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008271 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008272 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008273 if (res == -1)
8274 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00008275 if (outsize<requiredsize)
8276 if (charmapencode_resize(outobj, outpos, requiredsize))
8277 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00008278 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008279 outstart[(*outpos)++] = (char)res;
8280 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008281 }
8282
8283 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008284 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008285 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008286 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008287 Py_DECREF(rep);
8288 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008289 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008290 if (PyLong_Check(rep)) {
8291 Py_ssize_t requiredsize = *outpos+1;
8292 if (outsize<requiredsize)
8293 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8294 Py_DECREF(rep);
8295 return enc_EXCEPTION;
8296 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008297 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008298 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008299 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008300 else {
8301 const char *repchars = PyBytes_AS_STRING(rep);
8302 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
8303 Py_ssize_t requiredsize = *outpos+repsize;
8304 if (outsize<requiredsize)
8305 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8306 Py_DECREF(rep);
8307 return enc_EXCEPTION;
8308 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008309 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008310 memcpy(outstart + *outpos, repchars, repsize);
8311 *outpos += repsize;
8312 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008313 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008314 Py_DECREF(rep);
8315 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008316}
8317
8318/* handle an error in PyUnicode_EncodeCharmap
8319 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008320static int
8321charmap_encoding_error(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008322 PyObject *unicode, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008323 PyObject **exceptionObject,
Walter Dörwalde5402fb2003-08-14 20:25:29 +00008324 int *known_errorHandler, PyObject **errorHandler, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00008325 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008326{
8327 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008328 Py_ssize_t size, repsize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008329 Py_ssize_t newpos;
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008330 enum PyUnicode_Kind kind;
8331 void *data;
8332 Py_ssize_t index;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008333 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008334 Py_ssize_t collstartpos = *inpos;
8335 Py_ssize_t collendpos = *inpos+1;
8336 Py_ssize_t collpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008337 char *encoding = "charmap";
8338 char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008339 charmapencode_result x;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008340 Py_UCS4 ch;
Brian Curtin2787ea42011-11-02 15:09:37 -05008341 int val;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008342
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008343 if (PyUnicode_READY(unicode) < 0)
8344 return -1;
8345 size = PyUnicode_GET_LENGTH(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008346 /* find all unencodable characters */
8347 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008348 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00008349 if (Py_TYPE(mapping) == &EncodingMapType) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008350 ch = PyUnicode_READ_CHAR(unicode, collendpos);
Brian Curtin2787ea42011-11-02 15:09:37 -05008351 val = encoding_map_lookup(ch, mapping);
8352 if (val != -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008353 break;
8354 ++collendpos;
8355 continue;
8356 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008357
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008358 ch = PyUnicode_READ_CHAR(unicode, collendpos);
8359 rep = charmapencode_lookup(ch, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008360 if (rep==NULL)
8361 return -1;
8362 else if (rep!=Py_None) {
8363 Py_DECREF(rep);
8364 break;
8365 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008366 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00008367 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008368 }
8369 /* cache callback name lookup
8370 * (if not done yet, i.e. it's the first error) */
8371 if (*known_errorHandler==-1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008372 if ((errors==NULL) || (!strcmp(errors, "strict")))
8373 *known_errorHandler = 1;
8374 else if (!strcmp(errors, "replace"))
8375 *known_errorHandler = 2;
8376 else if (!strcmp(errors, "ignore"))
8377 *known_errorHandler = 3;
8378 else if (!strcmp(errors, "xmlcharrefreplace"))
8379 *known_errorHandler = 4;
8380 else
8381 *known_errorHandler = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008382 }
8383 switch (*known_errorHandler) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008384 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008385 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008386 return -1;
8387 case 2: /* replace */
8388 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008389 x = charmapencode_output('?', mapping, res, respos);
8390 if (x==enc_EXCEPTION) {
8391 return -1;
8392 }
8393 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008394 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008395 return -1;
8396 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008397 }
8398 /* fall through */
8399 case 3: /* ignore */
8400 *inpos = collendpos;
8401 break;
8402 case 4: /* xmlcharrefreplace */
8403 /* generate replacement (temporarily (mis)uses p) */
8404 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008405 char buffer[2+29+1+1];
8406 char *cp;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008407 sprintf(buffer, "&#%d;", (int)PyUnicode_READ_CHAR(unicode, collpos));
Benjamin Peterson29060642009-01-31 22:14:21 +00008408 for (cp = buffer; *cp; ++cp) {
8409 x = charmapencode_output(*cp, mapping, res, respos);
8410 if (x==enc_EXCEPTION)
8411 return -1;
8412 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008413 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008414 return -1;
8415 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008416 }
8417 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008418 *inpos = collendpos;
8419 break;
8420 default:
8421 repunicode = unicode_encode_call_errorhandler(errors, errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008422 encoding, reason, unicode, exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00008423 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008424 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008425 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00008426 if (PyBytes_Check(repunicode)) {
8427 /* Directly copy bytes result to output. */
8428 Py_ssize_t outsize = PyBytes_Size(*res);
8429 Py_ssize_t requiredsize;
8430 repsize = PyBytes_Size(repunicode);
8431 requiredsize = *respos + repsize;
8432 if (requiredsize > outsize)
8433 /* Make room for all additional bytes. */
8434 if (charmapencode_resize(res, respos, requiredsize)) {
8435 Py_DECREF(repunicode);
8436 return -1;
8437 }
8438 memcpy(PyBytes_AsString(*res) + *respos,
8439 PyBytes_AsString(repunicode), repsize);
8440 *respos += repsize;
8441 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008442 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00008443 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008444 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008445 /* generate replacement */
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008446 if (PyUnicode_READY(repunicode) < 0) {
8447 Py_DECREF(repunicode);
8448 return -1;
8449 }
Victor Stinner9e30aa52011-11-21 02:49:52 +01008450 repsize = PyUnicode_GET_LENGTH(repunicode);
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008451 data = PyUnicode_DATA(repunicode);
8452 kind = PyUnicode_KIND(repunicode);
8453 for (index = 0; index < repsize; index++) {
8454 Py_UCS4 repch = PyUnicode_READ(kind, data, index);
8455 x = charmapencode_output(repch, mapping, res, respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008456 if (x==enc_EXCEPTION) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008457 Py_DECREF(repunicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00008458 return -1;
8459 }
8460 else if (x==enc_FAILED) {
8461 Py_DECREF(repunicode);
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008462 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008463 return -1;
8464 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008465 }
8466 *inpos = newpos;
8467 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008468 }
8469 return 0;
8470}
8471
Alexander Belopolsky40018472011-02-26 01:02:56 +00008472PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008473_PyUnicode_EncodeCharmap(PyObject *unicode,
8474 PyObject *mapping,
8475 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008476{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008477 /* output object */
8478 PyObject *res = NULL;
8479 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008480 Py_ssize_t inpos = 0;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008481 Py_ssize_t size;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008482 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008483 Py_ssize_t respos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008484 PyObject *errorHandler = NULL;
8485 PyObject *exc = NULL;
8486 /* the following variable is used for caching string comparisons
8487 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8488 * 3=ignore, 4=xmlcharrefreplace */
8489 int known_errorHandler = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008490
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008491 if (PyUnicode_READY(unicode) < 0)
8492 return NULL;
8493 size = PyUnicode_GET_LENGTH(unicode);
8494
Guido van Rossumd57fd912000-03-10 22:53:23 +00008495 /* Default to Latin-1 */
8496 if (mapping == NULL)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008497 return unicode_encode_ucs1(unicode, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008498
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008499 /* allocate enough for a simple encoding without
8500 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00008501 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008502 if (res == NULL)
8503 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00008504 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008505 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008506
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008507 while (inpos<size) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008508 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, inpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008509 /* try to encode it */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008510 charmapencode_result x = charmapencode_output(ch, mapping, &res, &respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008511 if (x==enc_EXCEPTION) /* error */
8512 goto onError;
8513 if (x==enc_FAILED) { /* unencodable character */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008514 if (charmap_encoding_error(unicode, &inpos, mapping,
Benjamin Peterson29060642009-01-31 22:14:21 +00008515 &exc,
8516 &known_errorHandler, &errorHandler, errors,
8517 &res, &respos)) {
8518 goto onError;
8519 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008520 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008521 else
8522 /* done with this character => adjust input position */
8523 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008524 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008525
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008526 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00008527 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00008528 if (_PyBytes_Resize(&res, respos) < 0)
8529 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00008530
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008531 Py_XDECREF(exc);
8532 Py_XDECREF(errorHandler);
8533 return res;
8534
Benjamin Peterson29060642009-01-31 22:14:21 +00008535 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008536 Py_XDECREF(res);
8537 Py_XDECREF(exc);
8538 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008539 return NULL;
8540}
8541
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008542/* Deprecated */
8543PyObject *
8544PyUnicode_EncodeCharmap(const Py_UNICODE *p,
8545 Py_ssize_t size,
8546 PyObject *mapping,
8547 const char *errors)
8548{
8549 PyObject *result;
8550 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8551 if (unicode == NULL)
8552 return NULL;
8553 result = _PyUnicode_EncodeCharmap(unicode, mapping, errors);
8554 Py_DECREF(unicode);
Victor Stinnerfc026c92011-11-04 00:24:51 +01008555 return result;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008556}
8557
Alexander Belopolsky40018472011-02-26 01:02:56 +00008558PyObject *
8559PyUnicode_AsCharmapString(PyObject *unicode,
8560 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008561{
8562 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008563 PyErr_BadArgument();
8564 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008565 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008566 return _PyUnicode_EncodeCharmap(unicode, mapping, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008567}
8568
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008569/* create or adjust a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008570static void
8571make_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008572 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008573 Py_ssize_t startpos, Py_ssize_t endpos,
8574 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008575{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008576 if (*exceptionObject == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008577 *exceptionObject = _PyUnicodeTranslateError_Create(
8578 unicode, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008579 }
8580 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008581 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
8582 goto onError;
8583 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
8584 goto onError;
8585 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
8586 goto onError;
8587 return;
8588 onError:
8589 Py_DECREF(*exceptionObject);
8590 *exceptionObject = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008591 }
8592}
8593
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008594/* raises a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008595static void
8596raise_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008597 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008598 Py_ssize_t startpos, Py_ssize_t endpos,
8599 const char *reason)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008600{
8601 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008602 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008603 if (*exceptionObject != NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008604 PyCodec_StrictErrors(*exceptionObject);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008605}
8606
8607/* error handling callback helper:
8608 build arguments, call the callback and check the arguments,
8609 put the result into newpos and return the replacement string, which
8610 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008611static PyObject *
8612unicode_translate_call_errorhandler(const char *errors,
8613 PyObject **errorHandler,
8614 const char *reason,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008615 PyObject *unicode, PyObject **exceptionObject,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008616 Py_ssize_t startpos, Py_ssize_t endpos,
8617 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008618{
Benjamin Peterson142957c2008-07-04 19:55:29 +00008619 static char *argparse = "O!n;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008620
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008621 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008622 PyObject *restuple;
8623 PyObject *resunicode;
8624
8625 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008626 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008627 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008628 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008629 }
8630
8631 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008632 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008633 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008634 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008635
8636 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00008637 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008638 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008639 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008640 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00008641 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00008642 Py_DECREF(restuple);
8643 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008644 }
8645 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type,
Benjamin Peterson29060642009-01-31 22:14:21 +00008646 &resunicode, &i_newpos)) {
8647 Py_DECREF(restuple);
8648 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008649 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00008650 if (i_newpos<0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008651 *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008652 else
8653 *newpos = i_newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008654 if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008655 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
8656 Py_DECREF(restuple);
8657 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00008658 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008659 Py_INCREF(resunicode);
8660 Py_DECREF(restuple);
8661 return resunicode;
8662}
8663
8664/* Lookup the character ch in the mapping and put the result in result,
8665 which must be decrefed by the caller.
8666 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008667static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008668charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008669{
Christian Heimes217cfd12007-12-02 14:31:20 +00008670 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008671 PyObject *x;
8672
8673 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008674 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008675 x = PyObject_GetItem(mapping, w);
8676 Py_DECREF(w);
8677 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008678 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8679 /* No mapping found means: use 1:1 mapping. */
8680 PyErr_Clear();
8681 *result = NULL;
8682 return 0;
8683 } else
8684 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008685 }
8686 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008687 *result = x;
8688 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008689 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008690 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008691 long value = PyLong_AS_LONG(x);
8692 long max = PyUnicode_GetMax();
8693 if (value < 0 || value > max) {
8694 PyErr_Format(PyExc_TypeError,
Guido van Rossum5a2f7e602007-10-24 21:13:09 +00008695 "character mapping must be in range(0x%x)", max+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00008696 Py_DECREF(x);
8697 return -1;
8698 }
8699 *result = x;
8700 return 0;
8701 }
8702 else if (PyUnicode_Check(x)) {
8703 *result = x;
8704 return 0;
8705 }
8706 else {
8707 /* wrong return value */
8708 PyErr_SetString(PyExc_TypeError,
8709 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00008710 Py_DECREF(x);
8711 return -1;
8712 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008713}
8714/* ensure that *outobj is at least requiredsize characters long,
Benjamin Peterson29060642009-01-31 22:14:21 +00008715 if not reallocate and adjust various state variables.
8716 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008717static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008718charmaptranslate_makespace(Py_UCS4 **outobj, Py_ssize_t *psize,
Benjamin Peterson29060642009-01-31 22:14:21 +00008719 Py_ssize_t requiredsize)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008720{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008721 Py_ssize_t oldsize = *psize;
Walter Dörwald4894c302003-10-24 14:25:28 +00008722 if (requiredsize > oldsize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008723 /* exponentially overallocate to minimize reallocations */
8724 if (requiredsize < 2 * oldsize)
8725 requiredsize = 2 * oldsize;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008726 *outobj = PyMem_Realloc(*outobj, requiredsize * sizeof(Py_UCS4));
8727 if (*outobj == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008728 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008729 *psize = requiredsize;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008730 }
8731 return 0;
8732}
8733/* lookup the character, put the result in the output string and adjust
8734 various state variables. Return a new reference to the object that
8735 was put in the output buffer in *result, or Py_None, if the mapping was
8736 undefined (in which case no character was written).
8737 The called must decref result.
8738 Return 0 on success, -1 on error. */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008739static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008740charmaptranslate_output(PyObject *input, Py_ssize_t ipos,
8741 PyObject *mapping, Py_UCS4 **output,
8742 Py_ssize_t *osize, Py_ssize_t *opos,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008743 PyObject **res)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008744{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008745 Py_UCS4 curinp = PyUnicode_READ_CHAR(input, ipos);
8746 if (charmaptranslate_lookup(curinp, mapping, res))
Benjamin Peterson29060642009-01-31 22:14:21 +00008747 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008748 if (*res==NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008749 /* not found => default to 1:1 mapping */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008750 (*output)[(*opos)++] = curinp;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008751 }
8752 else if (*res==Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008753 ;
Christian Heimes217cfd12007-12-02 14:31:20 +00008754 else if (PyLong_Check(*res)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008755 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008756 (*output)[(*opos)++] = (Py_UCS4)PyLong_AS_LONG(*res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008757 }
8758 else if (PyUnicode_Check(*res)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008759 Py_ssize_t repsize;
8760 if (PyUnicode_READY(*res) == -1)
8761 return -1;
8762 repsize = PyUnicode_GET_LENGTH(*res);
Benjamin Peterson29060642009-01-31 22:14:21 +00008763 if (repsize==1) {
8764 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008765 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +00008766 }
8767 else if (repsize!=0) {
8768 /* more than one character */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008769 Py_ssize_t requiredsize = *opos +
8770 (PyUnicode_GET_LENGTH(input) - ipos) +
Benjamin Peterson29060642009-01-31 22:14:21 +00008771 repsize - 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008772 Py_ssize_t i;
8773 if (charmaptranslate_makespace(output, osize, requiredsize))
Benjamin Peterson29060642009-01-31 22:14:21 +00008774 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008775 for(i = 0; i < repsize; i++)
8776 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00008777 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008778 }
8779 else
Benjamin Peterson29060642009-01-31 22:14:21 +00008780 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008781 return 0;
8782}
8783
Alexander Belopolsky40018472011-02-26 01:02:56 +00008784PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008785_PyUnicode_TranslateCharmap(PyObject *input,
8786 PyObject *mapping,
8787 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008788{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008789 /* input object */
8790 char *idata;
8791 Py_ssize_t size, i;
8792 int kind;
8793 /* output buffer */
8794 Py_UCS4 *output = NULL;
8795 Py_ssize_t osize;
8796 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008797 /* current output position */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008798 Py_ssize_t opos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008799 char *reason = "character maps to <undefined>";
8800 PyObject *errorHandler = NULL;
8801 PyObject *exc = NULL;
8802 /* the following variable is used for caching string comparisons
8803 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8804 * 3=ignore, 4=xmlcharrefreplace */
8805 int known_errorHandler = -1;
8806
Guido van Rossumd57fd912000-03-10 22:53:23 +00008807 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008808 PyErr_BadArgument();
8809 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008810 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008811
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008812 if (PyUnicode_READY(input) == -1)
8813 return NULL;
8814 idata = (char*)PyUnicode_DATA(input);
8815 kind = PyUnicode_KIND(input);
8816 size = PyUnicode_GET_LENGTH(input);
8817 i = 0;
8818
8819 if (size == 0) {
8820 Py_INCREF(input);
8821 return input;
8822 }
8823
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008824 /* allocate enough for a simple 1:1 translation without
8825 replacements, if we need more, we'll resize */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008826 osize = size;
8827 output = PyMem_Malloc(osize * sizeof(Py_UCS4));
8828 opos = 0;
8829 if (output == NULL) {
8830 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00008831 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008832 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008833
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008834 while (i<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008835 /* try to encode it */
8836 PyObject *x = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008837 if (charmaptranslate_output(input, i, mapping,
8838 &output, &osize, &opos, &x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008839 Py_XDECREF(x);
8840 goto onError;
8841 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008842 Py_XDECREF(x);
Benjamin Peterson29060642009-01-31 22:14:21 +00008843 if (x!=Py_None) /* it worked => adjust input pointer */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008844 ++i;
Benjamin Peterson29060642009-01-31 22:14:21 +00008845 else { /* untranslatable character */
8846 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
8847 Py_ssize_t repsize;
8848 Py_ssize_t newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008849 Py_ssize_t uni2;
Benjamin Peterson29060642009-01-31 22:14:21 +00008850 /* startpos for collecting untranslatable chars */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008851 Py_ssize_t collstart = i;
8852 Py_ssize_t collend = i+1;
8853 Py_ssize_t coll;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008854
Benjamin Peterson29060642009-01-31 22:14:21 +00008855 /* find all untranslatable characters */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008856 while (collend < size) {
8857 if (charmaptranslate_lookup(PyUnicode_READ(kind,idata, collend), mapping, &x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008858 goto onError;
8859 Py_XDECREF(x);
8860 if (x!=Py_None)
8861 break;
8862 ++collend;
8863 }
8864 /* cache callback name lookup
8865 * (if not done yet, i.e. it's the first error) */
8866 if (known_errorHandler==-1) {
8867 if ((errors==NULL) || (!strcmp(errors, "strict")))
8868 known_errorHandler = 1;
8869 else if (!strcmp(errors, "replace"))
8870 known_errorHandler = 2;
8871 else if (!strcmp(errors, "ignore"))
8872 known_errorHandler = 3;
8873 else if (!strcmp(errors, "xmlcharrefreplace"))
8874 known_errorHandler = 4;
8875 else
8876 known_errorHandler = 0;
8877 }
8878 switch (known_errorHandler) {
8879 case 1: /* strict */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008880 raise_translate_exception(&exc, input, collstart,
8881 collend, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008882 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00008883 case 2: /* replace */
8884 /* No need to check for space, this is a 1:1 replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008885 for (coll = collstart; coll<collend; coll++)
8886 output[opos++] = '?';
Benjamin Peterson29060642009-01-31 22:14:21 +00008887 /* fall through */
8888 case 3: /* ignore */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008889 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008890 break;
8891 case 4: /* xmlcharrefreplace */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008892 /* generate replacement (temporarily (mis)uses i) */
8893 for (i = collstart; i < collend; ++i) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008894 char buffer[2+29+1+1];
8895 char *cp;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008896 sprintf(buffer, "&#%d;", PyUnicode_READ(kind, idata, i));
8897 if (charmaptranslate_makespace(&output, &osize,
8898 opos+strlen(buffer)+(size-collend)))
Benjamin Peterson29060642009-01-31 22:14:21 +00008899 goto onError;
8900 for (cp = buffer; *cp; ++cp)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008901 output[opos++] = *cp;
Benjamin Peterson29060642009-01-31 22:14:21 +00008902 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008903 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008904 break;
8905 default:
8906 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008907 reason, input, &exc,
8908 collstart, collend, &newpos);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008909 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008910 goto onError;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008911 if (PyUnicode_READY(repunicode) < 0) {
8912 Py_DECREF(repunicode);
8913 goto onError;
8914 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008915 /* generate replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008916 repsize = PyUnicode_GET_LENGTH(repunicode);
8917 if (charmaptranslate_makespace(&output, &osize,
8918 opos+repsize+(size-collend))) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008919 Py_DECREF(repunicode);
8920 goto onError;
8921 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008922 for (uni2 = 0; repsize-->0; ++uni2)
8923 output[opos++] = PyUnicode_READ_CHAR(repunicode, uni2);
8924 i = newpos;
Benjamin Peterson29060642009-01-31 22:14:21 +00008925 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008926 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008927 }
8928 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008929 res = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND, output, opos);
8930 if (!res)
8931 goto onError;
8932 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008933 Py_XDECREF(exc);
8934 Py_XDECREF(errorHandler);
8935 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008936
Benjamin Peterson29060642009-01-31 22:14:21 +00008937 onError:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008938 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008939 Py_XDECREF(exc);
8940 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008941 return NULL;
8942}
8943
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008944/* Deprecated. Use PyUnicode_Translate instead. */
8945PyObject *
8946PyUnicode_TranslateCharmap(const Py_UNICODE *p,
8947 Py_ssize_t size,
8948 PyObject *mapping,
8949 const char *errors)
8950{
8951 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8952 if (!unicode)
8953 return NULL;
8954 return _PyUnicode_TranslateCharmap(unicode, mapping, errors);
8955}
8956
Alexander Belopolsky40018472011-02-26 01:02:56 +00008957PyObject *
8958PyUnicode_Translate(PyObject *str,
8959 PyObject *mapping,
8960 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008961{
8962 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +00008963
Guido van Rossumd57fd912000-03-10 22:53:23 +00008964 str = PyUnicode_FromObject(str);
8965 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008966 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008967 result = _PyUnicode_TranslateCharmap(str, mapping, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008968 Py_DECREF(str);
8969 return result;
Tim Petersced69f82003-09-16 20:30:58 +00008970
Benjamin Peterson29060642009-01-31 22:14:21 +00008971 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00008972 Py_XDECREF(str);
8973 return NULL;
8974}
Tim Petersced69f82003-09-16 20:30:58 +00008975
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008976static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02008977fix_decimal_and_space_to_ascii(PyObject *self)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008978{
8979 /* No need to call PyUnicode_READY(self) because this function is only
8980 called as a callback from fixup() which does it already. */
8981 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
8982 const int kind = PyUnicode_KIND(self);
8983 void *data = PyUnicode_DATA(self);
8984 Py_UCS4 maxchar = 0, ch, fixed;
8985 Py_ssize_t i;
8986
8987 for (i = 0; i < len; ++i) {
8988 ch = PyUnicode_READ(kind, data, i);
8989 fixed = 0;
8990 if (ch > 127) {
8991 if (Py_UNICODE_ISSPACE(ch))
8992 fixed = ' ';
8993 else {
8994 const int decimal = Py_UNICODE_TODECIMAL(ch);
8995 if (decimal >= 0)
8996 fixed = '0' + decimal;
8997 }
8998 if (fixed != 0) {
8999 if (fixed > maxchar)
9000 maxchar = fixed;
9001 PyUnicode_WRITE(kind, data, i, fixed);
9002 }
9003 else if (ch > maxchar)
9004 maxchar = ch;
9005 }
9006 else if (ch > maxchar)
9007 maxchar = ch;
9008 }
9009
9010 return maxchar;
9011}
9012
9013PyObject *
9014_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
9015{
9016 if (!PyUnicode_Check(unicode)) {
9017 PyErr_BadInternalCall();
9018 return NULL;
9019 }
9020 if (PyUnicode_READY(unicode) == -1)
9021 return NULL;
9022 if (PyUnicode_MAX_CHAR_VALUE(unicode) <= 127) {
9023 /* If the string is already ASCII, just return the same string */
9024 Py_INCREF(unicode);
9025 return unicode;
9026 }
Victor Stinner9310abb2011-10-05 00:59:23 +02009027 return fixup(unicode, fix_decimal_and_space_to_ascii);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009028}
9029
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009030PyObject *
9031PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
9032 Py_ssize_t length)
9033{
Victor Stinnerf0124502011-11-21 23:12:56 +01009034 PyObject *decimal;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009035 Py_ssize_t i;
Victor Stinnerf0124502011-11-21 23:12:56 +01009036 Py_UCS4 maxchar;
9037 enum PyUnicode_Kind kind;
9038 void *data;
9039
9040 maxchar = 0;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009041 for (i = 0; i < length; i++) {
Victor Stinnerf0124502011-11-21 23:12:56 +01009042 Py_UNICODE ch = s[i];
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009043 if (ch > 127) {
9044 int decimal = Py_UNICODE_TODECIMAL(ch);
9045 if (decimal >= 0)
Victor Stinnerf0124502011-11-21 23:12:56 +01009046 ch = '0' + decimal;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009047 }
Victor Stinnerf0124502011-11-21 23:12:56 +01009048 maxchar = Py_MAX(maxchar, ch);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009049 }
Victor Stinnerf0124502011-11-21 23:12:56 +01009050
9051 /* Copy to a new string */
9052 decimal = PyUnicode_New(length, maxchar);
9053 if (decimal == NULL)
9054 return decimal;
9055 kind = PyUnicode_KIND(decimal);
9056 data = PyUnicode_DATA(decimal);
9057 /* Iterate over code points */
9058 for (i = 0; i < length; i++) {
9059 Py_UNICODE ch = s[i];
9060 if (ch > 127) {
9061 int decimal = Py_UNICODE_TODECIMAL(ch);
9062 if (decimal >= 0)
9063 ch = '0' + decimal;
9064 }
9065 PyUnicode_WRITE(kind, data, i, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009066 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01009067 return unicode_result(decimal);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009068}
Guido van Rossum9e896b32000-04-05 20:11:21 +00009069/* --- Decimal Encoder ---------------------------------------------------- */
9070
Alexander Belopolsky40018472011-02-26 01:02:56 +00009071int
9072PyUnicode_EncodeDecimal(Py_UNICODE *s,
9073 Py_ssize_t length,
9074 char *output,
9075 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00009076{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01009077 PyObject *unicode;
Victor Stinner6345be92011-11-25 20:09:01 +01009078 Py_ssize_t i;
Victor Stinner42bf7752011-11-21 22:52:58 +01009079 enum PyUnicode_Kind kind;
9080 void *data;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009081
9082 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009083 PyErr_BadArgument();
9084 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009085 }
9086
Victor Stinner42bf7752011-11-21 22:52:58 +01009087 unicode = PyUnicode_FromUnicode(s, length);
9088 if (unicode == NULL)
9089 return -1;
9090
Victor Stinner6345be92011-11-25 20:09:01 +01009091 if (PyUnicode_READY(unicode) < 0) {
9092 Py_DECREF(unicode);
9093 return -1;
9094 }
Victor Stinner42bf7752011-11-21 22:52:58 +01009095 kind = PyUnicode_KIND(unicode);
9096 data = PyUnicode_DATA(unicode);
9097
Victor Stinnerb84d7232011-11-22 01:50:07 +01009098 for (i=0; i < length; ) {
Victor Stinner6345be92011-11-25 20:09:01 +01009099 PyObject *exc;
9100 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00009101 int decimal;
Victor Stinner6345be92011-11-25 20:09:01 +01009102 Py_ssize_t startpos;
9103
9104 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +00009105
Benjamin Peterson29060642009-01-31 22:14:21 +00009106 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009107 *output++ = ' ';
Victor Stinnerb84d7232011-11-22 01:50:07 +01009108 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009109 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009110 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009111 decimal = Py_UNICODE_TODECIMAL(ch);
9112 if (decimal >= 0) {
9113 *output++ = '0' + decimal;
Victor Stinnerb84d7232011-11-22 01:50:07 +01009114 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009115 continue;
9116 }
9117 if (0 < ch && ch < 256) {
9118 *output++ = (char)ch;
Victor Stinnerb84d7232011-11-22 01:50:07 +01009119 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009120 continue;
9121 }
Victor Stinner6345be92011-11-25 20:09:01 +01009122
Victor Stinner42bf7752011-11-21 22:52:58 +01009123 startpos = i;
Victor Stinner6345be92011-11-25 20:09:01 +01009124 exc = NULL;
9125 raise_encode_exception(&exc, "decimal", unicode,
9126 startpos, startpos+1,
9127 "invalid decimal Unicode string");
9128 Py_XDECREF(exc);
9129 Py_DECREF(unicode);
9130 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009131 }
9132 /* 0-terminate the output string */
9133 *output++ = '\0';
Victor Stinner42bf7752011-11-21 22:52:58 +01009134 Py_DECREF(unicode);
Guido van Rossum9e896b32000-04-05 20:11:21 +00009135 return 0;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009136}
9137
Guido van Rossumd57fd912000-03-10 22:53:23 +00009138/* --- Helpers ------------------------------------------------------------ */
9139
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009140static Py_ssize_t
Victor Stinner794d5672011-10-10 03:21:36 +02009141any_find_slice(int direction, PyObject* s1, PyObject* s2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009142 Py_ssize_t start,
9143 Py_ssize_t end)
9144{
9145 int kind1, kind2, kind;
9146 void *buf1, *buf2;
9147 Py_ssize_t len1, len2, result;
9148
9149 kind1 = PyUnicode_KIND(s1);
9150 kind2 = PyUnicode_KIND(s2);
9151 kind = kind1 > kind2 ? kind1 : kind2;
9152 buf1 = PyUnicode_DATA(s1);
9153 buf2 = PyUnicode_DATA(s2);
9154 if (kind1 != kind)
9155 buf1 = _PyUnicode_AsKind(s1, kind);
9156 if (!buf1)
9157 return -2;
9158 if (kind2 != kind)
9159 buf2 = _PyUnicode_AsKind(s2, kind);
9160 if (!buf2) {
9161 if (kind1 != kind) PyMem_Free(buf1);
9162 return -2;
9163 }
9164 len1 = PyUnicode_GET_LENGTH(s1);
9165 len2 = PyUnicode_GET_LENGTH(s2);
9166
Victor Stinner794d5672011-10-10 03:21:36 +02009167 if (direction > 0) {
9168 switch(kind) {
9169 case PyUnicode_1BYTE_KIND:
9170 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9171 result = asciilib_find_slice(buf1, len1, buf2, len2, start, end);
9172 else
9173 result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end);
9174 break;
9175 case PyUnicode_2BYTE_KIND:
9176 result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end);
9177 break;
9178 case PyUnicode_4BYTE_KIND:
9179 result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end);
9180 break;
9181 default:
9182 assert(0); result = -2;
9183 }
9184 }
9185 else {
9186 switch(kind) {
9187 case PyUnicode_1BYTE_KIND:
9188 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9189 result = asciilib_rfind_slice(buf1, len1, buf2, len2, start, end);
9190 else
9191 result = ucs1lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9192 break;
9193 case PyUnicode_2BYTE_KIND:
9194 result = ucs2lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9195 break;
9196 case PyUnicode_4BYTE_KIND:
9197 result = ucs4lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9198 break;
9199 default:
9200 assert(0); result = -2;
9201 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009202 }
9203
9204 if (kind1 != kind)
9205 PyMem_Free(buf1);
9206 if (kind2 != kind)
9207 PyMem_Free(buf2);
9208
9209 return result;
9210}
9211
9212Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +02009213_PyUnicode_InsertThousandsGrouping(PyObject *unicode, int kind, void *data,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009214 Py_ssize_t n_buffer,
9215 void *digits, Py_ssize_t n_digits,
9216 Py_ssize_t min_width,
9217 const char *grouping,
9218 const char *thousands_sep)
9219{
9220 switch(kind) {
9221 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009222 if (unicode != NULL && PyUnicode_IS_ASCII(unicode))
9223 return _PyUnicode_ascii_InsertThousandsGrouping(
9224 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
9225 min_width, grouping, thousands_sep);
9226 else
9227 return _PyUnicode_ucs1_InsertThousandsGrouping(
9228 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
9229 min_width, grouping, thousands_sep);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009230 case PyUnicode_2BYTE_KIND:
9231 return _PyUnicode_ucs2_InsertThousandsGrouping(
9232 (Py_UCS2*)data, n_buffer, (Py_UCS2*)digits, n_digits,
9233 min_width, grouping, thousands_sep);
9234 case PyUnicode_4BYTE_KIND:
9235 return _PyUnicode_ucs4_InsertThousandsGrouping(
9236 (Py_UCS4*)data, n_buffer, (Py_UCS4*)digits, n_digits,
9237 min_width, grouping, thousands_sep);
9238 }
9239 assert(0);
9240 return -1;
9241}
9242
9243
Thomas Wouters477c8d52006-05-27 19:21:47 +00009244/* helper macro to fixup start/end slice values */
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009245#define ADJUST_INDICES(start, end, len) \
9246 if (end > len) \
9247 end = len; \
9248 else if (end < 0) { \
9249 end += len; \
9250 if (end < 0) \
9251 end = 0; \
9252 } \
9253 if (start < 0) { \
9254 start += len; \
9255 if (start < 0) \
9256 start = 0; \
9257 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009258
Alexander Belopolsky40018472011-02-26 01:02:56 +00009259Py_ssize_t
9260PyUnicode_Count(PyObject *str,
9261 PyObject *substr,
9262 Py_ssize_t start,
9263 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009264{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009265 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009266 PyObject* str_obj;
9267 PyObject* sub_obj;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009268 int kind1, kind2, kind;
9269 void *buf1 = NULL, *buf2 = NULL;
9270 Py_ssize_t len1, len2;
Tim Petersced69f82003-09-16 20:30:58 +00009271
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009272 str_obj = PyUnicode_FromObject(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009273 if (!str_obj || PyUnicode_READY(str_obj) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00009274 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009275 sub_obj = PyUnicode_FromObject(substr);
Victor Stinnere9a29352011-10-01 02:14:59 +02009276 if (!sub_obj || PyUnicode_READY(sub_obj) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009277 Py_DECREF(str_obj);
9278 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009279 }
Tim Petersced69f82003-09-16 20:30:58 +00009280
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009281 kind1 = PyUnicode_KIND(str_obj);
9282 kind2 = PyUnicode_KIND(sub_obj);
9283 kind = kind1 > kind2 ? kind1 : kind2;
9284 buf1 = PyUnicode_DATA(str_obj);
9285 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009286 buf1 = _PyUnicode_AsKind(str_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009287 if (!buf1)
9288 goto onError;
9289 buf2 = PyUnicode_DATA(sub_obj);
9290 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009291 buf2 = _PyUnicode_AsKind(sub_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009292 if (!buf2)
9293 goto onError;
9294 len1 = PyUnicode_GET_LENGTH(str_obj);
9295 len2 = PyUnicode_GET_LENGTH(sub_obj);
9296
9297 ADJUST_INDICES(start, end, len1);
9298 switch(kind) {
9299 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009300 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sub_obj))
9301 result = asciilib_count(
9302 ((Py_UCS1*)buf1) + start, end - start,
9303 buf2, len2, PY_SSIZE_T_MAX
9304 );
9305 else
9306 result = ucs1lib_count(
9307 ((Py_UCS1*)buf1) + start, end - start,
9308 buf2, len2, PY_SSIZE_T_MAX
9309 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009310 break;
9311 case PyUnicode_2BYTE_KIND:
9312 result = ucs2lib_count(
9313 ((Py_UCS2*)buf1) + start, end - start,
9314 buf2, len2, PY_SSIZE_T_MAX
9315 );
9316 break;
9317 case PyUnicode_4BYTE_KIND:
9318 result = ucs4lib_count(
9319 ((Py_UCS4*)buf1) + start, end - start,
9320 buf2, len2, PY_SSIZE_T_MAX
9321 );
9322 break;
9323 default:
9324 assert(0); result = 0;
9325 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009326
9327 Py_DECREF(sub_obj);
9328 Py_DECREF(str_obj);
9329
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009330 if (kind1 != kind)
9331 PyMem_Free(buf1);
9332 if (kind2 != kind)
9333 PyMem_Free(buf2);
9334
Guido van Rossumd57fd912000-03-10 22:53:23 +00009335 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009336 onError:
9337 Py_DECREF(sub_obj);
9338 Py_DECREF(str_obj);
9339 if (kind1 != kind && buf1)
9340 PyMem_Free(buf1);
9341 if (kind2 != kind && buf2)
9342 PyMem_Free(buf2);
9343 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009344}
9345
Alexander Belopolsky40018472011-02-26 01:02:56 +00009346Py_ssize_t
9347PyUnicode_Find(PyObject *str,
9348 PyObject *sub,
9349 Py_ssize_t start,
9350 Py_ssize_t end,
9351 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009352{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009353 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009354
Guido van Rossumd57fd912000-03-10 22:53:23 +00009355 str = PyUnicode_FromObject(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009356 if (!str || PyUnicode_READY(str) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00009357 return -2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009358 sub = PyUnicode_FromObject(sub);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009359 if (!sub || PyUnicode_READY(sub) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009360 Py_DECREF(str);
9361 return -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009362 }
Tim Petersced69f82003-09-16 20:30:58 +00009363
Victor Stinner794d5672011-10-10 03:21:36 +02009364 result = any_find_slice(direction,
9365 str, sub, start, end
9366 );
Thomas Wouters477c8d52006-05-27 19:21:47 +00009367
Guido van Rossumd57fd912000-03-10 22:53:23 +00009368 Py_DECREF(str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009369 Py_DECREF(sub);
9370
Guido van Rossumd57fd912000-03-10 22:53:23 +00009371 return result;
9372}
9373
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009374Py_ssize_t
9375PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
9376 Py_ssize_t start, Py_ssize_t end,
9377 int direction)
9378{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009379 int kind;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009380 Py_ssize_t result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009381 if (PyUnicode_READY(str) == -1)
9382 return -2;
Victor Stinner267aa242011-10-02 01:08:37 +02009383 if (start < 0 || end < 0) {
9384 PyErr_SetString(PyExc_IndexError, "string index out of range");
9385 return -2;
9386 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009387 if (end > PyUnicode_GET_LENGTH(str))
9388 end = PyUnicode_GET_LENGTH(str);
9389 kind = PyUnicode_KIND(str);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009390 result = findchar(PyUnicode_1BYTE_DATA(str) + kind*start,
9391 kind, end-start, ch, direction);
9392 if (result == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009393 return -1;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009394 else
9395 return start + result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009396}
9397
Alexander Belopolsky40018472011-02-26 01:02:56 +00009398static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009399tailmatch(PyObject *self,
9400 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009401 Py_ssize_t start,
9402 Py_ssize_t end,
9403 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009404{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009405 int kind_self;
9406 int kind_sub;
9407 void *data_self;
9408 void *data_sub;
9409 Py_ssize_t offset;
9410 Py_ssize_t i;
9411 Py_ssize_t end_sub;
9412
9413 if (PyUnicode_READY(self) == -1 ||
9414 PyUnicode_READY(substring) == -1)
9415 return 0;
9416
9417 if (PyUnicode_GET_LENGTH(substring) == 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009418 return 1;
9419
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009420 ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
9421 end -= PyUnicode_GET_LENGTH(substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009422 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00009423 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009424
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009425 kind_self = PyUnicode_KIND(self);
9426 data_self = PyUnicode_DATA(self);
9427 kind_sub = PyUnicode_KIND(substring);
9428 data_sub = PyUnicode_DATA(substring);
9429 end_sub = PyUnicode_GET_LENGTH(substring) - 1;
9430
9431 if (direction > 0)
9432 offset = end;
9433 else
9434 offset = start;
9435
9436 if (PyUnicode_READ(kind_self, data_self, offset) ==
9437 PyUnicode_READ(kind_sub, data_sub, 0) &&
9438 PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
9439 PyUnicode_READ(kind_sub, data_sub, end_sub)) {
9440 /* If both are of the same kind, memcmp is sufficient */
9441 if (kind_self == kind_sub) {
9442 return ! memcmp((char *)data_self +
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009443 (offset * PyUnicode_KIND(substring)),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009444 data_sub,
9445 PyUnicode_GET_LENGTH(substring) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009446 PyUnicode_KIND(substring));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009447 }
9448 /* otherwise we have to compare each character by first accesing it */
9449 else {
9450 /* We do not need to compare 0 and len(substring)-1 because
9451 the if statement above ensured already that they are equal
9452 when we end up here. */
9453 // TODO: honor direction and do a forward or backwards search
9454 for (i = 1; i < end_sub; ++i) {
9455 if (PyUnicode_READ(kind_self, data_self, offset + i) !=
9456 PyUnicode_READ(kind_sub, data_sub, i))
9457 return 0;
9458 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009459 return 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009460 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009461 }
9462
9463 return 0;
9464}
9465
Alexander Belopolsky40018472011-02-26 01:02:56 +00009466Py_ssize_t
9467PyUnicode_Tailmatch(PyObject *str,
9468 PyObject *substr,
9469 Py_ssize_t start,
9470 Py_ssize_t end,
9471 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009472{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009473 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009474
Guido van Rossumd57fd912000-03-10 22:53:23 +00009475 str = PyUnicode_FromObject(str);
9476 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009477 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009478 substr = PyUnicode_FromObject(substr);
9479 if (substr == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009480 Py_DECREF(str);
9481 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009482 }
Tim Petersced69f82003-09-16 20:30:58 +00009483
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009484 result = tailmatch(str, substr,
Benjamin Peterson29060642009-01-31 22:14:21 +00009485 start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009486 Py_DECREF(str);
9487 Py_DECREF(substr);
9488 return result;
9489}
9490
Guido van Rossumd57fd912000-03-10 22:53:23 +00009491/* Apply fixfct filter to the Unicode object self and return a
9492 reference to the modified object */
9493
Alexander Belopolsky40018472011-02-26 01:02:56 +00009494static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009495fixup(PyObject *self,
9496 Py_UCS4 (*fixfct)(PyObject *s))
Guido van Rossumd57fd912000-03-10 22:53:23 +00009497{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009498 PyObject *u;
9499 Py_UCS4 maxchar_old, maxchar_new = 0;
Victor Stinnereaab6042011-12-11 22:22:39 +01009500 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009501
Victor Stinnerbf6e5602011-12-12 01:53:47 +01009502 u = _PyUnicode_Copy(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009503 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009504 return NULL;
Victor Stinner87af4f22011-11-21 23:03:47 +01009505 maxchar_old = PyUnicode_MAX_CHAR_VALUE(u);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009506
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009507 /* fix functions return the new maximum character in a string,
9508 if the kind of the resulting unicode object does not change,
9509 everything is fine. Otherwise we need to change the string kind
9510 and re-run the fix function. */
Victor Stinner9310abb2011-10-05 00:59:23 +02009511 maxchar_new = fixfct(u);
Victor Stinnereaab6042011-12-11 22:22:39 +01009512
9513 if (maxchar_new == 0) {
9514 /* no changes */;
9515 if (PyUnicode_CheckExact(self)) {
9516 Py_DECREF(u);
9517 Py_INCREF(self);
9518 return self;
9519 }
9520 else
9521 return u;
9522 }
9523
9524 if (maxchar_new <= 127)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009525 maxchar_new = 127;
9526 else if (maxchar_new <= 255)
9527 maxchar_new = 255;
9528 else if (maxchar_new <= 65535)
9529 maxchar_new = 65535;
9530 else
Victor Stinner8faf8212011-12-08 22:14:11 +01009531 maxchar_new = MAX_UNICODE;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009532
Victor Stinnereaab6042011-12-11 22:22:39 +01009533 if (maxchar_new == maxchar_old)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009534 return u;
Victor Stinnereaab6042011-12-11 22:22:39 +01009535
9536 /* In case the maximum character changed, we need to
9537 convert the string to the new category. */
9538 v = PyUnicode_New(PyUnicode_GET_LENGTH(self), maxchar_new);
9539 if (v == NULL) {
9540 Py_DECREF(u);
9541 return NULL;
9542 }
9543 if (maxchar_new > maxchar_old) {
9544 /* If the maxchar increased so that the kind changed, not all
9545 characters are representable anymore and we need to fix the
9546 string again. This only happens in very few cases. */
9547 copy_characters(v, 0, self, 0, PyUnicode_GET_LENGTH(self));
9548 maxchar_old = fixfct(v);
9549 assert(maxchar_old > 0 && maxchar_old <= maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009550 }
9551 else {
Victor Stinnereaab6042011-12-11 22:22:39 +01009552 copy_characters(v, 0, u, 0, PyUnicode_GET_LENGTH(self));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009553 }
Victor Stinnereaab6042011-12-11 22:22:39 +01009554 Py_DECREF(u);
9555 assert(_PyUnicode_CheckConsistency(v, 1));
9556 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009557}
9558
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009559static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009560fixupper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009561{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009562 /* No need to call PyUnicode_READY(self) because this function is only
9563 called as a callback from fixup() which does it already. */
9564 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9565 const int kind = PyUnicode_KIND(self);
9566 void *data = PyUnicode_DATA(self);
9567 int touched = 0;
9568 Py_UCS4 maxchar = 0;
9569 Py_ssize_t i;
Tim Petersced69f82003-09-16 20:30:58 +00009570
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009571 for (i = 0; i < len; ++i) {
9572 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9573 const Py_UCS4 up = Py_UNICODE_TOUPPER(ch);
9574 if (up != ch) {
9575 if (up > maxchar)
9576 maxchar = up;
9577 PyUnicode_WRITE(kind, data, i, up);
9578 touched = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00009579 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009580 else if (ch > maxchar)
9581 maxchar = ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009582 }
9583
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009584 if (touched)
9585 return maxchar;
9586 else
9587 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009588}
9589
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009590static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009591fixlower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009592{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009593 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
9594 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9595 const int kind = PyUnicode_KIND(self);
9596 void *data = PyUnicode_DATA(self);
9597 int touched = 0;
9598 Py_UCS4 maxchar = 0;
9599 Py_ssize_t i;
Tim Petersced69f82003-09-16 20:30:58 +00009600
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009601 for(i = 0; i < len; ++i) {
9602 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9603 const Py_UCS4 lo = Py_UNICODE_TOLOWER(ch);
9604 if (lo != ch) {
9605 if (lo > maxchar)
9606 maxchar = lo;
9607 PyUnicode_WRITE(kind, data, i, lo);
9608 touched = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00009609 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009610 else if (ch > maxchar)
9611 maxchar = ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009612 }
9613
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009614 if (touched)
9615 return maxchar;
9616 else
9617 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009618}
9619
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009620static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009621fixswapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009622{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009623 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
9624 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9625 const int kind = PyUnicode_KIND(self);
9626 void *data = PyUnicode_DATA(self);
9627 int touched = 0;
9628 Py_UCS4 maxchar = 0;
9629 Py_ssize_t i;
Tim Petersced69f82003-09-16 20:30:58 +00009630
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009631 for(i = 0; i < len; ++i) {
9632 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9633 Py_UCS4 nu = 0;
9634
9635 if (Py_UNICODE_ISUPPER(ch))
9636 nu = Py_UNICODE_TOLOWER(ch);
9637 else if (Py_UNICODE_ISLOWER(ch))
9638 nu = Py_UNICODE_TOUPPER(ch);
9639
9640 if (nu != 0) {
9641 if (nu > maxchar)
9642 maxchar = nu;
9643 PyUnicode_WRITE(kind, data, i, nu);
9644 touched = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009645 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009646 else if (ch > maxchar)
9647 maxchar = ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009648 }
9649
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009650 if (touched)
9651 return maxchar;
9652 else
9653 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009654}
9655
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009656static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009657fixcapitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009658{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009659 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
9660 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9661 const int kind = PyUnicode_KIND(self);
9662 void *data = PyUnicode_DATA(self);
9663 int touched = 0;
9664 Py_UCS4 maxchar = 0;
9665 Py_ssize_t i = 0;
9666 Py_UCS4 ch;
Tim Petersced69f82003-09-16 20:30:58 +00009667
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009668 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009669 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009670
9671 ch = PyUnicode_READ(kind, data, i);
9672 if (!Py_UNICODE_ISUPPER(ch)) {
9673 maxchar = Py_UNICODE_TOUPPER(ch);
9674 PyUnicode_WRITE(kind, data, i, maxchar);
9675 touched = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009676 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009677 ++i;
9678 for(; i < len; ++i) {
9679 ch = PyUnicode_READ(kind, data, i);
9680 if (!Py_UNICODE_ISLOWER(ch)) {
9681 const Py_UCS4 lo = Py_UNICODE_TOLOWER(ch);
9682 if (lo > maxchar)
9683 maxchar = lo;
9684 PyUnicode_WRITE(kind, data, i, lo);
9685 touched = 1;
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009686 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009687 else if (ch > maxchar)
9688 maxchar = ch;
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009689 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009690
9691 if (touched)
9692 return maxchar;
9693 else
9694 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009695}
9696
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009697static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009698fixtitle(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009699{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009700 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
9701 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9702 const int kind = PyUnicode_KIND(self);
9703 void *data = PyUnicode_DATA(self);
9704 Py_UCS4 maxchar = 0;
9705 Py_ssize_t i = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009706 int previous_is_cased;
9707
9708 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009709 if (len == 1) {
9710 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9711 const Py_UCS4 ti = Py_UNICODE_TOTITLE(ch);
9712 if (ti != ch) {
9713 PyUnicode_WRITE(kind, data, i, ti);
9714 return ti;
Benjamin Peterson29060642009-01-31 22:14:21 +00009715 }
9716 else
9717 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009718 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009719 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009720 for(; i < len; ++i) {
9721 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9722 Py_UCS4 nu;
Tim Petersced69f82003-09-16 20:30:58 +00009723
Benjamin Peterson29060642009-01-31 22:14:21 +00009724 if (previous_is_cased)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009725 nu = Py_UNICODE_TOLOWER(ch);
Benjamin Peterson29060642009-01-31 22:14:21 +00009726 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009727 nu = Py_UNICODE_TOTITLE(ch);
9728
9729 if (nu > maxchar)
9730 maxchar = nu;
9731 PyUnicode_WRITE(kind, data, i, nu);
Tim Petersced69f82003-09-16 20:30:58 +00009732
Benjamin Peterson29060642009-01-31 22:14:21 +00009733 if (Py_UNICODE_ISLOWER(ch) ||
9734 Py_UNICODE_ISUPPER(ch) ||
9735 Py_UNICODE_ISTITLE(ch))
9736 previous_is_cased = 1;
9737 else
9738 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009739 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009740 return maxchar;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009741}
9742
Tim Peters8ce9f162004-08-27 01:49:32 +00009743PyObject *
9744PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009745{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009746 PyObject *sep = NULL;
Victor Stinnerdd077322011-10-07 17:02:31 +02009747 Py_ssize_t seplen;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009748 PyObject *res = NULL; /* the result */
Tim Peters05eba1f2004-08-27 21:32:02 +00009749 PyObject *fseq; /* PySequence_Fast(seq) */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009750 Py_ssize_t seqlen; /* len(fseq) -- number of items in sequence */
9751 PyObject **items;
Tim Peters8ce9f162004-08-27 01:49:32 +00009752 PyObject *item;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009753 Py_ssize_t sz, i, res_offset;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009754 Py_UCS4 maxchar;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009755 Py_UCS4 item_maxchar;
Victor Stinnerdd077322011-10-07 17:02:31 +02009756 int use_memcpy;
9757 unsigned char *res_data = NULL, *sep_data = NULL;
9758 PyObject *last_obj;
9759 unsigned int kind = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009760
Tim Peters05eba1f2004-08-27 21:32:02 +00009761 fseq = PySequence_Fast(seq, "");
9762 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009763 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00009764 }
9765
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009766 /* NOTE: the following code can't call back into Python code,
9767 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00009768 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009769
Tim Peters05eba1f2004-08-27 21:32:02 +00009770 seqlen = PySequence_Fast_GET_SIZE(fseq);
9771 /* If empty sequence, return u"". */
9772 if (seqlen == 0) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009773 Py_DECREF(fseq);
9774 Py_INCREF(unicode_empty);
9775 res = unicode_empty;
9776 return res;
Tim Peters05eba1f2004-08-27 21:32:02 +00009777 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009778
Tim Peters05eba1f2004-08-27 21:32:02 +00009779 /* If singleton sequence with an exact Unicode, return that. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009780 last_obj = NULL;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009781 items = PySequence_Fast_ITEMS(fseq);
Victor Stinneracf47b82011-10-06 12:32:37 +02009782 if (seqlen == 1) {
9783 if (PyUnicode_CheckExact(items[0])) {
9784 res = items[0];
9785 Py_INCREF(res);
9786 Py_DECREF(fseq);
9787 return res;
9788 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009789 seplen = 0;
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009790 maxchar = 0;
Tim Peters8ce9f162004-08-27 01:49:32 +00009791 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009792 else {
Victor Stinneracf47b82011-10-06 12:32:37 +02009793 /* Set up sep and seplen */
9794 if (separator == NULL) {
9795 /* fall back to a blank space separator */
9796 sep = PyUnicode_FromOrdinal(' ');
9797 if (!sep)
9798 goto onError;
Victor Stinnerdd077322011-10-07 17:02:31 +02009799 seplen = 1;
Victor Stinneracf47b82011-10-06 12:32:37 +02009800 maxchar = 32;
Tim Peters05eba1f2004-08-27 21:32:02 +00009801 }
Victor Stinneracf47b82011-10-06 12:32:37 +02009802 else {
9803 if (!PyUnicode_Check(separator)) {
9804 PyErr_Format(PyExc_TypeError,
9805 "separator: expected str instance,"
9806 " %.80s found",
9807 Py_TYPE(separator)->tp_name);
9808 goto onError;
9809 }
9810 if (PyUnicode_READY(separator))
9811 goto onError;
9812 sep = separator;
9813 seplen = PyUnicode_GET_LENGTH(separator);
9814 maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
9815 /* inc refcount to keep this code path symmetric with the
9816 above case of a blank separator */
9817 Py_INCREF(sep);
9818 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009819 last_obj = sep;
Tim Peters05eba1f2004-08-27 21:32:02 +00009820 }
9821
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009822 /* There are at least two things to join, or else we have a subclass
9823 * of str in the sequence.
9824 * Do a pre-pass to figure out the total amount of space we'll
9825 * need (sz), and see whether all argument are strings.
9826 */
9827 sz = 0;
Victor Stinnerdd077322011-10-07 17:02:31 +02009828#ifdef Py_DEBUG
9829 use_memcpy = 0;
9830#else
9831 use_memcpy = 1;
9832#endif
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009833 for (i = 0; i < seqlen; i++) {
9834 const Py_ssize_t old_sz = sz;
9835 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009836 if (!PyUnicode_Check(item)) {
9837 PyErr_Format(PyExc_TypeError,
9838 "sequence item %zd: expected str instance,"
9839 " %.80s found",
9840 i, Py_TYPE(item)->tp_name);
9841 goto onError;
9842 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009843 if (PyUnicode_READY(item) == -1)
9844 goto onError;
9845 sz += PyUnicode_GET_LENGTH(item);
9846 item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009847 maxchar = Py_MAX(maxchar, item_maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009848 if (i != 0)
9849 sz += seplen;
9850 if (sz < old_sz || sz > PY_SSIZE_T_MAX) {
9851 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009852 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009853 goto onError;
9854 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009855 if (use_memcpy && last_obj != NULL) {
9856 if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
9857 use_memcpy = 0;
9858 }
9859 last_obj = item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009860 }
Tim Petersced69f82003-09-16 20:30:58 +00009861
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009862 res = PyUnicode_New(sz, maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009863 if (res == NULL)
9864 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +00009865
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009866 /* Catenate everything. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009867#ifdef Py_DEBUG
9868 use_memcpy = 0;
9869#else
9870 if (use_memcpy) {
9871 res_data = PyUnicode_1BYTE_DATA(res);
9872 kind = PyUnicode_KIND(res);
9873 if (seplen != 0)
9874 sep_data = PyUnicode_1BYTE_DATA(sep);
9875 }
9876#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009877 for (i = 0, res_offset = 0; i < seqlen; ++i) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009878 Py_ssize_t itemlen;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009879 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009880 /* Copy item, and maybe the separator. */
Victor Stinner9ce5a832011-10-03 23:36:02 +02009881 if (i && seplen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009882 if (use_memcpy) {
9883 Py_MEMCPY(res_data,
9884 sep_data,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009885 kind * seplen);
9886 res_data += kind * seplen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009887 }
9888 else {
9889 copy_characters(res, res_offset, sep, 0, seplen);
9890 res_offset += seplen;
9891 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009892 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009893 itemlen = PyUnicode_GET_LENGTH(item);
9894 if (itemlen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009895 if (use_memcpy) {
9896 Py_MEMCPY(res_data,
9897 PyUnicode_DATA(item),
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009898 kind * itemlen);
9899 res_data += kind * itemlen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009900 }
9901 else {
9902 copy_characters(res, res_offset, item, 0, itemlen);
9903 res_offset += itemlen;
9904 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009905 }
Tim Peters05eba1f2004-08-27 21:32:02 +00009906 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009907 if (use_memcpy)
9908 assert(res_data == PyUnicode_1BYTE_DATA(res)
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009909 + kind * PyUnicode_GET_LENGTH(res));
Victor Stinnerdd077322011-10-07 17:02:31 +02009910 else
9911 assert(res_offset == PyUnicode_GET_LENGTH(res));
Tim Peters8ce9f162004-08-27 01:49:32 +00009912
Tim Peters05eba1f2004-08-27 21:32:02 +00009913 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009914 Py_XDECREF(sep);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009915 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009916 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009917
Benjamin Peterson29060642009-01-31 22:14:21 +00009918 onError:
Tim Peters05eba1f2004-08-27 21:32:02 +00009919 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009920 Py_XDECREF(sep);
Tim Peters8ce9f162004-08-27 01:49:32 +00009921 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009922 return NULL;
9923}
9924
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009925#define FILL(kind, data, value, start, length) \
9926 do { \
9927 Py_ssize_t i_ = 0; \
9928 assert(kind != PyUnicode_WCHAR_KIND); \
9929 switch ((kind)) { \
9930 case PyUnicode_1BYTE_KIND: { \
9931 unsigned char * to_ = (unsigned char *)((data)) + (start); \
9932 memset(to_, (unsigned char)value, length); \
9933 break; \
9934 } \
9935 case PyUnicode_2BYTE_KIND: { \
9936 Py_UCS2 * to_ = (Py_UCS2 *)((data)) + (start); \
9937 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9938 break; \
9939 } \
9940 default: { \
9941 Py_UCS4 * to_ = (Py_UCS4 *)((data)) + (start); \
9942 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9943 break; \
9944 } \
9945 } \
9946 } while (0)
9947
Victor Stinner9310abb2011-10-05 00:59:23 +02009948static PyObject *
9949pad(PyObject *self,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009950 Py_ssize_t left,
9951 Py_ssize_t right,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009952 Py_UCS4 fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009953{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009954 PyObject *u;
9955 Py_UCS4 maxchar;
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009956 int kind;
9957 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009958
9959 if (left < 0)
9960 left = 0;
9961 if (right < 0)
9962 right = 0;
9963
Victor Stinnerc4b49542011-12-11 22:44:26 +01009964 if (left == 0 && right == 0)
9965 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009966
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009967 if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
9968 right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +00009969 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
9970 return NULL;
9971 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009972 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
9973 if (fill > maxchar)
9974 maxchar = fill;
9975 u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009976 if (!u)
9977 return NULL;
9978
9979 kind = PyUnicode_KIND(u);
9980 data = PyUnicode_DATA(u);
9981 if (left)
9982 FILL(kind, data, fill, 0, left);
9983 if (right)
9984 FILL(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009985 copy_characters(u, left, self, 0, _PyUnicode_LENGTH(self));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009986 assert(_PyUnicode_CheckConsistency(u, 1));
9987 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009988}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009989#undef FILL
Guido van Rossumd57fd912000-03-10 22:53:23 +00009990
Alexander Belopolsky40018472011-02-26 01:02:56 +00009991PyObject *
9992PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009993{
Guido van Rossumd57fd912000-03-10 22:53:23 +00009994 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009995
9996 string = PyUnicode_FromObject(string);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009997 if (string == NULL || PyUnicode_READY(string) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00009998 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009999
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010000 switch(PyUnicode_KIND(string)) {
10001 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010002 if (PyUnicode_IS_ASCII(string))
10003 list = asciilib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010004 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010005 PyUnicode_GET_LENGTH(string), keepends);
10006 else
10007 list = ucs1lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010008 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010009 PyUnicode_GET_LENGTH(string), keepends);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010010 break;
10011 case PyUnicode_2BYTE_KIND:
10012 list = ucs2lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010013 string, PyUnicode_2BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010014 PyUnicode_GET_LENGTH(string), keepends);
10015 break;
10016 case PyUnicode_4BYTE_KIND:
10017 list = ucs4lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010018 string, PyUnicode_4BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010019 PyUnicode_GET_LENGTH(string), keepends);
10020 break;
10021 default:
10022 assert(0);
10023 list = 0;
10024 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010025 Py_DECREF(string);
10026 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010027}
10028
Alexander Belopolsky40018472011-02-26 01:02:56 +000010029static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010030split(PyObject *self,
10031 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010032 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010033{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010034 int kind1, kind2, kind;
10035 void *buf1, *buf2;
10036 Py_ssize_t len1, len2;
10037 PyObject* out;
10038
Guido van Rossumd57fd912000-03-10 22:53:23 +000010039 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010040 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010041
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010042 if (PyUnicode_READY(self) == -1)
10043 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010044
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010045 if (substring == NULL)
10046 switch(PyUnicode_KIND(self)) {
10047 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010048 if (PyUnicode_IS_ASCII(self))
10049 return asciilib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010050 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010051 PyUnicode_GET_LENGTH(self), maxcount
10052 );
10053 else
10054 return ucs1lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010055 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010056 PyUnicode_GET_LENGTH(self), maxcount
10057 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010058 case PyUnicode_2BYTE_KIND:
10059 return ucs2lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010060 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010061 PyUnicode_GET_LENGTH(self), maxcount
10062 );
10063 case PyUnicode_4BYTE_KIND:
10064 return ucs4lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010065 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010066 PyUnicode_GET_LENGTH(self), maxcount
10067 );
10068 default:
10069 assert(0);
10070 return NULL;
10071 }
10072
10073 if (PyUnicode_READY(substring) == -1)
10074 return NULL;
10075
10076 kind1 = PyUnicode_KIND(self);
10077 kind2 = PyUnicode_KIND(substring);
10078 kind = kind1 > kind2 ? kind1 : kind2;
10079 buf1 = PyUnicode_DATA(self);
10080 buf2 = PyUnicode_DATA(substring);
10081 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010082 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010083 if (!buf1)
10084 return NULL;
10085 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010086 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010087 if (!buf2) {
10088 if (kind1 != kind) PyMem_Free(buf1);
10089 return NULL;
10090 }
10091 len1 = PyUnicode_GET_LENGTH(self);
10092 len2 = PyUnicode_GET_LENGTH(substring);
10093
10094 switch(kind) {
10095 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010096 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10097 out = asciilib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010098 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010099 else
10100 out = ucs1lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010101 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010102 break;
10103 case PyUnicode_2BYTE_KIND:
10104 out = ucs2lib_split(
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_4BYTE_KIND:
10108 out = ucs4lib_split(
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 default:
10112 out = NULL;
10113 }
10114 if (kind1 != kind)
10115 PyMem_Free(buf1);
10116 if (kind2 != kind)
10117 PyMem_Free(buf2);
10118 return out;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010119}
10120
Alexander Belopolsky40018472011-02-26 01:02:56 +000010121static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010122rsplit(PyObject *self,
10123 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010124 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010125{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010126 int kind1, kind2, kind;
10127 void *buf1, *buf2;
10128 Py_ssize_t len1, len2;
10129 PyObject* out;
10130
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010131 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010132 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010133
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010134 if (PyUnicode_READY(self) == -1)
10135 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010136
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010137 if (substring == NULL)
10138 switch(PyUnicode_KIND(self)) {
10139 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010140 if (PyUnicode_IS_ASCII(self))
10141 return asciilib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010142 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010143 PyUnicode_GET_LENGTH(self), maxcount
10144 );
10145 else
10146 return ucs1lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010147 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010148 PyUnicode_GET_LENGTH(self), maxcount
10149 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010150 case PyUnicode_2BYTE_KIND:
10151 return ucs2lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010152 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010153 PyUnicode_GET_LENGTH(self), maxcount
10154 );
10155 case PyUnicode_4BYTE_KIND:
10156 return ucs4lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010157 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010158 PyUnicode_GET_LENGTH(self), maxcount
10159 );
10160 default:
10161 assert(0);
10162 return NULL;
10163 }
10164
10165 if (PyUnicode_READY(substring) == -1)
10166 return NULL;
10167
10168 kind1 = PyUnicode_KIND(self);
10169 kind2 = PyUnicode_KIND(substring);
10170 kind = kind1 > kind2 ? kind1 : kind2;
10171 buf1 = PyUnicode_DATA(self);
10172 buf2 = PyUnicode_DATA(substring);
10173 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010174 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010175 if (!buf1)
10176 return NULL;
10177 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010178 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010179 if (!buf2) {
10180 if (kind1 != kind) PyMem_Free(buf1);
10181 return NULL;
10182 }
10183 len1 = PyUnicode_GET_LENGTH(self);
10184 len2 = PyUnicode_GET_LENGTH(substring);
10185
10186 switch(kind) {
10187 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010188 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10189 out = asciilib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010190 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010191 else
10192 out = ucs1lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010193 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010194 break;
10195 case PyUnicode_2BYTE_KIND:
10196 out = ucs2lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010197 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010198 break;
10199 case PyUnicode_4BYTE_KIND:
10200 out = ucs4lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010201 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010202 break;
10203 default:
10204 out = NULL;
10205 }
10206 if (kind1 != kind)
10207 PyMem_Free(buf1);
10208 if (kind2 != kind)
10209 PyMem_Free(buf2);
10210 return out;
10211}
10212
10213static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010214anylib_find(int kind, PyObject *str1, void *buf1, Py_ssize_t len1,
10215 PyObject *str2, void *buf2, Py_ssize_t len2, Py_ssize_t offset)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010216{
10217 switch(kind) {
10218 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010219 if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
10220 return asciilib_find(buf1, len1, buf2, len2, offset);
10221 else
10222 return ucs1lib_find(buf1, len1, buf2, len2, offset);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010223 case PyUnicode_2BYTE_KIND:
10224 return ucs2lib_find(buf1, len1, buf2, len2, offset);
10225 case PyUnicode_4BYTE_KIND:
10226 return ucs4lib_find(buf1, len1, buf2, len2, offset);
10227 }
10228 assert(0);
10229 return -1;
10230}
10231
10232static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010233anylib_count(int kind, PyObject *sstr, void* sbuf, Py_ssize_t slen,
10234 PyObject *str1, void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010235{
10236 switch(kind) {
10237 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010238 if (PyUnicode_IS_ASCII(sstr) && PyUnicode_IS_ASCII(str1))
10239 return asciilib_count(sbuf, slen, buf1, len1, maxcount);
10240 else
10241 return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010242 case PyUnicode_2BYTE_KIND:
10243 return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
10244 case PyUnicode_4BYTE_KIND:
10245 return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
10246 }
10247 assert(0);
10248 return 0;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010249}
10250
Alexander Belopolsky40018472011-02-26 01:02:56 +000010251static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010252replace(PyObject *self, PyObject *str1,
10253 PyObject *str2, Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010254{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010255 PyObject *u;
10256 char *sbuf = PyUnicode_DATA(self);
10257 char *buf1 = PyUnicode_DATA(str1);
10258 char *buf2 = PyUnicode_DATA(str2);
10259 int srelease = 0, release1 = 0, release2 = 0;
10260 int skind = PyUnicode_KIND(self);
10261 int kind1 = PyUnicode_KIND(str1);
10262 int kind2 = PyUnicode_KIND(str2);
10263 Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
10264 Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
10265 Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010266 int mayshrink;
10267 Py_UCS4 maxchar, maxchar_str2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010268
10269 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010270 maxcount = PY_SSIZE_T_MAX;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010271 else if (maxcount == 0 || slen == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010272 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010273
Victor Stinner59de0ee2011-10-07 10:01:28 +020010274 if (str1 == str2)
10275 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010276 if (skind < kind1)
10277 /* substring too wide to be present */
10278 goto nothing;
10279
Victor Stinner49a0a212011-10-12 23:46:10 +020010280 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
10281 maxchar_str2 = PyUnicode_MAX_CHAR_VALUE(str2);
10282 /* Replacing str1 with str2 may cause a maxchar reduction in the
10283 result string. */
10284 mayshrink = (maxchar_str2 < maxchar);
10285 maxchar = Py_MAX(maxchar, maxchar_str2);
10286
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010287 if (len1 == len2) {
Antoine Pitroucbfdee32010-01-13 08:58:08 +000010288 Py_ssize_t i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010289 /* same length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010290 if (len1 == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010291 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010292 if (len1 == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010293 /* replace characters */
Victor Stinner49a0a212011-10-12 23:46:10 +020010294 Py_UCS4 u1, u2;
10295 int rkind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010296 u1 = PyUnicode_READ_CHAR(str1, 0);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +020010297 if (findchar(sbuf, PyUnicode_KIND(self),
10298 slen, u1, 1) < 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010299 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010300 u2 = PyUnicode_READ_CHAR(str2, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010301 u = PyUnicode_New(slen, maxchar);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010302 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010303 goto error;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020010304 copy_characters(u, 0, self, 0, slen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010305 rkind = PyUnicode_KIND(u);
10306 for (i = 0; i < PyUnicode_GET_LENGTH(u); i++)
10307 if (PyUnicode_READ(rkind, PyUnicode_DATA(u), i) == u1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010308 if (--maxcount < 0)
10309 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010310 PyUnicode_WRITE(rkind, PyUnicode_DATA(u), i, u2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010311 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010312 }
10313 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010314 int rkind = skind;
10315 char *res;
Victor Stinner25a4b292011-10-06 12:31:55 +020010316
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010317 if (kind1 < rkind) {
10318 /* widen substring */
10319 buf1 = _PyUnicode_AsKind(str1, rkind);
10320 if (!buf1) goto error;
10321 release1 = 1;
10322 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010323 i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010324 if (i < 0)
10325 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010326 if (rkind > kind2) {
10327 /* widen replacement */
10328 buf2 = _PyUnicode_AsKind(str2, rkind);
10329 if (!buf2) goto error;
10330 release2 = 1;
10331 }
10332 else if (rkind < kind2) {
10333 /* widen self and buf1 */
10334 rkind = kind2;
10335 if (release1) PyMem_Free(buf1);
10336 sbuf = _PyUnicode_AsKind(self, rkind);
10337 if (!sbuf) goto error;
10338 srelease = 1;
10339 buf1 = _PyUnicode_AsKind(str1, rkind);
10340 if (!buf1) goto error;
10341 release1 = 1;
10342 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010343 u = PyUnicode_New(slen, maxchar);
10344 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010345 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010346 assert(PyUnicode_KIND(u) == rkind);
10347 res = PyUnicode_DATA(u);
Victor Stinner25a4b292011-10-06 12:31:55 +020010348
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010349 memcpy(res, sbuf, rkind * slen);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010350 /* change everything in-place, starting with this one */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010351 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010352 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010353 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010354 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010355
10356 while ( --maxcount > 0) {
Victor Stinnerc3cec782011-10-05 21:24:08 +020010357 i = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010358 sbuf+rkind*i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010359 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010360 if (i == -1)
10361 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010362 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010363 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010364 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010365 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010366 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010367 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010368 }
10369 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010370 Py_ssize_t n, i, j, ires;
10371 Py_ssize_t product, new_size;
10372 int rkind = skind;
10373 char *res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010374
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010375 if (kind1 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010376 /* widen substring */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010377 buf1 = _PyUnicode_AsKind(str1, rkind);
10378 if (!buf1) goto error;
10379 release1 = 1;
10380 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010381 n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010382 if (n == 0)
10383 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010384 if (kind2 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010385 /* widen replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010386 buf2 = _PyUnicode_AsKind(str2, rkind);
10387 if (!buf2) goto error;
10388 release2 = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010389 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010390 else if (kind2 > rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010391 /* widen self and buf1 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010392 rkind = kind2;
10393 sbuf = _PyUnicode_AsKind(self, rkind);
10394 if (!sbuf) goto error;
10395 srelease = 1;
10396 if (release1) PyMem_Free(buf1);
10397 buf1 = _PyUnicode_AsKind(str1, rkind);
10398 if (!buf1) goto error;
10399 release1 = 1;
10400 }
10401 /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
10402 PyUnicode_GET_LENGTH(str1))); */
10403 product = n * (len2-len1);
10404 if ((product / (len2-len1)) != n) {
10405 PyErr_SetString(PyExc_OverflowError,
10406 "replace string is too long");
10407 goto error;
10408 }
10409 new_size = slen + product;
Victor Stinner49a0a212011-10-12 23:46:10 +020010410 if (new_size == 0) {
10411 Py_INCREF(unicode_empty);
10412 u = unicode_empty;
10413 goto done;
10414 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010415 if (new_size < 0 || new_size > (PY_SSIZE_T_MAX >> (rkind-1))) {
10416 PyErr_SetString(PyExc_OverflowError,
10417 "replace string is too long");
10418 goto error;
10419 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010420 u = PyUnicode_New(new_size, maxchar);
10421 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010422 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010423 assert(PyUnicode_KIND(u) == rkind);
10424 res = PyUnicode_DATA(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010425 ires = i = 0;
10426 if (len1 > 0) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010427 while (n-- > 0) {
10428 /* look for next match */
Victor Stinnerc3cec782011-10-05 21:24:08 +020010429 j = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010430 sbuf + rkind * i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010431 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010432 if (j == -1)
10433 break;
10434 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010435 /* copy unchanged part [i:j] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010436 memcpy(res + rkind * ires,
10437 sbuf + rkind * i,
10438 rkind * (j-i));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010439 ires += j - i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010440 }
10441 /* copy substitution string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010442 if (len2 > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010443 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010444 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010445 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010446 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010447 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010448 i = j + len1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010449 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010450 if (i < slen)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010451 /* copy tail [i:] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010452 memcpy(res + rkind * ires,
10453 sbuf + rkind * i,
10454 rkind * (slen-i));
Victor Stinner49a0a212011-10-12 23:46:10 +020010455 }
10456 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010457 /* interleave */
10458 while (n > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010459 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010460 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010461 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010462 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010463 if (--n <= 0)
10464 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010465 memcpy(res + rkind * ires,
10466 sbuf + rkind * i,
10467 rkind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010468 ires++;
10469 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010470 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010471 memcpy(res + rkind * ires,
10472 sbuf + rkind * i,
10473 rkind * (slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +000010474 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010475 }
10476
10477 if (mayshrink) {
Victor Stinner25a4b292011-10-06 12:31:55 +020010478 unicode_adjust_maxchar(&u);
10479 if (u == NULL)
10480 goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010481 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010482
10483 done:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010484 if (srelease)
10485 PyMem_FREE(sbuf);
10486 if (release1)
10487 PyMem_FREE(buf1);
10488 if (release2)
10489 PyMem_FREE(buf2);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010490 assert(_PyUnicode_CheckConsistency(u, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010491 return u;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010492
Benjamin Peterson29060642009-01-31 22:14:21 +000010493 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +000010494 /* nothing to replace; return original string (when possible) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010495 if (srelease)
10496 PyMem_FREE(sbuf);
10497 if (release1)
10498 PyMem_FREE(buf1);
10499 if (release2)
10500 PyMem_FREE(buf2);
Victor Stinnerc4b49542011-12-11 22:44:26 +010010501 return unicode_result_unchanged(self);
10502
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010503 error:
10504 if (srelease && sbuf)
10505 PyMem_FREE(sbuf);
10506 if (release1 && buf1)
10507 PyMem_FREE(buf1);
10508 if (release2 && buf2)
10509 PyMem_FREE(buf2);
10510 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010511}
10512
10513/* --- Unicode Object Methods --------------------------------------------- */
10514
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010515PyDoc_STRVAR(title__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010516 "S.title() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010517\n\
10518Return a titlecased version of S, i.e. words start with title case\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010519characters, all remaining cased characters have lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010520
10521static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010522unicode_title(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010523{
Guido van Rossumd57fd912000-03-10 22:53:23 +000010524 return fixup(self, fixtitle);
10525}
10526
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010527PyDoc_STRVAR(capitalize__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010528 "S.capitalize() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010529\n\
10530Return a capitalized version of S, i.e. make the first character\n\
Senthil Kumarane51ee8a2010-07-05 12:00:56 +000010531have upper case and the rest lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010532
10533static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010534unicode_capitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010535{
Guido van Rossumd57fd912000-03-10 22:53:23 +000010536 return fixup(self, fixcapitalize);
10537}
10538
10539#if 0
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010540PyDoc_STRVAR(capwords__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010541 "S.capwords() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010542\n\
10543Apply .capitalize() to all words in S and return the result with\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010544normalized whitespace (all whitespace strings are replaced by ' ').");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010545
10546static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010547unicode_capwords(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010548{
10549 PyObject *list;
10550 PyObject *item;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010551 Py_ssize_t i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010552
Guido van Rossumd57fd912000-03-10 22:53:23 +000010553 /* Split into words */
10554 list = split(self, NULL, -1);
10555 if (!list)
10556 return NULL;
10557
10558 /* Capitalize each word */
10559 for (i = 0; i < PyList_GET_SIZE(list); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010560 item = fixup(PyList_GET_ITEM(list, i),
Benjamin Peterson29060642009-01-31 22:14:21 +000010561 fixcapitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010562 if (item == NULL)
10563 goto onError;
10564 Py_DECREF(PyList_GET_ITEM(list, i));
10565 PyList_SET_ITEM(list, i, item);
10566 }
10567
10568 /* Join the words to form a new string */
10569 item = PyUnicode_Join(NULL, list);
10570
Benjamin Peterson29060642009-01-31 22:14:21 +000010571 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000010572 Py_DECREF(list);
Victor Stinner7931d9a2011-11-04 00:22:48 +010010573 return item;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010574}
10575#endif
10576
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010577/* Argument converter. Coerces to a single unicode character */
10578
10579static int
10580convert_uc(PyObject *obj, void *addr)
10581{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010582 Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010583 PyObject *uniobj;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010584
Benjamin Peterson14339b62009-01-31 16:36:08 +000010585 uniobj = PyUnicode_FromObject(obj);
10586 if (uniobj == NULL) {
10587 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010588 "The fill character cannot be converted to Unicode");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010589 return 0;
10590 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010591 if (PyUnicode_GET_LENGTH(uniobj) != 1) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010592 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010593 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010594 Py_DECREF(uniobj);
10595 return 0;
10596 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010597 *fillcharloc = PyUnicode_READ_CHAR(uniobj, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010598 Py_DECREF(uniobj);
10599 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010600}
10601
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010602PyDoc_STRVAR(center__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010603 "S.center(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010604\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010605Return S centered in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010606done using the specified fill character (default is a space)");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010607
10608static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010609unicode_center(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010610{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010611 Py_ssize_t marg, left;
10612 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010613 Py_UCS4 fillchar = ' ';
10614
Victor Stinnere9a29352011-10-01 02:14:59 +020010615 if (!PyArg_ParseTuple(args, "n|O&:center", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010616 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010617
Victor Stinnerc4b49542011-12-11 22:44:26 +010010618 if (PyUnicode_READY(self) < 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010619 return NULL;
10620
Victor Stinnerc4b49542011-12-11 22:44:26 +010010621 if (PyUnicode_GET_LENGTH(self) >= width)
10622 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010623
Victor Stinnerc4b49542011-12-11 22:44:26 +010010624 marg = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010625 left = marg / 2 + (marg & width & 1);
10626
Victor Stinner9310abb2011-10-05 00:59:23 +020010627 return pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010628}
10629
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010630/* This function assumes that str1 and str2 are readied by the caller. */
10631
Marc-André Lemburge5034372000-08-08 08:04:29 +000010632static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010633unicode_compare(PyObject *str1, PyObject *str2)
Marc-André Lemburge5034372000-08-08 08:04:29 +000010634{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010635 int kind1, kind2;
10636 void *data1, *data2;
10637 Py_ssize_t len1, len2, i;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010638
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010639 kind1 = PyUnicode_KIND(str1);
10640 kind2 = PyUnicode_KIND(str2);
10641 data1 = PyUnicode_DATA(str1);
10642 data2 = PyUnicode_DATA(str2);
10643 len1 = PyUnicode_GET_LENGTH(str1);
10644 len2 = PyUnicode_GET_LENGTH(str2);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010645
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010646 for (i = 0; i < len1 && i < len2; ++i) {
10647 Py_UCS4 c1, c2;
10648 c1 = PyUnicode_READ(kind1, data1, i);
10649 c2 = PyUnicode_READ(kind2, data2, i);
Fredrik Lundh45714e92001-06-26 16:39:36 +000010650
10651 if (c1 != c2)
10652 return (c1 < c2) ? -1 : 1;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010653 }
10654
10655 return (len1 < len2) ? -1 : (len1 != len2);
10656}
10657
Alexander Belopolsky40018472011-02-26 01:02:56 +000010658int
10659PyUnicode_Compare(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010660{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010661 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10662 if (PyUnicode_READY(left) == -1 ||
10663 PyUnicode_READY(right) == -1)
10664 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010665 return unicode_compare(left, right);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010666 }
Guido van Rossum09dc34f2007-05-04 04:17:33 +000010667 PyErr_Format(PyExc_TypeError,
10668 "Can't compare %.100s and %.100s",
10669 left->ob_type->tp_name,
10670 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010671 return -1;
10672}
10673
Martin v. Löwis5b222132007-06-10 09:51:05 +000010674int
10675PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
10676{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010677 Py_ssize_t i;
10678 int kind;
10679 void *data;
10680 Py_UCS4 chr;
10681
Victor Stinner910337b2011-10-03 03:20:16 +020010682 assert(_PyUnicode_CHECK(uni));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010683 if (PyUnicode_READY(uni) == -1)
10684 return -1;
10685 kind = PyUnicode_KIND(uni);
10686 data = PyUnicode_DATA(uni);
Martin v. Löwis5b222132007-06-10 09:51:05 +000010687 /* Compare Unicode string and source character set string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010688 for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
10689 if (chr != str[i])
10690 return (chr < (unsigned char)(str[i])) ? -1 : 1;
Benjamin Peterson8667a9b2010-01-09 21:45:28 +000010691 /* This check keeps Python strings that end in '\0' from comparing equal
10692 to C strings identical up to that point. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010693 if (PyUnicode_GET_LENGTH(uni) != i || chr)
Benjamin Peterson29060642009-01-31 22:14:21 +000010694 return 1; /* uni is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010695 if (str[i])
Benjamin Peterson29060642009-01-31 22:14:21 +000010696 return -1; /* str is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010697 return 0;
10698}
10699
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010700
Benjamin Peterson29060642009-01-31 22:14:21 +000010701#define TEST_COND(cond) \
Benjamin Peterson14339b62009-01-31 16:36:08 +000010702 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010703
Alexander Belopolsky40018472011-02-26 01:02:56 +000010704PyObject *
10705PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010706{
10707 int result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010708
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010709 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10710 PyObject *v;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010711 if (PyUnicode_READY(left) == -1 ||
10712 PyUnicode_READY(right) == -1)
10713 return NULL;
10714 if (PyUnicode_GET_LENGTH(left) != PyUnicode_GET_LENGTH(right) ||
10715 PyUnicode_KIND(left) != PyUnicode_KIND(right)) {
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010716 if (op == Py_EQ) {
10717 Py_INCREF(Py_False);
10718 return Py_False;
10719 }
10720 if (op == Py_NE) {
10721 Py_INCREF(Py_True);
10722 return Py_True;
10723 }
10724 }
10725 if (left == right)
10726 result = 0;
10727 else
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010728 result = unicode_compare(left, right);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010729
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010730 /* Convert the return value to a Boolean */
10731 switch (op) {
10732 case Py_EQ:
10733 v = TEST_COND(result == 0);
10734 break;
10735 case Py_NE:
10736 v = TEST_COND(result != 0);
10737 break;
10738 case Py_LE:
10739 v = TEST_COND(result <= 0);
10740 break;
10741 case Py_GE:
10742 v = TEST_COND(result >= 0);
10743 break;
10744 case Py_LT:
10745 v = TEST_COND(result == -1);
10746 break;
10747 case Py_GT:
10748 v = TEST_COND(result == 1);
10749 break;
10750 default:
10751 PyErr_BadArgument();
10752 return NULL;
10753 }
10754 Py_INCREF(v);
10755 return v;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010756 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000010757
Brian Curtindfc80e32011-08-10 20:28:54 -050010758 Py_RETURN_NOTIMPLEMENTED;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010759}
10760
Alexander Belopolsky40018472011-02-26 01:02:56 +000010761int
10762PyUnicode_Contains(PyObject *container, PyObject *element)
Guido van Rossum403d68b2000-03-13 15:55:09 +000010763{
Thomas Wouters477c8d52006-05-27 19:21:47 +000010764 PyObject *str, *sub;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010765 int kind1, kind2, kind;
10766 void *buf1, *buf2;
10767 Py_ssize_t len1, len2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010768 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010769
10770 /* Coerce the two arguments */
Thomas Wouters477c8d52006-05-27 19:21:47 +000010771 sub = PyUnicode_FromObject(element);
10772 if (!sub) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010773 PyErr_Format(PyExc_TypeError,
10774 "'in <string>' requires string as left operand, not %s",
10775 element->ob_type->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010776 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010777 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010778 if (PyUnicode_READY(sub) == -1)
10779 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010780
Thomas Wouters477c8d52006-05-27 19:21:47 +000010781 str = PyUnicode_FromObject(container);
Victor Stinnere9a29352011-10-01 02:14:59 +020010782 if (!str || PyUnicode_READY(str) == -1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010783 Py_DECREF(sub);
10784 return -1;
10785 }
10786
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010787 kind1 = PyUnicode_KIND(str);
10788 kind2 = PyUnicode_KIND(sub);
10789 kind = kind1 > kind2 ? kind1 : kind2;
10790 buf1 = PyUnicode_DATA(str);
10791 buf2 = PyUnicode_DATA(sub);
10792 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010793 buf1 = _PyUnicode_AsKind(str, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010794 if (!buf1) {
10795 Py_DECREF(sub);
10796 return -1;
10797 }
10798 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010799 buf2 = _PyUnicode_AsKind(sub, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010800 if (!buf2) {
10801 Py_DECREF(sub);
10802 if (kind1 != kind) PyMem_Free(buf1);
10803 return -1;
10804 }
10805 len1 = PyUnicode_GET_LENGTH(str);
10806 len2 = PyUnicode_GET_LENGTH(sub);
10807
10808 switch(kind) {
10809 case PyUnicode_1BYTE_KIND:
10810 result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
10811 break;
10812 case PyUnicode_2BYTE_KIND:
10813 result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
10814 break;
10815 case PyUnicode_4BYTE_KIND:
10816 result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
10817 break;
10818 default:
10819 result = -1;
10820 assert(0);
10821 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000010822
10823 Py_DECREF(str);
10824 Py_DECREF(sub);
10825
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010826 if (kind1 != kind)
10827 PyMem_Free(buf1);
10828 if (kind2 != kind)
10829 PyMem_Free(buf2);
10830
Guido van Rossum403d68b2000-03-13 15:55:09 +000010831 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010832}
10833
Guido van Rossumd57fd912000-03-10 22:53:23 +000010834/* Concat to string or Unicode object giving a new Unicode object. */
10835
Alexander Belopolsky40018472011-02-26 01:02:56 +000010836PyObject *
10837PyUnicode_Concat(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010838{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010839 PyObject *u = NULL, *v = NULL, *w;
Victor Stinner127226b2011-10-13 01:12:34 +020010840 Py_UCS4 maxchar, maxchar2;
Victor Stinner488fa492011-12-12 00:01:39 +010010841 Py_ssize_t u_len, v_len, new_len;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010842
10843 /* Coerce the two arguments */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010844 u = PyUnicode_FromObject(left);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010845 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010846 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010847 v = PyUnicode_FromObject(right);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010848 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010849 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010850
10851 /* Shortcuts */
Victor Stinnera464fc12011-10-02 20:39:30 +020010852 if (v == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010853 Py_DECREF(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010854 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010855 }
Victor Stinnera464fc12011-10-02 20:39:30 +020010856 if (u == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010857 Py_DECREF(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010858 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010859 }
10860
Victor Stinner488fa492011-12-12 00:01:39 +010010861 u_len = PyUnicode_GET_LENGTH(u);
10862 v_len = PyUnicode_GET_LENGTH(v);
10863 if (u_len > PY_SSIZE_T_MAX - v_len) {
10864 PyErr_SetString(PyExc_OverflowError,
10865 "strings are too large to concat");
10866 goto onError;
10867 }
10868 new_len = u_len + v_len;
10869
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010870 maxchar = PyUnicode_MAX_CHAR_VALUE(u);
Victor Stinner127226b2011-10-13 01:12:34 +020010871 maxchar2 = PyUnicode_MAX_CHAR_VALUE(v);
10872 maxchar = Py_MAX(maxchar, maxchar2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010873
Guido van Rossumd57fd912000-03-10 22:53:23 +000010874 /* Concat the two Unicode strings */
Victor Stinner488fa492011-12-12 00:01:39 +010010875 w = PyUnicode_New(new_len, maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010876 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010877 goto onError;
Victor Stinner488fa492011-12-12 00:01:39 +010010878 copy_characters(w, 0, u, 0, u_len);
10879 copy_characters(w, u_len, v, 0, v_len);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010880 Py_DECREF(u);
10881 Py_DECREF(v);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010882 assert(_PyUnicode_CheckConsistency(w, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010883 return w;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010884
Benjamin Peterson29060642009-01-31 22:14:21 +000010885 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000010886 Py_XDECREF(u);
10887 Py_XDECREF(v);
10888 return NULL;
10889}
10890
Walter Dörwald1ab83302007-05-18 17:15:44 +000010891void
Victor Stinner23e56682011-10-03 03:54:37 +020010892PyUnicode_Append(PyObject **p_left, PyObject *right)
Walter Dörwald1ab83302007-05-18 17:15:44 +000010893{
Victor Stinner23e56682011-10-03 03:54:37 +020010894 PyObject *left, *res;
Victor Stinner488fa492011-12-12 00:01:39 +010010895 Py_UCS4 maxchar, maxchar2;
10896 Py_ssize_t left_len, right_len, new_len;
Victor Stinner23e56682011-10-03 03:54:37 +020010897
10898 if (p_left == NULL) {
10899 if (!PyErr_Occurred())
10900 PyErr_BadInternalCall();
Benjamin Peterson14339b62009-01-31 16:36:08 +000010901 return;
10902 }
Victor Stinner23e56682011-10-03 03:54:37 +020010903 left = *p_left;
10904 if (right == NULL || !PyUnicode_Check(left)) {
10905 if (!PyErr_Occurred())
10906 PyErr_BadInternalCall();
10907 goto error;
10908 }
10909
Victor Stinnere1335c72011-10-04 20:53:03 +020010910 if (PyUnicode_READY(left))
10911 goto error;
10912 if (PyUnicode_READY(right))
10913 goto error;
10914
Victor Stinner488fa492011-12-12 00:01:39 +010010915 /* Shortcuts */
10916 if (left == unicode_empty) {
10917 Py_DECREF(left);
10918 Py_INCREF(right);
10919 *p_left = right;
10920 return;
10921 }
10922 if (right == unicode_empty)
10923 return;
10924
10925 left_len = PyUnicode_GET_LENGTH(left);
10926 right_len = PyUnicode_GET_LENGTH(right);
10927 if (left_len > PY_SSIZE_T_MAX - right_len) {
10928 PyErr_SetString(PyExc_OverflowError,
10929 "strings are too large to concat");
10930 goto error;
10931 }
10932 new_len = left_len + right_len;
10933
10934 if (unicode_modifiable(left)
10935 && PyUnicode_CheckExact(right)
10936 && PyUnicode_KIND(right) <= PyUnicode_KIND(left)
Victor Stinnerb0923652011-10-04 01:17:31 +020010937 /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
10938 to change the structure size, but characters are stored just after
Georg Brandl7597add2011-10-05 16:36:47 +020010939 the structure, and so it requires to move all characters which is
Victor Stinnerb0923652011-10-04 01:17:31 +020010940 not so different than duplicating the string. */
Victor Stinner488fa492011-12-12 00:01:39 +010010941 && !(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
10942 {
10943 /* append inplace */
10944 if (unicode_resize(p_left, new_len) != 0) {
10945 /* XXX if _PyUnicode_Resize() fails, 'left' has been
10946 * deallocated so it cannot be put back into
10947 * 'variable'. The MemoryError is raised when there
10948 * is no value in 'variable', which might (very
10949 * remotely) be a cause of incompatibilities.
10950 */
10951 goto error;
Victor Stinner23e56682011-10-03 03:54:37 +020010952 }
Victor Stinner488fa492011-12-12 00:01:39 +010010953 /* copy 'right' into the newly allocated area of 'left' */
10954 copy_characters(*p_left, left_len, right, 0, right_len);
Victor Stinner23e56682011-10-03 03:54:37 +020010955 }
Victor Stinner488fa492011-12-12 00:01:39 +010010956 else {
10957 maxchar = PyUnicode_MAX_CHAR_VALUE(left);
10958 maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
10959 maxchar = Py_MAX(maxchar, maxchar2);
Victor Stinner23e56682011-10-03 03:54:37 +020010960
Victor Stinner488fa492011-12-12 00:01:39 +010010961 /* Concat the two Unicode strings */
10962 res = PyUnicode_New(new_len, maxchar);
10963 if (res == NULL)
10964 goto error;
10965 copy_characters(res, 0, left, 0, left_len);
10966 copy_characters(res, left_len, right, 0, right_len);
10967 Py_DECREF(left);
10968 *p_left = res;
10969 }
10970 assert(_PyUnicode_CheckConsistency(*p_left, 1));
Victor Stinner23e56682011-10-03 03:54:37 +020010971 return;
10972
10973error:
Victor Stinner488fa492011-12-12 00:01:39 +010010974 Py_CLEAR(*p_left);
Walter Dörwald1ab83302007-05-18 17:15:44 +000010975}
10976
10977void
10978PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
10979{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010980 PyUnicode_Append(pleft, right);
10981 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +000010982}
10983
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010984PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010985 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010986\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000010987Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010988string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010989interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010990
10991static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010992unicode_count(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010993{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010994 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010995 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010996 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010997 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010998 int kind1, kind2, kind;
10999 void *buf1, *buf2;
11000 Py_ssize_t len1, len2, iresult;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011001
Jesus Ceaac451502011-04-20 17:09:23 +020011002 if (!stringlib_parse_args_finds_unicode("count", args, &substring,
11003 &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000011004 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000011005
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011006 kind1 = PyUnicode_KIND(self);
11007 kind2 = PyUnicode_KIND(substring);
11008 kind = kind1 > kind2 ? kind1 : kind2;
11009 buf1 = PyUnicode_DATA(self);
11010 buf2 = PyUnicode_DATA(substring);
11011 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010011012 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011013 if (!buf1) {
11014 Py_DECREF(substring);
11015 return NULL;
11016 }
11017 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010011018 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011019 if (!buf2) {
11020 Py_DECREF(substring);
11021 if (kind1 != kind) PyMem_Free(buf1);
11022 return NULL;
11023 }
11024 len1 = PyUnicode_GET_LENGTH(self);
11025 len2 = PyUnicode_GET_LENGTH(substring);
11026
11027 ADJUST_INDICES(start, end, len1);
11028 switch(kind) {
11029 case PyUnicode_1BYTE_KIND:
11030 iresult = ucs1lib_count(
11031 ((Py_UCS1*)buf1) + start, end - start,
11032 buf2, len2, PY_SSIZE_T_MAX
11033 );
11034 break;
11035 case PyUnicode_2BYTE_KIND:
11036 iresult = ucs2lib_count(
11037 ((Py_UCS2*)buf1) + start, end - start,
11038 buf2, len2, PY_SSIZE_T_MAX
11039 );
11040 break;
11041 case PyUnicode_4BYTE_KIND:
11042 iresult = ucs4lib_count(
11043 ((Py_UCS4*)buf1) + start, end - start,
11044 buf2, len2, PY_SSIZE_T_MAX
11045 );
11046 break;
11047 default:
11048 assert(0); iresult = 0;
11049 }
11050
11051 result = PyLong_FromSsize_t(iresult);
11052
11053 if (kind1 != kind)
11054 PyMem_Free(buf1);
11055 if (kind2 != kind)
11056 PyMem_Free(buf2);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011057
11058 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011059
Guido van Rossumd57fd912000-03-10 22:53:23 +000011060 return result;
11061}
11062
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011063PyDoc_STRVAR(encode__doc__,
Victor Stinnerc911bbf2010-11-07 19:04:46 +000011064 "S.encode(encoding='utf-8', errors='strict') -> bytes\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011065\n\
Victor Stinnere14e2122010-11-07 18:41:46 +000011066Encode S using the codec registered for encoding. Default encoding\n\
11067is 'utf-8'. errors may be given to set a different error\n\
Fred Drakee4315f52000-05-09 19:53:39 +000011068handling scheme. Default is 'strict' meaning that encoding errors raise\n\
Walter Dörwald3aeb6322002-09-02 13:14:32 +000011069a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
11070'xmlcharrefreplace' as well as any other name registered with\n\
11071codecs.register_error that can handle UnicodeEncodeErrors.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011072
11073static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011074unicode_encode(PyObject *self, PyObject *args, PyObject *kwargs)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011075{
Benjamin Peterson308d6372009-09-18 21:42:35 +000011076 static char *kwlist[] = {"encoding", "errors", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000011077 char *encoding = NULL;
11078 char *errors = NULL;
Guido van Rossum35d94282007-08-27 18:20:11 +000011079
Benjamin Peterson308d6372009-09-18 21:42:35 +000011080 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:encode",
11081 kwlist, &encoding, &errors))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011082 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011083 return PyUnicode_AsEncodedString(self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +000011084}
11085
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011086PyDoc_STRVAR(expandtabs__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011087 "S.expandtabs([tabsize]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011088\n\
11089Return a copy of S where all tab characters are expanded using spaces.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011090If tabsize is not given, a tab size of 8 characters is assumed.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011091
11092static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011093unicode_expandtabs(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011094{
Antoine Pitroue71d5742011-10-04 15:55:09 +020011095 Py_ssize_t i, j, line_pos, src_len, incr;
11096 Py_UCS4 ch;
11097 PyObject *u;
11098 void *src_data, *dest_data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011099 int tabsize = 8;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011100 int kind;
Antoine Pitroue19aa382011-10-04 16:04:01 +020011101 int found;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011102
11103 if (!PyArg_ParseTuple(args, "|i:expandtabs", &tabsize))
Benjamin Peterson29060642009-01-31 22:14:21 +000011104 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011105
Antoine Pitrou22425222011-10-04 19:10:51 +020011106 if (PyUnicode_READY(self) == -1)
11107 return NULL;
11108
Thomas Wouters7e474022000-07-16 12:04:32 +000011109 /* First pass: determine size of output string */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011110 src_len = PyUnicode_GET_LENGTH(self);
11111 i = j = line_pos = 0;
11112 kind = PyUnicode_KIND(self);
11113 src_data = PyUnicode_DATA(self);
Antoine Pitroue19aa382011-10-04 16:04:01 +020011114 found = 0;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011115 for (; i < src_len; i++) {
11116 ch = PyUnicode_READ(kind, src_data, i);
11117 if (ch == '\t') {
Antoine Pitroue19aa382011-10-04 16:04:01 +020011118 found = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000011119 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011120 incr = tabsize - (line_pos % tabsize); /* cannot overflow */
Benjamin Peterson29060642009-01-31 22:14:21 +000011121 if (j > PY_SSIZE_T_MAX - incr)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011122 goto overflow;
11123 line_pos += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011124 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011125 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011126 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011127 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000011128 if (j > PY_SSIZE_T_MAX - 1)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011129 goto overflow;
11130 line_pos++;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011131 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011132 if (ch == '\n' || ch == '\r')
11133 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011134 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011135 }
Victor Stinnerc4b49542011-12-11 22:44:26 +010011136 if (!found)
11137 return unicode_result_unchanged(self);
Guido van Rossumcd16bf62007-06-13 18:07:49 +000011138
Guido van Rossumd57fd912000-03-10 22:53:23 +000011139 /* Second pass: create output string and fill it */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011140 u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011141 if (!u)
11142 return NULL;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011143 dest_data = PyUnicode_DATA(u);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011144
Antoine Pitroue71d5742011-10-04 15:55:09 +020011145 i = j = line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011146
Antoine Pitroue71d5742011-10-04 15:55:09 +020011147 for (; i < src_len; i++) {
11148 ch = PyUnicode_READ(kind, src_data, i);
11149 if (ch == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +000011150 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011151 incr = tabsize - (line_pos % tabsize);
11152 line_pos += incr;
11153 while (incr--) {
11154 PyUnicode_WRITE(kind, dest_data, j, ' ');
11155 j++;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011156 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011157 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011158 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011159 else {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011160 line_pos++;
11161 PyUnicode_WRITE(kind, dest_data, j, ch);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011162 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011163 if (ch == '\n' || ch == '\r')
11164 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011165 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011166 }
11167 assert (j == PyUnicode_GET_LENGTH(u));
Victor Stinnerd3df8ab2011-11-22 01:22:34 +010011168 return unicode_result(u);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011169
Antoine Pitroue71d5742011-10-04 15:55:09 +020011170 overflow:
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011171 PyErr_SetString(PyExc_OverflowError, "new string is too long");
11172 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011173}
11174
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011175PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011176 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011177\n\
11178Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080011179such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011180arguments start and end are interpreted as in slice notation.\n\
11181\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011182Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011183
11184static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011185unicode_find(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011186{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011187 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011188 Py_ssize_t start;
11189 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011190 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011191
Jesus Ceaac451502011-04-20 17:09:23 +020011192 if (!stringlib_parse_args_finds_unicode("find", args, &substring,
11193 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011194 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011195
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011196 if (PyUnicode_READY(self) == -1)
11197 return NULL;
11198 if (PyUnicode_READY(substring) == -1)
11199 return NULL;
11200
Victor Stinner7931d9a2011-11-04 00:22:48 +010011201 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011202
11203 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011204
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011205 if (result == -2)
11206 return NULL;
11207
Christian Heimes217cfd12007-12-02 14:31:20 +000011208 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011209}
11210
11211static PyObject *
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011212unicode_getitem(PyObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011213{
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011214 Py_UCS4 ch = PyUnicode_ReadChar(self, index);
11215 if (ch == (Py_UCS4)-1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011216 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011217 return PyUnicode_FromOrdinal(ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011218}
11219
Guido van Rossumc2504932007-09-18 19:42:40 +000011220/* Believe it or not, this produces the same value for ASCII strings
Mark Dickinson57e683e2011-09-24 18:18:40 +010011221 as bytes_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +000011222static Py_hash_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011223unicode_hash(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011224{
Guido van Rossumc2504932007-09-18 19:42:40 +000011225 Py_ssize_t len;
Mark Dickinson57e683e2011-09-24 18:18:40 +010011226 Py_uhash_t x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011227
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011228 if (_PyUnicode_HASH(self) != -1)
11229 return _PyUnicode_HASH(self);
11230 if (PyUnicode_READY(self) == -1)
11231 return -1;
11232 len = PyUnicode_GET_LENGTH(self);
11233
11234 /* The hash function as a macro, gets expanded three times below. */
11235#define HASH(P) \
11236 x = (Py_uhash_t)*P << 7; \
11237 while (--len >= 0) \
11238 x = (1000003*x) ^ (Py_uhash_t)*P++;
11239
11240 switch (PyUnicode_KIND(self)) {
11241 case PyUnicode_1BYTE_KIND: {
11242 const unsigned char *c = PyUnicode_1BYTE_DATA(self);
11243 HASH(c);
11244 break;
11245 }
11246 case PyUnicode_2BYTE_KIND: {
11247 const Py_UCS2 *s = PyUnicode_2BYTE_DATA(self);
11248 HASH(s);
11249 break;
11250 }
11251 default: {
11252 Py_UCS4 *l;
11253 assert(PyUnicode_KIND(self) == PyUnicode_4BYTE_KIND &&
11254 "Impossible switch case in unicode_hash");
11255 l = PyUnicode_4BYTE_DATA(self);
11256 HASH(l);
11257 break;
11258 }
11259 }
11260 x ^= (Py_uhash_t)PyUnicode_GET_LENGTH(self);
11261
Guido van Rossumc2504932007-09-18 19:42:40 +000011262 if (x == -1)
11263 x = -2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011264 _PyUnicode_HASH(self) = x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011265 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011266}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011267#undef HASH
Guido van Rossumd57fd912000-03-10 22:53:23 +000011268
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011269PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011270 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011271\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011272Like S.find() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011273
11274static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011275unicode_index(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011276{
Martin v. Löwis18e16552006-02-15 17:27:45 +000011277 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011278 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011279 Py_ssize_t start;
11280 Py_ssize_t end;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011281
Jesus Ceaac451502011-04-20 17:09:23 +020011282 if (!stringlib_parse_args_finds_unicode("index", args, &substring,
11283 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011284 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011285
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011286 if (PyUnicode_READY(self) == -1)
11287 return NULL;
11288 if (PyUnicode_READY(substring) == -1)
11289 return NULL;
11290
Victor Stinner7931d9a2011-11-04 00:22:48 +010011291 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011292
11293 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011294
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011295 if (result == -2)
11296 return NULL;
11297
Guido van Rossumd57fd912000-03-10 22:53:23 +000011298 if (result < 0) {
11299 PyErr_SetString(PyExc_ValueError, "substring not found");
11300 return NULL;
11301 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011302
Christian Heimes217cfd12007-12-02 14:31:20 +000011303 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011304}
11305
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011306PyDoc_STRVAR(islower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011307 "S.islower() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011308\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011309Return True if all cased characters in S are lowercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011310at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011311
11312static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011313unicode_islower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011314{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011315 Py_ssize_t i, length;
11316 int kind;
11317 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011318 int cased;
11319
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011320 if (PyUnicode_READY(self) == -1)
11321 return NULL;
11322 length = PyUnicode_GET_LENGTH(self);
11323 kind = PyUnicode_KIND(self);
11324 data = PyUnicode_DATA(self);
11325
Guido van Rossumd57fd912000-03-10 22:53:23 +000011326 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011327 if (length == 1)
11328 return PyBool_FromLong(
11329 Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011330
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011331 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011332 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011333 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011334
Guido van Rossumd57fd912000-03-10 22:53:23 +000011335 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011336 for (i = 0; i < length; i++) {
11337 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011338
Benjamin Peterson29060642009-01-31 22:14:21 +000011339 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
11340 return PyBool_FromLong(0);
11341 else if (!cased && Py_UNICODE_ISLOWER(ch))
11342 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011343 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011344 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011345}
11346
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011347PyDoc_STRVAR(isupper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011348 "S.isupper() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011349\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011350Return True if all cased characters in S are uppercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011351at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011352
11353static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011354unicode_isupper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011355{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011356 Py_ssize_t i, length;
11357 int kind;
11358 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011359 int cased;
11360
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011361 if (PyUnicode_READY(self) == -1)
11362 return NULL;
11363 length = PyUnicode_GET_LENGTH(self);
11364 kind = PyUnicode_KIND(self);
11365 data = PyUnicode_DATA(self);
11366
Guido van Rossumd57fd912000-03-10 22:53:23 +000011367 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011368 if (length == 1)
11369 return PyBool_FromLong(
11370 Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011371
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011372 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011373 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011374 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011375
Guido van Rossumd57fd912000-03-10 22:53:23 +000011376 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011377 for (i = 0; i < length; i++) {
11378 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011379
Benjamin Peterson29060642009-01-31 22:14:21 +000011380 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
11381 return PyBool_FromLong(0);
11382 else if (!cased && Py_UNICODE_ISUPPER(ch))
11383 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011384 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011385 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011386}
11387
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011388PyDoc_STRVAR(istitle__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011389 "S.istitle() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011390\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011391Return True if S is a titlecased string and there is at least one\n\
11392character in S, i.e. upper- and titlecase characters may only\n\
11393follow uncased characters and lowercase characters only cased ones.\n\
11394Return False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011395
11396static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011397unicode_istitle(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011398{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011399 Py_ssize_t i, length;
11400 int kind;
11401 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011402 int cased, previous_is_cased;
11403
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011404 if (PyUnicode_READY(self) == -1)
11405 return NULL;
11406 length = PyUnicode_GET_LENGTH(self);
11407 kind = PyUnicode_KIND(self);
11408 data = PyUnicode_DATA(self);
11409
Guido van Rossumd57fd912000-03-10 22:53:23 +000011410 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011411 if (length == 1) {
11412 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11413 return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
11414 (Py_UNICODE_ISUPPER(ch) != 0));
11415 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011416
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011417 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011418 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011419 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011420
Guido van Rossumd57fd912000-03-10 22:53:23 +000011421 cased = 0;
11422 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011423 for (i = 0; i < length; i++) {
11424 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011425
Benjamin Peterson29060642009-01-31 22:14:21 +000011426 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
11427 if (previous_is_cased)
11428 return PyBool_FromLong(0);
11429 previous_is_cased = 1;
11430 cased = 1;
11431 }
11432 else if (Py_UNICODE_ISLOWER(ch)) {
11433 if (!previous_is_cased)
11434 return PyBool_FromLong(0);
11435 previous_is_cased = 1;
11436 cased = 1;
11437 }
11438 else
11439 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011440 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011441 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011442}
11443
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011444PyDoc_STRVAR(isspace__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011445 "S.isspace() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011446\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011447Return True if all characters in S are whitespace\n\
11448and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011449
11450static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011451unicode_isspace(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011452{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011453 Py_ssize_t i, length;
11454 int kind;
11455 void *data;
11456
11457 if (PyUnicode_READY(self) == -1)
11458 return NULL;
11459 length = PyUnicode_GET_LENGTH(self);
11460 kind = PyUnicode_KIND(self);
11461 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011462
Guido van Rossumd57fd912000-03-10 22:53:23 +000011463 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011464 if (length == 1)
11465 return PyBool_FromLong(
11466 Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011467
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011468 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011469 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011470 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011471
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011472 for (i = 0; i < length; i++) {
11473 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011474 if (!Py_UNICODE_ISSPACE(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011475 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011476 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011477 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011478}
11479
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011480PyDoc_STRVAR(isalpha__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011481 "S.isalpha() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011482\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011483Return True if all characters in S are alphabetic\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011484and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011485
11486static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011487unicode_isalpha(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011488{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011489 Py_ssize_t i, length;
11490 int kind;
11491 void *data;
11492
11493 if (PyUnicode_READY(self) == -1)
11494 return NULL;
11495 length = PyUnicode_GET_LENGTH(self);
11496 kind = PyUnicode_KIND(self);
11497 data = PyUnicode_DATA(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011498
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011499 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011500 if (length == 1)
11501 return PyBool_FromLong(
11502 Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011503
11504 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011505 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011506 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011507
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011508 for (i = 0; i < length; i++) {
11509 if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011510 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011511 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011512 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011513}
11514
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011515PyDoc_STRVAR(isalnum__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011516 "S.isalnum() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011517\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011518Return True if all characters in S are alphanumeric\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011519and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011520
11521static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011522unicode_isalnum(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011523{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011524 int kind;
11525 void *data;
11526 Py_ssize_t len, i;
11527
11528 if (PyUnicode_READY(self) == -1)
11529 return NULL;
11530
11531 kind = PyUnicode_KIND(self);
11532 data = PyUnicode_DATA(self);
11533 len = PyUnicode_GET_LENGTH(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011534
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011535 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011536 if (len == 1) {
11537 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11538 return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
11539 }
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011540
11541 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011542 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011543 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011544
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011545 for (i = 0; i < len; i++) {
11546 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011547 if (!Py_UNICODE_ISALNUM(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011548 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011549 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011550 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011551}
11552
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011553PyDoc_STRVAR(isdecimal__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011554 "S.isdecimal() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011555\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011556Return True if there are only decimal characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011557False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011558
11559static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011560unicode_isdecimal(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011561{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011562 Py_ssize_t i, length;
11563 int kind;
11564 void *data;
11565
11566 if (PyUnicode_READY(self) == -1)
11567 return NULL;
11568 length = PyUnicode_GET_LENGTH(self);
11569 kind = PyUnicode_KIND(self);
11570 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011571
Guido van Rossumd57fd912000-03-10 22:53:23 +000011572 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011573 if (length == 1)
11574 return PyBool_FromLong(
11575 Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011576
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011577 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011578 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011579 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011580
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011581 for (i = 0; i < length; i++) {
11582 if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011583 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011584 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011585 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011586}
11587
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011588PyDoc_STRVAR(isdigit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011589 "S.isdigit() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011590\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011591Return True if all characters in S are digits\n\
11592and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011593
11594static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011595unicode_isdigit(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011596{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011597 Py_ssize_t i, length;
11598 int kind;
11599 void *data;
11600
11601 if (PyUnicode_READY(self) == -1)
11602 return NULL;
11603 length = PyUnicode_GET_LENGTH(self);
11604 kind = PyUnicode_KIND(self);
11605 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011606
Guido van Rossumd57fd912000-03-10 22:53:23 +000011607 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011608 if (length == 1) {
11609 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11610 return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
11611 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011612
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011613 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011614 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011615 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011616
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011617 for (i = 0; i < length; i++) {
11618 if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011619 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011620 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011621 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011622}
11623
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011624PyDoc_STRVAR(isnumeric__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011625 "S.isnumeric() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011626\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011627Return True if there are only numeric characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011628False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011629
11630static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011631unicode_isnumeric(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011632{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011633 Py_ssize_t i, length;
11634 int kind;
11635 void *data;
11636
11637 if (PyUnicode_READY(self) == -1)
11638 return NULL;
11639 length = PyUnicode_GET_LENGTH(self);
11640 kind = PyUnicode_KIND(self);
11641 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011642
Guido van Rossumd57fd912000-03-10 22:53:23 +000011643 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011644 if (length == 1)
11645 return PyBool_FromLong(
11646 Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011647
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011648 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011649 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011650 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011651
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011652 for (i = 0; i < length; i++) {
11653 if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011654 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011655 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011656 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011657}
11658
Martin v. Löwis47383402007-08-15 07:32:56 +000011659int
11660PyUnicode_IsIdentifier(PyObject *self)
11661{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011662 int kind;
11663 void *data;
11664 Py_ssize_t i;
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011665 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +000011666
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011667 if (PyUnicode_READY(self) == -1) {
11668 Py_FatalError("identifier not ready");
Benjamin Peterson29060642009-01-31 22:14:21 +000011669 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011670 }
11671
11672 /* Special case for empty strings */
11673 if (PyUnicode_GET_LENGTH(self) == 0)
11674 return 0;
11675 kind = PyUnicode_KIND(self);
11676 data = PyUnicode_DATA(self);
Martin v. Löwis47383402007-08-15 07:32:56 +000011677
11678 /* PEP 3131 says that the first character must be in
11679 XID_Start and subsequent characters in XID_Continue,
11680 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +000011681 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +000011682 letters, digits, underscore). However, given the current
11683 definition of XID_Start and XID_Continue, it is sufficient
11684 to check just for these, except that _ must be allowed
11685 as starting an identifier. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011686 first = PyUnicode_READ(kind, data, 0);
Benjamin Petersonf413b802011-08-12 22:17:18 -050011687 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +000011688 return 0;
11689
Benjamin Peterson9c6e6a02011-09-28 08:09:05 -040011690 for (i = 1; i < PyUnicode_GET_LENGTH(self); i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011691 if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011692 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +000011693 return 1;
11694}
11695
11696PyDoc_STRVAR(isidentifier__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011697 "S.isidentifier() -> bool\n\
Martin v. Löwis47383402007-08-15 07:32:56 +000011698\n\
11699Return True if S is a valid identifier according\n\
11700to the language definition.");
11701
11702static PyObject*
11703unicode_isidentifier(PyObject *self)
11704{
11705 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
11706}
11707
Georg Brandl559e5d72008-06-11 18:37:52 +000011708PyDoc_STRVAR(isprintable__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011709 "S.isprintable() -> bool\n\
Georg Brandl559e5d72008-06-11 18:37:52 +000011710\n\
11711Return True if all characters in S are considered\n\
11712printable in repr() or S is empty, False otherwise.");
11713
11714static PyObject*
11715unicode_isprintable(PyObject *self)
11716{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011717 Py_ssize_t i, length;
11718 int kind;
11719 void *data;
11720
11721 if (PyUnicode_READY(self) == -1)
11722 return NULL;
11723 length = PyUnicode_GET_LENGTH(self);
11724 kind = PyUnicode_KIND(self);
11725 data = PyUnicode_DATA(self);
Georg Brandl559e5d72008-06-11 18:37:52 +000011726
11727 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011728 if (length == 1)
11729 return PyBool_FromLong(
11730 Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
Georg Brandl559e5d72008-06-11 18:37:52 +000011731
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011732 for (i = 0; i < length; i++) {
11733 if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
Georg Brandl559e5d72008-06-11 18:37:52 +000011734 Py_RETURN_FALSE;
11735 }
11736 }
11737 Py_RETURN_TRUE;
11738}
11739
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011740PyDoc_STRVAR(join__doc__,
Georg Brandl495f7b52009-10-27 15:28:25 +000011741 "S.join(iterable) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011742\n\
11743Return a string which is the concatenation of the strings in the\n\
Georg Brandl495f7b52009-10-27 15:28:25 +000011744iterable. The separator between elements is S.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011745
11746static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011747unicode_join(PyObject *self, PyObject *data)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011748{
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011749 return PyUnicode_Join(self, data);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011750}
11751
Martin v. Löwis18e16552006-02-15 17:27:45 +000011752static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011753unicode_length(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011754{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011755 if (PyUnicode_READY(self) == -1)
11756 return -1;
11757 return PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011758}
11759
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011760PyDoc_STRVAR(ljust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011761 "S.ljust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011762\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000011763Return S left-justified in a Unicode string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011764done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011765
11766static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020011767unicode_ljust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011768{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011769 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011770 Py_UCS4 fillchar = ' ';
11771
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011772 if (!PyArg_ParseTuple(args, "n|O&:ljust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011773 return NULL;
11774
Victor Stinnerc4b49542011-12-11 22:44:26 +010011775 if (PyUnicode_READY(self) < 0)
11776 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011777
Victor Stinnerc4b49542011-12-11 22:44:26 +010011778 if (PyUnicode_GET_LENGTH(self) >= width)
11779 return unicode_result_unchanged(self);
11780
11781 return pad(self, 0, width - PyUnicode_GET_LENGTH(self), fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011782}
11783
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011784PyDoc_STRVAR(lower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011785 "S.lower() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011786\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011787Return a copy of the string S converted to lowercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011788
11789static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020011790unicode_lower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011791{
Guido van Rossumd57fd912000-03-10 22:53:23 +000011792 return fixup(self, fixlower);
11793}
11794
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011795#define LEFTSTRIP 0
11796#define RIGHTSTRIP 1
11797#define BOTHSTRIP 2
11798
11799/* Arrays indexed by above */
11800static const char *stripformat[] = {"|O:lstrip", "|O:rstrip", "|O:strip"};
11801
11802#define STRIPNAME(i) (stripformat[i]+3)
11803
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011804/* externally visible for str.strip(unicode) */
11805PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011806_PyUnicode_XStrip(PyObject *self, int striptype, PyObject *sepobj)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011807{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011808 void *data;
11809 int kind;
11810 Py_ssize_t i, j, len;
11811 BLOOM_MASK sepmask;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011812
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011813 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
11814 return NULL;
11815
11816 kind = PyUnicode_KIND(self);
11817 data = PyUnicode_DATA(self);
11818 len = PyUnicode_GET_LENGTH(self);
11819 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
11820 PyUnicode_DATA(sepobj),
11821 PyUnicode_GET_LENGTH(sepobj));
Thomas Wouters477c8d52006-05-27 19:21:47 +000011822
Benjamin Peterson14339b62009-01-31 16:36:08 +000011823 i = 0;
11824 if (striptype != RIGHTSTRIP) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011825 while (i < len &&
11826 BLOOM_MEMBER(sepmask, PyUnicode_READ(kind, data, i), sepobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011827 i++;
11828 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011829 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011830
Benjamin Peterson14339b62009-01-31 16:36:08 +000011831 j = len;
11832 if (striptype != LEFTSTRIP) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011833 do {
11834 j--;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011835 } while (j >= i &&
11836 BLOOM_MEMBER(sepmask, PyUnicode_READ(kind, data, j), sepobj));
Benjamin Peterson29060642009-01-31 22:14:21 +000011837 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011838 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011839
Victor Stinner7931d9a2011-11-04 00:22:48 +010011840 return PyUnicode_Substring(self, i, j);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011841}
11842
11843PyObject*
11844PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
11845{
11846 unsigned char *data;
11847 int kind;
Victor Stinner12bab6d2011-10-01 01:53:49 +020011848 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011849
Victor Stinnerde636f32011-10-01 03:55:54 +020011850 if (PyUnicode_READY(self) == -1)
11851 return NULL;
11852
11853 end = Py_MIN(end, PyUnicode_GET_LENGTH(self));
11854
Victor Stinner12bab6d2011-10-01 01:53:49 +020011855 if (start == 0 && end == PyUnicode_GET_LENGTH(self))
Victor Stinnerc4b49542011-12-11 22:44:26 +010011856 return unicode_result_unchanged(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011857
Victor Stinner12bab6d2011-10-01 01:53:49 +020011858 length = end - start;
11859 if (length == 1)
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011860 return unicode_getitem(self, start);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011861
Victor Stinnerde636f32011-10-01 03:55:54 +020011862 if (start < 0 || end < 0) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020011863 PyErr_SetString(PyExc_IndexError, "string index out of range");
11864 return NULL;
11865 }
11866
Victor Stinnerb9275c12011-10-05 14:01:42 +020011867 if (PyUnicode_IS_ASCII(self)) {
11868 kind = PyUnicode_KIND(self);
11869 data = PyUnicode_1BYTE_DATA(self);
11870 return unicode_fromascii(data + start, length);
11871 }
11872 else {
11873 kind = PyUnicode_KIND(self);
11874 data = PyUnicode_1BYTE_DATA(self);
11875 return PyUnicode_FromKindAndData(kind,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020011876 data + kind * start,
Victor Stinnerb9275c12011-10-05 14:01:42 +020011877 length);
11878 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011879}
Guido van Rossumd57fd912000-03-10 22:53:23 +000011880
11881static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011882do_strip(PyObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011883{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011884 int kind;
11885 void *data;
11886 Py_ssize_t len, i, j;
11887
11888 if (PyUnicode_READY(self) == -1)
11889 return NULL;
11890
11891 kind = PyUnicode_KIND(self);
11892 data = PyUnicode_DATA(self);
11893 len = PyUnicode_GET_LENGTH(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011894
Benjamin Peterson14339b62009-01-31 16:36:08 +000011895 i = 0;
11896 if (striptype != RIGHTSTRIP) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011897 while (i < len && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, i))) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000011898 i++;
11899 }
11900 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011901
Benjamin Peterson14339b62009-01-31 16:36:08 +000011902 j = len;
11903 if (striptype != LEFTSTRIP) {
11904 do {
11905 j--;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011906 } while (j >= i && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, j)));
Benjamin Peterson14339b62009-01-31 16:36:08 +000011907 j++;
11908 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011909
Victor Stinner7931d9a2011-11-04 00:22:48 +010011910 return PyUnicode_Substring(self, i, j);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011911}
11912
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011913
11914static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011915do_argstrip(PyObject *self, int striptype, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011916{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011917 PyObject *sep = NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011918
Benjamin Peterson14339b62009-01-31 16:36:08 +000011919 if (!PyArg_ParseTuple(args, (char *)stripformat[striptype], &sep))
11920 return NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011921
Benjamin Peterson14339b62009-01-31 16:36:08 +000011922 if (sep != NULL && sep != Py_None) {
11923 if (PyUnicode_Check(sep))
11924 return _PyUnicode_XStrip(self, striptype, sep);
11925 else {
11926 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000011927 "%s arg must be None or str",
11928 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +000011929 return NULL;
11930 }
11931 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011932
Benjamin Peterson14339b62009-01-31 16:36:08 +000011933 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011934}
11935
11936
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011937PyDoc_STRVAR(strip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011938 "S.strip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011939\n\
11940Return a copy of the string S with leading and trailing\n\
11941whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011942If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011943
11944static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011945unicode_strip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011946{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011947 if (PyTuple_GET_SIZE(args) == 0)
11948 return do_strip(self, BOTHSTRIP); /* Common case */
11949 else
11950 return do_argstrip(self, BOTHSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011951}
11952
11953
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011954PyDoc_STRVAR(lstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011955 "S.lstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011956\n\
11957Return a copy of the string S with leading whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011958If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011959
11960static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011961unicode_lstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011962{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011963 if (PyTuple_GET_SIZE(args) == 0)
11964 return do_strip(self, LEFTSTRIP); /* Common case */
11965 else
11966 return do_argstrip(self, LEFTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011967}
11968
11969
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011970PyDoc_STRVAR(rstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011971 "S.rstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011972\n\
11973Return a copy of the string S with trailing whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011974If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011975
11976static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011977unicode_rstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011978{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011979 if (PyTuple_GET_SIZE(args) == 0)
11980 return do_strip(self, RIGHTSTRIP); /* Common case */
11981 else
11982 return do_argstrip(self, RIGHTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011983}
11984
11985
Guido van Rossumd57fd912000-03-10 22:53:23 +000011986static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011987unicode_repeat(PyObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011988{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011989 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011990 Py_ssize_t nchars, n;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011991
Georg Brandl222de0f2009-04-12 12:01:50 +000011992 if (len < 1) {
11993 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +020011994 return unicode_empty;
Georg Brandl222de0f2009-04-12 12:01:50 +000011995 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011996
Victor Stinnerc4b49542011-12-11 22:44:26 +010011997 /* no repeat, return original string */
11998 if (len == 1)
11999 return unicode_result_unchanged(str);
Tim Peters8f422462000-09-09 06:13:41 +000012000
Victor Stinnerc4b49542011-12-11 22:44:26 +010012001 if (PyUnicode_READY(str) < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012002 return NULL;
12003
Victor Stinnerc759f3e2011-10-01 03:09:58 +020012004 if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
Victor Stinner67ca64c2011-10-01 02:47:29 +020012005 PyErr_SetString(PyExc_OverflowError,
12006 "repeated string is too long");
12007 return NULL;
12008 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012009 nchars = len * PyUnicode_GET_LENGTH(str);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012010
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012011 u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012012 if (!u)
12013 return NULL;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012014 assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012015
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012016 if (PyUnicode_GET_LENGTH(str) == 1) {
12017 const int kind = PyUnicode_KIND(str);
12018 const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
12019 void *to = PyUnicode_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012020 if (kind == PyUnicode_1BYTE_KIND)
12021 memset(to, (unsigned char)fill_char, len);
12022 else {
12023 for (n = 0; n < len; ++n)
12024 PyUnicode_WRITE(kind, to, n, fill_char);
12025 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012026 }
12027 else {
12028 /* number of characters copied this far */
12029 Py_ssize_t done = PyUnicode_GET_LENGTH(str);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012030 const Py_ssize_t char_size = PyUnicode_KIND(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012031 char *to = (char *) PyUnicode_DATA(u);
12032 Py_MEMCPY(to, PyUnicode_DATA(str),
12033 PyUnicode_GET_LENGTH(str) * char_size);
Benjamin Peterson29060642009-01-31 22:14:21 +000012034 while (done < nchars) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012035 n = (done <= nchars-done) ? done : nchars-done;
12036 Py_MEMCPY(to + (done * char_size), to, n * char_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012037 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +000012038 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012039 }
12040
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012041 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012042 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012043}
12044
Alexander Belopolsky40018472011-02-26 01:02:56 +000012045PyObject *
12046PyUnicode_Replace(PyObject *obj,
12047 PyObject *subobj,
12048 PyObject *replobj,
12049 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012050{
12051 PyObject *self;
12052 PyObject *str1;
12053 PyObject *str2;
12054 PyObject *result;
12055
12056 self = PyUnicode_FromObject(obj);
Victor Stinnere9a29352011-10-01 02:14:59 +020012057 if (self == NULL || PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000012058 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012059 str1 = PyUnicode_FromObject(subobj);
Victor Stinnere9a29352011-10-01 02:14:59 +020012060 if (str1 == NULL || PyUnicode_READY(str1) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012061 Py_DECREF(self);
12062 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012063 }
12064 str2 = PyUnicode_FromObject(replobj);
Victor Stinnere9a29352011-10-01 02:14:59 +020012065 if (str2 == NULL || PyUnicode_READY(str2)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012066 Py_DECREF(self);
12067 Py_DECREF(str1);
12068 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012069 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012070 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012071 Py_DECREF(self);
12072 Py_DECREF(str1);
12073 Py_DECREF(str2);
12074 return result;
12075}
12076
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012077PyDoc_STRVAR(replace__doc__,
Ezio Melottic1897e72010-06-26 18:50:39 +000012078 "S.replace(old, new[, count]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012079\n\
12080Return a copy of S with all occurrences of substring\n\
Georg Brandlf08a9dd2008-06-10 16:57:31 +000012081old replaced by new. If the optional argument count is\n\
12082given, only the first count occurrences are replaced.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012083
12084static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012085unicode_replace(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012086{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012087 PyObject *str1;
12088 PyObject *str2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012089 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012090 PyObject *result;
12091
Martin v. Löwis18e16552006-02-15 17:27:45 +000012092 if (!PyArg_ParseTuple(args, "OO|n:replace", &str1, &str2, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012093 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012094 if (!PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000012095 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012096 str1 = PyUnicode_FromObject(str1);
12097 if (str1 == NULL || PyUnicode_READY(str1) == -1)
12098 return NULL;
12099 str2 = PyUnicode_FromObject(str2);
Victor Stinnere9a29352011-10-01 02:14:59 +020012100 if (str2 == NULL || PyUnicode_READY(str2) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012101 Py_DECREF(str1);
12102 return NULL;
Walter Dörwaldf6b56ae2003-02-09 23:42:56 +000012103 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012104
12105 result = replace(self, str1, str2, maxcount);
12106
12107 Py_DECREF(str1);
12108 Py_DECREF(str2);
12109 return result;
12110}
12111
Alexander Belopolsky40018472011-02-26 01:02:56 +000012112static PyObject *
12113unicode_repr(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012114{
Walter Dörwald79e913e2007-05-12 11:08:06 +000012115 PyObject *repr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012116 Py_ssize_t isize;
12117 Py_ssize_t osize, squote, dquote, i, o;
12118 Py_UCS4 max, quote;
12119 int ikind, okind;
12120 void *idata, *odata;
Walter Dörwald79e913e2007-05-12 11:08:06 +000012121
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012122 if (PyUnicode_READY(unicode) == -1)
Walter Dörwald79e913e2007-05-12 11:08:06 +000012123 return NULL;
12124
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012125 isize = PyUnicode_GET_LENGTH(unicode);
12126 idata = PyUnicode_DATA(unicode);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012127
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012128 /* Compute length of output, quote characters, and
12129 maximum character */
12130 osize = 2; /* quotes */
12131 max = 127;
12132 squote = dquote = 0;
12133 ikind = PyUnicode_KIND(unicode);
12134 for (i = 0; i < isize; i++) {
12135 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
12136 switch (ch) {
12137 case '\'': squote++; osize++; break;
12138 case '"': dquote++; osize++; break;
12139 case '\\': case '\t': case '\r': case '\n':
12140 osize += 2; break;
12141 default:
12142 /* Fast-path ASCII */
12143 if (ch < ' ' || ch == 0x7f)
12144 osize += 4; /* \xHH */
12145 else if (ch < 0x7f)
12146 osize++;
12147 else if (Py_UNICODE_ISPRINTABLE(ch)) {
12148 osize++;
12149 max = ch > max ? ch : max;
12150 }
12151 else if (ch < 0x100)
12152 osize += 4; /* \xHH */
12153 else if (ch < 0x10000)
12154 osize += 6; /* \uHHHH */
12155 else
12156 osize += 10; /* \uHHHHHHHH */
12157 }
12158 }
12159
12160 quote = '\'';
12161 if (squote) {
12162 if (dquote)
12163 /* Both squote and dquote present. Use squote,
12164 and escape them */
12165 osize += squote;
12166 else
12167 quote = '"';
12168 }
12169
12170 repr = PyUnicode_New(osize, max);
12171 if (repr == NULL)
12172 return NULL;
12173 okind = PyUnicode_KIND(repr);
12174 odata = PyUnicode_DATA(repr);
12175
12176 PyUnicode_WRITE(okind, odata, 0, quote);
12177 PyUnicode_WRITE(okind, odata, osize-1, quote);
12178
12179 for (i = 0, o = 1; i < isize; i++) {
12180 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012181
12182 /* Escape quotes and backslashes */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012183 if ((ch == quote) || (ch == '\\')) {
12184 PyUnicode_WRITE(okind, odata, o++, '\\');
12185 PyUnicode_WRITE(okind, odata, o++, ch);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012186 continue;
12187 }
12188
Benjamin Peterson29060642009-01-31 22:14:21 +000012189 /* Map special whitespace to '\t', \n', '\r' */
Georg Brandl559e5d72008-06-11 18:37:52 +000012190 if (ch == '\t') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012191 PyUnicode_WRITE(okind, odata, o++, '\\');
12192 PyUnicode_WRITE(okind, odata, o++, 't');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012193 }
12194 else if (ch == '\n') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012195 PyUnicode_WRITE(okind, odata, o++, '\\');
12196 PyUnicode_WRITE(okind, odata, o++, 'n');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012197 }
12198 else if (ch == '\r') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012199 PyUnicode_WRITE(okind, odata, o++, '\\');
12200 PyUnicode_WRITE(okind, odata, o++, 'r');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012201 }
12202
12203 /* Map non-printable US ASCII to '\xhh' */
Georg Brandl559e5d72008-06-11 18:37:52 +000012204 else if (ch < ' ' || ch == 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012205 PyUnicode_WRITE(okind, odata, o++, '\\');
12206 PyUnicode_WRITE(okind, odata, o++, 'x');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012207 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12208 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012209 }
12210
Georg Brandl559e5d72008-06-11 18:37:52 +000012211 /* Copy ASCII characters as-is */
12212 else if (ch < 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012213 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000012214 }
12215
Benjamin Peterson29060642009-01-31 22:14:21 +000012216 /* Non-ASCII characters */
Georg Brandl559e5d72008-06-11 18:37:52 +000012217 else {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012218 /* Map Unicode whitespace and control characters
Georg Brandl559e5d72008-06-11 18:37:52 +000012219 (categories Z* and C* except ASCII space)
12220 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012221 if (!Py_UNICODE_ISPRINTABLE(ch)) {
Georg Brandl559e5d72008-06-11 18:37:52 +000012222 /* Map 8-bit characters to '\xhh' */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012223 if (ch <= 0xff) {
12224 PyUnicode_WRITE(okind, odata, o++, '\\');
12225 PyUnicode_WRITE(okind, odata, o++, 'x');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012226 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12227 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012228 }
12229 /* Map 21-bit characters to '\U00xxxxxx' */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012230 else if (ch >= 0x10000) {
12231 PyUnicode_WRITE(okind, odata, o++, '\\');
12232 PyUnicode_WRITE(okind, odata, o++, 'U');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012233 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 28) & 0xF]);
12234 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 24) & 0xF]);
12235 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 20) & 0xF]);
12236 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 16) & 0xF]);
12237 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12238 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12239 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12240 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012241 }
12242 /* Map 16-bit characters to '\uxxxx' */
12243 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012244 PyUnicode_WRITE(okind, odata, o++, '\\');
12245 PyUnicode_WRITE(okind, odata, o++, 'u');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012246 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12247 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12248 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12249 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012250 }
12251 }
12252 /* Copy characters as-is */
12253 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012254 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000012255 }
12256 }
Walter Dörwald79e913e2007-05-12 11:08:06 +000012257 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012258 /* Closing quote already added at the beginning */
Victor Stinner05d11892011-10-06 01:13:58 +020012259 assert(_PyUnicode_CheckConsistency(repr, 1));
Walter Dörwald79e913e2007-05-12 11:08:06 +000012260 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012261}
12262
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012263PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012264 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012265\n\
12266Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080012267such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012268arguments start and end are interpreted as in slice notation.\n\
12269\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012270Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012271
12272static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012273unicode_rfind(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012274{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012275 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012276 Py_ssize_t start;
12277 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012278 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012279
Jesus Ceaac451502011-04-20 17:09:23 +020012280 if (!stringlib_parse_args_finds_unicode("rfind", args, &substring,
12281 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012282 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012283
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012284 if (PyUnicode_READY(self) == -1)
12285 return NULL;
12286 if (PyUnicode_READY(substring) == -1)
12287 return NULL;
12288
Victor Stinner7931d9a2011-11-04 00:22:48 +010012289 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012290
12291 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012292
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012293 if (result == -2)
12294 return NULL;
12295
Christian Heimes217cfd12007-12-02 14:31:20 +000012296 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012297}
12298
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012299PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012300 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012301\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012302Like S.rfind() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012303
12304static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012305unicode_rindex(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012306{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012307 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012308 Py_ssize_t start;
12309 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012310 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012311
Jesus Ceaac451502011-04-20 17:09:23 +020012312 if (!stringlib_parse_args_finds_unicode("rindex", args, &substring,
12313 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012314 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012315
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012316 if (PyUnicode_READY(self) == -1)
12317 return NULL;
12318 if (PyUnicode_READY(substring) == -1)
12319 return NULL;
12320
Victor Stinner7931d9a2011-11-04 00:22:48 +010012321 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012322
12323 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012324
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012325 if (result == -2)
12326 return NULL;
12327
Guido van Rossumd57fd912000-03-10 22:53:23 +000012328 if (result < 0) {
12329 PyErr_SetString(PyExc_ValueError, "substring not found");
12330 return NULL;
12331 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012332
Christian Heimes217cfd12007-12-02 14:31:20 +000012333 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012334}
12335
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012336PyDoc_STRVAR(rjust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012337 "S.rjust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012338\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012339Return S right-justified in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012340done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012341
12342static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012343unicode_rjust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012344{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012345 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012346 Py_UCS4 fillchar = ' ';
12347
Victor Stinnere9a29352011-10-01 02:14:59 +020012348 if (!PyArg_ParseTuple(args, "n|O&:rjust", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012349 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012350
Victor Stinnerc4b49542011-12-11 22:44:26 +010012351 if (PyUnicode_READY(self) < 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012352 return NULL;
12353
Victor Stinnerc4b49542011-12-11 22:44:26 +010012354 if (PyUnicode_GET_LENGTH(self) >= width)
12355 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012356
Victor Stinnerc4b49542011-12-11 22:44:26 +010012357 return pad(self, width - PyUnicode_GET_LENGTH(self), 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012358}
12359
Alexander Belopolsky40018472011-02-26 01:02:56 +000012360PyObject *
12361PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012362{
12363 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +000012364
Guido van Rossumd57fd912000-03-10 22:53:23 +000012365 s = PyUnicode_FromObject(s);
12366 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012367 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012368 if (sep != NULL) {
12369 sep = PyUnicode_FromObject(sep);
12370 if (sep == NULL) {
12371 Py_DECREF(s);
12372 return NULL;
12373 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012374 }
12375
Victor Stinner9310abb2011-10-05 00:59:23 +020012376 result = split(s, sep, maxsplit);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012377
12378 Py_DECREF(s);
12379 Py_XDECREF(sep);
12380 return result;
12381}
12382
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012383PyDoc_STRVAR(split__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012384 "S.split([sep[, maxsplit]]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012385\n\
12386Return a list of the words in S, using sep as the\n\
12387delimiter string. If maxsplit is given, at most maxsplit\n\
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000012388splits are done. If sep is not specified or is None, any\n\
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +000012389whitespace string is a separator and empty strings are\n\
12390removed from the result.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012391
12392static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012393unicode_split(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012394{
12395 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012396 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012397
Martin v. Löwis18e16552006-02-15 17:27:45 +000012398 if (!PyArg_ParseTuple(args, "|On:split", &substring, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012399 return NULL;
12400
12401 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012402 return split(self, NULL, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012403 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012404 return split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012405 else
Victor Stinner7931d9a2011-11-04 00:22:48 +010012406 return PyUnicode_Split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012407}
12408
Thomas Wouters477c8d52006-05-27 19:21:47 +000012409PyObject *
12410PyUnicode_Partition(PyObject *str_in, PyObject *sep_in)
12411{
12412 PyObject* str_obj;
12413 PyObject* sep_obj;
12414 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012415 int kind1, kind2, kind;
12416 void *buf1 = NULL, *buf2 = NULL;
12417 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012418
12419 str_obj = PyUnicode_FromObject(str_in);
Victor Stinnere9a29352011-10-01 02:14:59 +020012420 if (!str_obj || PyUnicode_READY(str_obj) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000012421 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012422 sep_obj = PyUnicode_FromObject(sep_in);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012423 if (!sep_obj || PyUnicode_READY(sep_obj) == -1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000012424 Py_DECREF(str_obj);
12425 return NULL;
12426 }
12427
Victor Stinner14f8f022011-10-05 20:58:25 +020012428 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012429 kind2 = PyUnicode_KIND(sep_obj);
Victor Stinner14f8f022011-10-05 20:58:25 +020012430 kind = Py_MAX(kind1, kind2);
12431 buf1 = PyUnicode_DATA(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012432 if (kind1 != kind)
Victor Stinner14f8f022011-10-05 20:58:25 +020012433 buf1 = _PyUnicode_AsKind(str_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012434 if (!buf1)
12435 goto onError;
12436 buf2 = PyUnicode_DATA(sep_obj);
12437 if (kind2 != kind)
12438 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12439 if (!buf2)
12440 goto onError;
12441 len1 = PyUnicode_GET_LENGTH(str_obj);
12442 len2 = PyUnicode_GET_LENGTH(sep_obj);
12443
Victor Stinner14f8f022011-10-05 20:58:25 +020012444 switch(PyUnicode_KIND(str_obj)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012445 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012446 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12447 out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12448 else
12449 out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012450 break;
12451 case PyUnicode_2BYTE_KIND:
12452 out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12453 break;
12454 case PyUnicode_4BYTE_KIND:
12455 out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12456 break;
12457 default:
12458 assert(0);
12459 out = 0;
12460 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012461
12462 Py_DECREF(sep_obj);
12463 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012464 if (kind1 != kind)
12465 PyMem_Free(buf1);
12466 if (kind2 != kind)
12467 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012468
12469 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012470 onError:
12471 Py_DECREF(sep_obj);
12472 Py_DECREF(str_obj);
12473 if (kind1 != kind && buf1)
12474 PyMem_Free(buf1);
12475 if (kind2 != kind && buf2)
12476 PyMem_Free(buf2);
12477 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012478}
12479
12480
12481PyObject *
12482PyUnicode_RPartition(PyObject *str_in, PyObject *sep_in)
12483{
12484 PyObject* str_obj;
12485 PyObject* sep_obj;
12486 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012487 int kind1, kind2, kind;
12488 void *buf1 = NULL, *buf2 = NULL;
12489 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012490
12491 str_obj = PyUnicode_FromObject(str_in);
12492 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012493 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012494 sep_obj = PyUnicode_FromObject(sep_in);
12495 if (!sep_obj) {
12496 Py_DECREF(str_obj);
12497 return NULL;
12498 }
12499
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012500 kind1 = PyUnicode_KIND(str_in);
12501 kind2 = PyUnicode_KIND(sep_obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +020012502 kind = Py_MAX(kind1, kind2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012503 buf1 = PyUnicode_DATA(str_in);
12504 if (kind1 != kind)
12505 buf1 = _PyUnicode_AsKind(str_in, kind);
12506 if (!buf1)
12507 goto onError;
12508 buf2 = PyUnicode_DATA(sep_obj);
12509 if (kind2 != kind)
12510 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12511 if (!buf2)
12512 goto onError;
12513 len1 = PyUnicode_GET_LENGTH(str_obj);
12514 len2 = PyUnicode_GET_LENGTH(sep_obj);
12515
12516 switch(PyUnicode_KIND(str_in)) {
12517 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012518 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12519 out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12520 else
12521 out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012522 break;
12523 case PyUnicode_2BYTE_KIND:
12524 out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12525 break;
12526 case PyUnicode_4BYTE_KIND:
12527 out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12528 break;
12529 default:
12530 assert(0);
12531 out = 0;
12532 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012533
12534 Py_DECREF(sep_obj);
12535 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012536 if (kind1 != kind)
12537 PyMem_Free(buf1);
12538 if (kind2 != kind)
12539 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012540
12541 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012542 onError:
12543 Py_DECREF(sep_obj);
12544 Py_DECREF(str_obj);
12545 if (kind1 != kind && buf1)
12546 PyMem_Free(buf1);
12547 if (kind2 != kind && buf2)
12548 PyMem_Free(buf2);
12549 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012550}
12551
12552PyDoc_STRVAR(partition__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012553 "S.partition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012554\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012555Search for the separator sep in S, and return the part before it,\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012556the separator itself, and the part after it. If the separator is not\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012557found, return S and two empty strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012558
12559static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012560unicode_partition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012561{
Victor Stinner9310abb2011-10-05 00:59:23 +020012562 return PyUnicode_Partition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012563}
12564
12565PyDoc_STRVAR(rpartition__doc__,
Ezio Melotti5b2b2422010-01-25 11:58:28 +000012566 "S.rpartition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012567\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012568Search for the separator sep in S, starting at the end of S, and return\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012569the part before it, the separator itself, and the part after it. If the\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012570separator is not found, return two empty strings and S.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012571
12572static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012573unicode_rpartition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012574{
Victor Stinner9310abb2011-10-05 00:59:23 +020012575 return PyUnicode_RPartition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012576}
12577
Alexander Belopolsky40018472011-02-26 01:02:56 +000012578PyObject *
12579PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012580{
12581 PyObject *result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012582
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012583 s = PyUnicode_FromObject(s);
12584 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012585 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012586 if (sep != NULL) {
12587 sep = PyUnicode_FromObject(sep);
12588 if (sep == NULL) {
12589 Py_DECREF(s);
12590 return NULL;
12591 }
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012592 }
12593
Victor Stinner9310abb2011-10-05 00:59:23 +020012594 result = rsplit(s, sep, maxsplit);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012595
12596 Py_DECREF(s);
12597 Py_XDECREF(sep);
12598 return result;
12599}
12600
12601PyDoc_STRVAR(rsplit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012602 "S.rsplit([sep[, maxsplit]]) -> list of strings\n\
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012603\n\
12604Return a list of the words in S, using sep as the\n\
12605delimiter string, starting at the end of the string and\n\
12606working to the front. If maxsplit is given, at most maxsplit\n\
12607splits are done. If sep is not specified, any whitespace string\n\
12608is a separator.");
12609
12610static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012611unicode_rsplit(PyObject *self, PyObject *args)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012612{
12613 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012614 Py_ssize_t maxcount = -1;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012615
Martin v. Löwis18e16552006-02-15 17:27:45 +000012616 if (!PyArg_ParseTuple(args, "|On:rsplit", &substring, &maxcount))
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012617 return NULL;
12618
12619 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012620 return rsplit(self, NULL, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012621 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012622 return rsplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012623 else
Victor Stinner9310abb2011-10-05 00:59:23 +020012624 return PyUnicode_RSplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012625}
12626
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012627PyDoc_STRVAR(splitlines__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012628 "S.splitlines([keepends]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012629\n\
12630Return a list of the lines in S, breaking at line boundaries.\n\
Guido van Rossum86662912000-04-11 15:38:46 +000012631Line breaks are not included in the resulting list unless keepends\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012632is given and true.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012633
12634static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012635unicode_splitlines(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012636{
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012637 static char *kwlist[] = {"keepends", 0};
Guido van Rossum86662912000-04-11 15:38:46 +000012638 int keepends = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012639
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012640 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:splitlines",
12641 kwlist, &keepends))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012642 return NULL;
12643
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012644 return PyUnicode_Splitlines(self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012645}
12646
12647static
Guido van Rossumf15a29f2007-05-04 00:41:39 +000012648PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012649{
Victor Stinnerc4b49542011-12-11 22:44:26 +010012650 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012651}
12652
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012653PyDoc_STRVAR(swapcase__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012654 "S.swapcase() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012655\n\
12656Return a copy of S with uppercase characters converted to lowercase\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012657and vice versa.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012658
12659static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012660unicode_swapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012661{
Guido van Rossumd57fd912000-03-10 22:53:23 +000012662 return fixup(self, fixswapcase);
12663}
12664
Georg Brandlceee0772007-11-27 23:48:05 +000012665PyDoc_STRVAR(maketrans__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012666 "str.maketrans(x[, y[, z]]) -> dict (static method)\n\
Georg Brandlceee0772007-11-27 23:48:05 +000012667\n\
12668Return a translation table usable for str.translate().\n\
12669If there is only one argument, it must be a dictionary mapping Unicode\n\
12670ordinals (integers) or characters to Unicode ordinals, strings or None.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012671Character keys will be then converted to ordinals.\n\
Georg Brandlceee0772007-11-27 23:48:05 +000012672If there are two arguments, they must be strings of equal length, and\n\
12673in the resulting dictionary, each character in x will be mapped to the\n\
12674character at the same position in y. If there is a third argument, it\n\
12675must be a string, whose characters will be mapped to None in the result.");
12676
12677static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012678unicode_maketrans(PyObject *null, PyObject *args)
Georg Brandlceee0772007-11-27 23:48:05 +000012679{
12680 PyObject *x, *y = NULL, *z = NULL;
12681 PyObject *new = NULL, *key, *value;
12682 Py_ssize_t i = 0;
12683 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012684
Georg Brandlceee0772007-11-27 23:48:05 +000012685 if (!PyArg_ParseTuple(args, "O|UU:maketrans", &x, &y, &z))
12686 return NULL;
12687 new = PyDict_New();
12688 if (!new)
12689 return NULL;
12690 if (y != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012691 int x_kind, y_kind, z_kind;
12692 void *x_data, *y_data, *z_data;
12693
Georg Brandlceee0772007-11-27 23:48:05 +000012694 /* x must be a string too, of equal length */
Georg Brandlceee0772007-11-27 23:48:05 +000012695 if (!PyUnicode_Check(x)) {
12696 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
12697 "be a string if there is a second argument");
12698 goto err;
12699 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012700 if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012701 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
12702 "arguments must have equal length");
12703 goto err;
12704 }
12705 /* create entries for translating chars in x to those in y */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012706 x_kind = PyUnicode_KIND(x);
12707 y_kind = PyUnicode_KIND(y);
12708 x_data = PyUnicode_DATA(x);
12709 y_data = PyUnicode_DATA(y);
12710 for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
12711 key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
12712 value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000012713 if (!key || !value)
12714 goto err;
12715 res = PyDict_SetItem(new, key, value);
12716 Py_DECREF(key);
12717 Py_DECREF(value);
12718 if (res < 0)
12719 goto err;
12720 }
12721 /* create entries for deleting chars in z */
12722 if (z != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012723 z_kind = PyUnicode_KIND(z);
12724 z_data = PyUnicode_DATA(z);
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012725 for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012726 key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000012727 if (!key)
12728 goto err;
12729 res = PyDict_SetItem(new, key, Py_None);
12730 Py_DECREF(key);
12731 if (res < 0)
12732 goto err;
12733 }
12734 }
12735 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012736 int kind;
12737 void *data;
12738
Georg Brandlceee0772007-11-27 23:48:05 +000012739 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +000012740 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012741 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
12742 "to maketrans it must be a dict");
12743 goto err;
12744 }
12745 /* copy entries into the new dict, converting string keys to int keys */
12746 while (PyDict_Next(x, &i, &key, &value)) {
12747 if (PyUnicode_Check(key)) {
12748 /* convert string keys to integer keys */
12749 PyObject *newkey;
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012750 if (PyUnicode_GET_LENGTH(key) != 1) {
Georg Brandlceee0772007-11-27 23:48:05 +000012751 PyErr_SetString(PyExc_ValueError, "string keys in translate "
12752 "table must be of length 1");
12753 goto err;
12754 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012755 kind = PyUnicode_KIND(key);
12756 data = PyUnicode_DATA(key);
12757 newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
Georg Brandlceee0772007-11-27 23:48:05 +000012758 if (!newkey)
12759 goto err;
12760 res = PyDict_SetItem(new, newkey, value);
12761 Py_DECREF(newkey);
12762 if (res < 0)
12763 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +000012764 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012765 /* just keep integer keys */
12766 if (PyDict_SetItem(new, key, value) < 0)
12767 goto err;
12768 } else {
12769 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
12770 "be strings or integers");
12771 goto err;
12772 }
12773 }
12774 }
12775 return new;
12776 err:
12777 Py_DECREF(new);
12778 return NULL;
12779}
12780
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012781PyDoc_STRVAR(translate__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012782 "S.translate(table) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012783\n\
12784Return a copy of the string S, where all characters have been mapped\n\
12785through the given translation table, which must be a mapping of\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012786Unicode ordinals to Unicode ordinals, strings, or None.\n\
Walter Dörwald5c1ee172002-09-04 20:31:32 +000012787Unmapped characters are left untouched. Characters mapped to None\n\
12788are deleted.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012789
12790static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012791unicode_translate(PyObject *self, PyObject *table)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012792{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012793 return _PyUnicode_TranslateCharmap(self, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012794}
12795
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012796PyDoc_STRVAR(upper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012797 "S.upper() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012798\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012799Return a copy of S converted to uppercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012800
12801static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012802unicode_upper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012803{
Guido van Rossumd57fd912000-03-10 22:53:23 +000012804 return fixup(self, fixupper);
12805}
12806
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012807PyDoc_STRVAR(zfill__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012808 "S.zfill(width) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012809\n\
Benjamin Peterson9aa42992008-09-10 21:57:34 +000012810Pad a numeric string S with zeros on the left, to fill a field\n\
12811of the specified width. The string S is never truncated.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012812
12813static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012814unicode_zfill(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012815{
Martin v. Löwis18e16552006-02-15 17:27:45 +000012816 Py_ssize_t fill;
Victor Stinner9310abb2011-10-05 00:59:23 +020012817 PyObject *u;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012818 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012819 int kind;
12820 void *data;
12821 Py_UCS4 chr;
12822
Martin v. Löwis18e16552006-02-15 17:27:45 +000012823 if (!PyArg_ParseTuple(args, "n:zfill", &width))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012824 return NULL;
12825
Victor Stinnerc4b49542011-12-11 22:44:26 +010012826 if (PyUnicode_READY(self) < 0)
12827 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012828
Victor Stinnerc4b49542011-12-11 22:44:26 +010012829 if (PyUnicode_GET_LENGTH(self) >= width)
12830 return unicode_result_unchanged(self);
12831
12832 fill = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012833
12834 u = pad(self, fill, 0, '0');
12835
Walter Dörwald068325e2002-04-15 13:36:47 +000012836 if (u == NULL)
12837 return NULL;
12838
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012839 kind = PyUnicode_KIND(u);
12840 data = PyUnicode_DATA(u);
12841 chr = PyUnicode_READ(kind, data, fill);
12842
12843 if (chr == '+' || chr == '-') {
Guido van Rossumd57fd912000-03-10 22:53:23 +000012844 /* move sign to beginning of string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012845 PyUnicode_WRITE(kind, data, 0, chr);
12846 PyUnicode_WRITE(kind, data, fill, '0');
Guido van Rossumd57fd912000-03-10 22:53:23 +000012847 }
12848
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012849 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +010012850 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012851}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012852
12853#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012854static PyObject *
12855unicode__decimal2ascii(PyObject *self)
12856{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012857 return PyUnicode_TransformDecimalAndSpaceToASCII(self);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012858}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012859#endif
12860
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012861PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012862 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012863\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000012864Return True if S starts with the specified prefix, False otherwise.\n\
12865With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012866With optional end, stop comparing S at that position.\n\
12867prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012868
12869static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012870unicode_startswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000012871 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012872{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012873 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012874 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012875 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012876 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012877 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012878
Jesus Ceaac451502011-04-20 17:09:23 +020012879 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000012880 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012881 if (PyTuple_Check(subobj)) {
12882 Py_ssize_t i;
12883 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012884 substring = PyUnicode_FromObject(PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012885 if (substring == NULL)
12886 return NULL;
12887 result = tailmatch(self, substring, start, end, -1);
12888 Py_DECREF(substring);
12889 if (result) {
12890 Py_RETURN_TRUE;
12891 }
12892 }
12893 /* nothing matched */
12894 Py_RETURN_FALSE;
12895 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012896 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030012897 if (substring == NULL) {
12898 if (PyErr_ExceptionMatches(PyExc_TypeError))
12899 PyErr_Format(PyExc_TypeError, "startswith first arg must be str or "
12900 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000012901 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030012902 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012903 result = tailmatch(self, substring, start, end, -1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012904 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012905 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012906}
12907
12908
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012909PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012910 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012911\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000012912Return True if S ends with the specified suffix, False otherwise.\n\
12913With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012914With optional end, stop comparing S at that position.\n\
12915suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012916
12917static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012918unicode_endswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000012919 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012920{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012921 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012922 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012923 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012924 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012925 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012926
Jesus Ceaac451502011-04-20 17:09:23 +020012927 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000012928 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012929 if (PyTuple_Check(subobj)) {
12930 Py_ssize_t i;
12931 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012932 substring = PyUnicode_FromObject(
Benjamin Peterson29060642009-01-31 22:14:21 +000012933 PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012934 if (substring == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000012935 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012936 result = tailmatch(self, substring, start, end, +1);
12937 Py_DECREF(substring);
12938 if (result) {
12939 Py_RETURN_TRUE;
12940 }
12941 }
12942 Py_RETURN_FALSE;
12943 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012944 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030012945 if (substring == NULL) {
12946 if (PyErr_ExceptionMatches(PyExc_TypeError))
12947 PyErr_Format(PyExc_TypeError, "endswith first arg must be str or "
12948 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000012949 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030012950 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012951 result = tailmatch(self, substring, start, end, +1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012952 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012953 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012954}
12955
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012956#include "stringlib/unicode_format.h"
Eric Smith8c663262007-08-25 02:26:07 +000012957
12958PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012959 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000012960\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012961Return a formatted version of S, using substitutions from args and kwargs.\n\
12962The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +000012963
Eric Smith27bbca62010-11-04 17:06:58 +000012964PyDoc_STRVAR(format_map__doc__,
12965 "S.format_map(mapping) -> str\n\
12966\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012967Return a formatted version of S, using substitutions from mapping.\n\
12968The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +000012969
Eric Smith4a7d76d2008-05-30 18:10:19 +000012970static PyObject *
12971unicode__format__(PyObject* self, PyObject* args)
12972{
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012973 PyObject *format_spec, *out;
Eric Smith4a7d76d2008-05-30 18:10:19 +000012974
12975 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
12976 return NULL;
12977
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012978 out = _PyUnicode_FormatAdvanced(self, format_spec, 0,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012979 PyUnicode_GET_LENGTH(format_spec));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012980 return out;
Eric Smith4a7d76d2008-05-30 18:10:19 +000012981}
12982
Eric Smith8c663262007-08-25 02:26:07 +000012983PyDoc_STRVAR(p_format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012984 "S.__format__(format_spec) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000012985\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012986Return a formatted version of S as described by format_spec.");
Eric Smith8c663262007-08-25 02:26:07 +000012987
12988static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012989unicode__sizeof__(PyObject *v)
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012990{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012991 Py_ssize_t size;
12992
12993 /* If it's a compact object, account for base structure +
12994 character data. */
12995 if (PyUnicode_IS_COMPACT_ASCII(v))
12996 size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(v) + 1;
12997 else if (PyUnicode_IS_COMPACT(v))
12998 size = sizeof(PyCompactUnicodeObject) +
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012999 (PyUnicode_GET_LENGTH(v) + 1) * PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013000 else {
13001 /* If it is a two-block object, account for base object, and
13002 for character block if present. */
13003 size = sizeof(PyUnicodeObject);
Victor Stinnerc3c74152011-10-02 20:39:55 +020013004 if (_PyUnicode_DATA_ANY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013005 size += (PyUnicode_GET_LENGTH(v) + 1) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013006 PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013007 }
13008 /* If the wstr pointer is present, account for it unless it is shared
Victor Stinnera3be6132011-10-03 02:16:37 +020013009 with the data pointer. Check if the data is not shared. */
Victor Stinner03490912011-10-03 23:45:12 +020013010 if (_PyUnicode_HAS_WSTR_MEMORY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013011 size += (PyUnicode_WSTR_LENGTH(v) + 1) * sizeof(wchar_t);
Victor Stinner829c0ad2011-10-03 01:08:02 +020013012 if (_PyUnicode_HAS_UTF8_MEMORY(v))
Victor Stinnere90fe6a2011-10-01 16:48:13 +020013013 size += PyUnicode_UTF8_LENGTH(v) + 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013014
13015 return PyLong_FromSsize_t(size);
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013016}
13017
13018PyDoc_STRVAR(sizeof__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013019 "S.__sizeof__() -> size of S in memory, in bytes");
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013020
13021static PyObject *
Victor Stinner034f6cf2011-09-30 02:26:44 +020013022unicode_getnewargs(PyObject *v)
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013023{
Victor Stinnerbf6e5602011-12-12 01:53:47 +010013024 PyObject *copy = _PyUnicode_Copy(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013025 if (!copy)
13026 return NULL;
13027 return Py_BuildValue("(N)", copy);
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013028}
13029
Guido van Rossumd57fd912000-03-10 22:53:23 +000013030static PyMethodDef unicode_methods[] = {
13031
13032 /* Order is according to common usage: often used methods should
13033 appear first, since lookup is done sequentially. */
13034
Benjamin Peterson28a4dce2010-12-12 01:33:04 +000013035 {"encode", (PyCFunction) unicode_encode, METH_VARARGS | METH_KEYWORDS, encode__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013036 {"replace", (PyCFunction) unicode_replace, METH_VARARGS, replace__doc__},
13037 {"split", (PyCFunction) unicode_split, METH_VARARGS, split__doc__},
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013038 {"rsplit", (PyCFunction) unicode_rsplit, METH_VARARGS, rsplit__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013039 {"join", (PyCFunction) unicode_join, METH_O, join__doc__},
13040 {"capitalize", (PyCFunction) unicode_capitalize, METH_NOARGS, capitalize__doc__},
13041 {"title", (PyCFunction) unicode_title, METH_NOARGS, title__doc__},
13042 {"center", (PyCFunction) unicode_center, METH_VARARGS, center__doc__},
13043 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
13044 {"expandtabs", (PyCFunction) unicode_expandtabs, METH_VARARGS, expandtabs__doc__},
13045 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013046 {"partition", (PyCFunction) unicode_partition, METH_O, partition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013047 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
13048 {"ljust", (PyCFunction) unicode_ljust, METH_VARARGS, ljust__doc__},
13049 {"lower", (PyCFunction) unicode_lower, METH_NOARGS, lower__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013050 {"lstrip", (PyCFunction) unicode_lstrip, METH_VARARGS, lstrip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013051 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
13052 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
13053 {"rjust", (PyCFunction) unicode_rjust, METH_VARARGS, rjust__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013054 {"rstrip", (PyCFunction) unicode_rstrip, METH_VARARGS, rstrip__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013055 {"rpartition", (PyCFunction) unicode_rpartition, METH_O, rpartition__doc__},
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010013056 {"splitlines", (PyCFunction) unicode_splitlines, METH_VARARGS | METH_KEYWORDS, splitlines__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013057 {"strip", (PyCFunction) unicode_strip, METH_VARARGS, strip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013058 {"swapcase", (PyCFunction) unicode_swapcase, METH_NOARGS, swapcase__doc__},
13059 {"translate", (PyCFunction) unicode_translate, METH_O, translate__doc__},
13060 {"upper", (PyCFunction) unicode_upper, METH_NOARGS, upper__doc__},
13061 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
13062 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
13063 {"islower", (PyCFunction) unicode_islower, METH_NOARGS, islower__doc__},
13064 {"isupper", (PyCFunction) unicode_isupper, METH_NOARGS, isupper__doc__},
13065 {"istitle", (PyCFunction) unicode_istitle, METH_NOARGS, istitle__doc__},
13066 {"isspace", (PyCFunction) unicode_isspace, METH_NOARGS, isspace__doc__},
13067 {"isdecimal", (PyCFunction) unicode_isdecimal, METH_NOARGS, isdecimal__doc__},
13068 {"isdigit", (PyCFunction) unicode_isdigit, METH_NOARGS, isdigit__doc__},
13069 {"isnumeric", (PyCFunction) unicode_isnumeric, METH_NOARGS, isnumeric__doc__},
13070 {"isalpha", (PyCFunction) unicode_isalpha, METH_NOARGS, isalpha__doc__},
13071 {"isalnum", (PyCFunction) unicode_isalnum, METH_NOARGS, isalnum__doc__},
Martin v. Löwis47383402007-08-15 07:32:56 +000013072 {"isidentifier", (PyCFunction) unicode_isidentifier, METH_NOARGS, isidentifier__doc__},
Georg Brandl559e5d72008-06-11 18:37:52 +000013073 {"isprintable", (PyCFunction) unicode_isprintable, METH_NOARGS, isprintable__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013074 {"zfill", (PyCFunction) unicode_zfill, METH_VARARGS, zfill__doc__},
Eric Smith9cd1e092007-08-31 18:39:38 +000013075 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +000013076 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
Eric Smith4a7d76d2008-05-30 18:10:19 +000013077 {"__format__", (PyCFunction) unicode__format__, METH_VARARGS, p_format__doc__},
Georg Brandlceee0772007-11-27 23:48:05 +000013078 {"maketrans", (PyCFunction) unicode_maketrans,
13079 METH_VARARGS | METH_STATIC, maketrans__doc__},
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013080 {"__sizeof__", (PyCFunction) unicode__sizeof__, METH_NOARGS, sizeof__doc__},
Walter Dörwald068325e2002-04-15 13:36:47 +000013081#if 0
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013082 {"capwords", (PyCFunction) unicode_capwords, METH_NOARGS, capwords__doc__},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013083#endif
13084
13085#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013086 /* These methods are just used for debugging the implementation. */
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013087 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013088#endif
13089
Benjamin Peterson14339b62009-01-31 16:36:08 +000013090 {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013091 {NULL, NULL}
13092};
13093
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013094static PyObject *
13095unicode_mod(PyObject *v, PyObject *w)
13096{
Brian Curtindfc80e32011-08-10 20:28:54 -050013097 if (!PyUnicode_Check(v))
13098 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson29060642009-01-31 22:14:21 +000013099 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013100}
13101
13102static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013103 0, /*nb_add*/
13104 0, /*nb_subtract*/
13105 0, /*nb_multiply*/
13106 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013107};
13108
Guido van Rossumd57fd912000-03-10 22:53:23 +000013109static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013110 (lenfunc) unicode_length, /* sq_length */
13111 PyUnicode_Concat, /* sq_concat */
13112 (ssizeargfunc) unicode_repeat, /* sq_repeat */
13113 (ssizeargfunc) unicode_getitem, /* sq_item */
13114 0, /* sq_slice */
13115 0, /* sq_ass_item */
13116 0, /* sq_ass_slice */
13117 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013118};
13119
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013120static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013121unicode_subscript(PyObject* self, PyObject* item)
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013122{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013123 if (PyUnicode_READY(self) == -1)
13124 return NULL;
13125
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000013126 if (PyIndex_Check(item)) {
13127 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013128 if (i == -1 && PyErr_Occurred())
13129 return NULL;
13130 if (i < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013131 i += PyUnicode_GET_LENGTH(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013132 return unicode_getitem(self, i);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013133 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000013134 Py_ssize_t start, stop, step, slicelength, cur, i;
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013135 PyObject *result;
13136 void *src_data, *dest_data;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013137 int src_kind, dest_kind;
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013138 Py_UCS4 ch, max_char, kind_limit;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013139
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013140 if (PySlice_GetIndicesEx(item, PyUnicode_GET_LENGTH(self),
Benjamin Peterson29060642009-01-31 22:14:21 +000013141 &start, &stop, &step, &slicelength) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013142 return NULL;
13143 }
13144
13145 if (slicelength <= 0) {
Victor Stinner382955f2011-12-11 21:44:00 +010013146 Py_INCREF(unicode_empty);
13147 return unicode_empty;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013148 } else if (start == 0 && step == 1 &&
Victor Stinnerc4b49542011-12-11 22:44:26 +010013149 slicelength == PyUnicode_GET_LENGTH(self)) {
13150 return unicode_result_unchanged(self);
Thomas Woutersed03b412007-08-28 21:37:11 +000013151 } else if (step == 1) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013152 return PyUnicode_Substring(self,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013153 start, start + slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013154 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013155 /* General case */
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013156 src_kind = PyUnicode_KIND(self);
13157 src_data = PyUnicode_DATA(self);
Victor Stinner55c99112011-10-13 01:17:06 +020013158 if (!PyUnicode_IS_ASCII(self)) {
13159 kind_limit = kind_maxchar_limit(src_kind);
13160 max_char = 0;
13161 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
13162 ch = PyUnicode_READ(src_kind, src_data, cur);
13163 if (ch > max_char) {
13164 max_char = ch;
13165 if (max_char >= kind_limit)
13166 break;
13167 }
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013168 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013169 }
Victor Stinner55c99112011-10-13 01:17:06 +020013170 else
13171 max_char = 127;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013172 result = PyUnicode_New(slicelength, max_char);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013173 if (result == NULL)
13174 return NULL;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013175 dest_kind = PyUnicode_KIND(result);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013176 dest_data = PyUnicode_DATA(result);
13177
13178 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013179 Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
13180 PyUnicode_WRITE(dest_kind, dest_data, i, ch);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013181 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013182 assert(_PyUnicode_CheckConsistency(result, 1));
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013183 return result;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013184 } else {
13185 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
13186 return NULL;
13187 }
13188}
13189
13190static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013191 (lenfunc)unicode_length, /* mp_length */
13192 (binaryfunc)unicode_subscript, /* mp_subscript */
13193 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013194};
13195
Guido van Rossumd57fd912000-03-10 22:53:23 +000013196
Guido van Rossumd57fd912000-03-10 22:53:23 +000013197/* Helpers for PyUnicode_Format() */
13198
13199static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +000013200getnextarg(PyObject *args, Py_ssize_t arglen, Py_ssize_t *p_argidx)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013201{
Martin v. Löwis18e16552006-02-15 17:27:45 +000013202 Py_ssize_t argidx = *p_argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013203 if (argidx < arglen) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013204 (*p_argidx)++;
13205 if (arglen < 0)
13206 return args;
13207 else
13208 return PyTuple_GetItem(args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013209 }
13210 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013211 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013212 return NULL;
13213}
13214
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013215/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013216
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013217static PyObject *
13218formatfloat(PyObject *v, int flags, int prec, int type)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013219{
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013220 char *p;
13221 PyObject *result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013222 double x;
Tim Petersced69f82003-09-16 20:30:58 +000013223
Guido van Rossumd57fd912000-03-10 22:53:23 +000013224 x = PyFloat_AsDouble(v);
13225 if (x == -1.0 && PyErr_Occurred())
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013226 return NULL;
13227
Guido van Rossumd57fd912000-03-10 22:53:23 +000013228 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000013229 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +000013230
Eric Smith0923d1d2009-04-16 20:16:10 +000013231 p = PyOS_double_to_string(x, type, prec,
13232 (flags & F_ALT) ? Py_DTSF_ALT : 0, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013233 if (p == NULL)
13234 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013235 result = PyUnicode_DecodeASCII(p, strlen(p), NULL);
Eric Smith0923d1d2009-04-16 20:16:10 +000013236 PyMem_Free(p);
13237 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013238}
13239
Tim Peters38fd5b62000-09-21 05:43:11 +000013240static PyObject*
13241formatlong(PyObject *val, int flags, int prec, int type)
13242{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013243 char *buf;
13244 int len;
13245 PyObject *str; /* temporary string object. */
13246 PyObject *result;
Tim Peters38fd5b62000-09-21 05:43:11 +000013247
Benjamin Peterson14339b62009-01-31 16:36:08 +000013248 str = _PyBytes_FormatLong(val, flags, prec, type, &buf, &len);
13249 if (!str)
13250 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013251 result = PyUnicode_DecodeASCII(buf, len, NULL);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013252 Py_DECREF(str);
13253 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +000013254}
13255
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013256static Py_UCS4
13257formatchar(PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013258{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000013259 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000013260 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013261 if (PyUnicode_GET_LENGTH(v) == 1) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013262 return PyUnicode_READ_CHAR(v, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +000013263 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013264 goto onError;
13265 }
13266 else {
13267 /* Integer input truncated to a character */
13268 long x;
13269 x = PyLong_AsLong(v);
13270 if (x == -1 && PyErr_Occurred())
13271 goto onError;
13272
Victor Stinner8faf8212011-12-08 22:14:11 +010013273 if (x < 0 || x > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013274 PyErr_SetString(PyExc_OverflowError,
13275 "%c arg not in range(0x110000)");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013276 return (Py_UCS4) -1;
Benjamin Peterson29060642009-01-31 22:14:21 +000013277 }
13278
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013279 return (Py_UCS4) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013280 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000013281
Benjamin Peterson29060642009-01-31 22:14:21 +000013282 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000013283 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013284 "%c requires int or char");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013285 return (Py_UCS4) -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013286}
13287
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013288static int
13289repeat_accumulate(_PyAccu *acc, PyObject *obj, Py_ssize_t count)
13290{
13291 int r;
13292 assert(count > 0);
13293 assert(PyUnicode_Check(obj));
13294 if (count > 5) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013295 PyObject *repeated = unicode_repeat(obj, count);
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013296 if (repeated == NULL)
13297 return -1;
13298 r = _PyAccu_Accumulate(acc, repeated);
13299 Py_DECREF(repeated);
13300 return r;
13301 }
13302 else {
13303 do {
13304 if (_PyAccu_Accumulate(acc, obj))
13305 return -1;
13306 } while (--count);
13307 return 0;
13308 }
13309}
13310
Alexander Belopolsky40018472011-02-26 01:02:56 +000013311PyObject *
13312PyUnicode_Format(PyObject *format, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013313{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013314 void *fmt;
13315 int fmtkind;
13316 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013317 int kind;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013318 int r;
13319 Py_ssize_t fmtcnt, fmtpos, arglen, argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013320 int args_owned = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013321 PyObject *dict = NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013322 PyObject *temp = NULL;
13323 PyObject *second = NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013324 PyObject *uformat;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013325 _PyAccu acc;
13326 static PyObject *plus, *minus, *blank, *zero, *percent;
13327
13328 if (!plus && !(plus = get_latin1_char('+')))
13329 return NULL;
13330 if (!minus && !(minus = get_latin1_char('-')))
13331 return NULL;
13332 if (!blank && !(blank = get_latin1_char(' ')))
13333 return NULL;
13334 if (!zero && !(zero = get_latin1_char('0')))
13335 return NULL;
13336 if (!percent && !(percent = get_latin1_char('%')))
13337 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000013338
Guido van Rossumd57fd912000-03-10 22:53:23 +000013339 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013340 PyErr_BadInternalCall();
13341 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013342 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013343 uformat = PyUnicode_FromObject(format);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013344 if (uformat == NULL || PyUnicode_READY(uformat) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000013345 return NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013346 if (_PyAccu_Init(&acc))
13347 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013348 fmt = PyUnicode_DATA(uformat);
13349 fmtkind = PyUnicode_KIND(uformat);
13350 fmtcnt = PyUnicode_GET_LENGTH(uformat);
13351 fmtpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013352
Guido van Rossumd57fd912000-03-10 22:53:23 +000013353 if (PyTuple_Check(args)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013354 arglen = PyTuple_Size(args);
13355 argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013356 }
13357 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013358 arglen = -1;
13359 argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013360 }
Christian Heimes90aa7642007-12-19 02:45:37 +000013361 if (Py_TYPE(args)->tp_as_mapping && !PyTuple_Check(args) &&
Christian Heimesf3863112007-11-22 07:46:41 +000013362 !PyUnicode_Check(args))
Benjamin Peterson29060642009-01-31 22:14:21 +000013363 dict = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013364
13365 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013366 if (PyUnicode_READ(fmtkind, fmt, fmtpos) != '%') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013367 PyObject *nonfmt;
13368 Py_ssize_t nonfmtpos;
13369 nonfmtpos = fmtpos++;
13370 while (fmtcnt >= 0 &&
13371 PyUnicode_READ(fmtkind, fmt, fmtpos) != '%') {
13372 fmtpos++;
13373 fmtcnt--;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013374 }
Victor Stinner7931d9a2011-11-04 00:22:48 +010013375 nonfmt = PyUnicode_Substring(uformat, nonfmtpos, fmtpos);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013376 if (nonfmt == NULL)
13377 goto onError;
13378 r = _PyAccu_Accumulate(&acc, nonfmt);
13379 Py_DECREF(nonfmt);
13380 if (r)
13381 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013382 }
13383 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013384 /* Got a format specifier */
13385 int flags = 0;
13386 Py_ssize_t width = -1;
13387 int prec = -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013388 Py_UCS4 c = '\0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013389 Py_UCS4 fill, sign;
Benjamin Peterson29060642009-01-31 22:14:21 +000013390 int isnumok;
13391 PyObject *v = NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013392 void *pbuf = NULL;
13393 Py_ssize_t pindex, len;
13394 PyObject *signobj = NULL, *fillobj = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013395
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013396 fmtpos++;
13397 if (PyUnicode_READ(fmtkind, fmt, fmtpos) == '(') {
13398 Py_ssize_t keystart;
Benjamin Peterson29060642009-01-31 22:14:21 +000013399 Py_ssize_t keylen;
13400 PyObject *key;
13401 int pcount = 1;
Christian Heimesa612dc02008-02-24 13:08:18 +000013402
Benjamin Peterson29060642009-01-31 22:14:21 +000013403 if (dict == NULL) {
13404 PyErr_SetString(PyExc_TypeError,
13405 "format requires a mapping");
13406 goto onError;
13407 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013408 ++fmtpos;
Benjamin Peterson29060642009-01-31 22:14:21 +000013409 --fmtcnt;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013410 keystart = fmtpos;
Benjamin Peterson29060642009-01-31 22:14:21 +000013411 /* Skip over balanced parentheses */
13412 while (pcount > 0 && --fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013413 if (PyUnicode_READ(fmtkind, fmt, fmtpos) == ')')
Benjamin Peterson29060642009-01-31 22:14:21 +000013414 --pcount;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013415 else if (PyUnicode_READ(fmtkind, fmt, fmtpos) == '(')
Benjamin Peterson29060642009-01-31 22:14:21 +000013416 ++pcount;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013417 fmtpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +000013418 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013419 keylen = fmtpos - keystart - 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000013420 if (fmtcnt < 0 || pcount > 0) {
13421 PyErr_SetString(PyExc_ValueError,
13422 "incomplete format key");
13423 goto onError;
13424 }
Victor Stinner7931d9a2011-11-04 00:22:48 +010013425 key = PyUnicode_Substring(uformat,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013426 keystart, keystart + keylen);
Benjamin Peterson29060642009-01-31 22:14:21 +000013427 if (key == NULL)
13428 goto onError;
13429 if (args_owned) {
13430 Py_DECREF(args);
13431 args_owned = 0;
13432 }
13433 args = PyObject_GetItem(dict, key);
13434 Py_DECREF(key);
13435 if (args == NULL) {
13436 goto onError;
13437 }
13438 args_owned = 1;
13439 arglen = -1;
13440 argidx = -2;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013441 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013442 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013443 switch (c = PyUnicode_READ(fmtkind, fmt, fmtpos++)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013444 case '-': flags |= F_LJUST; continue;
13445 case '+': flags |= F_SIGN; continue;
13446 case ' ': flags |= F_BLANK; continue;
13447 case '#': flags |= F_ALT; continue;
13448 case '0': flags |= F_ZERO; continue;
13449 }
13450 break;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013451 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013452 if (c == '*') {
13453 v = getnextarg(args, arglen, &argidx);
13454 if (v == NULL)
13455 goto onError;
13456 if (!PyLong_Check(v)) {
13457 PyErr_SetString(PyExc_TypeError,
13458 "* wants int");
13459 goto onError;
13460 }
13461 width = PyLong_AsLong(v);
13462 if (width == -1 && PyErr_Occurred())
13463 goto onError;
13464 if (width < 0) {
13465 flags |= F_LJUST;
13466 width = -width;
13467 }
13468 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013469 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013470 }
13471 else if (c >= '0' && c <= '9') {
13472 width = c - '0';
13473 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013474 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013475 if (c < '0' || c > '9')
13476 break;
13477 if ((width*10) / 10 != width) {
13478 PyErr_SetString(PyExc_ValueError,
13479 "width too big");
Benjamin Peterson14339b62009-01-31 16:36:08 +000013480 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +000013481 }
13482 width = width*10 + (c - '0');
13483 }
13484 }
13485 if (c == '.') {
13486 prec = 0;
13487 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013488 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013489 if (c == '*') {
13490 v = getnextarg(args, arglen, &argidx);
13491 if (v == NULL)
13492 goto onError;
13493 if (!PyLong_Check(v)) {
13494 PyErr_SetString(PyExc_TypeError,
13495 "* wants int");
13496 goto onError;
13497 }
13498 prec = PyLong_AsLong(v);
13499 if (prec == -1 && PyErr_Occurred())
13500 goto onError;
13501 if (prec < 0)
13502 prec = 0;
13503 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013504 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013505 }
13506 else if (c >= '0' && c <= '9') {
13507 prec = c - '0';
13508 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013509 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013510 if (c < '0' || c > '9')
13511 break;
13512 if ((prec*10) / 10 != prec) {
13513 PyErr_SetString(PyExc_ValueError,
13514 "prec too big");
13515 goto onError;
13516 }
13517 prec = prec*10 + (c - '0');
13518 }
13519 }
13520 } /* prec */
13521 if (fmtcnt >= 0) {
13522 if (c == 'h' || c == 'l' || c == 'L') {
13523 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013524 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013525 }
13526 }
13527 if (fmtcnt < 0) {
13528 PyErr_SetString(PyExc_ValueError,
13529 "incomplete format");
13530 goto onError;
13531 }
13532 if (c != '%') {
13533 v = getnextarg(args, arglen, &argidx);
13534 if (v == NULL)
13535 goto onError;
13536 }
13537 sign = 0;
13538 fill = ' ';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013539 fillobj = blank;
Benjamin Peterson29060642009-01-31 22:14:21 +000013540 switch (c) {
13541
13542 case '%':
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013543 _PyAccu_Accumulate(&acc, percent);
13544 continue;
Benjamin Peterson29060642009-01-31 22:14:21 +000013545
13546 case 's':
13547 case 'r':
13548 case 'a':
Victor Stinner808fc0a2010-03-22 12:50:40 +000013549 if (PyUnicode_CheckExact(v) && c == 's') {
Benjamin Peterson29060642009-01-31 22:14:21 +000013550 temp = v;
13551 Py_INCREF(temp);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013552 }
13553 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013554 if (c == 's')
13555 temp = PyObject_Str(v);
13556 else if (c == 'r')
13557 temp = PyObject_Repr(v);
13558 else
13559 temp = PyObject_ASCII(v);
13560 if (temp == NULL)
13561 goto onError;
13562 if (PyUnicode_Check(temp))
13563 /* nothing to do */;
13564 else {
13565 Py_DECREF(temp);
13566 PyErr_SetString(PyExc_TypeError,
13567 "%s argument has non-string str()");
13568 goto onError;
13569 }
13570 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013571 if (PyUnicode_READY(temp) == -1) {
13572 Py_CLEAR(temp);
13573 goto onError;
13574 }
13575 pbuf = PyUnicode_DATA(temp);
13576 kind = PyUnicode_KIND(temp);
13577 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013578 if (prec >= 0 && len > prec)
13579 len = prec;
13580 break;
13581
13582 case 'i':
13583 case 'd':
13584 case 'u':
13585 case 'o':
13586 case 'x':
13587 case 'X':
Benjamin Peterson29060642009-01-31 22:14:21 +000013588 isnumok = 0;
13589 if (PyNumber_Check(v)) {
13590 PyObject *iobj=NULL;
13591
13592 if (PyLong_Check(v)) {
13593 iobj = v;
13594 Py_INCREF(iobj);
13595 }
13596 else {
13597 iobj = PyNumber_Long(v);
13598 }
13599 if (iobj!=NULL) {
13600 if (PyLong_Check(iobj)) {
13601 isnumok = 1;
Senthil Kumaran9ebe08d2011-07-03 21:03:16 -070013602 temp = formatlong(iobj, flags, prec, (c == 'i'? 'd': c));
Benjamin Peterson29060642009-01-31 22:14:21 +000013603 Py_DECREF(iobj);
13604 if (!temp)
13605 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013606 if (PyUnicode_READY(temp) == -1) {
13607 Py_CLEAR(temp);
13608 goto onError;
13609 }
13610 pbuf = PyUnicode_DATA(temp);
13611 kind = PyUnicode_KIND(temp);
13612 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013613 sign = 1;
13614 }
13615 else {
13616 Py_DECREF(iobj);
13617 }
13618 }
13619 }
13620 if (!isnumok) {
13621 PyErr_Format(PyExc_TypeError,
13622 "%%%c format: a number is required, "
13623 "not %.200s", (char)c, Py_TYPE(v)->tp_name);
13624 goto onError;
13625 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013626 if (flags & F_ZERO) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013627 fill = '0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013628 fillobj = zero;
13629 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013630 break;
13631
13632 case 'e':
13633 case 'E':
13634 case 'f':
13635 case 'F':
13636 case 'g':
13637 case 'G':
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013638 temp = formatfloat(v, flags, prec, c);
13639 if (!temp)
Benjamin Peterson29060642009-01-31 22:14:21 +000013640 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013641 if (PyUnicode_READY(temp) == -1) {
13642 Py_CLEAR(temp);
13643 goto onError;
13644 }
13645 pbuf = PyUnicode_DATA(temp);
13646 kind = PyUnicode_KIND(temp);
13647 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013648 sign = 1;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013649 if (flags & F_ZERO) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013650 fill = '0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013651 fillobj = zero;
13652 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013653 break;
13654
13655 case 'c':
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013656 {
13657 Py_UCS4 ch = formatchar(v);
13658 if (ch == (Py_UCS4) -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000013659 goto onError;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013660 temp = _PyUnicode_FromUCS4(&ch, 1);
13661 if (temp == NULL)
13662 goto onError;
13663 pbuf = PyUnicode_DATA(temp);
13664 kind = PyUnicode_KIND(temp);
13665 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013666 break;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013667 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013668
13669 default:
13670 PyErr_Format(PyExc_ValueError,
13671 "unsupported format character '%c' (0x%x) "
13672 "at index %zd",
13673 (31<=c && c<=126) ? (char)c : '?',
13674 (int)c,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013675 fmtpos - 1);
Benjamin Peterson29060642009-01-31 22:14:21 +000013676 goto onError;
13677 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013678 /* pbuf is initialized here. */
13679 pindex = 0;
Benjamin Peterson29060642009-01-31 22:14:21 +000013680 if (sign) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013681 if (PyUnicode_READ(kind, pbuf, pindex) == '-') {
13682 signobj = minus;
Benjamin Peterson29060642009-01-31 22:14:21 +000013683 len--;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013684 pindex++;
13685 }
13686 else if (PyUnicode_READ(kind, pbuf, pindex) == '+') {
13687 signobj = plus;
13688 len--;
13689 pindex++;
Benjamin Peterson29060642009-01-31 22:14:21 +000013690 }
13691 else if (flags & F_SIGN)
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013692 signobj = plus;
Benjamin Peterson29060642009-01-31 22:14:21 +000013693 else if (flags & F_BLANK)
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013694 signobj = blank;
Benjamin Peterson29060642009-01-31 22:14:21 +000013695 else
13696 sign = 0;
13697 }
13698 if (width < len)
13699 width = len;
Benjamin Peterson29060642009-01-31 22:14:21 +000013700 if (sign) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013701 if (fill != ' ') {
13702 assert(signobj != NULL);
13703 if (_PyAccu_Accumulate(&acc, signobj))
13704 goto onError;
13705 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013706 if (width > len)
13707 width--;
13708 }
13709 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013710 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013711 assert(PyUnicode_READ(kind, pbuf, pindex + 1) == c);
Benjamin Peterson29060642009-01-31 22:14:21 +000013712 if (fill != ' ') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013713 second = get_latin1_char(
13714 PyUnicode_READ(kind, pbuf, pindex + 1));
13715 pindex += 2;
13716 if (second == NULL ||
13717 _PyAccu_Accumulate(&acc, zero) ||
13718 _PyAccu_Accumulate(&acc, second))
13719 goto onError;
13720 Py_CLEAR(second);
Benjamin Peterson29060642009-01-31 22:14:21 +000013721 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013722 width -= 2;
13723 if (width < 0)
13724 width = 0;
13725 len -= 2;
13726 }
13727 if (width > len && !(flags & F_LJUST)) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013728 assert(fillobj != NULL);
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013729 if (repeat_accumulate(&acc, fillobj, width - len))
13730 goto onError;
13731 width = len;
Benjamin Peterson29060642009-01-31 22:14:21 +000013732 }
13733 if (fill == ' ') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013734 if (sign) {
13735 assert(signobj != NULL);
13736 if (_PyAccu_Accumulate(&acc, signobj))
13737 goto onError;
13738 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013739 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013740 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
13741 assert(PyUnicode_READ(kind, pbuf, pindex+1) == c);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013742 second = get_latin1_char(
13743 PyUnicode_READ(kind, pbuf, pindex + 1));
13744 pindex += 2;
13745 if (second == NULL ||
13746 _PyAccu_Accumulate(&acc, zero) ||
13747 _PyAccu_Accumulate(&acc, second))
13748 goto onError;
13749 Py_CLEAR(second);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013750 }
13751 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013752 /* Copy all characters, preserving len */
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013753 if (temp != NULL) {
13754 assert(pbuf == PyUnicode_DATA(temp));
13755 v = PyUnicode_Substring(temp, pindex, pindex + len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013756 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013757 else {
13758 const char *p = (const char *) pbuf;
13759 assert(pbuf != NULL);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013760 p += kind * pindex;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013761 v = PyUnicode_FromKindAndData(kind, p, len);
13762 }
13763 if (v == NULL)
13764 goto onError;
13765 r = _PyAccu_Accumulate(&acc, v);
13766 Py_DECREF(v);
13767 if (r)
13768 goto onError;
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013769 if (width > len && repeat_accumulate(&acc, blank, width - len))
13770 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +000013771 if (dict && (argidx < arglen) && c != '%') {
13772 PyErr_SetString(PyExc_TypeError,
13773 "not all arguments converted during string formatting");
Benjamin Peterson29060642009-01-31 22:14:21 +000013774 goto onError;
13775 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013776 Py_CLEAR(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013777 } /* '%' */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013778 } /* until end */
13779 if (argidx < arglen && !dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013780 PyErr_SetString(PyExc_TypeError,
13781 "not all arguments converted during string formatting");
13782 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013783 }
13784
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013785 result = _PyAccu_Finish(&acc);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013786 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013787 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013788 }
13789 Py_DECREF(uformat);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013790 Py_XDECREF(temp);
13791 Py_XDECREF(second);
Victor Stinner7931d9a2011-11-04 00:22:48 +010013792 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013793
Benjamin Peterson29060642009-01-31 22:14:21 +000013794 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000013795 Py_DECREF(uformat);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013796 Py_XDECREF(temp);
13797 Py_XDECREF(second);
13798 _PyAccu_Destroy(&acc);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013799 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013800 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013801 }
13802 return NULL;
13803}
13804
Jeremy Hylton938ace62002-07-17 16:30:39 +000013805static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +000013806unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
13807
Tim Peters6d6c1a32001-08-02 04:15:00 +000013808static PyObject *
13809unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
13810{
Benjamin Peterson29060642009-01-31 22:14:21 +000013811 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013812 static char *kwlist[] = {"object", "encoding", "errors", 0};
13813 char *encoding = NULL;
13814 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000013815
Benjamin Peterson14339b62009-01-31 16:36:08 +000013816 if (type != &PyUnicode_Type)
13817 return unicode_subtype_new(type, args, kwds);
13818 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +000013819 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +000013820 return NULL;
Victor Stinner382955f2011-12-11 21:44:00 +010013821 if (x == NULL) {
13822 Py_INCREF(unicode_empty);
13823 return unicode_empty;
13824 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000013825 if (encoding == NULL && errors == NULL)
13826 return PyObject_Str(x);
13827 else
Benjamin Peterson29060642009-01-31 22:14:21 +000013828 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +000013829}
13830
Guido van Rossume023fe02001-08-30 03:12:59 +000013831static PyObject *
13832unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
13833{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013834 PyObject *unicode, *self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013835 Py_ssize_t length, char_size;
13836 int share_wstr, share_utf8;
13837 unsigned int kind;
13838 void *data;
Guido van Rossume023fe02001-08-30 03:12:59 +000013839
Benjamin Peterson14339b62009-01-31 16:36:08 +000013840 assert(PyType_IsSubtype(type, &PyUnicode_Type));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013841
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013842 unicode = unicode_new(&PyUnicode_Type, args, kwds);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013843 if (unicode == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000013844 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020013845 assert(_PyUnicode_CHECK(unicode));
Victor Stinnere06e1452011-10-04 20:52:31 +020013846 if (PyUnicode_READY(unicode))
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013847 return NULL;
13848
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013849 self = type->tp_alloc(type, 0);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013850 if (self == NULL) {
13851 Py_DECREF(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013852 return NULL;
13853 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013854 kind = PyUnicode_KIND(unicode);
13855 length = PyUnicode_GET_LENGTH(unicode);
13856
13857 _PyUnicode_LENGTH(self) = length;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020013858#ifdef Py_DEBUG
13859 _PyUnicode_HASH(self) = -1;
13860#else
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013861 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020013862#endif
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013863 _PyUnicode_STATE(self).interned = 0;
13864 _PyUnicode_STATE(self).kind = kind;
13865 _PyUnicode_STATE(self).compact = 0;
Victor Stinner3cf46372011-10-03 14:42:15 +020013866 _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013867 _PyUnicode_STATE(self).ready = 1;
13868 _PyUnicode_WSTR(self) = NULL;
13869 _PyUnicode_UTF8_LENGTH(self) = 0;
13870 _PyUnicode_UTF8(self) = NULL;
13871 _PyUnicode_WSTR_LENGTH(self) = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +020013872 _PyUnicode_DATA_ANY(self) = NULL;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013873
13874 share_utf8 = 0;
13875 share_wstr = 0;
13876 if (kind == PyUnicode_1BYTE_KIND) {
13877 char_size = 1;
13878 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
13879 share_utf8 = 1;
13880 }
13881 else if (kind == PyUnicode_2BYTE_KIND) {
13882 char_size = 2;
13883 if (sizeof(wchar_t) == 2)
13884 share_wstr = 1;
13885 }
13886 else {
13887 assert(kind == PyUnicode_4BYTE_KIND);
13888 char_size = 4;
13889 if (sizeof(wchar_t) == 4)
13890 share_wstr = 1;
13891 }
13892
13893 /* Ensure we won't overflow the length. */
13894 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
13895 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013896 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013897 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013898 data = PyObject_MALLOC((length + 1) * char_size);
13899 if (data == NULL) {
13900 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013901 goto onError;
13902 }
13903
Victor Stinnerc3c74152011-10-02 20:39:55 +020013904 _PyUnicode_DATA_ANY(self) = data;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013905 if (share_utf8) {
13906 _PyUnicode_UTF8_LENGTH(self) = length;
13907 _PyUnicode_UTF8(self) = data;
13908 }
13909 if (share_wstr) {
13910 _PyUnicode_WSTR_LENGTH(self) = length;
13911 _PyUnicode_WSTR(self) = (wchar_t *)data;
13912 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013913
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013914 Py_MEMCPY(data, PyUnicode_DATA(unicode),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013915 kind * (length + 1));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013916 assert(_PyUnicode_CheckConsistency(self, 1));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020013917#ifdef Py_DEBUG
13918 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
13919#endif
Victor Stinnerdd18d3a2011-10-22 11:08:10 +020013920 Py_DECREF(unicode);
Victor Stinner7931d9a2011-11-04 00:22:48 +010013921 return self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013922
13923onError:
13924 Py_DECREF(unicode);
13925 Py_DECREF(self);
13926 return NULL;
Guido van Rossume023fe02001-08-30 03:12:59 +000013927}
13928
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013929PyDoc_STRVAR(unicode_doc,
Benjamin Peterson29060642009-01-31 22:14:21 +000013930 "str(string[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +000013931\n\
Collin Winterd474ce82007-08-07 19:42:11 +000013932Create a new string object from the given encoded string.\n\
Skip Montanaro35b37a52002-07-26 16:22:46 +000013933encoding defaults to the current default string encoding.\n\
13934errors can be 'strict', 'replace' or 'ignore' and defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +000013935
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013936static PyObject *unicode_iter(PyObject *seq);
13937
Guido van Rossumd57fd912000-03-10 22:53:23 +000013938PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000013939 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Benjamin Peterson14339b62009-01-31 16:36:08 +000013940 "str", /* tp_name */
13941 sizeof(PyUnicodeObject), /* tp_size */
13942 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013943 /* Slots */
Benjamin Peterson14339b62009-01-31 16:36:08 +000013944 (destructor)unicode_dealloc, /* tp_dealloc */
13945 0, /* tp_print */
13946 0, /* tp_getattr */
13947 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000013948 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000013949 unicode_repr, /* tp_repr */
13950 &unicode_as_number, /* tp_as_number */
13951 &unicode_as_sequence, /* tp_as_sequence */
13952 &unicode_as_mapping, /* tp_as_mapping */
13953 (hashfunc) unicode_hash, /* tp_hash*/
13954 0, /* tp_call*/
13955 (reprfunc) unicode_str, /* tp_str */
13956 PyObject_GenericGetAttr, /* tp_getattro */
13957 0, /* tp_setattro */
13958 0, /* tp_as_buffer */
13959 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Benjamin Peterson29060642009-01-31 22:14:21 +000013960 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
Benjamin Peterson14339b62009-01-31 16:36:08 +000013961 unicode_doc, /* tp_doc */
13962 0, /* tp_traverse */
13963 0, /* tp_clear */
13964 PyUnicode_RichCompare, /* tp_richcompare */
13965 0, /* tp_weaklistoffset */
13966 unicode_iter, /* tp_iter */
13967 0, /* tp_iternext */
13968 unicode_methods, /* tp_methods */
13969 0, /* tp_members */
13970 0, /* tp_getset */
13971 &PyBaseObject_Type, /* tp_base */
13972 0, /* tp_dict */
13973 0, /* tp_descr_get */
13974 0, /* tp_descr_set */
13975 0, /* tp_dictoffset */
13976 0, /* tp_init */
13977 0, /* tp_alloc */
13978 unicode_new, /* tp_new */
13979 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013980};
13981
13982/* Initialize the Unicode implementation */
13983
Victor Stinner3a50e702011-10-18 21:21:00 +020013984int _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013985{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013986 int i;
13987
Thomas Wouters477c8d52006-05-27 19:21:47 +000013988 /* XXX - move this array to unicodectype.c ? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013989 Py_UCS2 linebreak[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +000013990 0x000A, /* LINE FEED */
13991 0x000D, /* CARRIAGE RETURN */
13992 0x001C, /* FILE SEPARATOR */
13993 0x001D, /* GROUP SEPARATOR */
13994 0x001E, /* RECORD SEPARATOR */
13995 0x0085, /* NEXT LINE */
13996 0x2028, /* LINE SEPARATOR */
13997 0x2029, /* PARAGRAPH SEPARATOR */
13998 };
13999
Fred Drakee4315f52000-05-09 19:53:39 +000014000 /* Init the implementation */
Victor Stinnera464fc12011-10-02 20:39:30 +020014001 unicode_empty = PyUnicode_New(0, 0);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014002 if (!unicode_empty)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014003 Py_FatalError("Can't create empty string");
Victor Stinnerd3df8ab2011-11-22 01:22:34 +010014004 assert(_PyUnicode_CheckConsistency(unicode_empty, 1));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014005
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014006 for (i = 0; i < 256; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +000014007 unicode_latin1[i] = NULL;
Guido van Rossumcacfc072002-05-24 19:01:59 +000014008 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000014009 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +000014010
14011 /* initialize the linebreak bloom filter */
14012 bloom_linebreak = make_bloom_mask(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014013 PyUnicode_2BYTE_KIND, linebreak,
Victor Stinner63941882011-09-29 00:42:28 +020014014 Py_ARRAY_LENGTH(linebreak));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014015
14016 PyType_Ready(&EncodingMapType);
Victor Stinner3a50e702011-10-18 21:21:00 +020014017
14018#ifdef HAVE_MBCS
14019 winver.dwOSVersionInfoSize = sizeof(winver);
14020 if (!GetVersionEx((OSVERSIONINFO*)&winver)) {
14021 PyErr_SetFromWindowsErr(0);
14022 return -1;
14023 }
14024#endif
14025 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014026}
14027
14028/* Finalize the Unicode implementation */
14029
Christian Heimesa156e092008-02-16 07:38:31 +000014030int
14031PyUnicode_ClearFreeList(void)
14032{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014033 return 0;
Christian Heimesa156e092008-02-16 07:38:31 +000014034}
14035
Guido van Rossumd57fd912000-03-10 22:53:23 +000014036void
Thomas Wouters78890102000-07-22 19:25:51 +000014037_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014038{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014039 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014040
Guido van Rossum4ae8ef82000-10-03 18:09:04 +000014041 Py_XDECREF(unicode_empty);
14042 unicode_empty = NULL;
Barry Warsaw5b4c2282000-10-03 20:45:26 +000014043
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014044 for (i = 0; i < 256; i++) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014045 if (unicode_latin1[i]) {
14046 Py_DECREF(unicode_latin1[i]);
14047 unicode_latin1[i] = NULL;
14048 }
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014049 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020014050 _PyUnicode_ClearStaticStrings();
Christian Heimesa156e092008-02-16 07:38:31 +000014051 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +000014052}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000014053
Walter Dörwald16807132007-05-25 13:52:07 +000014054void
14055PyUnicode_InternInPlace(PyObject **p)
14056{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014057 register PyObject *s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014058 PyObject *t;
Victor Stinner4fae54c2011-10-03 02:01:52 +020014059#ifdef Py_DEBUG
14060 assert(s != NULL);
14061 assert(_PyUnicode_CHECK(s));
14062#else
Benjamin Peterson14339b62009-01-31 16:36:08 +000014063 if (s == NULL || !PyUnicode_Check(s))
Victor Stinner4fae54c2011-10-03 02:01:52 +020014064 return;
14065#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000014066 /* If it's a subclass, we don't really know what putting
14067 it in the interned dict might do. */
14068 if (!PyUnicode_CheckExact(s))
14069 return;
14070 if (PyUnicode_CHECK_INTERNED(s))
14071 return;
14072 if (interned == NULL) {
14073 interned = PyDict_New();
14074 if (interned == NULL) {
14075 PyErr_Clear(); /* Don't leave an exception */
14076 return;
14077 }
14078 }
14079 /* It might be that the GetItem call fails even
14080 though the key is present in the dictionary,
14081 namely when this happens during a stack overflow. */
14082 Py_ALLOW_RECURSION
Victor Stinner7931d9a2011-11-04 00:22:48 +010014083 t = PyDict_GetItem(interned, s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014084 Py_END_ALLOW_RECURSION
Martin v. Löwis5b222132007-06-10 09:51:05 +000014085
Benjamin Peterson29060642009-01-31 22:14:21 +000014086 if (t) {
14087 Py_INCREF(t);
14088 Py_DECREF(*p);
14089 *p = t;
14090 return;
14091 }
Walter Dörwald16807132007-05-25 13:52:07 +000014092
Benjamin Peterson14339b62009-01-31 16:36:08 +000014093 PyThreadState_GET()->recursion_critical = 1;
Victor Stinner7931d9a2011-11-04 00:22:48 +010014094 if (PyDict_SetItem(interned, s, s) < 0) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014095 PyErr_Clear();
14096 PyThreadState_GET()->recursion_critical = 0;
14097 return;
14098 }
14099 PyThreadState_GET()->recursion_critical = 0;
14100 /* The two references in interned are not counted by refcnt.
14101 The deallocator will take care of this */
14102 Py_REFCNT(s) -= 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014103 _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000014104}
14105
14106void
14107PyUnicode_InternImmortal(PyObject **p)
14108{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014109 PyUnicode_InternInPlace(p);
14110 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
Victor Stinneraf9e4b82011-10-23 20:07:00 +020014111 _PyUnicode_STATE(*p).interned = SSTATE_INTERNED_IMMORTAL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014112 Py_INCREF(*p);
14113 }
Walter Dörwald16807132007-05-25 13:52:07 +000014114}
14115
14116PyObject *
14117PyUnicode_InternFromString(const char *cp)
14118{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014119 PyObject *s = PyUnicode_FromString(cp);
14120 if (s == NULL)
14121 return NULL;
14122 PyUnicode_InternInPlace(&s);
14123 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000014124}
14125
Alexander Belopolsky40018472011-02-26 01:02:56 +000014126void
14127_Py_ReleaseInternedUnicodeStrings(void)
Walter Dörwald16807132007-05-25 13:52:07 +000014128{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014129 PyObject *keys;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014130 PyObject *s;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014131 Py_ssize_t i, n;
14132 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000014133
Benjamin Peterson14339b62009-01-31 16:36:08 +000014134 if (interned == NULL || !PyDict_Check(interned))
14135 return;
14136 keys = PyDict_Keys(interned);
14137 if (keys == NULL || !PyList_Check(keys)) {
14138 PyErr_Clear();
14139 return;
14140 }
Walter Dörwald16807132007-05-25 13:52:07 +000014141
Benjamin Peterson14339b62009-01-31 16:36:08 +000014142 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
14143 detector, interned unicode strings are not forcibly deallocated;
14144 rather, we give them their stolen references back, and then clear
14145 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000014146
Benjamin Peterson14339b62009-01-31 16:36:08 +000014147 n = PyList_GET_SIZE(keys);
14148 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000014149 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014150 for (i = 0; i < n; i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014151 s = PyList_GET_ITEM(keys, i);
Victor Stinner6b56a7f2011-10-04 20:04:52 +020014152 if (PyUnicode_READY(s) == -1) {
14153 assert(0 && "could not ready string");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014154 fprintf(stderr, "could not ready string\n");
Victor Stinner6b56a7f2011-10-04 20:04:52 +020014155 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014156 switch (PyUnicode_CHECK_INTERNED(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014157 case SSTATE_NOT_INTERNED:
14158 /* XXX Shouldn't happen */
14159 break;
14160 case SSTATE_INTERNED_IMMORTAL:
14161 Py_REFCNT(s) += 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014162 immortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014163 break;
14164 case SSTATE_INTERNED_MORTAL:
14165 Py_REFCNT(s) += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014166 mortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014167 break;
14168 default:
14169 Py_FatalError("Inconsistent interned string state.");
14170 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014171 _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014172 }
14173 fprintf(stderr, "total size of all interned strings: "
14174 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
14175 "mortal/immortal\n", mortal_size, immortal_size);
14176 Py_DECREF(keys);
14177 PyDict_Clear(interned);
14178 Py_DECREF(interned);
14179 interned = NULL;
Walter Dörwald16807132007-05-25 13:52:07 +000014180}
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014181
14182
14183/********************* Unicode Iterator **************************/
14184
14185typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014186 PyObject_HEAD
14187 Py_ssize_t it_index;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014188 PyObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014189} unicodeiterobject;
14190
14191static void
14192unicodeiter_dealloc(unicodeiterobject *it)
14193{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014194 _PyObject_GC_UNTRACK(it);
14195 Py_XDECREF(it->it_seq);
14196 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014197}
14198
14199static int
14200unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
14201{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014202 Py_VISIT(it->it_seq);
14203 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014204}
14205
14206static PyObject *
14207unicodeiter_next(unicodeiterobject *it)
14208{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014209 PyObject *seq, *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014210
Benjamin Peterson14339b62009-01-31 16:36:08 +000014211 assert(it != NULL);
14212 seq = it->it_seq;
14213 if (seq == NULL)
14214 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020014215 assert(_PyUnicode_CHECK(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014216
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014217 if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
14218 int kind = PyUnicode_KIND(seq);
14219 void *data = PyUnicode_DATA(seq);
14220 Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
14221 item = PyUnicode_FromOrdinal(chr);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014222 if (item != NULL)
14223 ++it->it_index;
14224 return item;
14225 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014226
Benjamin Peterson14339b62009-01-31 16:36:08 +000014227 Py_DECREF(seq);
14228 it->it_seq = NULL;
14229 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014230}
14231
14232static PyObject *
14233unicodeiter_len(unicodeiterobject *it)
14234{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014235 Py_ssize_t len = 0;
14236 if (it->it_seq)
Victor Stinnerc4f281e2011-10-11 22:11:42 +020014237 len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014238 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014239}
14240
14241PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
14242
14243static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014244 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000014245 length_hint_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000014246 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014247};
14248
14249PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014250 PyVarObject_HEAD_INIT(&PyType_Type, 0)
14251 "str_iterator", /* tp_name */
14252 sizeof(unicodeiterobject), /* tp_basicsize */
14253 0, /* tp_itemsize */
14254 /* methods */
14255 (destructor)unicodeiter_dealloc, /* tp_dealloc */
14256 0, /* tp_print */
14257 0, /* tp_getattr */
14258 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000014259 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014260 0, /* tp_repr */
14261 0, /* tp_as_number */
14262 0, /* tp_as_sequence */
14263 0, /* tp_as_mapping */
14264 0, /* tp_hash */
14265 0, /* tp_call */
14266 0, /* tp_str */
14267 PyObject_GenericGetAttr, /* tp_getattro */
14268 0, /* tp_setattro */
14269 0, /* tp_as_buffer */
14270 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
14271 0, /* tp_doc */
14272 (traverseproc)unicodeiter_traverse, /* tp_traverse */
14273 0, /* tp_clear */
14274 0, /* tp_richcompare */
14275 0, /* tp_weaklistoffset */
14276 PyObject_SelfIter, /* tp_iter */
14277 (iternextfunc)unicodeiter_next, /* tp_iternext */
14278 unicodeiter_methods, /* tp_methods */
14279 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014280};
14281
14282static PyObject *
14283unicode_iter(PyObject *seq)
14284{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014285 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014286
Benjamin Peterson14339b62009-01-31 16:36:08 +000014287 if (!PyUnicode_Check(seq)) {
14288 PyErr_BadInternalCall();
14289 return NULL;
14290 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014291 if (PyUnicode_READY(seq) == -1)
14292 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014293 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
14294 if (it == NULL)
14295 return NULL;
14296 it->it_index = 0;
14297 Py_INCREF(seq);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014298 it->it_seq = seq;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014299 _PyObject_GC_TRACK(it);
14300 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014301}
14302
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010014303
14304size_t
14305Py_UNICODE_strlen(const Py_UNICODE *u)
14306{
14307 int res = 0;
14308 while(*u++)
14309 res++;
14310 return res;
14311}
14312
14313Py_UNICODE*
14314Py_UNICODE_strcpy(Py_UNICODE *s1, const Py_UNICODE *s2)
14315{
14316 Py_UNICODE *u = s1;
14317 while ((*u++ = *s2++));
14318 return s1;
14319}
14320
14321Py_UNICODE*
14322Py_UNICODE_strncpy(Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
14323{
14324 Py_UNICODE *u = s1;
14325 while ((*u++ = *s2++))
14326 if (n-- == 0)
14327 break;
14328 return s1;
14329}
14330
14331Py_UNICODE*
14332Py_UNICODE_strcat(Py_UNICODE *s1, const Py_UNICODE *s2)
14333{
14334 Py_UNICODE *u1 = s1;
14335 u1 += Py_UNICODE_strlen(u1);
14336 Py_UNICODE_strcpy(u1, s2);
14337 return s1;
14338}
14339
14340int
14341Py_UNICODE_strcmp(const Py_UNICODE *s1, const Py_UNICODE *s2)
14342{
14343 while (*s1 && *s2 && *s1 == *s2)
14344 s1++, s2++;
14345 if (*s1 && *s2)
14346 return (*s1 < *s2) ? -1 : +1;
14347 if (*s1)
14348 return 1;
14349 if (*s2)
14350 return -1;
14351 return 0;
14352}
14353
14354int
14355Py_UNICODE_strncmp(const Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
14356{
14357 register Py_UNICODE u1, u2;
14358 for (; n != 0; n--) {
14359 u1 = *s1;
14360 u2 = *s2;
14361 if (u1 != u2)
14362 return (u1 < u2) ? -1 : +1;
14363 if (u1 == '\0')
14364 return 0;
14365 s1++;
14366 s2++;
14367 }
14368 return 0;
14369}
14370
14371Py_UNICODE*
14372Py_UNICODE_strchr(const Py_UNICODE *s, Py_UNICODE c)
14373{
14374 const Py_UNICODE *p;
14375 for (p = s; *p; p++)
14376 if (*p == c)
14377 return (Py_UNICODE*)p;
14378 return NULL;
14379}
14380
14381Py_UNICODE*
14382Py_UNICODE_strrchr(const Py_UNICODE *s, Py_UNICODE c)
14383{
14384 const Py_UNICODE *p;
14385 p = s + Py_UNICODE_strlen(s);
14386 while (p != s) {
14387 p--;
14388 if (*p == c)
14389 return (Py_UNICODE*)p;
14390 }
14391 return NULL;
14392}
Victor Stinner331ea922010-08-10 16:37:20 +000014393
Victor Stinner71133ff2010-09-01 23:43:53 +000014394Py_UNICODE*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014395PyUnicode_AsUnicodeCopy(PyObject *unicode)
Victor Stinner71133ff2010-09-01 23:43:53 +000014396{
Victor Stinner577db2c2011-10-11 22:12:48 +020014397 Py_UNICODE *u, *copy;
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014398 Py_ssize_t len, size;
Victor Stinner71133ff2010-09-01 23:43:53 +000014399
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014400 if (!PyUnicode_Check(unicode)) {
14401 PyErr_BadArgument();
14402 return NULL;
14403 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014404 u = PyUnicode_AsUnicodeAndSize(unicode, &len);
Victor Stinner577db2c2011-10-11 22:12:48 +020014405 if (u == NULL)
14406 return NULL;
Victor Stinner71133ff2010-09-01 23:43:53 +000014407 /* Ensure we won't overflow the size. */
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014408 if (len > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
Victor Stinner71133ff2010-09-01 23:43:53 +000014409 PyErr_NoMemory();
14410 return NULL;
14411 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014412 size = len + 1; /* copy the null character */
Victor Stinner71133ff2010-09-01 23:43:53 +000014413 size *= sizeof(Py_UNICODE);
14414 copy = PyMem_Malloc(size);
14415 if (copy == NULL) {
14416 PyErr_NoMemory();
14417 return NULL;
14418 }
Victor Stinner577db2c2011-10-11 22:12:48 +020014419 memcpy(copy, u, size);
Victor Stinner71133ff2010-09-01 23:43:53 +000014420 return copy;
14421}
Martin v. Löwis5b222132007-06-10 09:51:05 +000014422
Georg Brandl66c221e2010-10-14 07:04:07 +000014423/* A _string module, to export formatter_parser and formatter_field_name_split
14424 to the string.Formatter class implemented in Python. */
14425
14426static PyMethodDef _string_methods[] = {
14427 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
14428 METH_O, PyDoc_STR("split the argument as a field name")},
14429 {"formatter_parser", (PyCFunction) formatter_parser,
14430 METH_O, PyDoc_STR("parse the argument as a format string")},
14431 {NULL, NULL}
14432};
14433
14434static struct PyModuleDef _string_module = {
14435 PyModuleDef_HEAD_INIT,
14436 "_string",
14437 PyDoc_STR("string helper module"),
14438 0,
14439 _string_methods,
14440 NULL,
14441 NULL,
14442 NULL,
14443 NULL
14444};
14445
14446PyMODINIT_FUNC
14447PyInit__string(void)
14448{
14449 return PyModule_Create(&_string_module);
14450}
14451
14452
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000014453#ifdef __cplusplus
14454}
14455#endif