blob: ab0d9fa1f8706471dc84a27aa0ebaf03faed6eb0 [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;
Victor Stinnerab870212011-12-17 22:39:43 +01004835 return unicode_fromascii((const unsigned char *)s, size);
Victor Stinner785938e2011-12-11 20:09:03 +01004836 }
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) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010288 /* same length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010289 if (len1 == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010290 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010291 if (len1 == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010292 /* replace characters */
Victor Stinner49a0a212011-10-12 23:46:10 +020010293 Py_UCS4 u1, u2;
10294 int rkind;
Victor Stinnerf6441102011-12-18 02:43:08 +010010295 Py_ssize_t index, pos;
10296 char *src;
10297
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010298 u1 = PyUnicode_READ_CHAR(str1, 0);
Victor Stinnerf6441102011-12-18 02:43:08 +010010299 pos = findchar(sbuf, PyUnicode_KIND(self), slen, u1, 1);
10300 if (pos < 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010301 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010302 u2 = PyUnicode_READ_CHAR(str2, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010303 u = PyUnicode_New(slen, maxchar);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010304 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010305 goto error;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020010306 copy_characters(u, 0, self, 0, slen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010307 rkind = PyUnicode_KIND(u);
Victor Stinnerf6441102011-12-18 02:43:08 +010010308
10309 PyUnicode_WRITE(rkind, PyUnicode_DATA(u), pos, u2);
10310 index = 0;
10311 src = sbuf;
10312 while (--maxcount)
10313 {
10314 pos++;
10315 src += pos * PyUnicode_KIND(self);
10316 slen -= pos;
10317 index += pos;
10318 pos = findchar(src, PyUnicode_KIND(self), slen, u1, 1);
10319 if (pos < 0)
10320 break;
10321 PyUnicode_WRITE(rkind, PyUnicode_DATA(u), index + pos, u2);
10322 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010323 }
10324 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010325 int rkind = skind;
10326 char *res;
Victor Stinnerf6441102011-12-18 02:43:08 +010010327 Py_ssize_t i;
Victor Stinner25a4b292011-10-06 12:31:55 +020010328
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010329 if (kind1 < rkind) {
10330 /* widen substring */
10331 buf1 = _PyUnicode_AsKind(str1, rkind);
10332 if (!buf1) goto error;
10333 release1 = 1;
10334 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010335 i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010336 if (i < 0)
10337 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010338 if (rkind > kind2) {
10339 /* widen replacement */
10340 buf2 = _PyUnicode_AsKind(str2, rkind);
10341 if (!buf2) goto error;
10342 release2 = 1;
10343 }
10344 else if (rkind < kind2) {
10345 /* widen self and buf1 */
10346 rkind = kind2;
10347 if (release1) PyMem_Free(buf1);
10348 sbuf = _PyUnicode_AsKind(self, rkind);
10349 if (!sbuf) goto error;
10350 srelease = 1;
10351 buf1 = _PyUnicode_AsKind(str1, rkind);
10352 if (!buf1) goto error;
10353 release1 = 1;
10354 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010355 u = PyUnicode_New(slen, maxchar);
10356 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010357 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010358 assert(PyUnicode_KIND(u) == rkind);
10359 res = PyUnicode_DATA(u);
Victor Stinner25a4b292011-10-06 12:31:55 +020010360
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010361 memcpy(res, sbuf, rkind * slen);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010362 /* change everything in-place, starting with this one */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010363 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010364 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010365 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010366 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010367
10368 while ( --maxcount > 0) {
Victor Stinnerc3cec782011-10-05 21:24:08 +020010369 i = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010370 sbuf+rkind*i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010371 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010372 if (i == -1)
10373 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010374 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010375 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010376 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010377 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010378 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010379 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010380 }
10381 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010382 Py_ssize_t n, i, j, ires;
10383 Py_ssize_t product, new_size;
10384 int rkind = skind;
10385 char *res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010386
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010387 if (kind1 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010388 /* widen substring */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010389 buf1 = _PyUnicode_AsKind(str1, rkind);
10390 if (!buf1) goto error;
10391 release1 = 1;
10392 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010393 n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010394 if (n == 0)
10395 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010396 if (kind2 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010397 /* widen replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010398 buf2 = _PyUnicode_AsKind(str2, rkind);
10399 if (!buf2) goto error;
10400 release2 = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010401 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010402 else if (kind2 > rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010403 /* widen self and buf1 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010404 rkind = kind2;
10405 sbuf = _PyUnicode_AsKind(self, rkind);
10406 if (!sbuf) goto error;
10407 srelease = 1;
10408 if (release1) PyMem_Free(buf1);
10409 buf1 = _PyUnicode_AsKind(str1, rkind);
10410 if (!buf1) goto error;
10411 release1 = 1;
10412 }
10413 /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
10414 PyUnicode_GET_LENGTH(str1))); */
10415 product = n * (len2-len1);
10416 if ((product / (len2-len1)) != n) {
10417 PyErr_SetString(PyExc_OverflowError,
10418 "replace string is too long");
10419 goto error;
10420 }
10421 new_size = slen + product;
Victor Stinner49a0a212011-10-12 23:46:10 +020010422 if (new_size == 0) {
10423 Py_INCREF(unicode_empty);
10424 u = unicode_empty;
10425 goto done;
10426 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010427 if (new_size < 0 || new_size > (PY_SSIZE_T_MAX >> (rkind-1))) {
10428 PyErr_SetString(PyExc_OverflowError,
10429 "replace string is too long");
10430 goto error;
10431 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010432 u = PyUnicode_New(new_size, maxchar);
10433 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010434 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010435 assert(PyUnicode_KIND(u) == rkind);
10436 res = PyUnicode_DATA(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010437 ires = i = 0;
10438 if (len1 > 0) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010439 while (n-- > 0) {
10440 /* look for next match */
Victor Stinnerc3cec782011-10-05 21:24:08 +020010441 j = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010442 sbuf + rkind * i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010443 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010444 if (j == -1)
10445 break;
10446 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010447 /* copy unchanged part [i:j] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010448 memcpy(res + rkind * ires,
10449 sbuf + rkind * i,
10450 rkind * (j-i));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010451 ires += j - i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010452 }
10453 /* copy substitution string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010454 if (len2 > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010455 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010456 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010457 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010458 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010459 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010460 i = j + len1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010461 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010462 if (i < slen)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010463 /* copy tail [i:] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010464 memcpy(res + rkind * ires,
10465 sbuf + rkind * i,
10466 rkind * (slen-i));
Victor Stinner49a0a212011-10-12 23:46:10 +020010467 }
10468 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010469 /* interleave */
10470 while (n > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010471 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010472 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010473 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010474 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010475 if (--n <= 0)
10476 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010477 memcpy(res + rkind * ires,
10478 sbuf + rkind * i,
10479 rkind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010480 ires++;
10481 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010482 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010483 memcpy(res + rkind * ires,
10484 sbuf + rkind * i,
10485 rkind * (slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +000010486 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010487 }
10488
10489 if (mayshrink) {
Victor Stinner25a4b292011-10-06 12:31:55 +020010490 unicode_adjust_maxchar(&u);
10491 if (u == NULL)
10492 goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010493 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010494
10495 done:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010496 if (srelease)
10497 PyMem_FREE(sbuf);
10498 if (release1)
10499 PyMem_FREE(buf1);
10500 if (release2)
10501 PyMem_FREE(buf2);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010502 assert(_PyUnicode_CheckConsistency(u, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010503 return u;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010504
Benjamin Peterson29060642009-01-31 22:14:21 +000010505 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +000010506 /* nothing to replace; return original string (when possible) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010507 if (srelease)
10508 PyMem_FREE(sbuf);
10509 if (release1)
10510 PyMem_FREE(buf1);
10511 if (release2)
10512 PyMem_FREE(buf2);
Victor Stinnerc4b49542011-12-11 22:44:26 +010010513 return unicode_result_unchanged(self);
10514
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010515 error:
10516 if (srelease && sbuf)
10517 PyMem_FREE(sbuf);
10518 if (release1 && buf1)
10519 PyMem_FREE(buf1);
10520 if (release2 && buf2)
10521 PyMem_FREE(buf2);
10522 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010523}
10524
10525/* --- Unicode Object Methods --------------------------------------------- */
10526
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010527PyDoc_STRVAR(title__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010528 "S.title() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010529\n\
10530Return a titlecased version of S, i.e. words start with title case\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010531characters, all remaining cased characters have lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010532
10533static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010534unicode_title(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010535{
Guido van Rossumd57fd912000-03-10 22:53:23 +000010536 return fixup(self, fixtitle);
10537}
10538
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010539PyDoc_STRVAR(capitalize__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010540 "S.capitalize() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010541\n\
10542Return a capitalized version of S, i.e. make the first character\n\
Senthil Kumarane51ee8a2010-07-05 12:00:56 +000010543have upper case and the rest lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010544
10545static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010546unicode_capitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010547{
Guido van Rossumd57fd912000-03-10 22:53:23 +000010548 return fixup(self, fixcapitalize);
10549}
10550
10551#if 0
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010552PyDoc_STRVAR(capwords__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010553 "S.capwords() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010554\n\
10555Apply .capitalize() to all words in S and return the result with\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010556normalized whitespace (all whitespace strings are replaced by ' ').");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010557
10558static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010559unicode_capwords(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010560{
10561 PyObject *list;
10562 PyObject *item;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010563 Py_ssize_t i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010564
Guido van Rossumd57fd912000-03-10 22:53:23 +000010565 /* Split into words */
10566 list = split(self, NULL, -1);
10567 if (!list)
10568 return NULL;
10569
10570 /* Capitalize each word */
10571 for (i = 0; i < PyList_GET_SIZE(list); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010572 item = fixup(PyList_GET_ITEM(list, i),
Benjamin Peterson29060642009-01-31 22:14:21 +000010573 fixcapitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010574 if (item == NULL)
10575 goto onError;
10576 Py_DECREF(PyList_GET_ITEM(list, i));
10577 PyList_SET_ITEM(list, i, item);
10578 }
10579
10580 /* Join the words to form a new string */
10581 item = PyUnicode_Join(NULL, list);
10582
Benjamin Peterson29060642009-01-31 22:14:21 +000010583 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000010584 Py_DECREF(list);
Victor Stinner7931d9a2011-11-04 00:22:48 +010010585 return item;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010586}
10587#endif
10588
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010589/* Argument converter. Coerces to a single unicode character */
10590
10591static int
10592convert_uc(PyObject *obj, void *addr)
10593{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010594 Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010595 PyObject *uniobj;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010596
Benjamin Peterson14339b62009-01-31 16:36:08 +000010597 uniobj = PyUnicode_FromObject(obj);
10598 if (uniobj == NULL) {
10599 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010600 "The fill character cannot be converted to Unicode");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010601 return 0;
10602 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010603 if (PyUnicode_GET_LENGTH(uniobj) != 1) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010604 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010605 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010606 Py_DECREF(uniobj);
10607 return 0;
10608 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010609 *fillcharloc = PyUnicode_READ_CHAR(uniobj, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010610 Py_DECREF(uniobj);
10611 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010612}
10613
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010614PyDoc_STRVAR(center__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010615 "S.center(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010616\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010617Return S centered in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010618done using the specified fill character (default is a space)");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010619
10620static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010621unicode_center(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010622{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010623 Py_ssize_t marg, left;
10624 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010625 Py_UCS4 fillchar = ' ';
10626
Victor Stinnere9a29352011-10-01 02:14:59 +020010627 if (!PyArg_ParseTuple(args, "n|O&:center", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010628 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010629
Victor Stinnerc4b49542011-12-11 22:44:26 +010010630 if (PyUnicode_READY(self) < 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010631 return NULL;
10632
Victor Stinnerc4b49542011-12-11 22:44:26 +010010633 if (PyUnicode_GET_LENGTH(self) >= width)
10634 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010635
Victor Stinnerc4b49542011-12-11 22:44:26 +010010636 marg = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010637 left = marg / 2 + (marg & width & 1);
10638
Victor Stinner9310abb2011-10-05 00:59:23 +020010639 return pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010640}
10641
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010642/* This function assumes that str1 and str2 are readied by the caller. */
10643
Marc-André Lemburge5034372000-08-08 08:04:29 +000010644static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010645unicode_compare(PyObject *str1, PyObject *str2)
Marc-André Lemburge5034372000-08-08 08:04:29 +000010646{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010647 int kind1, kind2;
10648 void *data1, *data2;
10649 Py_ssize_t len1, len2, i;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010650
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010651 kind1 = PyUnicode_KIND(str1);
10652 kind2 = PyUnicode_KIND(str2);
10653 data1 = PyUnicode_DATA(str1);
10654 data2 = PyUnicode_DATA(str2);
10655 len1 = PyUnicode_GET_LENGTH(str1);
10656 len2 = PyUnicode_GET_LENGTH(str2);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010657
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010658 for (i = 0; i < len1 && i < len2; ++i) {
10659 Py_UCS4 c1, c2;
10660 c1 = PyUnicode_READ(kind1, data1, i);
10661 c2 = PyUnicode_READ(kind2, data2, i);
Fredrik Lundh45714e92001-06-26 16:39:36 +000010662
10663 if (c1 != c2)
10664 return (c1 < c2) ? -1 : 1;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010665 }
10666
10667 return (len1 < len2) ? -1 : (len1 != len2);
10668}
10669
Alexander Belopolsky40018472011-02-26 01:02:56 +000010670int
10671PyUnicode_Compare(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010672{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010673 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10674 if (PyUnicode_READY(left) == -1 ||
10675 PyUnicode_READY(right) == -1)
10676 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010677 return unicode_compare(left, right);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010678 }
Guido van Rossum09dc34f2007-05-04 04:17:33 +000010679 PyErr_Format(PyExc_TypeError,
10680 "Can't compare %.100s and %.100s",
10681 left->ob_type->tp_name,
10682 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010683 return -1;
10684}
10685
Martin v. Löwis5b222132007-06-10 09:51:05 +000010686int
10687PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
10688{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010689 Py_ssize_t i;
10690 int kind;
10691 void *data;
10692 Py_UCS4 chr;
10693
Victor Stinner910337b2011-10-03 03:20:16 +020010694 assert(_PyUnicode_CHECK(uni));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010695 if (PyUnicode_READY(uni) == -1)
10696 return -1;
10697 kind = PyUnicode_KIND(uni);
10698 data = PyUnicode_DATA(uni);
Martin v. Löwis5b222132007-06-10 09:51:05 +000010699 /* Compare Unicode string and source character set string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010700 for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
10701 if (chr != str[i])
10702 return (chr < (unsigned char)(str[i])) ? -1 : 1;
Benjamin Peterson8667a9b2010-01-09 21:45:28 +000010703 /* This check keeps Python strings that end in '\0' from comparing equal
10704 to C strings identical up to that point. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010705 if (PyUnicode_GET_LENGTH(uni) != i || chr)
Benjamin Peterson29060642009-01-31 22:14:21 +000010706 return 1; /* uni is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010707 if (str[i])
Benjamin Peterson29060642009-01-31 22:14:21 +000010708 return -1; /* str is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010709 return 0;
10710}
10711
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010712
Benjamin Peterson29060642009-01-31 22:14:21 +000010713#define TEST_COND(cond) \
Benjamin Peterson14339b62009-01-31 16:36:08 +000010714 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010715
Alexander Belopolsky40018472011-02-26 01:02:56 +000010716PyObject *
10717PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010718{
10719 int result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010720
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010721 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10722 PyObject *v;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010723 if (PyUnicode_READY(left) == -1 ||
10724 PyUnicode_READY(right) == -1)
10725 return NULL;
10726 if (PyUnicode_GET_LENGTH(left) != PyUnicode_GET_LENGTH(right) ||
10727 PyUnicode_KIND(left) != PyUnicode_KIND(right)) {
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010728 if (op == Py_EQ) {
10729 Py_INCREF(Py_False);
10730 return Py_False;
10731 }
10732 if (op == Py_NE) {
10733 Py_INCREF(Py_True);
10734 return Py_True;
10735 }
10736 }
10737 if (left == right)
10738 result = 0;
10739 else
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010740 result = unicode_compare(left, right);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010741
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010742 /* Convert the return value to a Boolean */
10743 switch (op) {
10744 case Py_EQ:
10745 v = TEST_COND(result == 0);
10746 break;
10747 case Py_NE:
10748 v = TEST_COND(result != 0);
10749 break;
10750 case Py_LE:
10751 v = TEST_COND(result <= 0);
10752 break;
10753 case Py_GE:
10754 v = TEST_COND(result >= 0);
10755 break;
10756 case Py_LT:
10757 v = TEST_COND(result == -1);
10758 break;
10759 case Py_GT:
10760 v = TEST_COND(result == 1);
10761 break;
10762 default:
10763 PyErr_BadArgument();
10764 return NULL;
10765 }
10766 Py_INCREF(v);
10767 return v;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010768 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000010769
Brian Curtindfc80e32011-08-10 20:28:54 -050010770 Py_RETURN_NOTIMPLEMENTED;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010771}
10772
Alexander Belopolsky40018472011-02-26 01:02:56 +000010773int
10774PyUnicode_Contains(PyObject *container, PyObject *element)
Guido van Rossum403d68b2000-03-13 15:55:09 +000010775{
Thomas Wouters477c8d52006-05-27 19:21:47 +000010776 PyObject *str, *sub;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010777 int kind1, kind2, kind;
10778 void *buf1, *buf2;
10779 Py_ssize_t len1, len2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010780 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010781
10782 /* Coerce the two arguments */
Thomas Wouters477c8d52006-05-27 19:21:47 +000010783 sub = PyUnicode_FromObject(element);
10784 if (!sub) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010785 PyErr_Format(PyExc_TypeError,
10786 "'in <string>' requires string as left operand, not %s",
10787 element->ob_type->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010788 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010789 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010790 if (PyUnicode_READY(sub) == -1)
10791 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010792
Thomas Wouters477c8d52006-05-27 19:21:47 +000010793 str = PyUnicode_FromObject(container);
Victor Stinnere9a29352011-10-01 02:14:59 +020010794 if (!str || PyUnicode_READY(str) == -1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010795 Py_DECREF(sub);
10796 return -1;
10797 }
10798
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010799 kind1 = PyUnicode_KIND(str);
10800 kind2 = PyUnicode_KIND(sub);
10801 kind = kind1 > kind2 ? kind1 : kind2;
10802 buf1 = PyUnicode_DATA(str);
10803 buf2 = PyUnicode_DATA(sub);
10804 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010805 buf1 = _PyUnicode_AsKind(str, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010806 if (!buf1) {
10807 Py_DECREF(sub);
10808 return -1;
10809 }
10810 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010811 buf2 = _PyUnicode_AsKind(sub, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010812 if (!buf2) {
10813 Py_DECREF(sub);
10814 if (kind1 != kind) PyMem_Free(buf1);
10815 return -1;
10816 }
10817 len1 = PyUnicode_GET_LENGTH(str);
10818 len2 = PyUnicode_GET_LENGTH(sub);
10819
10820 switch(kind) {
10821 case PyUnicode_1BYTE_KIND:
10822 result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
10823 break;
10824 case PyUnicode_2BYTE_KIND:
10825 result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
10826 break;
10827 case PyUnicode_4BYTE_KIND:
10828 result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
10829 break;
10830 default:
10831 result = -1;
10832 assert(0);
10833 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000010834
10835 Py_DECREF(str);
10836 Py_DECREF(sub);
10837
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010838 if (kind1 != kind)
10839 PyMem_Free(buf1);
10840 if (kind2 != kind)
10841 PyMem_Free(buf2);
10842
Guido van Rossum403d68b2000-03-13 15:55:09 +000010843 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010844}
10845
Guido van Rossumd57fd912000-03-10 22:53:23 +000010846/* Concat to string or Unicode object giving a new Unicode object. */
10847
Alexander Belopolsky40018472011-02-26 01:02:56 +000010848PyObject *
10849PyUnicode_Concat(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010850{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010851 PyObject *u = NULL, *v = NULL, *w;
Victor Stinner127226b2011-10-13 01:12:34 +020010852 Py_UCS4 maxchar, maxchar2;
Victor Stinner488fa492011-12-12 00:01:39 +010010853 Py_ssize_t u_len, v_len, new_len;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010854
10855 /* Coerce the two arguments */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010856 u = PyUnicode_FromObject(left);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010857 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010858 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010859 v = PyUnicode_FromObject(right);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010860 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010861 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010862
10863 /* Shortcuts */
Victor Stinnera464fc12011-10-02 20:39:30 +020010864 if (v == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010865 Py_DECREF(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010866 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010867 }
Victor Stinnera464fc12011-10-02 20:39:30 +020010868 if (u == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010869 Py_DECREF(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010870 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010871 }
10872
Victor Stinner488fa492011-12-12 00:01:39 +010010873 u_len = PyUnicode_GET_LENGTH(u);
10874 v_len = PyUnicode_GET_LENGTH(v);
10875 if (u_len > PY_SSIZE_T_MAX - v_len) {
10876 PyErr_SetString(PyExc_OverflowError,
10877 "strings are too large to concat");
10878 goto onError;
10879 }
10880 new_len = u_len + v_len;
10881
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010882 maxchar = PyUnicode_MAX_CHAR_VALUE(u);
Victor Stinner127226b2011-10-13 01:12:34 +020010883 maxchar2 = PyUnicode_MAX_CHAR_VALUE(v);
10884 maxchar = Py_MAX(maxchar, maxchar2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010885
Guido van Rossumd57fd912000-03-10 22:53:23 +000010886 /* Concat the two Unicode strings */
Victor Stinner488fa492011-12-12 00:01:39 +010010887 w = PyUnicode_New(new_len, maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010888 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010889 goto onError;
Victor Stinner488fa492011-12-12 00:01:39 +010010890 copy_characters(w, 0, u, 0, u_len);
10891 copy_characters(w, u_len, v, 0, v_len);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010892 Py_DECREF(u);
10893 Py_DECREF(v);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010894 assert(_PyUnicode_CheckConsistency(w, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010895 return w;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010896
Benjamin Peterson29060642009-01-31 22:14:21 +000010897 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000010898 Py_XDECREF(u);
10899 Py_XDECREF(v);
10900 return NULL;
10901}
10902
Walter Dörwald1ab83302007-05-18 17:15:44 +000010903void
Victor Stinner23e56682011-10-03 03:54:37 +020010904PyUnicode_Append(PyObject **p_left, PyObject *right)
Walter Dörwald1ab83302007-05-18 17:15:44 +000010905{
Victor Stinner23e56682011-10-03 03:54:37 +020010906 PyObject *left, *res;
Victor Stinner488fa492011-12-12 00:01:39 +010010907 Py_UCS4 maxchar, maxchar2;
10908 Py_ssize_t left_len, right_len, new_len;
Victor Stinner23e56682011-10-03 03:54:37 +020010909
10910 if (p_left == NULL) {
10911 if (!PyErr_Occurred())
10912 PyErr_BadInternalCall();
Benjamin Peterson14339b62009-01-31 16:36:08 +000010913 return;
10914 }
Victor Stinner23e56682011-10-03 03:54:37 +020010915 left = *p_left;
10916 if (right == NULL || !PyUnicode_Check(left)) {
10917 if (!PyErr_Occurred())
10918 PyErr_BadInternalCall();
10919 goto error;
10920 }
10921
Victor Stinnere1335c72011-10-04 20:53:03 +020010922 if (PyUnicode_READY(left))
10923 goto error;
10924 if (PyUnicode_READY(right))
10925 goto error;
10926
Victor Stinner488fa492011-12-12 00:01:39 +010010927 /* Shortcuts */
10928 if (left == unicode_empty) {
10929 Py_DECREF(left);
10930 Py_INCREF(right);
10931 *p_left = right;
10932 return;
10933 }
10934 if (right == unicode_empty)
10935 return;
10936
10937 left_len = PyUnicode_GET_LENGTH(left);
10938 right_len = PyUnicode_GET_LENGTH(right);
10939 if (left_len > PY_SSIZE_T_MAX - right_len) {
10940 PyErr_SetString(PyExc_OverflowError,
10941 "strings are too large to concat");
10942 goto error;
10943 }
10944 new_len = left_len + right_len;
10945
10946 if (unicode_modifiable(left)
10947 && PyUnicode_CheckExact(right)
10948 && PyUnicode_KIND(right) <= PyUnicode_KIND(left)
Victor Stinnerb0923652011-10-04 01:17:31 +020010949 /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
10950 to change the structure size, but characters are stored just after
Georg Brandl7597add2011-10-05 16:36:47 +020010951 the structure, and so it requires to move all characters which is
Victor Stinnerb0923652011-10-04 01:17:31 +020010952 not so different than duplicating the string. */
Victor Stinner488fa492011-12-12 00:01:39 +010010953 && !(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
10954 {
10955 /* append inplace */
10956 if (unicode_resize(p_left, new_len) != 0) {
10957 /* XXX if _PyUnicode_Resize() fails, 'left' has been
10958 * deallocated so it cannot be put back into
10959 * 'variable'. The MemoryError is raised when there
10960 * is no value in 'variable', which might (very
10961 * remotely) be a cause of incompatibilities.
10962 */
10963 goto error;
Victor Stinner23e56682011-10-03 03:54:37 +020010964 }
Victor Stinner488fa492011-12-12 00:01:39 +010010965 /* copy 'right' into the newly allocated area of 'left' */
10966 copy_characters(*p_left, left_len, right, 0, right_len);
Victor Stinner23e56682011-10-03 03:54:37 +020010967 }
Victor Stinner488fa492011-12-12 00:01:39 +010010968 else {
10969 maxchar = PyUnicode_MAX_CHAR_VALUE(left);
10970 maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
10971 maxchar = Py_MAX(maxchar, maxchar2);
Victor Stinner23e56682011-10-03 03:54:37 +020010972
Victor Stinner488fa492011-12-12 00:01:39 +010010973 /* Concat the two Unicode strings */
10974 res = PyUnicode_New(new_len, maxchar);
10975 if (res == NULL)
10976 goto error;
10977 copy_characters(res, 0, left, 0, left_len);
10978 copy_characters(res, left_len, right, 0, right_len);
10979 Py_DECREF(left);
10980 *p_left = res;
10981 }
10982 assert(_PyUnicode_CheckConsistency(*p_left, 1));
Victor Stinner23e56682011-10-03 03:54:37 +020010983 return;
10984
10985error:
Victor Stinner488fa492011-12-12 00:01:39 +010010986 Py_CLEAR(*p_left);
Walter Dörwald1ab83302007-05-18 17:15:44 +000010987}
10988
10989void
10990PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
10991{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010992 PyUnicode_Append(pleft, right);
10993 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +000010994}
10995
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010996PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010997 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010998\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000010999Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011000string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011001interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011002
11003static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011004unicode_count(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011005{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011006 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011007 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011008 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011009 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011010 int kind1, kind2, kind;
11011 void *buf1, *buf2;
11012 Py_ssize_t len1, len2, iresult;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011013
Jesus Ceaac451502011-04-20 17:09:23 +020011014 if (!stringlib_parse_args_finds_unicode("count", args, &substring,
11015 &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000011016 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000011017
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011018 kind1 = PyUnicode_KIND(self);
11019 kind2 = PyUnicode_KIND(substring);
11020 kind = kind1 > kind2 ? kind1 : kind2;
11021 buf1 = PyUnicode_DATA(self);
11022 buf2 = PyUnicode_DATA(substring);
11023 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010011024 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011025 if (!buf1) {
11026 Py_DECREF(substring);
11027 return NULL;
11028 }
11029 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010011030 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011031 if (!buf2) {
11032 Py_DECREF(substring);
11033 if (kind1 != kind) PyMem_Free(buf1);
11034 return NULL;
11035 }
11036 len1 = PyUnicode_GET_LENGTH(self);
11037 len2 = PyUnicode_GET_LENGTH(substring);
11038
11039 ADJUST_INDICES(start, end, len1);
11040 switch(kind) {
11041 case PyUnicode_1BYTE_KIND:
11042 iresult = ucs1lib_count(
11043 ((Py_UCS1*)buf1) + start, end - start,
11044 buf2, len2, PY_SSIZE_T_MAX
11045 );
11046 break;
11047 case PyUnicode_2BYTE_KIND:
11048 iresult = ucs2lib_count(
11049 ((Py_UCS2*)buf1) + start, end - start,
11050 buf2, len2, PY_SSIZE_T_MAX
11051 );
11052 break;
11053 case PyUnicode_4BYTE_KIND:
11054 iresult = ucs4lib_count(
11055 ((Py_UCS4*)buf1) + start, end - start,
11056 buf2, len2, PY_SSIZE_T_MAX
11057 );
11058 break;
11059 default:
11060 assert(0); iresult = 0;
11061 }
11062
11063 result = PyLong_FromSsize_t(iresult);
11064
11065 if (kind1 != kind)
11066 PyMem_Free(buf1);
11067 if (kind2 != kind)
11068 PyMem_Free(buf2);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011069
11070 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011071
Guido van Rossumd57fd912000-03-10 22:53:23 +000011072 return result;
11073}
11074
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011075PyDoc_STRVAR(encode__doc__,
Victor Stinnerc911bbf2010-11-07 19:04:46 +000011076 "S.encode(encoding='utf-8', errors='strict') -> bytes\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011077\n\
Victor Stinnere14e2122010-11-07 18:41:46 +000011078Encode S using the codec registered for encoding. Default encoding\n\
11079is 'utf-8'. errors may be given to set a different error\n\
Fred Drakee4315f52000-05-09 19:53:39 +000011080handling scheme. Default is 'strict' meaning that encoding errors raise\n\
Walter Dörwald3aeb6322002-09-02 13:14:32 +000011081a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
11082'xmlcharrefreplace' as well as any other name registered with\n\
11083codecs.register_error that can handle UnicodeEncodeErrors.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011084
11085static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011086unicode_encode(PyObject *self, PyObject *args, PyObject *kwargs)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011087{
Benjamin Peterson308d6372009-09-18 21:42:35 +000011088 static char *kwlist[] = {"encoding", "errors", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000011089 char *encoding = NULL;
11090 char *errors = NULL;
Guido van Rossum35d94282007-08-27 18:20:11 +000011091
Benjamin Peterson308d6372009-09-18 21:42:35 +000011092 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:encode",
11093 kwlist, &encoding, &errors))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011094 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011095 return PyUnicode_AsEncodedString(self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +000011096}
11097
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011098PyDoc_STRVAR(expandtabs__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011099 "S.expandtabs([tabsize]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011100\n\
11101Return a copy of S where all tab characters are expanded using spaces.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011102If tabsize is not given, a tab size of 8 characters is assumed.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011103
11104static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011105unicode_expandtabs(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011106{
Antoine Pitroue71d5742011-10-04 15:55:09 +020011107 Py_ssize_t i, j, line_pos, src_len, incr;
11108 Py_UCS4 ch;
11109 PyObject *u;
11110 void *src_data, *dest_data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011111 int tabsize = 8;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011112 int kind;
Antoine Pitroue19aa382011-10-04 16:04:01 +020011113 int found;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011114
11115 if (!PyArg_ParseTuple(args, "|i:expandtabs", &tabsize))
Benjamin Peterson29060642009-01-31 22:14:21 +000011116 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011117
Antoine Pitrou22425222011-10-04 19:10:51 +020011118 if (PyUnicode_READY(self) == -1)
11119 return NULL;
11120
Thomas Wouters7e474022000-07-16 12:04:32 +000011121 /* First pass: determine size of output string */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011122 src_len = PyUnicode_GET_LENGTH(self);
11123 i = j = line_pos = 0;
11124 kind = PyUnicode_KIND(self);
11125 src_data = PyUnicode_DATA(self);
Antoine Pitroue19aa382011-10-04 16:04:01 +020011126 found = 0;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011127 for (; i < src_len; i++) {
11128 ch = PyUnicode_READ(kind, src_data, i);
11129 if (ch == '\t') {
Antoine Pitroue19aa382011-10-04 16:04:01 +020011130 found = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000011131 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011132 incr = tabsize - (line_pos % tabsize); /* cannot overflow */
Benjamin Peterson29060642009-01-31 22:14:21 +000011133 if (j > PY_SSIZE_T_MAX - incr)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011134 goto overflow;
11135 line_pos += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011136 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011137 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011138 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011139 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000011140 if (j > PY_SSIZE_T_MAX - 1)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011141 goto overflow;
11142 line_pos++;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011143 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011144 if (ch == '\n' || ch == '\r')
11145 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011146 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011147 }
Victor Stinnerc4b49542011-12-11 22:44:26 +010011148 if (!found)
11149 return unicode_result_unchanged(self);
Guido van Rossumcd16bf62007-06-13 18:07:49 +000011150
Guido van Rossumd57fd912000-03-10 22:53:23 +000011151 /* Second pass: create output string and fill it */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011152 u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011153 if (!u)
11154 return NULL;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011155 dest_data = PyUnicode_DATA(u);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011156
Antoine Pitroue71d5742011-10-04 15:55:09 +020011157 i = j = line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011158
Antoine Pitroue71d5742011-10-04 15:55:09 +020011159 for (; i < src_len; i++) {
11160 ch = PyUnicode_READ(kind, src_data, i);
11161 if (ch == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +000011162 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011163 incr = tabsize - (line_pos % tabsize);
11164 line_pos += incr;
11165 while (incr--) {
11166 PyUnicode_WRITE(kind, dest_data, j, ' ');
11167 j++;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011168 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011169 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011170 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011171 else {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011172 line_pos++;
11173 PyUnicode_WRITE(kind, dest_data, j, ch);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011174 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011175 if (ch == '\n' || ch == '\r')
11176 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011177 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011178 }
11179 assert (j == PyUnicode_GET_LENGTH(u));
Victor Stinnerd3df8ab2011-11-22 01:22:34 +010011180 return unicode_result(u);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011181
Antoine Pitroue71d5742011-10-04 15:55:09 +020011182 overflow:
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011183 PyErr_SetString(PyExc_OverflowError, "new string is too long");
11184 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011185}
11186
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011187PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011188 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011189\n\
11190Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080011191such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011192arguments start and end are interpreted as in slice notation.\n\
11193\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011194Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011195
11196static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011197unicode_find(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011198{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011199 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011200 Py_ssize_t start;
11201 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011202 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011203
Jesus Ceaac451502011-04-20 17:09:23 +020011204 if (!stringlib_parse_args_finds_unicode("find", args, &substring,
11205 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011206 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011207
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011208 if (PyUnicode_READY(self) == -1)
11209 return NULL;
11210 if (PyUnicode_READY(substring) == -1)
11211 return NULL;
11212
Victor Stinner7931d9a2011-11-04 00:22:48 +010011213 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011214
11215 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011216
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011217 if (result == -2)
11218 return NULL;
11219
Christian Heimes217cfd12007-12-02 14:31:20 +000011220 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011221}
11222
11223static PyObject *
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011224unicode_getitem(PyObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011225{
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011226 Py_UCS4 ch = PyUnicode_ReadChar(self, index);
11227 if (ch == (Py_UCS4)-1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011228 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011229 return PyUnicode_FromOrdinal(ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011230}
11231
Guido van Rossumc2504932007-09-18 19:42:40 +000011232/* Believe it or not, this produces the same value for ASCII strings
Mark Dickinson57e683e2011-09-24 18:18:40 +010011233 as bytes_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +000011234static Py_hash_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011235unicode_hash(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011236{
Guido van Rossumc2504932007-09-18 19:42:40 +000011237 Py_ssize_t len;
Mark Dickinson57e683e2011-09-24 18:18:40 +010011238 Py_uhash_t x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011239
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011240 if (_PyUnicode_HASH(self) != -1)
11241 return _PyUnicode_HASH(self);
11242 if (PyUnicode_READY(self) == -1)
11243 return -1;
11244 len = PyUnicode_GET_LENGTH(self);
11245
11246 /* The hash function as a macro, gets expanded three times below. */
11247#define HASH(P) \
11248 x = (Py_uhash_t)*P << 7; \
11249 while (--len >= 0) \
11250 x = (1000003*x) ^ (Py_uhash_t)*P++;
11251
11252 switch (PyUnicode_KIND(self)) {
11253 case PyUnicode_1BYTE_KIND: {
11254 const unsigned char *c = PyUnicode_1BYTE_DATA(self);
11255 HASH(c);
11256 break;
11257 }
11258 case PyUnicode_2BYTE_KIND: {
11259 const Py_UCS2 *s = PyUnicode_2BYTE_DATA(self);
11260 HASH(s);
11261 break;
11262 }
11263 default: {
11264 Py_UCS4 *l;
11265 assert(PyUnicode_KIND(self) == PyUnicode_4BYTE_KIND &&
11266 "Impossible switch case in unicode_hash");
11267 l = PyUnicode_4BYTE_DATA(self);
11268 HASH(l);
11269 break;
11270 }
11271 }
11272 x ^= (Py_uhash_t)PyUnicode_GET_LENGTH(self);
11273
Guido van Rossumc2504932007-09-18 19:42:40 +000011274 if (x == -1)
11275 x = -2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011276 _PyUnicode_HASH(self) = x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011277 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011278}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011279#undef HASH
Guido van Rossumd57fd912000-03-10 22:53:23 +000011280
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011281PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011282 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011283\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011284Like S.find() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011285
11286static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011287unicode_index(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011288{
Martin v. Löwis18e16552006-02-15 17:27:45 +000011289 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011290 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011291 Py_ssize_t start;
11292 Py_ssize_t end;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011293
Jesus Ceaac451502011-04-20 17:09:23 +020011294 if (!stringlib_parse_args_finds_unicode("index", args, &substring,
11295 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011296 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011297
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011298 if (PyUnicode_READY(self) == -1)
11299 return NULL;
11300 if (PyUnicode_READY(substring) == -1)
11301 return NULL;
11302
Victor Stinner7931d9a2011-11-04 00:22:48 +010011303 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011304
11305 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011306
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011307 if (result == -2)
11308 return NULL;
11309
Guido van Rossumd57fd912000-03-10 22:53:23 +000011310 if (result < 0) {
11311 PyErr_SetString(PyExc_ValueError, "substring not found");
11312 return NULL;
11313 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011314
Christian Heimes217cfd12007-12-02 14:31:20 +000011315 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011316}
11317
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011318PyDoc_STRVAR(islower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011319 "S.islower() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011320\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011321Return True if all cased characters in S are lowercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011322at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011323
11324static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011325unicode_islower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011326{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011327 Py_ssize_t i, length;
11328 int kind;
11329 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011330 int cased;
11331
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011332 if (PyUnicode_READY(self) == -1)
11333 return NULL;
11334 length = PyUnicode_GET_LENGTH(self);
11335 kind = PyUnicode_KIND(self);
11336 data = PyUnicode_DATA(self);
11337
Guido van Rossumd57fd912000-03-10 22:53:23 +000011338 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011339 if (length == 1)
11340 return PyBool_FromLong(
11341 Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011342
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011343 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011344 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011345 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011346
Guido van Rossumd57fd912000-03-10 22:53:23 +000011347 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011348 for (i = 0; i < length; i++) {
11349 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011350
Benjamin Peterson29060642009-01-31 22:14:21 +000011351 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
11352 return PyBool_FromLong(0);
11353 else if (!cased && Py_UNICODE_ISLOWER(ch))
11354 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011355 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011356 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011357}
11358
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011359PyDoc_STRVAR(isupper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011360 "S.isupper() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011361\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011362Return True if all cased characters in S are uppercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011363at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011364
11365static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011366unicode_isupper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011367{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011368 Py_ssize_t i, length;
11369 int kind;
11370 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011371 int cased;
11372
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011373 if (PyUnicode_READY(self) == -1)
11374 return NULL;
11375 length = PyUnicode_GET_LENGTH(self);
11376 kind = PyUnicode_KIND(self);
11377 data = PyUnicode_DATA(self);
11378
Guido van Rossumd57fd912000-03-10 22:53:23 +000011379 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011380 if (length == 1)
11381 return PyBool_FromLong(
11382 Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011383
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011384 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011385 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011386 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011387
Guido van Rossumd57fd912000-03-10 22:53:23 +000011388 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011389 for (i = 0; i < length; i++) {
11390 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011391
Benjamin Peterson29060642009-01-31 22:14:21 +000011392 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
11393 return PyBool_FromLong(0);
11394 else if (!cased && Py_UNICODE_ISUPPER(ch))
11395 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011396 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011397 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011398}
11399
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011400PyDoc_STRVAR(istitle__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011401 "S.istitle() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011402\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011403Return True if S is a titlecased string and there is at least one\n\
11404character in S, i.e. upper- and titlecase characters may only\n\
11405follow uncased characters and lowercase characters only cased ones.\n\
11406Return False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011407
11408static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011409unicode_istitle(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011410{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011411 Py_ssize_t i, length;
11412 int kind;
11413 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011414 int cased, previous_is_cased;
11415
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011416 if (PyUnicode_READY(self) == -1)
11417 return NULL;
11418 length = PyUnicode_GET_LENGTH(self);
11419 kind = PyUnicode_KIND(self);
11420 data = PyUnicode_DATA(self);
11421
Guido van Rossumd57fd912000-03-10 22:53:23 +000011422 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011423 if (length == 1) {
11424 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11425 return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
11426 (Py_UNICODE_ISUPPER(ch) != 0));
11427 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011428
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011429 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011430 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011431 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011432
Guido van Rossumd57fd912000-03-10 22:53:23 +000011433 cased = 0;
11434 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011435 for (i = 0; i < length; i++) {
11436 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011437
Benjamin Peterson29060642009-01-31 22:14:21 +000011438 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
11439 if (previous_is_cased)
11440 return PyBool_FromLong(0);
11441 previous_is_cased = 1;
11442 cased = 1;
11443 }
11444 else if (Py_UNICODE_ISLOWER(ch)) {
11445 if (!previous_is_cased)
11446 return PyBool_FromLong(0);
11447 previous_is_cased = 1;
11448 cased = 1;
11449 }
11450 else
11451 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011452 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011453 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011454}
11455
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011456PyDoc_STRVAR(isspace__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011457 "S.isspace() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011458\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011459Return True if all characters in S are whitespace\n\
11460and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011461
11462static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011463unicode_isspace(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011464{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011465 Py_ssize_t i, length;
11466 int kind;
11467 void *data;
11468
11469 if (PyUnicode_READY(self) == -1)
11470 return NULL;
11471 length = PyUnicode_GET_LENGTH(self);
11472 kind = PyUnicode_KIND(self);
11473 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011474
Guido van Rossumd57fd912000-03-10 22:53:23 +000011475 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011476 if (length == 1)
11477 return PyBool_FromLong(
11478 Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011479
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011480 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011481 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011482 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011483
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011484 for (i = 0; i < length; i++) {
11485 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011486 if (!Py_UNICODE_ISSPACE(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011487 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011488 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011489 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011490}
11491
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011492PyDoc_STRVAR(isalpha__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011493 "S.isalpha() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011494\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011495Return True if all characters in S are alphabetic\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011496and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011497
11498static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011499unicode_isalpha(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011500{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011501 Py_ssize_t i, length;
11502 int kind;
11503 void *data;
11504
11505 if (PyUnicode_READY(self) == -1)
11506 return NULL;
11507 length = PyUnicode_GET_LENGTH(self);
11508 kind = PyUnicode_KIND(self);
11509 data = PyUnicode_DATA(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011510
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011511 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011512 if (length == 1)
11513 return PyBool_FromLong(
11514 Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011515
11516 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011517 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011518 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011519
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011520 for (i = 0; i < length; i++) {
11521 if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011522 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011523 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011524 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011525}
11526
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011527PyDoc_STRVAR(isalnum__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011528 "S.isalnum() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011529\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011530Return True if all characters in S are alphanumeric\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011531and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011532
11533static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011534unicode_isalnum(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011535{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011536 int kind;
11537 void *data;
11538 Py_ssize_t len, i;
11539
11540 if (PyUnicode_READY(self) == -1)
11541 return NULL;
11542
11543 kind = PyUnicode_KIND(self);
11544 data = PyUnicode_DATA(self);
11545 len = PyUnicode_GET_LENGTH(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011546
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011547 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011548 if (len == 1) {
11549 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11550 return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
11551 }
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011552
11553 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011554 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011555 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011556
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011557 for (i = 0; i < len; i++) {
11558 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011559 if (!Py_UNICODE_ISALNUM(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011560 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011561 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011562 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011563}
11564
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011565PyDoc_STRVAR(isdecimal__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011566 "S.isdecimal() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011567\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011568Return True if there are only decimal characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011569False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011570
11571static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011572unicode_isdecimal(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011573{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011574 Py_ssize_t i, length;
11575 int kind;
11576 void *data;
11577
11578 if (PyUnicode_READY(self) == -1)
11579 return NULL;
11580 length = PyUnicode_GET_LENGTH(self);
11581 kind = PyUnicode_KIND(self);
11582 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011583
Guido van Rossumd57fd912000-03-10 22:53:23 +000011584 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011585 if (length == 1)
11586 return PyBool_FromLong(
11587 Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011588
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011589 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011590 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011591 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011592
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011593 for (i = 0; i < length; i++) {
11594 if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011595 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011596 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011597 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011598}
11599
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011600PyDoc_STRVAR(isdigit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011601 "S.isdigit() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011602\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011603Return True if all characters in S are digits\n\
11604and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011605
11606static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011607unicode_isdigit(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011608{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011609 Py_ssize_t i, length;
11610 int kind;
11611 void *data;
11612
11613 if (PyUnicode_READY(self) == -1)
11614 return NULL;
11615 length = PyUnicode_GET_LENGTH(self);
11616 kind = PyUnicode_KIND(self);
11617 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011618
Guido van Rossumd57fd912000-03-10 22:53:23 +000011619 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011620 if (length == 1) {
11621 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11622 return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
11623 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011624
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011625 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011626 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011627 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011628
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011629 for (i = 0; i < length; i++) {
11630 if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011631 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011632 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011633 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011634}
11635
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011636PyDoc_STRVAR(isnumeric__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011637 "S.isnumeric() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011638\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011639Return True if there are only numeric characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011640False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011641
11642static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011643unicode_isnumeric(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011644{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011645 Py_ssize_t i, length;
11646 int kind;
11647 void *data;
11648
11649 if (PyUnicode_READY(self) == -1)
11650 return NULL;
11651 length = PyUnicode_GET_LENGTH(self);
11652 kind = PyUnicode_KIND(self);
11653 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011654
Guido van Rossumd57fd912000-03-10 22:53:23 +000011655 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011656 if (length == 1)
11657 return PyBool_FromLong(
11658 Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011659
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011660 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011661 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011662 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011663
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011664 for (i = 0; i < length; i++) {
11665 if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011666 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011667 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011668 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011669}
11670
Martin v. Löwis47383402007-08-15 07:32:56 +000011671int
11672PyUnicode_IsIdentifier(PyObject *self)
11673{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011674 int kind;
11675 void *data;
11676 Py_ssize_t i;
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011677 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +000011678
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011679 if (PyUnicode_READY(self) == -1) {
11680 Py_FatalError("identifier not ready");
Benjamin Peterson29060642009-01-31 22:14:21 +000011681 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011682 }
11683
11684 /* Special case for empty strings */
11685 if (PyUnicode_GET_LENGTH(self) == 0)
11686 return 0;
11687 kind = PyUnicode_KIND(self);
11688 data = PyUnicode_DATA(self);
Martin v. Löwis47383402007-08-15 07:32:56 +000011689
11690 /* PEP 3131 says that the first character must be in
11691 XID_Start and subsequent characters in XID_Continue,
11692 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +000011693 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +000011694 letters, digits, underscore). However, given the current
11695 definition of XID_Start and XID_Continue, it is sufficient
11696 to check just for these, except that _ must be allowed
11697 as starting an identifier. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011698 first = PyUnicode_READ(kind, data, 0);
Benjamin Petersonf413b802011-08-12 22:17:18 -050011699 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +000011700 return 0;
11701
Benjamin Peterson9c6e6a02011-09-28 08:09:05 -040011702 for (i = 1; i < PyUnicode_GET_LENGTH(self); i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011703 if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011704 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +000011705 return 1;
11706}
11707
11708PyDoc_STRVAR(isidentifier__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011709 "S.isidentifier() -> bool\n\
Martin v. Löwis47383402007-08-15 07:32:56 +000011710\n\
11711Return True if S is a valid identifier according\n\
11712to the language definition.");
11713
11714static PyObject*
11715unicode_isidentifier(PyObject *self)
11716{
11717 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
11718}
11719
Georg Brandl559e5d72008-06-11 18:37:52 +000011720PyDoc_STRVAR(isprintable__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011721 "S.isprintable() -> bool\n\
Georg Brandl559e5d72008-06-11 18:37:52 +000011722\n\
11723Return True if all characters in S are considered\n\
11724printable in repr() or S is empty, False otherwise.");
11725
11726static PyObject*
11727unicode_isprintable(PyObject *self)
11728{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011729 Py_ssize_t i, length;
11730 int kind;
11731 void *data;
11732
11733 if (PyUnicode_READY(self) == -1)
11734 return NULL;
11735 length = PyUnicode_GET_LENGTH(self);
11736 kind = PyUnicode_KIND(self);
11737 data = PyUnicode_DATA(self);
Georg Brandl559e5d72008-06-11 18:37:52 +000011738
11739 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011740 if (length == 1)
11741 return PyBool_FromLong(
11742 Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
Georg Brandl559e5d72008-06-11 18:37:52 +000011743
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011744 for (i = 0; i < length; i++) {
11745 if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
Georg Brandl559e5d72008-06-11 18:37:52 +000011746 Py_RETURN_FALSE;
11747 }
11748 }
11749 Py_RETURN_TRUE;
11750}
11751
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011752PyDoc_STRVAR(join__doc__,
Georg Brandl495f7b52009-10-27 15:28:25 +000011753 "S.join(iterable) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011754\n\
11755Return a string which is the concatenation of the strings in the\n\
Georg Brandl495f7b52009-10-27 15:28:25 +000011756iterable. The separator between elements is S.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011757
11758static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011759unicode_join(PyObject *self, PyObject *data)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011760{
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011761 return PyUnicode_Join(self, data);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011762}
11763
Martin v. Löwis18e16552006-02-15 17:27:45 +000011764static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011765unicode_length(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011766{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011767 if (PyUnicode_READY(self) == -1)
11768 return -1;
11769 return PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011770}
11771
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011772PyDoc_STRVAR(ljust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011773 "S.ljust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011774\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000011775Return S left-justified in a Unicode string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011776done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011777
11778static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020011779unicode_ljust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011780{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011781 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011782 Py_UCS4 fillchar = ' ';
11783
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011784 if (!PyArg_ParseTuple(args, "n|O&:ljust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011785 return NULL;
11786
Victor Stinnerc4b49542011-12-11 22:44:26 +010011787 if (PyUnicode_READY(self) < 0)
11788 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011789
Victor Stinnerc4b49542011-12-11 22:44:26 +010011790 if (PyUnicode_GET_LENGTH(self) >= width)
11791 return unicode_result_unchanged(self);
11792
11793 return pad(self, 0, width - PyUnicode_GET_LENGTH(self), fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011794}
11795
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011796PyDoc_STRVAR(lower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011797 "S.lower() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011798\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011799Return a copy of the string S converted to lowercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011800
11801static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020011802unicode_lower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011803{
Guido van Rossumd57fd912000-03-10 22:53:23 +000011804 return fixup(self, fixlower);
11805}
11806
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011807#define LEFTSTRIP 0
11808#define RIGHTSTRIP 1
11809#define BOTHSTRIP 2
11810
11811/* Arrays indexed by above */
11812static const char *stripformat[] = {"|O:lstrip", "|O:rstrip", "|O:strip"};
11813
11814#define STRIPNAME(i) (stripformat[i]+3)
11815
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011816/* externally visible for str.strip(unicode) */
11817PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011818_PyUnicode_XStrip(PyObject *self, int striptype, PyObject *sepobj)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011819{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011820 void *data;
11821 int kind;
11822 Py_ssize_t i, j, len;
11823 BLOOM_MASK sepmask;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011824
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011825 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
11826 return NULL;
11827
11828 kind = PyUnicode_KIND(self);
11829 data = PyUnicode_DATA(self);
11830 len = PyUnicode_GET_LENGTH(self);
11831 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
11832 PyUnicode_DATA(sepobj),
11833 PyUnicode_GET_LENGTH(sepobj));
Thomas Wouters477c8d52006-05-27 19:21:47 +000011834
Benjamin Peterson14339b62009-01-31 16:36:08 +000011835 i = 0;
11836 if (striptype != RIGHTSTRIP) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011837 while (i < len &&
11838 BLOOM_MEMBER(sepmask, PyUnicode_READ(kind, data, i), sepobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011839 i++;
11840 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011841 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011842
Benjamin Peterson14339b62009-01-31 16:36:08 +000011843 j = len;
11844 if (striptype != LEFTSTRIP) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011845 do {
11846 j--;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011847 } while (j >= i &&
11848 BLOOM_MEMBER(sepmask, PyUnicode_READ(kind, data, j), sepobj));
Benjamin Peterson29060642009-01-31 22:14:21 +000011849 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011850 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011851
Victor Stinner7931d9a2011-11-04 00:22:48 +010011852 return PyUnicode_Substring(self, i, j);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011853}
11854
11855PyObject*
11856PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
11857{
11858 unsigned char *data;
11859 int kind;
Victor Stinner12bab6d2011-10-01 01:53:49 +020011860 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011861
Victor Stinnerde636f32011-10-01 03:55:54 +020011862 if (PyUnicode_READY(self) == -1)
11863 return NULL;
11864
11865 end = Py_MIN(end, PyUnicode_GET_LENGTH(self));
11866
Victor Stinner12bab6d2011-10-01 01:53:49 +020011867 if (start == 0 && end == PyUnicode_GET_LENGTH(self))
Victor Stinnerc4b49542011-12-11 22:44:26 +010011868 return unicode_result_unchanged(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011869
Victor Stinner12bab6d2011-10-01 01:53:49 +020011870 length = end - start;
11871 if (length == 1)
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011872 return unicode_getitem(self, start);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011873
Victor Stinnerde636f32011-10-01 03:55:54 +020011874 if (start < 0 || end < 0) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020011875 PyErr_SetString(PyExc_IndexError, "string index out of range");
11876 return NULL;
11877 }
11878
Victor Stinnerb9275c12011-10-05 14:01:42 +020011879 if (PyUnicode_IS_ASCII(self)) {
11880 kind = PyUnicode_KIND(self);
11881 data = PyUnicode_1BYTE_DATA(self);
11882 return unicode_fromascii(data + start, length);
11883 }
11884 else {
11885 kind = PyUnicode_KIND(self);
11886 data = PyUnicode_1BYTE_DATA(self);
11887 return PyUnicode_FromKindAndData(kind,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020011888 data + kind * start,
Victor Stinnerb9275c12011-10-05 14:01:42 +020011889 length);
11890 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011891}
Guido van Rossumd57fd912000-03-10 22:53:23 +000011892
11893static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011894do_strip(PyObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011895{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011896 int kind;
11897 void *data;
11898 Py_ssize_t len, i, j;
11899
11900 if (PyUnicode_READY(self) == -1)
11901 return NULL;
11902
11903 kind = PyUnicode_KIND(self);
11904 data = PyUnicode_DATA(self);
11905 len = PyUnicode_GET_LENGTH(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011906
Benjamin Peterson14339b62009-01-31 16:36:08 +000011907 i = 0;
11908 if (striptype != RIGHTSTRIP) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011909 while (i < len && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, i))) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000011910 i++;
11911 }
11912 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011913
Benjamin Peterson14339b62009-01-31 16:36:08 +000011914 j = len;
11915 if (striptype != LEFTSTRIP) {
11916 do {
11917 j--;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011918 } while (j >= i && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, j)));
Benjamin Peterson14339b62009-01-31 16:36:08 +000011919 j++;
11920 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011921
Victor Stinner7931d9a2011-11-04 00:22:48 +010011922 return PyUnicode_Substring(self, i, j);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011923}
11924
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011925
11926static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011927do_argstrip(PyObject *self, int striptype, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011928{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011929 PyObject *sep = NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011930
Benjamin Peterson14339b62009-01-31 16:36:08 +000011931 if (!PyArg_ParseTuple(args, (char *)stripformat[striptype], &sep))
11932 return NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011933
Benjamin Peterson14339b62009-01-31 16:36:08 +000011934 if (sep != NULL && sep != Py_None) {
11935 if (PyUnicode_Check(sep))
11936 return _PyUnicode_XStrip(self, striptype, sep);
11937 else {
11938 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000011939 "%s arg must be None or str",
11940 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +000011941 return NULL;
11942 }
11943 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011944
Benjamin Peterson14339b62009-01-31 16:36:08 +000011945 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011946}
11947
11948
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011949PyDoc_STRVAR(strip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011950 "S.strip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011951\n\
11952Return a copy of the string S with leading and trailing\n\
11953whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011954If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011955
11956static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011957unicode_strip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011958{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011959 if (PyTuple_GET_SIZE(args) == 0)
11960 return do_strip(self, BOTHSTRIP); /* Common case */
11961 else
11962 return do_argstrip(self, BOTHSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011963}
11964
11965
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011966PyDoc_STRVAR(lstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011967 "S.lstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011968\n\
11969Return a copy of the string S with leading whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011970If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011971
11972static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011973unicode_lstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011974{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011975 if (PyTuple_GET_SIZE(args) == 0)
11976 return do_strip(self, LEFTSTRIP); /* Common case */
11977 else
11978 return do_argstrip(self, LEFTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011979}
11980
11981
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011982PyDoc_STRVAR(rstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011983 "S.rstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011984\n\
11985Return a copy of the string S with trailing whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011986If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011987
11988static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011989unicode_rstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011990{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011991 if (PyTuple_GET_SIZE(args) == 0)
11992 return do_strip(self, RIGHTSTRIP); /* Common case */
11993 else
11994 return do_argstrip(self, RIGHTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011995}
11996
11997
Guido van Rossumd57fd912000-03-10 22:53:23 +000011998static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011999unicode_repeat(PyObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012000{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012001 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012002 Py_ssize_t nchars, n;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012003
Georg Brandl222de0f2009-04-12 12:01:50 +000012004 if (len < 1) {
12005 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +020012006 return unicode_empty;
Georg Brandl222de0f2009-04-12 12:01:50 +000012007 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012008
Victor Stinnerc4b49542011-12-11 22:44:26 +010012009 /* no repeat, return original string */
12010 if (len == 1)
12011 return unicode_result_unchanged(str);
Tim Peters8f422462000-09-09 06:13:41 +000012012
Victor Stinnerc4b49542011-12-11 22:44:26 +010012013 if (PyUnicode_READY(str) < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012014 return NULL;
12015
Victor Stinnerc759f3e2011-10-01 03:09:58 +020012016 if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
Victor Stinner67ca64c2011-10-01 02:47:29 +020012017 PyErr_SetString(PyExc_OverflowError,
12018 "repeated string is too long");
12019 return NULL;
12020 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012021 nchars = len * PyUnicode_GET_LENGTH(str);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012022
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012023 u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012024 if (!u)
12025 return NULL;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012026 assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012027
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012028 if (PyUnicode_GET_LENGTH(str) == 1) {
12029 const int kind = PyUnicode_KIND(str);
12030 const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
12031 void *to = PyUnicode_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012032 if (kind == PyUnicode_1BYTE_KIND)
12033 memset(to, (unsigned char)fill_char, len);
12034 else {
12035 for (n = 0; n < len; ++n)
12036 PyUnicode_WRITE(kind, to, n, fill_char);
12037 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012038 }
12039 else {
12040 /* number of characters copied this far */
12041 Py_ssize_t done = PyUnicode_GET_LENGTH(str);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012042 const Py_ssize_t char_size = PyUnicode_KIND(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012043 char *to = (char *) PyUnicode_DATA(u);
12044 Py_MEMCPY(to, PyUnicode_DATA(str),
12045 PyUnicode_GET_LENGTH(str) * char_size);
Benjamin Peterson29060642009-01-31 22:14:21 +000012046 while (done < nchars) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012047 n = (done <= nchars-done) ? done : nchars-done;
12048 Py_MEMCPY(to + (done * char_size), to, n * char_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012049 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +000012050 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012051 }
12052
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012053 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012054 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012055}
12056
Alexander Belopolsky40018472011-02-26 01:02:56 +000012057PyObject *
12058PyUnicode_Replace(PyObject *obj,
12059 PyObject *subobj,
12060 PyObject *replobj,
12061 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012062{
12063 PyObject *self;
12064 PyObject *str1;
12065 PyObject *str2;
12066 PyObject *result;
12067
12068 self = PyUnicode_FromObject(obj);
Victor Stinnere9a29352011-10-01 02:14:59 +020012069 if (self == NULL || PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000012070 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012071 str1 = PyUnicode_FromObject(subobj);
Victor Stinnere9a29352011-10-01 02:14:59 +020012072 if (str1 == NULL || PyUnicode_READY(str1) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012073 Py_DECREF(self);
12074 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012075 }
12076 str2 = PyUnicode_FromObject(replobj);
Victor Stinnere9a29352011-10-01 02:14:59 +020012077 if (str2 == NULL || PyUnicode_READY(str2)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012078 Py_DECREF(self);
12079 Py_DECREF(str1);
12080 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012081 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012082 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012083 Py_DECREF(self);
12084 Py_DECREF(str1);
12085 Py_DECREF(str2);
12086 return result;
12087}
12088
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012089PyDoc_STRVAR(replace__doc__,
Ezio Melottic1897e72010-06-26 18:50:39 +000012090 "S.replace(old, new[, count]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012091\n\
12092Return a copy of S with all occurrences of substring\n\
Georg Brandlf08a9dd2008-06-10 16:57:31 +000012093old replaced by new. If the optional argument count is\n\
12094given, only the first count occurrences are replaced.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012095
12096static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012097unicode_replace(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012098{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012099 PyObject *str1;
12100 PyObject *str2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012101 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012102 PyObject *result;
12103
Martin v. Löwis18e16552006-02-15 17:27:45 +000012104 if (!PyArg_ParseTuple(args, "OO|n:replace", &str1, &str2, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012105 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012106 if (!PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000012107 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012108 str1 = PyUnicode_FromObject(str1);
12109 if (str1 == NULL || PyUnicode_READY(str1) == -1)
12110 return NULL;
12111 str2 = PyUnicode_FromObject(str2);
Victor Stinnere9a29352011-10-01 02:14:59 +020012112 if (str2 == NULL || PyUnicode_READY(str2) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012113 Py_DECREF(str1);
12114 return NULL;
Walter Dörwaldf6b56ae2003-02-09 23:42:56 +000012115 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012116
12117 result = replace(self, str1, str2, maxcount);
12118
12119 Py_DECREF(str1);
12120 Py_DECREF(str2);
12121 return result;
12122}
12123
Alexander Belopolsky40018472011-02-26 01:02:56 +000012124static PyObject *
12125unicode_repr(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012126{
Walter Dörwald79e913e2007-05-12 11:08:06 +000012127 PyObject *repr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012128 Py_ssize_t isize;
12129 Py_ssize_t osize, squote, dquote, i, o;
12130 Py_UCS4 max, quote;
12131 int ikind, okind;
12132 void *idata, *odata;
Walter Dörwald79e913e2007-05-12 11:08:06 +000012133
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012134 if (PyUnicode_READY(unicode) == -1)
Walter Dörwald79e913e2007-05-12 11:08:06 +000012135 return NULL;
12136
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012137 isize = PyUnicode_GET_LENGTH(unicode);
12138 idata = PyUnicode_DATA(unicode);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012139
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012140 /* Compute length of output, quote characters, and
12141 maximum character */
12142 osize = 2; /* quotes */
12143 max = 127;
12144 squote = dquote = 0;
12145 ikind = PyUnicode_KIND(unicode);
12146 for (i = 0; i < isize; i++) {
12147 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
12148 switch (ch) {
12149 case '\'': squote++; osize++; break;
12150 case '"': dquote++; osize++; break;
12151 case '\\': case '\t': case '\r': case '\n':
12152 osize += 2; break;
12153 default:
12154 /* Fast-path ASCII */
12155 if (ch < ' ' || ch == 0x7f)
12156 osize += 4; /* \xHH */
12157 else if (ch < 0x7f)
12158 osize++;
12159 else if (Py_UNICODE_ISPRINTABLE(ch)) {
12160 osize++;
12161 max = ch > max ? ch : max;
12162 }
12163 else if (ch < 0x100)
12164 osize += 4; /* \xHH */
12165 else if (ch < 0x10000)
12166 osize += 6; /* \uHHHH */
12167 else
12168 osize += 10; /* \uHHHHHHHH */
12169 }
12170 }
12171
12172 quote = '\'';
12173 if (squote) {
12174 if (dquote)
12175 /* Both squote and dquote present. Use squote,
12176 and escape them */
12177 osize += squote;
12178 else
12179 quote = '"';
12180 }
12181
12182 repr = PyUnicode_New(osize, max);
12183 if (repr == NULL)
12184 return NULL;
12185 okind = PyUnicode_KIND(repr);
12186 odata = PyUnicode_DATA(repr);
12187
12188 PyUnicode_WRITE(okind, odata, 0, quote);
12189 PyUnicode_WRITE(okind, odata, osize-1, quote);
12190
12191 for (i = 0, o = 1; i < isize; i++) {
12192 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012193
12194 /* Escape quotes and backslashes */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012195 if ((ch == quote) || (ch == '\\')) {
12196 PyUnicode_WRITE(okind, odata, o++, '\\');
12197 PyUnicode_WRITE(okind, odata, o++, ch);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012198 continue;
12199 }
12200
Benjamin Peterson29060642009-01-31 22:14:21 +000012201 /* Map special whitespace to '\t', \n', '\r' */
Georg Brandl559e5d72008-06-11 18:37:52 +000012202 if (ch == '\t') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012203 PyUnicode_WRITE(okind, odata, o++, '\\');
12204 PyUnicode_WRITE(okind, odata, o++, 't');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012205 }
12206 else if (ch == '\n') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012207 PyUnicode_WRITE(okind, odata, o++, '\\');
12208 PyUnicode_WRITE(okind, odata, o++, 'n');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012209 }
12210 else if (ch == '\r') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012211 PyUnicode_WRITE(okind, odata, o++, '\\');
12212 PyUnicode_WRITE(okind, odata, o++, 'r');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012213 }
12214
12215 /* Map non-printable US ASCII to '\xhh' */
Georg Brandl559e5d72008-06-11 18:37:52 +000012216 else if (ch < ' ' || ch == 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012217 PyUnicode_WRITE(okind, odata, o++, '\\');
12218 PyUnicode_WRITE(okind, odata, o++, 'x');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012219 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12220 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012221 }
12222
Georg Brandl559e5d72008-06-11 18:37:52 +000012223 /* Copy ASCII characters as-is */
12224 else if (ch < 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012225 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000012226 }
12227
Benjamin Peterson29060642009-01-31 22:14:21 +000012228 /* Non-ASCII characters */
Georg Brandl559e5d72008-06-11 18:37:52 +000012229 else {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012230 /* Map Unicode whitespace and control characters
Georg Brandl559e5d72008-06-11 18:37:52 +000012231 (categories Z* and C* except ASCII space)
12232 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012233 if (!Py_UNICODE_ISPRINTABLE(ch)) {
Georg Brandl559e5d72008-06-11 18:37:52 +000012234 /* Map 8-bit characters to '\xhh' */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012235 if (ch <= 0xff) {
12236 PyUnicode_WRITE(okind, odata, o++, '\\');
12237 PyUnicode_WRITE(okind, odata, o++, 'x');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012238 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12239 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012240 }
12241 /* Map 21-bit characters to '\U00xxxxxx' */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012242 else if (ch >= 0x10000) {
12243 PyUnicode_WRITE(okind, odata, o++, '\\');
12244 PyUnicode_WRITE(okind, odata, o++, 'U');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012245 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 28) & 0xF]);
12246 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 24) & 0xF]);
12247 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 20) & 0xF]);
12248 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 16) & 0xF]);
12249 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12250 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12251 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12252 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012253 }
12254 /* Map 16-bit characters to '\uxxxx' */
12255 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012256 PyUnicode_WRITE(okind, odata, o++, '\\');
12257 PyUnicode_WRITE(okind, odata, o++, 'u');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012258 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12259 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12260 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12261 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012262 }
12263 }
12264 /* Copy characters as-is */
12265 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012266 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000012267 }
12268 }
Walter Dörwald79e913e2007-05-12 11:08:06 +000012269 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012270 /* Closing quote already added at the beginning */
Victor Stinner05d11892011-10-06 01:13:58 +020012271 assert(_PyUnicode_CheckConsistency(repr, 1));
Walter Dörwald79e913e2007-05-12 11:08:06 +000012272 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012273}
12274
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012275PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012276 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012277\n\
12278Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080012279such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012280arguments start and end are interpreted as in slice notation.\n\
12281\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012282Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012283
12284static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012285unicode_rfind(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012286{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012287 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012288 Py_ssize_t start;
12289 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012290 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012291
Jesus Ceaac451502011-04-20 17:09:23 +020012292 if (!stringlib_parse_args_finds_unicode("rfind", args, &substring,
12293 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012294 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012295
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012296 if (PyUnicode_READY(self) == -1)
12297 return NULL;
12298 if (PyUnicode_READY(substring) == -1)
12299 return NULL;
12300
Victor Stinner7931d9a2011-11-04 00:22:48 +010012301 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012302
12303 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012304
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012305 if (result == -2)
12306 return NULL;
12307
Christian Heimes217cfd12007-12-02 14:31:20 +000012308 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012309}
12310
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012311PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012312 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012313\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012314Like S.rfind() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012315
12316static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012317unicode_rindex(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012318{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012319 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012320 Py_ssize_t start;
12321 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012322 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012323
Jesus Ceaac451502011-04-20 17:09:23 +020012324 if (!stringlib_parse_args_finds_unicode("rindex", args, &substring,
12325 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012326 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012327
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012328 if (PyUnicode_READY(self) == -1)
12329 return NULL;
12330 if (PyUnicode_READY(substring) == -1)
12331 return NULL;
12332
Victor Stinner7931d9a2011-11-04 00:22:48 +010012333 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012334
12335 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012336
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012337 if (result == -2)
12338 return NULL;
12339
Guido van Rossumd57fd912000-03-10 22:53:23 +000012340 if (result < 0) {
12341 PyErr_SetString(PyExc_ValueError, "substring not found");
12342 return NULL;
12343 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012344
Christian Heimes217cfd12007-12-02 14:31:20 +000012345 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012346}
12347
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012348PyDoc_STRVAR(rjust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012349 "S.rjust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012350\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012351Return S right-justified in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012352done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012353
12354static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012355unicode_rjust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012356{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012357 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012358 Py_UCS4 fillchar = ' ';
12359
Victor Stinnere9a29352011-10-01 02:14:59 +020012360 if (!PyArg_ParseTuple(args, "n|O&:rjust", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012361 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012362
Victor Stinnerc4b49542011-12-11 22:44:26 +010012363 if (PyUnicode_READY(self) < 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012364 return NULL;
12365
Victor Stinnerc4b49542011-12-11 22:44:26 +010012366 if (PyUnicode_GET_LENGTH(self) >= width)
12367 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012368
Victor Stinnerc4b49542011-12-11 22:44:26 +010012369 return pad(self, width - PyUnicode_GET_LENGTH(self), 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012370}
12371
Alexander Belopolsky40018472011-02-26 01:02:56 +000012372PyObject *
12373PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012374{
12375 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +000012376
Guido van Rossumd57fd912000-03-10 22:53:23 +000012377 s = PyUnicode_FromObject(s);
12378 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012379 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012380 if (sep != NULL) {
12381 sep = PyUnicode_FromObject(sep);
12382 if (sep == NULL) {
12383 Py_DECREF(s);
12384 return NULL;
12385 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012386 }
12387
Victor Stinner9310abb2011-10-05 00:59:23 +020012388 result = split(s, sep, maxsplit);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012389
12390 Py_DECREF(s);
12391 Py_XDECREF(sep);
12392 return result;
12393}
12394
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012395PyDoc_STRVAR(split__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012396 "S.split([sep[, maxsplit]]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012397\n\
12398Return a list of the words in S, using sep as the\n\
12399delimiter string. If maxsplit is given, at most maxsplit\n\
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000012400splits are done. If sep is not specified or is None, any\n\
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +000012401whitespace string is a separator and empty strings are\n\
12402removed from the result.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012403
12404static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012405unicode_split(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012406{
12407 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012408 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012409
Martin v. Löwis18e16552006-02-15 17:27:45 +000012410 if (!PyArg_ParseTuple(args, "|On:split", &substring, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012411 return NULL;
12412
12413 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012414 return split(self, NULL, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012415 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012416 return split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012417 else
Victor Stinner7931d9a2011-11-04 00:22:48 +010012418 return PyUnicode_Split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012419}
12420
Thomas Wouters477c8d52006-05-27 19:21:47 +000012421PyObject *
12422PyUnicode_Partition(PyObject *str_in, PyObject *sep_in)
12423{
12424 PyObject* str_obj;
12425 PyObject* sep_obj;
12426 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012427 int kind1, kind2, kind;
12428 void *buf1 = NULL, *buf2 = NULL;
12429 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012430
12431 str_obj = PyUnicode_FromObject(str_in);
Victor Stinnere9a29352011-10-01 02:14:59 +020012432 if (!str_obj || PyUnicode_READY(str_obj) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000012433 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012434 sep_obj = PyUnicode_FromObject(sep_in);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012435 if (!sep_obj || PyUnicode_READY(sep_obj) == -1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000012436 Py_DECREF(str_obj);
12437 return NULL;
12438 }
12439
Victor Stinner14f8f022011-10-05 20:58:25 +020012440 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012441 kind2 = PyUnicode_KIND(sep_obj);
Victor Stinner14f8f022011-10-05 20:58:25 +020012442 kind = Py_MAX(kind1, kind2);
12443 buf1 = PyUnicode_DATA(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012444 if (kind1 != kind)
Victor Stinner14f8f022011-10-05 20:58:25 +020012445 buf1 = _PyUnicode_AsKind(str_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012446 if (!buf1)
12447 goto onError;
12448 buf2 = PyUnicode_DATA(sep_obj);
12449 if (kind2 != kind)
12450 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12451 if (!buf2)
12452 goto onError;
12453 len1 = PyUnicode_GET_LENGTH(str_obj);
12454 len2 = PyUnicode_GET_LENGTH(sep_obj);
12455
Victor Stinner14f8f022011-10-05 20:58:25 +020012456 switch(PyUnicode_KIND(str_obj)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012457 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012458 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12459 out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12460 else
12461 out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012462 break;
12463 case PyUnicode_2BYTE_KIND:
12464 out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12465 break;
12466 case PyUnicode_4BYTE_KIND:
12467 out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12468 break;
12469 default:
12470 assert(0);
12471 out = 0;
12472 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012473
12474 Py_DECREF(sep_obj);
12475 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012476 if (kind1 != kind)
12477 PyMem_Free(buf1);
12478 if (kind2 != kind)
12479 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012480
12481 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012482 onError:
12483 Py_DECREF(sep_obj);
12484 Py_DECREF(str_obj);
12485 if (kind1 != kind && buf1)
12486 PyMem_Free(buf1);
12487 if (kind2 != kind && buf2)
12488 PyMem_Free(buf2);
12489 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012490}
12491
12492
12493PyObject *
12494PyUnicode_RPartition(PyObject *str_in, PyObject *sep_in)
12495{
12496 PyObject* str_obj;
12497 PyObject* sep_obj;
12498 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012499 int kind1, kind2, kind;
12500 void *buf1 = NULL, *buf2 = NULL;
12501 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012502
12503 str_obj = PyUnicode_FromObject(str_in);
12504 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012505 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012506 sep_obj = PyUnicode_FromObject(sep_in);
12507 if (!sep_obj) {
12508 Py_DECREF(str_obj);
12509 return NULL;
12510 }
12511
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012512 kind1 = PyUnicode_KIND(str_in);
12513 kind2 = PyUnicode_KIND(sep_obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +020012514 kind = Py_MAX(kind1, kind2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012515 buf1 = PyUnicode_DATA(str_in);
12516 if (kind1 != kind)
12517 buf1 = _PyUnicode_AsKind(str_in, kind);
12518 if (!buf1)
12519 goto onError;
12520 buf2 = PyUnicode_DATA(sep_obj);
12521 if (kind2 != kind)
12522 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12523 if (!buf2)
12524 goto onError;
12525 len1 = PyUnicode_GET_LENGTH(str_obj);
12526 len2 = PyUnicode_GET_LENGTH(sep_obj);
12527
12528 switch(PyUnicode_KIND(str_in)) {
12529 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012530 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12531 out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12532 else
12533 out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012534 break;
12535 case PyUnicode_2BYTE_KIND:
12536 out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12537 break;
12538 case PyUnicode_4BYTE_KIND:
12539 out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12540 break;
12541 default:
12542 assert(0);
12543 out = 0;
12544 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012545
12546 Py_DECREF(sep_obj);
12547 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012548 if (kind1 != kind)
12549 PyMem_Free(buf1);
12550 if (kind2 != kind)
12551 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012552
12553 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012554 onError:
12555 Py_DECREF(sep_obj);
12556 Py_DECREF(str_obj);
12557 if (kind1 != kind && buf1)
12558 PyMem_Free(buf1);
12559 if (kind2 != kind && buf2)
12560 PyMem_Free(buf2);
12561 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012562}
12563
12564PyDoc_STRVAR(partition__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012565 "S.partition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012566\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012567Search for the separator sep in S, and return the part before it,\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012568the separator itself, and the part after it. If the separator is not\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012569found, return S and two empty strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012570
12571static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012572unicode_partition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012573{
Victor Stinner9310abb2011-10-05 00:59:23 +020012574 return PyUnicode_Partition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012575}
12576
12577PyDoc_STRVAR(rpartition__doc__,
Ezio Melotti5b2b2422010-01-25 11:58:28 +000012578 "S.rpartition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012579\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012580Search for the separator sep in S, starting at the end of S, and return\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012581the part before it, the separator itself, and the part after it. If the\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012582separator is not found, return two empty strings and S.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012583
12584static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012585unicode_rpartition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012586{
Victor Stinner9310abb2011-10-05 00:59:23 +020012587 return PyUnicode_RPartition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012588}
12589
Alexander Belopolsky40018472011-02-26 01:02:56 +000012590PyObject *
12591PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012592{
12593 PyObject *result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012594
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012595 s = PyUnicode_FromObject(s);
12596 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012597 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012598 if (sep != NULL) {
12599 sep = PyUnicode_FromObject(sep);
12600 if (sep == NULL) {
12601 Py_DECREF(s);
12602 return NULL;
12603 }
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012604 }
12605
Victor Stinner9310abb2011-10-05 00:59:23 +020012606 result = rsplit(s, sep, maxsplit);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012607
12608 Py_DECREF(s);
12609 Py_XDECREF(sep);
12610 return result;
12611}
12612
12613PyDoc_STRVAR(rsplit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012614 "S.rsplit([sep[, maxsplit]]) -> list of strings\n\
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012615\n\
12616Return a list of the words in S, using sep as the\n\
12617delimiter string, starting at the end of the string and\n\
12618working to the front. If maxsplit is given, at most maxsplit\n\
12619splits are done. If sep is not specified, any whitespace string\n\
12620is a separator.");
12621
12622static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012623unicode_rsplit(PyObject *self, PyObject *args)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012624{
12625 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012626 Py_ssize_t maxcount = -1;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012627
Martin v. Löwis18e16552006-02-15 17:27:45 +000012628 if (!PyArg_ParseTuple(args, "|On:rsplit", &substring, &maxcount))
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012629 return NULL;
12630
12631 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012632 return rsplit(self, NULL, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012633 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012634 return rsplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012635 else
Victor Stinner9310abb2011-10-05 00:59:23 +020012636 return PyUnicode_RSplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012637}
12638
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012639PyDoc_STRVAR(splitlines__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012640 "S.splitlines([keepends]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012641\n\
12642Return a list of the lines in S, breaking at line boundaries.\n\
Guido van Rossum86662912000-04-11 15:38:46 +000012643Line breaks are not included in the resulting list unless keepends\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012644is given and true.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012645
12646static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012647unicode_splitlines(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012648{
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012649 static char *kwlist[] = {"keepends", 0};
Guido van Rossum86662912000-04-11 15:38:46 +000012650 int keepends = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012651
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012652 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:splitlines",
12653 kwlist, &keepends))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012654 return NULL;
12655
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012656 return PyUnicode_Splitlines(self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012657}
12658
12659static
Guido van Rossumf15a29f2007-05-04 00:41:39 +000012660PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012661{
Victor Stinnerc4b49542011-12-11 22:44:26 +010012662 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012663}
12664
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012665PyDoc_STRVAR(swapcase__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012666 "S.swapcase() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012667\n\
12668Return a copy of S with uppercase characters converted to lowercase\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012669and vice versa.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012670
12671static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012672unicode_swapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012673{
Guido van Rossumd57fd912000-03-10 22:53:23 +000012674 return fixup(self, fixswapcase);
12675}
12676
Georg Brandlceee0772007-11-27 23:48:05 +000012677PyDoc_STRVAR(maketrans__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012678 "str.maketrans(x[, y[, z]]) -> dict (static method)\n\
Georg Brandlceee0772007-11-27 23:48:05 +000012679\n\
12680Return a translation table usable for str.translate().\n\
12681If there is only one argument, it must be a dictionary mapping Unicode\n\
12682ordinals (integers) or characters to Unicode ordinals, strings or None.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012683Character keys will be then converted to ordinals.\n\
Georg Brandlceee0772007-11-27 23:48:05 +000012684If there are two arguments, they must be strings of equal length, and\n\
12685in the resulting dictionary, each character in x will be mapped to the\n\
12686character at the same position in y. If there is a third argument, it\n\
12687must be a string, whose characters will be mapped to None in the result.");
12688
12689static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012690unicode_maketrans(PyObject *null, PyObject *args)
Georg Brandlceee0772007-11-27 23:48:05 +000012691{
12692 PyObject *x, *y = NULL, *z = NULL;
12693 PyObject *new = NULL, *key, *value;
12694 Py_ssize_t i = 0;
12695 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012696
Georg Brandlceee0772007-11-27 23:48:05 +000012697 if (!PyArg_ParseTuple(args, "O|UU:maketrans", &x, &y, &z))
12698 return NULL;
12699 new = PyDict_New();
12700 if (!new)
12701 return NULL;
12702 if (y != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012703 int x_kind, y_kind, z_kind;
12704 void *x_data, *y_data, *z_data;
12705
Georg Brandlceee0772007-11-27 23:48:05 +000012706 /* x must be a string too, of equal length */
Georg Brandlceee0772007-11-27 23:48:05 +000012707 if (!PyUnicode_Check(x)) {
12708 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
12709 "be a string if there is a second argument");
12710 goto err;
12711 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012712 if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012713 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
12714 "arguments must have equal length");
12715 goto err;
12716 }
12717 /* create entries for translating chars in x to those in y */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012718 x_kind = PyUnicode_KIND(x);
12719 y_kind = PyUnicode_KIND(y);
12720 x_data = PyUnicode_DATA(x);
12721 y_data = PyUnicode_DATA(y);
12722 for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
12723 key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
12724 value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000012725 if (!key || !value)
12726 goto err;
12727 res = PyDict_SetItem(new, key, value);
12728 Py_DECREF(key);
12729 Py_DECREF(value);
12730 if (res < 0)
12731 goto err;
12732 }
12733 /* create entries for deleting chars in z */
12734 if (z != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012735 z_kind = PyUnicode_KIND(z);
12736 z_data = PyUnicode_DATA(z);
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012737 for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012738 key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000012739 if (!key)
12740 goto err;
12741 res = PyDict_SetItem(new, key, Py_None);
12742 Py_DECREF(key);
12743 if (res < 0)
12744 goto err;
12745 }
12746 }
12747 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012748 int kind;
12749 void *data;
12750
Georg Brandlceee0772007-11-27 23:48:05 +000012751 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +000012752 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012753 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
12754 "to maketrans it must be a dict");
12755 goto err;
12756 }
12757 /* copy entries into the new dict, converting string keys to int keys */
12758 while (PyDict_Next(x, &i, &key, &value)) {
12759 if (PyUnicode_Check(key)) {
12760 /* convert string keys to integer keys */
12761 PyObject *newkey;
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012762 if (PyUnicode_GET_LENGTH(key) != 1) {
Georg Brandlceee0772007-11-27 23:48:05 +000012763 PyErr_SetString(PyExc_ValueError, "string keys in translate "
12764 "table must be of length 1");
12765 goto err;
12766 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012767 kind = PyUnicode_KIND(key);
12768 data = PyUnicode_DATA(key);
12769 newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
Georg Brandlceee0772007-11-27 23:48:05 +000012770 if (!newkey)
12771 goto err;
12772 res = PyDict_SetItem(new, newkey, value);
12773 Py_DECREF(newkey);
12774 if (res < 0)
12775 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +000012776 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012777 /* just keep integer keys */
12778 if (PyDict_SetItem(new, key, value) < 0)
12779 goto err;
12780 } else {
12781 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
12782 "be strings or integers");
12783 goto err;
12784 }
12785 }
12786 }
12787 return new;
12788 err:
12789 Py_DECREF(new);
12790 return NULL;
12791}
12792
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012793PyDoc_STRVAR(translate__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012794 "S.translate(table) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012795\n\
12796Return a copy of the string S, where all characters have been mapped\n\
12797through the given translation table, which must be a mapping of\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012798Unicode ordinals to Unicode ordinals, strings, or None.\n\
Walter Dörwald5c1ee172002-09-04 20:31:32 +000012799Unmapped characters are left untouched. Characters mapped to None\n\
12800are deleted.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012801
12802static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012803unicode_translate(PyObject *self, PyObject *table)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012804{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012805 return _PyUnicode_TranslateCharmap(self, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012806}
12807
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012808PyDoc_STRVAR(upper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012809 "S.upper() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012810\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012811Return a copy of S converted to uppercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012812
12813static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012814unicode_upper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012815{
Guido van Rossumd57fd912000-03-10 22:53:23 +000012816 return fixup(self, fixupper);
12817}
12818
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012819PyDoc_STRVAR(zfill__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012820 "S.zfill(width) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012821\n\
Benjamin Peterson9aa42992008-09-10 21:57:34 +000012822Pad a numeric string S with zeros on the left, to fill a field\n\
12823of the specified width. The string S is never truncated.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012824
12825static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012826unicode_zfill(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012827{
Martin v. Löwis18e16552006-02-15 17:27:45 +000012828 Py_ssize_t fill;
Victor Stinner9310abb2011-10-05 00:59:23 +020012829 PyObject *u;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012830 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012831 int kind;
12832 void *data;
12833 Py_UCS4 chr;
12834
Martin v. Löwis18e16552006-02-15 17:27:45 +000012835 if (!PyArg_ParseTuple(args, "n:zfill", &width))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012836 return NULL;
12837
Victor Stinnerc4b49542011-12-11 22:44:26 +010012838 if (PyUnicode_READY(self) < 0)
12839 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012840
Victor Stinnerc4b49542011-12-11 22:44:26 +010012841 if (PyUnicode_GET_LENGTH(self) >= width)
12842 return unicode_result_unchanged(self);
12843
12844 fill = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012845
12846 u = pad(self, fill, 0, '0');
12847
Walter Dörwald068325e2002-04-15 13:36:47 +000012848 if (u == NULL)
12849 return NULL;
12850
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012851 kind = PyUnicode_KIND(u);
12852 data = PyUnicode_DATA(u);
12853 chr = PyUnicode_READ(kind, data, fill);
12854
12855 if (chr == '+' || chr == '-') {
Guido van Rossumd57fd912000-03-10 22:53:23 +000012856 /* move sign to beginning of string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012857 PyUnicode_WRITE(kind, data, 0, chr);
12858 PyUnicode_WRITE(kind, data, fill, '0');
Guido van Rossumd57fd912000-03-10 22:53:23 +000012859 }
12860
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012861 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +010012862 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012863}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012864
12865#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012866static PyObject *
12867unicode__decimal2ascii(PyObject *self)
12868{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012869 return PyUnicode_TransformDecimalAndSpaceToASCII(self);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012870}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012871#endif
12872
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012873PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012874 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012875\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000012876Return True if S starts with the specified prefix, False otherwise.\n\
12877With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012878With optional end, stop comparing S at that position.\n\
12879prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012880
12881static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012882unicode_startswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000012883 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012884{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012885 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012886 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012887 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012888 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012889 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012890
Jesus Ceaac451502011-04-20 17:09:23 +020012891 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000012892 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012893 if (PyTuple_Check(subobj)) {
12894 Py_ssize_t i;
12895 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012896 substring = PyUnicode_FromObject(PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012897 if (substring == NULL)
12898 return NULL;
12899 result = tailmatch(self, substring, start, end, -1);
12900 Py_DECREF(substring);
12901 if (result) {
12902 Py_RETURN_TRUE;
12903 }
12904 }
12905 /* nothing matched */
12906 Py_RETURN_FALSE;
12907 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012908 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030012909 if (substring == NULL) {
12910 if (PyErr_ExceptionMatches(PyExc_TypeError))
12911 PyErr_Format(PyExc_TypeError, "startswith first arg must be str or "
12912 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000012913 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030012914 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012915 result = tailmatch(self, substring, start, end, -1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012916 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012917 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012918}
12919
12920
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012921PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012922 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012923\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000012924Return True if S ends with the specified suffix, False otherwise.\n\
12925With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012926With optional end, stop comparing S at that position.\n\
12927suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012928
12929static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012930unicode_endswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000012931 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012932{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012933 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012934 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012935 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012936 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012937 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012938
Jesus Ceaac451502011-04-20 17:09:23 +020012939 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000012940 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012941 if (PyTuple_Check(subobj)) {
12942 Py_ssize_t i;
12943 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012944 substring = PyUnicode_FromObject(
Benjamin Peterson29060642009-01-31 22:14:21 +000012945 PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012946 if (substring == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000012947 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012948 result = tailmatch(self, substring, start, end, +1);
12949 Py_DECREF(substring);
12950 if (result) {
12951 Py_RETURN_TRUE;
12952 }
12953 }
12954 Py_RETURN_FALSE;
12955 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012956 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030012957 if (substring == NULL) {
12958 if (PyErr_ExceptionMatches(PyExc_TypeError))
12959 PyErr_Format(PyExc_TypeError, "endswith first arg must be str or "
12960 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000012961 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030012962 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012963 result = tailmatch(self, substring, start, end, +1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012964 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012965 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012966}
12967
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012968#include "stringlib/unicode_format.h"
Eric Smith8c663262007-08-25 02:26:07 +000012969
12970PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012971 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000012972\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012973Return a formatted version of S, using substitutions from args and kwargs.\n\
12974The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +000012975
Eric Smith27bbca62010-11-04 17:06:58 +000012976PyDoc_STRVAR(format_map__doc__,
12977 "S.format_map(mapping) -> str\n\
12978\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012979Return a formatted version of S, using substitutions from mapping.\n\
12980The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +000012981
Eric Smith4a7d76d2008-05-30 18:10:19 +000012982static PyObject *
12983unicode__format__(PyObject* self, PyObject* args)
12984{
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012985 PyObject *format_spec, *out;
Eric Smith4a7d76d2008-05-30 18:10:19 +000012986
12987 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
12988 return NULL;
12989
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012990 out = _PyUnicode_FormatAdvanced(self, format_spec, 0,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012991 PyUnicode_GET_LENGTH(format_spec));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012992 return out;
Eric Smith4a7d76d2008-05-30 18:10:19 +000012993}
12994
Eric Smith8c663262007-08-25 02:26:07 +000012995PyDoc_STRVAR(p_format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012996 "S.__format__(format_spec) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000012997\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012998Return a formatted version of S as described by format_spec.");
Eric Smith8c663262007-08-25 02:26:07 +000012999
13000static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013001unicode__sizeof__(PyObject *v)
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013002{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013003 Py_ssize_t size;
13004
13005 /* If it's a compact object, account for base structure +
13006 character data. */
13007 if (PyUnicode_IS_COMPACT_ASCII(v))
13008 size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(v) + 1;
13009 else if (PyUnicode_IS_COMPACT(v))
13010 size = sizeof(PyCompactUnicodeObject) +
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013011 (PyUnicode_GET_LENGTH(v) + 1) * PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013012 else {
13013 /* If it is a two-block object, account for base object, and
13014 for character block if present. */
13015 size = sizeof(PyUnicodeObject);
Victor Stinnerc3c74152011-10-02 20:39:55 +020013016 if (_PyUnicode_DATA_ANY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013017 size += (PyUnicode_GET_LENGTH(v) + 1) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013018 PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013019 }
13020 /* If the wstr pointer is present, account for it unless it is shared
Victor Stinnera3be6132011-10-03 02:16:37 +020013021 with the data pointer. Check if the data is not shared. */
Victor Stinner03490912011-10-03 23:45:12 +020013022 if (_PyUnicode_HAS_WSTR_MEMORY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013023 size += (PyUnicode_WSTR_LENGTH(v) + 1) * sizeof(wchar_t);
Victor Stinner829c0ad2011-10-03 01:08:02 +020013024 if (_PyUnicode_HAS_UTF8_MEMORY(v))
Victor Stinnere90fe6a2011-10-01 16:48:13 +020013025 size += PyUnicode_UTF8_LENGTH(v) + 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013026
13027 return PyLong_FromSsize_t(size);
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013028}
13029
13030PyDoc_STRVAR(sizeof__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013031 "S.__sizeof__() -> size of S in memory, in bytes");
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013032
13033static PyObject *
Victor Stinner034f6cf2011-09-30 02:26:44 +020013034unicode_getnewargs(PyObject *v)
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013035{
Victor Stinnerbf6e5602011-12-12 01:53:47 +010013036 PyObject *copy = _PyUnicode_Copy(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013037 if (!copy)
13038 return NULL;
13039 return Py_BuildValue("(N)", copy);
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013040}
13041
Guido van Rossumd57fd912000-03-10 22:53:23 +000013042static PyMethodDef unicode_methods[] = {
13043
13044 /* Order is according to common usage: often used methods should
13045 appear first, since lookup is done sequentially. */
13046
Benjamin Peterson28a4dce2010-12-12 01:33:04 +000013047 {"encode", (PyCFunction) unicode_encode, METH_VARARGS | METH_KEYWORDS, encode__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013048 {"replace", (PyCFunction) unicode_replace, METH_VARARGS, replace__doc__},
13049 {"split", (PyCFunction) unicode_split, METH_VARARGS, split__doc__},
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013050 {"rsplit", (PyCFunction) unicode_rsplit, METH_VARARGS, rsplit__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013051 {"join", (PyCFunction) unicode_join, METH_O, join__doc__},
13052 {"capitalize", (PyCFunction) unicode_capitalize, METH_NOARGS, capitalize__doc__},
13053 {"title", (PyCFunction) unicode_title, METH_NOARGS, title__doc__},
13054 {"center", (PyCFunction) unicode_center, METH_VARARGS, center__doc__},
13055 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
13056 {"expandtabs", (PyCFunction) unicode_expandtabs, METH_VARARGS, expandtabs__doc__},
13057 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013058 {"partition", (PyCFunction) unicode_partition, METH_O, partition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013059 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
13060 {"ljust", (PyCFunction) unicode_ljust, METH_VARARGS, ljust__doc__},
13061 {"lower", (PyCFunction) unicode_lower, METH_NOARGS, lower__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013062 {"lstrip", (PyCFunction) unicode_lstrip, METH_VARARGS, lstrip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013063 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
13064 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
13065 {"rjust", (PyCFunction) unicode_rjust, METH_VARARGS, rjust__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013066 {"rstrip", (PyCFunction) unicode_rstrip, METH_VARARGS, rstrip__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013067 {"rpartition", (PyCFunction) unicode_rpartition, METH_O, rpartition__doc__},
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010013068 {"splitlines", (PyCFunction) unicode_splitlines, METH_VARARGS | METH_KEYWORDS, splitlines__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013069 {"strip", (PyCFunction) unicode_strip, METH_VARARGS, strip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013070 {"swapcase", (PyCFunction) unicode_swapcase, METH_NOARGS, swapcase__doc__},
13071 {"translate", (PyCFunction) unicode_translate, METH_O, translate__doc__},
13072 {"upper", (PyCFunction) unicode_upper, METH_NOARGS, upper__doc__},
13073 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
13074 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
13075 {"islower", (PyCFunction) unicode_islower, METH_NOARGS, islower__doc__},
13076 {"isupper", (PyCFunction) unicode_isupper, METH_NOARGS, isupper__doc__},
13077 {"istitle", (PyCFunction) unicode_istitle, METH_NOARGS, istitle__doc__},
13078 {"isspace", (PyCFunction) unicode_isspace, METH_NOARGS, isspace__doc__},
13079 {"isdecimal", (PyCFunction) unicode_isdecimal, METH_NOARGS, isdecimal__doc__},
13080 {"isdigit", (PyCFunction) unicode_isdigit, METH_NOARGS, isdigit__doc__},
13081 {"isnumeric", (PyCFunction) unicode_isnumeric, METH_NOARGS, isnumeric__doc__},
13082 {"isalpha", (PyCFunction) unicode_isalpha, METH_NOARGS, isalpha__doc__},
13083 {"isalnum", (PyCFunction) unicode_isalnum, METH_NOARGS, isalnum__doc__},
Martin v. Löwis47383402007-08-15 07:32:56 +000013084 {"isidentifier", (PyCFunction) unicode_isidentifier, METH_NOARGS, isidentifier__doc__},
Georg Brandl559e5d72008-06-11 18:37:52 +000013085 {"isprintable", (PyCFunction) unicode_isprintable, METH_NOARGS, isprintable__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013086 {"zfill", (PyCFunction) unicode_zfill, METH_VARARGS, zfill__doc__},
Eric Smith9cd1e092007-08-31 18:39:38 +000013087 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +000013088 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
Eric Smith4a7d76d2008-05-30 18:10:19 +000013089 {"__format__", (PyCFunction) unicode__format__, METH_VARARGS, p_format__doc__},
Georg Brandlceee0772007-11-27 23:48:05 +000013090 {"maketrans", (PyCFunction) unicode_maketrans,
13091 METH_VARARGS | METH_STATIC, maketrans__doc__},
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013092 {"__sizeof__", (PyCFunction) unicode__sizeof__, METH_NOARGS, sizeof__doc__},
Walter Dörwald068325e2002-04-15 13:36:47 +000013093#if 0
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013094 {"capwords", (PyCFunction) unicode_capwords, METH_NOARGS, capwords__doc__},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013095#endif
13096
13097#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013098 /* These methods are just used for debugging the implementation. */
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013099 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013100#endif
13101
Benjamin Peterson14339b62009-01-31 16:36:08 +000013102 {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013103 {NULL, NULL}
13104};
13105
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013106static PyObject *
13107unicode_mod(PyObject *v, PyObject *w)
13108{
Brian Curtindfc80e32011-08-10 20:28:54 -050013109 if (!PyUnicode_Check(v))
13110 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson29060642009-01-31 22:14:21 +000013111 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013112}
13113
13114static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013115 0, /*nb_add*/
13116 0, /*nb_subtract*/
13117 0, /*nb_multiply*/
13118 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013119};
13120
Guido van Rossumd57fd912000-03-10 22:53:23 +000013121static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013122 (lenfunc) unicode_length, /* sq_length */
13123 PyUnicode_Concat, /* sq_concat */
13124 (ssizeargfunc) unicode_repeat, /* sq_repeat */
13125 (ssizeargfunc) unicode_getitem, /* sq_item */
13126 0, /* sq_slice */
13127 0, /* sq_ass_item */
13128 0, /* sq_ass_slice */
13129 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013130};
13131
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013132static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013133unicode_subscript(PyObject* self, PyObject* item)
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013134{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013135 if (PyUnicode_READY(self) == -1)
13136 return NULL;
13137
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000013138 if (PyIndex_Check(item)) {
13139 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013140 if (i == -1 && PyErr_Occurred())
13141 return NULL;
13142 if (i < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013143 i += PyUnicode_GET_LENGTH(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013144 return unicode_getitem(self, i);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013145 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000013146 Py_ssize_t start, stop, step, slicelength, cur, i;
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013147 PyObject *result;
13148 void *src_data, *dest_data;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013149 int src_kind, dest_kind;
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013150 Py_UCS4 ch, max_char, kind_limit;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013151
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013152 if (PySlice_GetIndicesEx(item, PyUnicode_GET_LENGTH(self),
Benjamin Peterson29060642009-01-31 22:14:21 +000013153 &start, &stop, &step, &slicelength) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013154 return NULL;
13155 }
13156
13157 if (slicelength <= 0) {
Victor Stinner382955f2011-12-11 21:44:00 +010013158 Py_INCREF(unicode_empty);
13159 return unicode_empty;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013160 } else if (start == 0 && step == 1 &&
Victor Stinnerc4b49542011-12-11 22:44:26 +010013161 slicelength == PyUnicode_GET_LENGTH(self)) {
13162 return unicode_result_unchanged(self);
Thomas Woutersed03b412007-08-28 21:37:11 +000013163 } else if (step == 1) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013164 return PyUnicode_Substring(self,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013165 start, start + slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013166 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013167 /* General case */
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013168 src_kind = PyUnicode_KIND(self);
13169 src_data = PyUnicode_DATA(self);
Victor Stinner55c99112011-10-13 01:17:06 +020013170 if (!PyUnicode_IS_ASCII(self)) {
13171 kind_limit = kind_maxchar_limit(src_kind);
13172 max_char = 0;
13173 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
13174 ch = PyUnicode_READ(src_kind, src_data, cur);
13175 if (ch > max_char) {
13176 max_char = ch;
13177 if (max_char >= kind_limit)
13178 break;
13179 }
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013180 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013181 }
Victor Stinner55c99112011-10-13 01:17:06 +020013182 else
13183 max_char = 127;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013184 result = PyUnicode_New(slicelength, max_char);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013185 if (result == NULL)
13186 return NULL;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013187 dest_kind = PyUnicode_KIND(result);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013188 dest_data = PyUnicode_DATA(result);
13189
13190 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013191 Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
13192 PyUnicode_WRITE(dest_kind, dest_data, i, ch);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013193 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013194 assert(_PyUnicode_CheckConsistency(result, 1));
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013195 return result;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013196 } else {
13197 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
13198 return NULL;
13199 }
13200}
13201
13202static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013203 (lenfunc)unicode_length, /* mp_length */
13204 (binaryfunc)unicode_subscript, /* mp_subscript */
13205 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013206};
13207
Guido van Rossumd57fd912000-03-10 22:53:23 +000013208
Guido van Rossumd57fd912000-03-10 22:53:23 +000013209/* Helpers for PyUnicode_Format() */
13210
13211static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +000013212getnextarg(PyObject *args, Py_ssize_t arglen, Py_ssize_t *p_argidx)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013213{
Martin v. Löwis18e16552006-02-15 17:27:45 +000013214 Py_ssize_t argidx = *p_argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013215 if (argidx < arglen) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013216 (*p_argidx)++;
13217 if (arglen < 0)
13218 return args;
13219 else
13220 return PyTuple_GetItem(args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013221 }
13222 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013223 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013224 return NULL;
13225}
13226
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013227/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013228
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013229static PyObject *
13230formatfloat(PyObject *v, int flags, int prec, int type)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013231{
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013232 char *p;
13233 PyObject *result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013234 double x;
Tim Petersced69f82003-09-16 20:30:58 +000013235
Guido van Rossumd57fd912000-03-10 22:53:23 +000013236 x = PyFloat_AsDouble(v);
13237 if (x == -1.0 && PyErr_Occurred())
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013238 return NULL;
13239
Guido van Rossumd57fd912000-03-10 22:53:23 +000013240 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000013241 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +000013242
Eric Smith0923d1d2009-04-16 20:16:10 +000013243 p = PyOS_double_to_string(x, type, prec,
13244 (flags & F_ALT) ? Py_DTSF_ALT : 0, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013245 if (p == NULL)
13246 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013247 result = PyUnicode_DecodeASCII(p, strlen(p), NULL);
Eric Smith0923d1d2009-04-16 20:16:10 +000013248 PyMem_Free(p);
13249 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013250}
13251
Tim Peters38fd5b62000-09-21 05:43:11 +000013252static PyObject*
13253formatlong(PyObject *val, int flags, int prec, int type)
13254{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013255 char *buf;
13256 int len;
13257 PyObject *str; /* temporary string object. */
13258 PyObject *result;
Tim Peters38fd5b62000-09-21 05:43:11 +000013259
Benjamin Peterson14339b62009-01-31 16:36:08 +000013260 str = _PyBytes_FormatLong(val, flags, prec, type, &buf, &len);
13261 if (!str)
13262 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013263 result = PyUnicode_DecodeASCII(buf, len, NULL);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013264 Py_DECREF(str);
13265 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +000013266}
13267
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013268static Py_UCS4
13269formatchar(PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013270{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000013271 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000013272 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013273 if (PyUnicode_GET_LENGTH(v) == 1) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013274 return PyUnicode_READ_CHAR(v, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +000013275 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013276 goto onError;
13277 }
13278 else {
13279 /* Integer input truncated to a character */
13280 long x;
13281 x = PyLong_AsLong(v);
13282 if (x == -1 && PyErr_Occurred())
13283 goto onError;
13284
Victor Stinner8faf8212011-12-08 22:14:11 +010013285 if (x < 0 || x > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013286 PyErr_SetString(PyExc_OverflowError,
13287 "%c arg not in range(0x110000)");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013288 return (Py_UCS4) -1;
Benjamin Peterson29060642009-01-31 22:14:21 +000013289 }
13290
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013291 return (Py_UCS4) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013292 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000013293
Benjamin Peterson29060642009-01-31 22:14:21 +000013294 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000013295 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013296 "%c requires int or char");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013297 return (Py_UCS4) -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013298}
13299
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013300static int
13301repeat_accumulate(_PyAccu *acc, PyObject *obj, Py_ssize_t count)
13302{
13303 int r;
13304 assert(count > 0);
13305 assert(PyUnicode_Check(obj));
13306 if (count > 5) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013307 PyObject *repeated = unicode_repeat(obj, count);
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013308 if (repeated == NULL)
13309 return -1;
13310 r = _PyAccu_Accumulate(acc, repeated);
13311 Py_DECREF(repeated);
13312 return r;
13313 }
13314 else {
13315 do {
13316 if (_PyAccu_Accumulate(acc, obj))
13317 return -1;
13318 } while (--count);
13319 return 0;
13320 }
13321}
13322
Alexander Belopolsky40018472011-02-26 01:02:56 +000013323PyObject *
13324PyUnicode_Format(PyObject *format, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013325{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013326 void *fmt;
13327 int fmtkind;
13328 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013329 int kind;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013330 int r;
13331 Py_ssize_t fmtcnt, fmtpos, arglen, argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013332 int args_owned = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013333 PyObject *dict = NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013334 PyObject *temp = NULL;
13335 PyObject *second = NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013336 PyObject *uformat;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013337 _PyAccu acc;
13338 static PyObject *plus, *minus, *blank, *zero, *percent;
13339
13340 if (!plus && !(plus = get_latin1_char('+')))
13341 return NULL;
13342 if (!minus && !(minus = get_latin1_char('-')))
13343 return NULL;
13344 if (!blank && !(blank = get_latin1_char(' ')))
13345 return NULL;
13346 if (!zero && !(zero = get_latin1_char('0')))
13347 return NULL;
13348 if (!percent && !(percent = get_latin1_char('%')))
13349 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000013350
Guido van Rossumd57fd912000-03-10 22:53:23 +000013351 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013352 PyErr_BadInternalCall();
13353 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013354 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013355 uformat = PyUnicode_FromObject(format);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013356 if (uformat == NULL || PyUnicode_READY(uformat) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000013357 return NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013358 if (_PyAccu_Init(&acc))
13359 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013360 fmt = PyUnicode_DATA(uformat);
13361 fmtkind = PyUnicode_KIND(uformat);
13362 fmtcnt = PyUnicode_GET_LENGTH(uformat);
13363 fmtpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013364
Guido van Rossumd57fd912000-03-10 22:53:23 +000013365 if (PyTuple_Check(args)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013366 arglen = PyTuple_Size(args);
13367 argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013368 }
13369 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013370 arglen = -1;
13371 argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013372 }
Christian Heimes90aa7642007-12-19 02:45:37 +000013373 if (Py_TYPE(args)->tp_as_mapping && !PyTuple_Check(args) &&
Christian Heimesf3863112007-11-22 07:46:41 +000013374 !PyUnicode_Check(args))
Benjamin Peterson29060642009-01-31 22:14:21 +000013375 dict = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013376
13377 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013378 if (PyUnicode_READ(fmtkind, fmt, fmtpos) != '%') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013379 PyObject *nonfmt;
13380 Py_ssize_t nonfmtpos;
13381 nonfmtpos = fmtpos++;
13382 while (fmtcnt >= 0 &&
13383 PyUnicode_READ(fmtkind, fmt, fmtpos) != '%') {
13384 fmtpos++;
13385 fmtcnt--;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013386 }
Victor Stinner7931d9a2011-11-04 00:22:48 +010013387 nonfmt = PyUnicode_Substring(uformat, nonfmtpos, fmtpos);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013388 if (nonfmt == NULL)
13389 goto onError;
13390 r = _PyAccu_Accumulate(&acc, nonfmt);
13391 Py_DECREF(nonfmt);
13392 if (r)
13393 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013394 }
13395 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013396 /* Got a format specifier */
13397 int flags = 0;
13398 Py_ssize_t width = -1;
13399 int prec = -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013400 Py_UCS4 c = '\0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013401 Py_UCS4 fill, sign;
Benjamin Peterson29060642009-01-31 22:14:21 +000013402 int isnumok;
13403 PyObject *v = NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013404 void *pbuf = NULL;
13405 Py_ssize_t pindex, len;
13406 PyObject *signobj = NULL, *fillobj = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013407
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013408 fmtpos++;
13409 if (PyUnicode_READ(fmtkind, fmt, fmtpos) == '(') {
13410 Py_ssize_t keystart;
Benjamin Peterson29060642009-01-31 22:14:21 +000013411 Py_ssize_t keylen;
13412 PyObject *key;
13413 int pcount = 1;
Christian Heimesa612dc02008-02-24 13:08:18 +000013414
Benjamin Peterson29060642009-01-31 22:14:21 +000013415 if (dict == NULL) {
13416 PyErr_SetString(PyExc_TypeError,
13417 "format requires a mapping");
13418 goto onError;
13419 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013420 ++fmtpos;
Benjamin Peterson29060642009-01-31 22:14:21 +000013421 --fmtcnt;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013422 keystart = fmtpos;
Benjamin Peterson29060642009-01-31 22:14:21 +000013423 /* Skip over balanced parentheses */
13424 while (pcount > 0 && --fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013425 if (PyUnicode_READ(fmtkind, fmt, fmtpos) == ')')
Benjamin Peterson29060642009-01-31 22:14:21 +000013426 --pcount;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013427 else if (PyUnicode_READ(fmtkind, fmt, fmtpos) == '(')
Benjamin Peterson29060642009-01-31 22:14:21 +000013428 ++pcount;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013429 fmtpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +000013430 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013431 keylen = fmtpos - keystart - 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000013432 if (fmtcnt < 0 || pcount > 0) {
13433 PyErr_SetString(PyExc_ValueError,
13434 "incomplete format key");
13435 goto onError;
13436 }
Victor Stinner7931d9a2011-11-04 00:22:48 +010013437 key = PyUnicode_Substring(uformat,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013438 keystart, keystart + keylen);
Benjamin Peterson29060642009-01-31 22:14:21 +000013439 if (key == NULL)
13440 goto onError;
13441 if (args_owned) {
13442 Py_DECREF(args);
13443 args_owned = 0;
13444 }
13445 args = PyObject_GetItem(dict, key);
13446 Py_DECREF(key);
13447 if (args == NULL) {
13448 goto onError;
13449 }
13450 args_owned = 1;
13451 arglen = -1;
13452 argidx = -2;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013453 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013454 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013455 switch (c = PyUnicode_READ(fmtkind, fmt, fmtpos++)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013456 case '-': flags |= F_LJUST; continue;
13457 case '+': flags |= F_SIGN; continue;
13458 case ' ': flags |= F_BLANK; continue;
13459 case '#': flags |= F_ALT; continue;
13460 case '0': flags |= F_ZERO; continue;
13461 }
13462 break;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013463 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013464 if (c == '*') {
13465 v = getnextarg(args, arglen, &argidx);
13466 if (v == NULL)
13467 goto onError;
13468 if (!PyLong_Check(v)) {
13469 PyErr_SetString(PyExc_TypeError,
13470 "* wants int");
13471 goto onError;
13472 }
13473 width = PyLong_AsLong(v);
13474 if (width == -1 && PyErr_Occurred())
13475 goto onError;
13476 if (width < 0) {
13477 flags |= F_LJUST;
13478 width = -width;
13479 }
13480 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013481 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013482 }
13483 else if (c >= '0' && c <= '9') {
13484 width = c - '0';
13485 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013486 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013487 if (c < '0' || c > '9')
13488 break;
13489 if ((width*10) / 10 != width) {
13490 PyErr_SetString(PyExc_ValueError,
13491 "width too big");
Benjamin Peterson14339b62009-01-31 16:36:08 +000013492 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +000013493 }
13494 width = width*10 + (c - '0');
13495 }
13496 }
13497 if (c == '.') {
13498 prec = 0;
13499 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013500 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013501 if (c == '*') {
13502 v = getnextarg(args, arglen, &argidx);
13503 if (v == NULL)
13504 goto onError;
13505 if (!PyLong_Check(v)) {
13506 PyErr_SetString(PyExc_TypeError,
13507 "* wants int");
13508 goto onError;
13509 }
13510 prec = PyLong_AsLong(v);
13511 if (prec == -1 && PyErr_Occurred())
13512 goto onError;
13513 if (prec < 0)
13514 prec = 0;
13515 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013516 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013517 }
13518 else if (c >= '0' && c <= '9') {
13519 prec = c - '0';
13520 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013521 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013522 if (c < '0' || c > '9')
13523 break;
13524 if ((prec*10) / 10 != prec) {
13525 PyErr_SetString(PyExc_ValueError,
13526 "prec too big");
13527 goto onError;
13528 }
13529 prec = prec*10 + (c - '0');
13530 }
13531 }
13532 } /* prec */
13533 if (fmtcnt >= 0) {
13534 if (c == 'h' || c == 'l' || c == 'L') {
13535 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013536 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013537 }
13538 }
13539 if (fmtcnt < 0) {
13540 PyErr_SetString(PyExc_ValueError,
13541 "incomplete format");
13542 goto onError;
13543 }
13544 if (c != '%') {
13545 v = getnextarg(args, arglen, &argidx);
13546 if (v == NULL)
13547 goto onError;
13548 }
13549 sign = 0;
13550 fill = ' ';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013551 fillobj = blank;
Benjamin Peterson29060642009-01-31 22:14:21 +000013552 switch (c) {
13553
13554 case '%':
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013555 _PyAccu_Accumulate(&acc, percent);
13556 continue;
Benjamin Peterson29060642009-01-31 22:14:21 +000013557
13558 case 's':
13559 case 'r':
13560 case 'a':
Victor Stinner808fc0a2010-03-22 12:50:40 +000013561 if (PyUnicode_CheckExact(v) && c == 's') {
Benjamin Peterson29060642009-01-31 22:14:21 +000013562 temp = v;
13563 Py_INCREF(temp);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013564 }
13565 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013566 if (c == 's')
13567 temp = PyObject_Str(v);
13568 else if (c == 'r')
13569 temp = PyObject_Repr(v);
13570 else
13571 temp = PyObject_ASCII(v);
13572 if (temp == NULL)
13573 goto onError;
13574 if (PyUnicode_Check(temp))
13575 /* nothing to do */;
13576 else {
13577 Py_DECREF(temp);
13578 PyErr_SetString(PyExc_TypeError,
13579 "%s argument has non-string str()");
13580 goto onError;
13581 }
13582 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013583 if (PyUnicode_READY(temp) == -1) {
13584 Py_CLEAR(temp);
13585 goto onError;
13586 }
13587 pbuf = PyUnicode_DATA(temp);
13588 kind = PyUnicode_KIND(temp);
13589 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013590 if (prec >= 0 && len > prec)
13591 len = prec;
13592 break;
13593
13594 case 'i':
13595 case 'd':
13596 case 'u':
13597 case 'o':
13598 case 'x':
13599 case 'X':
Benjamin Peterson29060642009-01-31 22:14:21 +000013600 isnumok = 0;
13601 if (PyNumber_Check(v)) {
13602 PyObject *iobj=NULL;
13603
13604 if (PyLong_Check(v)) {
13605 iobj = v;
13606 Py_INCREF(iobj);
13607 }
13608 else {
13609 iobj = PyNumber_Long(v);
13610 }
13611 if (iobj!=NULL) {
13612 if (PyLong_Check(iobj)) {
13613 isnumok = 1;
Senthil Kumaran9ebe08d2011-07-03 21:03:16 -070013614 temp = formatlong(iobj, flags, prec, (c == 'i'? 'd': c));
Benjamin Peterson29060642009-01-31 22:14:21 +000013615 Py_DECREF(iobj);
13616 if (!temp)
13617 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013618 if (PyUnicode_READY(temp) == -1) {
13619 Py_CLEAR(temp);
13620 goto onError;
13621 }
13622 pbuf = PyUnicode_DATA(temp);
13623 kind = PyUnicode_KIND(temp);
13624 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013625 sign = 1;
13626 }
13627 else {
13628 Py_DECREF(iobj);
13629 }
13630 }
13631 }
13632 if (!isnumok) {
13633 PyErr_Format(PyExc_TypeError,
13634 "%%%c format: a number is required, "
13635 "not %.200s", (char)c, Py_TYPE(v)->tp_name);
13636 goto onError;
13637 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013638 if (flags & F_ZERO) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013639 fill = '0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013640 fillobj = zero;
13641 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013642 break;
13643
13644 case 'e':
13645 case 'E':
13646 case 'f':
13647 case 'F':
13648 case 'g':
13649 case 'G':
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013650 temp = formatfloat(v, flags, prec, c);
13651 if (!temp)
Benjamin Peterson29060642009-01-31 22:14:21 +000013652 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013653 if (PyUnicode_READY(temp) == -1) {
13654 Py_CLEAR(temp);
13655 goto onError;
13656 }
13657 pbuf = PyUnicode_DATA(temp);
13658 kind = PyUnicode_KIND(temp);
13659 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013660 sign = 1;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013661 if (flags & F_ZERO) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013662 fill = '0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013663 fillobj = zero;
13664 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013665 break;
13666
13667 case 'c':
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013668 {
13669 Py_UCS4 ch = formatchar(v);
13670 if (ch == (Py_UCS4) -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000013671 goto onError;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013672 temp = _PyUnicode_FromUCS4(&ch, 1);
13673 if (temp == NULL)
13674 goto onError;
13675 pbuf = PyUnicode_DATA(temp);
13676 kind = PyUnicode_KIND(temp);
13677 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013678 break;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013679 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013680
13681 default:
13682 PyErr_Format(PyExc_ValueError,
13683 "unsupported format character '%c' (0x%x) "
13684 "at index %zd",
13685 (31<=c && c<=126) ? (char)c : '?',
13686 (int)c,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013687 fmtpos - 1);
Benjamin Peterson29060642009-01-31 22:14:21 +000013688 goto onError;
13689 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013690 /* pbuf is initialized here. */
13691 pindex = 0;
Benjamin Peterson29060642009-01-31 22:14:21 +000013692 if (sign) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013693 if (PyUnicode_READ(kind, pbuf, pindex) == '-') {
13694 signobj = minus;
Benjamin Peterson29060642009-01-31 22:14:21 +000013695 len--;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013696 pindex++;
13697 }
13698 else if (PyUnicode_READ(kind, pbuf, pindex) == '+') {
13699 signobj = plus;
13700 len--;
13701 pindex++;
Benjamin Peterson29060642009-01-31 22:14:21 +000013702 }
13703 else if (flags & F_SIGN)
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013704 signobj = plus;
Benjamin Peterson29060642009-01-31 22:14:21 +000013705 else if (flags & F_BLANK)
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013706 signobj = blank;
Benjamin Peterson29060642009-01-31 22:14:21 +000013707 else
13708 sign = 0;
13709 }
13710 if (width < len)
13711 width = len;
Benjamin Peterson29060642009-01-31 22:14:21 +000013712 if (sign) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013713 if (fill != ' ') {
13714 assert(signobj != NULL);
13715 if (_PyAccu_Accumulate(&acc, signobj))
13716 goto onError;
13717 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013718 if (width > len)
13719 width--;
13720 }
13721 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013722 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013723 assert(PyUnicode_READ(kind, pbuf, pindex + 1) == c);
Benjamin Peterson29060642009-01-31 22:14:21 +000013724 if (fill != ' ') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013725 second = get_latin1_char(
13726 PyUnicode_READ(kind, pbuf, pindex + 1));
13727 pindex += 2;
13728 if (second == NULL ||
13729 _PyAccu_Accumulate(&acc, zero) ||
13730 _PyAccu_Accumulate(&acc, second))
13731 goto onError;
13732 Py_CLEAR(second);
Benjamin Peterson29060642009-01-31 22:14:21 +000013733 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013734 width -= 2;
13735 if (width < 0)
13736 width = 0;
13737 len -= 2;
13738 }
13739 if (width > len && !(flags & F_LJUST)) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013740 assert(fillobj != NULL);
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013741 if (repeat_accumulate(&acc, fillobj, width - len))
13742 goto onError;
13743 width = len;
Benjamin Peterson29060642009-01-31 22:14:21 +000013744 }
13745 if (fill == ' ') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013746 if (sign) {
13747 assert(signobj != NULL);
13748 if (_PyAccu_Accumulate(&acc, signobj))
13749 goto onError;
13750 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013751 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013752 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
13753 assert(PyUnicode_READ(kind, pbuf, pindex+1) == c);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013754 second = get_latin1_char(
13755 PyUnicode_READ(kind, pbuf, pindex + 1));
13756 pindex += 2;
13757 if (second == NULL ||
13758 _PyAccu_Accumulate(&acc, zero) ||
13759 _PyAccu_Accumulate(&acc, second))
13760 goto onError;
13761 Py_CLEAR(second);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013762 }
13763 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013764 /* Copy all characters, preserving len */
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013765 if (temp != NULL) {
13766 assert(pbuf == PyUnicode_DATA(temp));
13767 v = PyUnicode_Substring(temp, pindex, pindex + len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013768 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013769 else {
13770 const char *p = (const char *) pbuf;
13771 assert(pbuf != NULL);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013772 p += kind * pindex;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013773 v = PyUnicode_FromKindAndData(kind, p, len);
13774 }
13775 if (v == NULL)
13776 goto onError;
13777 r = _PyAccu_Accumulate(&acc, v);
13778 Py_DECREF(v);
13779 if (r)
13780 goto onError;
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013781 if (width > len && repeat_accumulate(&acc, blank, width - len))
13782 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +000013783 if (dict && (argidx < arglen) && c != '%') {
13784 PyErr_SetString(PyExc_TypeError,
13785 "not all arguments converted during string formatting");
Benjamin Peterson29060642009-01-31 22:14:21 +000013786 goto onError;
13787 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013788 Py_CLEAR(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013789 } /* '%' */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013790 } /* until end */
13791 if (argidx < arglen && !dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013792 PyErr_SetString(PyExc_TypeError,
13793 "not all arguments converted during string formatting");
13794 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013795 }
13796
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013797 result = _PyAccu_Finish(&acc);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013798 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013799 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013800 }
13801 Py_DECREF(uformat);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013802 Py_XDECREF(temp);
13803 Py_XDECREF(second);
Victor Stinner7931d9a2011-11-04 00:22:48 +010013804 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013805
Benjamin Peterson29060642009-01-31 22:14:21 +000013806 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000013807 Py_DECREF(uformat);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013808 Py_XDECREF(temp);
13809 Py_XDECREF(second);
13810 _PyAccu_Destroy(&acc);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013811 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013812 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013813 }
13814 return NULL;
13815}
13816
Jeremy Hylton938ace62002-07-17 16:30:39 +000013817static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +000013818unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
13819
Tim Peters6d6c1a32001-08-02 04:15:00 +000013820static PyObject *
13821unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
13822{
Benjamin Peterson29060642009-01-31 22:14:21 +000013823 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013824 static char *kwlist[] = {"object", "encoding", "errors", 0};
13825 char *encoding = NULL;
13826 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000013827
Benjamin Peterson14339b62009-01-31 16:36:08 +000013828 if (type != &PyUnicode_Type)
13829 return unicode_subtype_new(type, args, kwds);
13830 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +000013831 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +000013832 return NULL;
Victor Stinner382955f2011-12-11 21:44:00 +010013833 if (x == NULL) {
13834 Py_INCREF(unicode_empty);
13835 return unicode_empty;
13836 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000013837 if (encoding == NULL && errors == NULL)
13838 return PyObject_Str(x);
13839 else
Benjamin Peterson29060642009-01-31 22:14:21 +000013840 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +000013841}
13842
Guido van Rossume023fe02001-08-30 03:12:59 +000013843static PyObject *
13844unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
13845{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013846 PyObject *unicode, *self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013847 Py_ssize_t length, char_size;
13848 int share_wstr, share_utf8;
13849 unsigned int kind;
13850 void *data;
Guido van Rossume023fe02001-08-30 03:12:59 +000013851
Benjamin Peterson14339b62009-01-31 16:36:08 +000013852 assert(PyType_IsSubtype(type, &PyUnicode_Type));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013853
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013854 unicode = unicode_new(&PyUnicode_Type, args, kwds);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013855 if (unicode == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000013856 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020013857 assert(_PyUnicode_CHECK(unicode));
Victor Stinnere06e1452011-10-04 20:52:31 +020013858 if (PyUnicode_READY(unicode))
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013859 return NULL;
13860
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013861 self = type->tp_alloc(type, 0);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013862 if (self == NULL) {
13863 Py_DECREF(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013864 return NULL;
13865 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013866 kind = PyUnicode_KIND(unicode);
13867 length = PyUnicode_GET_LENGTH(unicode);
13868
13869 _PyUnicode_LENGTH(self) = length;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020013870#ifdef Py_DEBUG
13871 _PyUnicode_HASH(self) = -1;
13872#else
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013873 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020013874#endif
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013875 _PyUnicode_STATE(self).interned = 0;
13876 _PyUnicode_STATE(self).kind = kind;
13877 _PyUnicode_STATE(self).compact = 0;
Victor Stinner3cf46372011-10-03 14:42:15 +020013878 _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013879 _PyUnicode_STATE(self).ready = 1;
13880 _PyUnicode_WSTR(self) = NULL;
13881 _PyUnicode_UTF8_LENGTH(self) = 0;
13882 _PyUnicode_UTF8(self) = NULL;
13883 _PyUnicode_WSTR_LENGTH(self) = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +020013884 _PyUnicode_DATA_ANY(self) = NULL;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013885
13886 share_utf8 = 0;
13887 share_wstr = 0;
13888 if (kind == PyUnicode_1BYTE_KIND) {
13889 char_size = 1;
13890 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
13891 share_utf8 = 1;
13892 }
13893 else if (kind == PyUnicode_2BYTE_KIND) {
13894 char_size = 2;
13895 if (sizeof(wchar_t) == 2)
13896 share_wstr = 1;
13897 }
13898 else {
13899 assert(kind == PyUnicode_4BYTE_KIND);
13900 char_size = 4;
13901 if (sizeof(wchar_t) == 4)
13902 share_wstr = 1;
13903 }
13904
13905 /* Ensure we won't overflow the length. */
13906 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
13907 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013908 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013909 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013910 data = PyObject_MALLOC((length + 1) * char_size);
13911 if (data == NULL) {
13912 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013913 goto onError;
13914 }
13915
Victor Stinnerc3c74152011-10-02 20:39:55 +020013916 _PyUnicode_DATA_ANY(self) = data;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013917 if (share_utf8) {
13918 _PyUnicode_UTF8_LENGTH(self) = length;
13919 _PyUnicode_UTF8(self) = data;
13920 }
13921 if (share_wstr) {
13922 _PyUnicode_WSTR_LENGTH(self) = length;
13923 _PyUnicode_WSTR(self) = (wchar_t *)data;
13924 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013925
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013926 Py_MEMCPY(data, PyUnicode_DATA(unicode),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013927 kind * (length + 1));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013928 assert(_PyUnicode_CheckConsistency(self, 1));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020013929#ifdef Py_DEBUG
13930 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
13931#endif
Victor Stinnerdd18d3a2011-10-22 11:08:10 +020013932 Py_DECREF(unicode);
Victor Stinner7931d9a2011-11-04 00:22:48 +010013933 return self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013934
13935onError:
13936 Py_DECREF(unicode);
13937 Py_DECREF(self);
13938 return NULL;
Guido van Rossume023fe02001-08-30 03:12:59 +000013939}
13940
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013941PyDoc_STRVAR(unicode_doc,
Benjamin Peterson29060642009-01-31 22:14:21 +000013942 "str(string[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +000013943\n\
Collin Winterd474ce82007-08-07 19:42:11 +000013944Create a new string object from the given encoded string.\n\
Skip Montanaro35b37a52002-07-26 16:22:46 +000013945encoding defaults to the current default string encoding.\n\
13946errors can be 'strict', 'replace' or 'ignore' and defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +000013947
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013948static PyObject *unicode_iter(PyObject *seq);
13949
Guido van Rossumd57fd912000-03-10 22:53:23 +000013950PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000013951 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Benjamin Peterson14339b62009-01-31 16:36:08 +000013952 "str", /* tp_name */
13953 sizeof(PyUnicodeObject), /* tp_size */
13954 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013955 /* Slots */
Benjamin Peterson14339b62009-01-31 16:36:08 +000013956 (destructor)unicode_dealloc, /* tp_dealloc */
13957 0, /* tp_print */
13958 0, /* tp_getattr */
13959 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000013960 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000013961 unicode_repr, /* tp_repr */
13962 &unicode_as_number, /* tp_as_number */
13963 &unicode_as_sequence, /* tp_as_sequence */
13964 &unicode_as_mapping, /* tp_as_mapping */
13965 (hashfunc) unicode_hash, /* tp_hash*/
13966 0, /* tp_call*/
13967 (reprfunc) unicode_str, /* tp_str */
13968 PyObject_GenericGetAttr, /* tp_getattro */
13969 0, /* tp_setattro */
13970 0, /* tp_as_buffer */
13971 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Benjamin Peterson29060642009-01-31 22:14:21 +000013972 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
Benjamin Peterson14339b62009-01-31 16:36:08 +000013973 unicode_doc, /* tp_doc */
13974 0, /* tp_traverse */
13975 0, /* tp_clear */
13976 PyUnicode_RichCompare, /* tp_richcompare */
13977 0, /* tp_weaklistoffset */
13978 unicode_iter, /* tp_iter */
13979 0, /* tp_iternext */
13980 unicode_methods, /* tp_methods */
13981 0, /* tp_members */
13982 0, /* tp_getset */
13983 &PyBaseObject_Type, /* tp_base */
13984 0, /* tp_dict */
13985 0, /* tp_descr_get */
13986 0, /* tp_descr_set */
13987 0, /* tp_dictoffset */
13988 0, /* tp_init */
13989 0, /* tp_alloc */
13990 unicode_new, /* tp_new */
13991 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013992};
13993
13994/* Initialize the Unicode implementation */
13995
Victor Stinner3a50e702011-10-18 21:21:00 +020013996int _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013997{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013998 int i;
13999
Thomas Wouters477c8d52006-05-27 19:21:47 +000014000 /* XXX - move this array to unicodectype.c ? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014001 Py_UCS2 linebreak[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +000014002 0x000A, /* LINE FEED */
14003 0x000D, /* CARRIAGE RETURN */
14004 0x001C, /* FILE SEPARATOR */
14005 0x001D, /* GROUP SEPARATOR */
14006 0x001E, /* RECORD SEPARATOR */
14007 0x0085, /* NEXT LINE */
14008 0x2028, /* LINE SEPARATOR */
14009 0x2029, /* PARAGRAPH SEPARATOR */
14010 };
14011
Fred Drakee4315f52000-05-09 19:53:39 +000014012 /* Init the implementation */
Victor Stinnera464fc12011-10-02 20:39:30 +020014013 unicode_empty = PyUnicode_New(0, 0);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014014 if (!unicode_empty)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014015 Py_FatalError("Can't create empty string");
Victor Stinnerd3df8ab2011-11-22 01:22:34 +010014016 assert(_PyUnicode_CheckConsistency(unicode_empty, 1));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014017
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014018 for (i = 0; i < 256; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +000014019 unicode_latin1[i] = NULL;
Guido van Rossumcacfc072002-05-24 19:01:59 +000014020 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000014021 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +000014022
14023 /* initialize the linebreak bloom filter */
14024 bloom_linebreak = make_bloom_mask(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014025 PyUnicode_2BYTE_KIND, linebreak,
Victor Stinner63941882011-09-29 00:42:28 +020014026 Py_ARRAY_LENGTH(linebreak));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014027
14028 PyType_Ready(&EncodingMapType);
Victor Stinner3a50e702011-10-18 21:21:00 +020014029
14030#ifdef HAVE_MBCS
14031 winver.dwOSVersionInfoSize = sizeof(winver);
14032 if (!GetVersionEx((OSVERSIONINFO*)&winver)) {
14033 PyErr_SetFromWindowsErr(0);
14034 return -1;
14035 }
14036#endif
14037 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014038}
14039
14040/* Finalize the Unicode implementation */
14041
Christian Heimesa156e092008-02-16 07:38:31 +000014042int
14043PyUnicode_ClearFreeList(void)
14044{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014045 return 0;
Christian Heimesa156e092008-02-16 07:38:31 +000014046}
14047
Guido van Rossumd57fd912000-03-10 22:53:23 +000014048void
Thomas Wouters78890102000-07-22 19:25:51 +000014049_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014050{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014051 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014052
Guido van Rossum4ae8ef82000-10-03 18:09:04 +000014053 Py_XDECREF(unicode_empty);
14054 unicode_empty = NULL;
Barry Warsaw5b4c2282000-10-03 20:45:26 +000014055
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014056 for (i = 0; i < 256; i++) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014057 if (unicode_latin1[i]) {
14058 Py_DECREF(unicode_latin1[i]);
14059 unicode_latin1[i] = NULL;
14060 }
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014061 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020014062 _PyUnicode_ClearStaticStrings();
Christian Heimesa156e092008-02-16 07:38:31 +000014063 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +000014064}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000014065
Walter Dörwald16807132007-05-25 13:52:07 +000014066void
14067PyUnicode_InternInPlace(PyObject **p)
14068{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014069 register PyObject *s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014070 PyObject *t;
Victor Stinner4fae54c2011-10-03 02:01:52 +020014071#ifdef Py_DEBUG
14072 assert(s != NULL);
14073 assert(_PyUnicode_CHECK(s));
14074#else
Benjamin Peterson14339b62009-01-31 16:36:08 +000014075 if (s == NULL || !PyUnicode_Check(s))
Victor Stinner4fae54c2011-10-03 02:01:52 +020014076 return;
14077#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000014078 /* If it's a subclass, we don't really know what putting
14079 it in the interned dict might do. */
14080 if (!PyUnicode_CheckExact(s))
14081 return;
14082 if (PyUnicode_CHECK_INTERNED(s))
14083 return;
14084 if (interned == NULL) {
14085 interned = PyDict_New();
14086 if (interned == NULL) {
14087 PyErr_Clear(); /* Don't leave an exception */
14088 return;
14089 }
14090 }
14091 /* It might be that the GetItem call fails even
14092 though the key is present in the dictionary,
14093 namely when this happens during a stack overflow. */
14094 Py_ALLOW_RECURSION
Victor Stinner7931d9a2011-11-04 00:22:48 +010014095 t = PyDict_GetItem(interned, s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014096 Py_END_ALLOW_RECURSION
Martin v. Löwis5b222132007-06-10 09:51:05 +000014097
Benjamin Peterson29060642009-01-31 22:14:21 +000014098 if (t) {
14099 Py_INCREF(t);
14100 Py_DECREF(*p);
14101 *p = t;
14102 return;
14103 }
Walter Dörwald16807132007-05-25 13:52:07 +000014104
Benjamin Peterson14339b62009-01-31 16:36:08 +000014105 PyThreadState_GET()->recursion_critical = 1;
Victor Stinner7931d9a2011-11-04 00:22:48 +010014106 if (PyDict_SetItem(interned, s, s) < 0) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014107 PyErr_Clear();
14108 PyThreadState_GET()->recursion_critical = 0;
14109 return;
14110 }
14111 PyThreadState_GET()->recursion_critical = 0;
14112 /* The two references in interned are not counted by refcnt.
14113 The deallocator will take care of this */
14114 Py_REFCNT(s) -= 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014115 _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000014116}
14117
14118void
14119PyUnicode_InternImmortal(PyObject **p)
14120{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014121 PyUnicode_InternInPlace(p);
14122 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
Victor Stinneraf9e4b82011-10-23 20:07:00 +020014123 _PyUnicode_STATE(*p).interned = SSTATE_INTERNED_IMMORTAL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014124 Py_INCREF(*p);
14125 }
Walter Dörwald16807132007-05-25 13:52:07 +000014126}
14127
14128PyObject *
14129PyUnicode_InternFromString(const char *cp)
14130{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014131 PyObject *s = PyUnicode_FromString(cp);
14132 if (s == NULL)
14133 return NULL;
14134 PyUnicode_InternInPlace(&s);
14135 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000014136}
14137
Alexander Belopolsky40018472011-02-26 01:02:56 +000014138void
14139_Py_ReleaseInternedUnicodeStrings(void)
Walter Dörwald16807132007-05-25 13:52:07 +000014140{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014141 PyObject *keys;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014142 PyObject *s;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014143 Py_ssize_t i, n;
14144 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000014145
Benjamin Peterson14339b62009-01-31 16:36:08 +000014146 if (interned == NULL || !PyDict_Check(interned))
14147 return;
14148 keys = PyDict_Keys(interned);
14149 if (keys == NULL || !PyList_Check(keys)) {
14150 PyErr_Clear();
14151 return;
14152 }
Walter Dörwald16807132007-05-25 13:52:07 +000014153
Benjamin Peterson14339b62009-01-31 16:36:08 +000014154 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
14155 detector, interned unicode strings are not forcibly deallocated;
14156 rather, we give them their stolen references back, and then clear
14157 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000014158
Benjamin Peterson14339b62009-01-31 16:36:08 +000014159 n = PyList_GET_SIZE(keys);
14160 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000014161 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014162 for (i = 0; i < n; i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014163 s = PyList_GET_ITEM(keys, i);
Victor Stinner6b56a7f2011-10-04 20:04:52 +020014164 if (PyUnicode_READY(s) == -1) {
14165 assert(0 && "could not ready string");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014166 fprintf(stderr, "could not ready string\n");
Victor Stinner6b56a7f2011-10-04 20:04:52 +020014167 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014168 switch (PyUnicode_CHECK_INTERNED(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014169 case SSTATE_NOT_INTERNED:
14170 /* XXX Shouldn't happen */
14171 break;
14172 case SSTATE_INTERNED_IMMORTAL:
14173 Py_REFCNT(s) += 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014174 immortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014175 break;
14176 case SSTATE_INTERNED_MORTAL:
14177 Py_REFCNT(s) += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014178 mortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014179 break;
14180 default:
14181 Py_FatalError("Inconsistent interned string state.");
14182 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014183 _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014184 }
14185 fprintf(stderr, "total size of all interned strings: "
14186 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
14187 "mortal/immortal\n", mortal_size, immortal_size);
14188 Py_DECREF(keys);
14189 PyDict_Clear(interned);
14190 Py_DECREF(interned);
14191 interned = NULL;
Walter Dörwald16807132007-05-25 13:52:07 +000014192}
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014193
14194
14195/********************* Unicode Iterator **************************/
14196
14197typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014198 PyObject_HEAD
14199 Py_ssize_t it_index;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014200 PyObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014201} unicodeiterobject;
14202
14203static void
14204unicodeiter_dealloc(unicodeiterobject *it)
14205{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014206 _PyObject_GC_UNTRACK(it);
14207 Py_XDECREF(it->it_seq);
14208 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014209}
14210
14211static int
14212unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
14213{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014214 Py_VISIT(it->it_seq);
14215 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014216}
14217
14218static PyObject *
14219unicodeiter_next(unicodeiterobject *it)
14220{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014221 PyObject *seq, *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014222
Benjamin Peterson14339b62009-01-31 16:36:08 +000014223 assert(it != NULL);
14224 seq = it->it_seq;
14225 if (seq == NULL)
14226 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020014227 assert(_PyUnicode_CHECK(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014228
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014229 if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
14230 int kind = PyUnicode_KIND(seq);
14231 void *data = PyUnicode_DATA(seq);
14232 Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
14233 item = PyUnicode_FromOrdinal(chr);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014234 if (item != NULL)
14235 ++it->it_index;
14236 return item;
14237 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014238
Benjamin Peterson14339b62009-01-31 16:36:08 +000014239 Py_DECREF(seq);
14240 it->it_seq = NULL;
14241 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014242}
14243
14244static PyObject *
14245unicodeiter_len(unicodeiterobject *it)
14246{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014247 Py_ssize_t len = 0;
14248 if (it->it_seq)
Victor Stinnerc4f281e2011-10-11 22:11:42 +020014249 len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014250 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014251}
14252
14253PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
14254
14255static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014256 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000014257 length_hint_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000014258 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014259};
14260
14261PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014262 PyVarObject_HEAD_INIT(&PyType_Type, 0)
14263 "str_iterator", /* tp_name */
14264 sizeof(unicodeiterobject), /* tp_basicsize */
14265 0, /* tp_itemsize */
14266 /* methods */
14267 (destructor)unicodeiter_dealloc, /* tp_dealloc */
14268 0, /* tp_print */
14269 0, /* tp_getattr */
14270 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000014271 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014272 0, /* tp_repr */
14273 0, /* tp_as_number */
14274 0, /* tp_as_sequence */
14275 0, /* tp_as_mapping */
14276 0, /* tp_hash */
14277 0, /* tp_call */
14278 0, /* tp_str */
14279 PyObject_GenericGetAttr, /* tp_getattro */
14280 0, /* tp_setattro */
14281 0, /* tp_as_buffer */
14282 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
14283 0, /* tp_doc */
14284 (traverseproc)unicodeiter_traverse, /* tp_traverse */
14285 0, /* tp_clear */
14286 0, /* tp_richcompare */
14287 0, /* tp_weaklistoffset */
14288 PyObject_SelfIter, /* tp_iter */
14289 (iternextfunc)unicodeiter_next, /* tp_iternext */
14290 unicodeiter_methods, /* tp_methods */
14291 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014292};
14293
14294static PyObject *
14295unicode_iter(PyObject *seq)
14296{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014297 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014298
Benjamin Peterson14339b62009-01-31 16:36:08 +000014299 if (!PyUnicode_Check(seq)) {
14300 PyErr_BadInternalCall();
14301 return NULL;
14302 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014303 if (PyUnicode_READY(seq) == -1)
14304 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014305 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
14306 if (it == NULL)
14307 return NULL;
14308 it->it_index = 0;
14309 Py_INCREF(seq);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014310 it->it_seq = seq;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014311 _PyObject_GC_TRACK(it);
14312 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014313}
14314
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010014315
14316size_t
14317Py_UNICODE_strlen(const Py_UNICODE *u)
14318{
14319 int res = 0;
14320 while(*u++)
14321 res++;
14322 return res;
14323}
14324
14325Py_UNICODE*
14326Py_UNICODE_strcpy(Py_UNICODE *s1, const Py_UNICODE *s2)
14327{
14328 Py_UNICODE *u = s1;
14329 while ((*u++ = *s2++));
14330 return s1;
14331}
14332
14333Py_UNICODE*
14334Py_UNICODE_strncpy(Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
14335{
14336 Py_UNICODE *u = s1;
14337 while ((*u++ = *s2++))
14338 if (n-- == 0)
14339 break;
14340 return s1;
14341}
14342
14343Py_UNICODE*
14344Py_UNICODE_strcat(Py_UNICODE *s1, const Py_UNICODE *s2)
14345{
14346 Py_UNICODE *u1 = s1;
14347 u1 += Py_UNICODE_strlen(u1);
14348 Py_UNICODE_strcpy(u1, s2);
14349 return s1;
14350}
14351
14352int
14353Py_UNICODE_strcmp(const Py_UNICODE *s1, const Py_UNICODE *s2)
14354{
14355 while (*s1 && *s2 && *s1 == *s2)
14356 s1++, s2++;
14357 if (*s1 && *s2)
14358 return (*s1 < *s2) ? -1 : +1;
14359 if (*s1)
14360 return 1;
14361 if (*s2)
14362 return -1;
14363 return 0;
14364}
14365
14366int
14367Py_UNICODE_strncmp(const Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
14368{
14369 register Py_UNICODE u1, u2;
14370 for (; n != 0; n--) {
14371 u1 = *s1;
14372 u2 = *s2;
14373 if (u1 != u2)
14374 return (u1 < u2) ? -1 : +1;
14375 if (u1 == '\0')
14376 return 0;
14377 s1++;
14378 s2++;
14379 }
14380 return 0;
14381}
14382
14383Py_UNICODE*
14384Py_UNICODE_strchr(const Py_UNICODE *s, Py_UNICODE c)
14385{
14386 const Py_UNICODE *p;
14387 for (p = s; *p; p++)
14388 if (*p == c)
14389 return (Py_UNICODE*)p;
14390 return NULL;
14391}
14392
14393Py_UNICODE*
14394Py_UNICODE_strrchr(const Py_UNICODE *s, Py_UNICODE c)
14395{
14396 const Py_UNICODE *p;
14397 p = s + Py_UNICODE_strlen(s);
14398 while (p != s) {
14399 p--;
14400 if (*p == c)
14401 return (Py_UNICODE*)p;
14402 }
14403 return NULL;
14404}
Victor Stinner331ea922010-08-10 16:37:20 +000014405
Victor Stinner71133ff2010-09-01 23:43:53 +000014406Py_UNICODE*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014407PyUnicode_AsUnicodeCopy(PyObject *unicode)
Victor Stinner71133ff2010-09-01 23:43:53 +000014408{
Victor Stinner577db2c2011-10-11 22:12:48 +020014409 Py_UNICODE *u, *copy;
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014410 Py_ssize_t len, size;
Victor Stinner71133ff2010-09-01 23:43:53 +000014411
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014412 if (!PyUnicode_Check(unicode)) {
14413 PyErr_BadArgument();
14414 return NULL;
14415 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014416 u = PyUnicode_AsUnicodeAndSize(unicode, &len);
Victor Stinner577db2c2011-10-11 22:12:48 +020014417 if (u == NULL)
14418 return NULL;
Victor Stinner71133ff2010-09-01 23:43:53 +000014419 /* Ensure we won't overflow the size. */
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014420 if (len > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
Victor Stinner71133ff2010-09-01 23:43:53 +000014421 PyErr_NoMemory();
14422 return NULL;
14423 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014424 size = len + 1; /* copy the null character */
Victor Stinner71133ff2010-09-01 23:43:53 +000014425 size *= sizeof(Py_UNICODE);
14426 copy = PyMem_Malloc(size);
14427 if (copy == NULL) {
14428 PyErr_NoMemory();
14429 return NULL;
14430 }
Victor Stinner577db2c2011-10-11 22:12:48 +020014431 memcpy(copy, u, size);
Victor Stinner71133ff2010-09-01 23:43:53 +000014432 return copy;
14433}
Martin v. Löwis5b222132007-06-10 09:51:05 +000014434
Georg Brandl66c221e2010-10-14 07:04:07 +000014435/* A _string module, to export formatter_parser and formatter_field_name_split
14436 to the string.Formatter class implemented in Python. */
14437
14438static PyMethodDef _string_methods[] = {
14439 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
14440 METH_O, PyDoc_STR("split the argument as a field name")},
14441 {"formatter_parser", (PyCFunction) formatter_parser,
14442 METH_O, PyDoc_STR("parse the argument as a format string")},
14443 {NULL, NULL}
14444};
14445
14446static struct PyModuleDef _string_module = {
14447 PyModuleDef_HEAD_INIT,
14448 "_string",
14449 PyDoc_STR("string helper module"),
14450 0,
14451 _string_methods,
14452 NULL,
14453 NULL,
14454 NULL,
14455 NULL
14456};
14457
14458PyMODINIT_FUNC
14459PyInit__string(void)
14460{
14461 return PyModule_Create(&_string_module);
14462}
14463
14464
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000014465#ifdef __cplusplus
14466}
14467#endif