blob: aeccfe40e00bba2858185371b0110f91af2906e2 [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;
3087 int save_errno;
3088
3089 save_errno = errno;
3090#if SIZEOF_WCHAR_T == 2
3091 buf[2] = 0;
3092#else
3093 buf[1] = 0;
3094#endif
3095 start = wstr;
3096 while (*wstr != L'\0')
3097 {
3098 previous = wstr;
3099#if SIZEOF_WCHAR_T == 2
3100 if (Py_UNICODE_IS_HIGH_SURROGATE(wstr[0])
3101 && Py_UNICODE_IS_LOW_SURROGATE(wstr[1]))
3102 {
3103 buf[0] = wstr[0];
3104 buf[1] = wstr[1];
3105 wstr += 2;
3106 }
3107 else {
3108 buf[0] = *wstr;
3109 buf[1] = 0;
3110 wstr++;
3111 }
3112#else
3113 buf[0] = *wstr;
3114 wstr++;
3115#endif
3116 len = wcstombs(outbuf, buf, sizeof(outbuf));
3117 if (len == (size_t)-1) {
3118 errno = save_errno;
3119 return previous - start;
3120 }
3121 }
3122
3123 /* failed to find the unencodable character */
3124 errno = save_errno;
3125 return 0;
3126}
3127
3128PyObject *
3129PyUnicode_EncodeLocale(PyObject *unicode, int surrogateescape)
3130{
3131 Py_ssize_t wlen, wlen2;
3132 wchar_t *wstr;
3133 PyObject *bytes = NULL;
3134 char *errmsg;
Victor Stinner1f33f2b2011-12-17 04:45:09 +01003135 PyObject *reason;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003136 PyObject *exc;
3137 size_t error_pos;
3138
3139 wstr = PyUnicode_AsWideCharString(unicode, &wlen);
3140 if (wstr == NULL)
3141 return NULL;
3142
3143 wlen2 = wcslen(wstr);
3144 if (wlen2 != wlen) {
3145 PyMem_Free(wstr);
3146 PyErr_SetString(PyExc_TypeError, "embedded null character");
3147 return NULL;
3148 }
3149
3150 if (surrogateescape) {
3151 /* locale encoding with surrogateescape */
3152 char *str;
3153
3154 str = _Py_wchar2char(wstr, &error_pos);
3155 if (str == NULL) {
3156 if (error_pos == (size_t)-1) {
3157 PyErr_NoMemory();
3158 PyMem_Free(wstr);
3159 return NULL;
3160 }
3161 else {
3162 goto encode_error;
3163 }
3164 }
3165 PyMem_Free(wstr);
3166
3167 bytes = PyBytes_FromString(str);
3168 PyMem_Free(str);
3169 }
3170 else {
3171 size_t len, len2;
3172
3173 len = wcstombs(NULL, wstr, 0);
3174 if (len == (size_t)-1) {
3175 error_pos = wcstombs_errorpos(wstr);
3176 goto encode_error;
3177 }
3178
3179 bytes = PyBytes_FromStringAndSize(NULL, len);
3180 if (bytes == NULL) {
3181 PyMem_Free(wstr);
3182 return NULL;
3183 }
3184
3185 len2 = wcstombs(PyBytes_AS_STRING(bytes), wstr, len+1);
3186 if (len2 == (size_t)-1 || len2 > len) {
3187 error_pos = wcstombs_errorpos(wstr);
3188 goto encode_error;
3189 }
3190 PyMem_Free(wstr);
3191 }
3192 return bytes;
3193
3194encode_error:
3195 errmsg = strerror(errno);
3196 assert(errmsg != NULL);
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003197 PyMem_Free(wstr);
3198 Py_XDECREF(bytes);
3199
Victor Stinner1f33f2b2011-12-17 04:45:09 +01003200 if (errmsg != NULL)
3201 reason = PyUnicode_DecodeLocale(errmsg, 1);
3202 else
3203 reason = PyUnicode_FromString(
3204 "wcstombs() encountered an unencodable "
3205 "wide character");
3206 if (reason == NULL)
3207 return NULL;
3208
3209 exc = PyObject_CallFunction(PyExc_UnicodeEncodeError, "sOnnO",
3210 "locale", unicode,
3211 (Py_ssize_t)error_pos,
3212 (Py_ssize_t)(error_pos+1),
3213 reason);
3214 Py_DECREF(reason);
3215 if (exc != NULL) {
3216 PyCodec_StrictErrors(exc);
3217 Py_XDECREF(exc);
3218 }
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003219 return NULL;
3220}
3221
Victor Stinnerad158722010-10-27 00:25:46 +00003222PyObject *
3223PyUnicode_EncodeFSDefault(PyObject *unicode)
Victor Stinnerae6265f2010-05-15 16:27:27 +00003224{
Victor Stinner99b95382011-07-04 14:23:54 +02003225#ifdef HAVE_MBCS
Victor Stinnerac931b12011-11-20 18:27:03 +01003226 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003227#elif defined(__APPLE__)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003228 return _PyUnicode_AsUTF8String(unicode, "surrogateescape");
Victor Stinnerad158722010-10-27 00:25:46 +00003229#else
Victor Stinner793b5312011-04-27 00:24:21 +02003230 PyInterpreterState *interp = PyThreadState_GET()->interp;
3231 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3232 cannot use it to encode and decode filenames before it is loaded. Load
3233 the Python codec requires to encode at least its own filename. Use the C
3234 version of the locale codec until the codec registry is initialized and
3235 the Python codec is loaded.
3236
3237 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3238 cannot only rely on it: check also interp->fscodec_initialized for
3239 subinterpreters. */
3240 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Victor Stinnerae6265f2010-05-15 16:27:27 +00003241 return PyUnicode_AsEncodedString(unicode,
3242 Py_FileSystemDefaultEncoding,
3243 "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00003244 }
3245 else {
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003246 return PyUnicode_EncodeLocale(unicode, 1);
Victor Stinnerc39211f2010-09-29 16:35:47 +00003247 }
Victor Stinnerad158722010-10-27 00:25:46 +00003248#endif
Victor Stinnerae6265f2010-05-15 16:27:27 +00003249}
3250
Alexander Belopolsky40018472011-02-26 01:02:56 +00003251PyObject *
3252PyUnicode_AsEncodedString(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003253 const char *encoding,
3254 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003255{
3256 PyObject *v;
Victor Stinner600d3be2010-06-10 12:00:55 +00003257 char lower[11]; /* Enough for any encoding shortcut */
Tim Petersced69f82003-09-16 20:30:58 +00003258
Guido van Rossumd57fd912000-03-10 22:53:23 +00003259 if (!PyUnicode_Check(unicode)) {
3260 PyErr_BadArgument();
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003261 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003262 }
Fred Drakee4315f52000-05-09 19:53:39 +00003263
Fred Drakee4315f52000-05-09 19:53:39 +00003264 /* Shortcuts for common default encodings */
Victor Stinner37296e82010-06-10 13:36:23 +00003265 if (normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003266 if ((strcmp(lower, "utf-8") == 0) ||
3267 (strcmp(lower, "utf8") == 0))
Victor Stinnera5c68c32011-03-02 01:03:14 +00003268 {
Victor Stinner2f283c22011-03-02 01:21:46 +00003269 if (errors == NULL || strcmp(errors, "strict") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003270 return _PyUnicode_AsUTF8String(unicode, NULL);
Victor Stinner2f283c22011-03-02 01:21:46 +00003271 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003272 return _PyUnicode_AsUTF8String(unicode, errors);
Victor Stinnera5c68c32011-03-02 01:03:14 +00003273 }
Victor Stinner37296e82010-06-10 13:36:23 +00003274 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003275 (strcmp(lower, "latin1") == 0) ||
Victor Stinner37296e82010-06-10 13:36:23 +00003276 (strcmp(lower, "iso-8859-1") == 0))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003277 return _PyUnicode_AsLatin1String(unicode, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02003278#ifdef HAVE_MBCS
Victor Stinnerac931b12011-11-20 18:27:03 +01003279 else if (strcmp(lower, "mbcs") == 0)
3280 return PyUnicode_EncodeCodePage(CP_ACP, unicode, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003281#endif
Victor Stinner37296e82010-06-10 13:36:23 +00003282 else if (strcmp(lower, "ascii") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003283 return _PyUnicode_AsASCIIString(unicode, errors);
Victor Stinner37296e82010-06-10 13:36:23 +00003284 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003285
3286 /* Encode via the codec registry */
3287 v = PyCodec_Encode(unicode, encoding, errors);
3288 if (v == NULL)
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003289 return NULL;
3290
3291 /* The normal path */
3292 if (PyBytes_Check(v))
3293 return v;
3294
3295 /* If the codec returns a buffer, raise a warning and convert to bytes */
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003296 if (PyByteArray_Check(v)) {
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003297 int error;
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003298 PyObject *b;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003299
3300 error = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
3301 "encoder %s returned bytearray instead of bytes",
3302 encoding);
3303 if (error) {
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003304 Py_DECREF(v);
3305 return NULL;
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003306 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003307
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003308 b = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(v), Py_SIZE(v));
3309 Py_DECREF(v);
3310 return b;
3311 }
3312
3313 PyErr_Format(PyExc_TypeError,
3314 "encoder did not return a bytes object (type=%.400s)",
3315 Py_TYPE(v)->tp_name);
3316 Py_DECREF(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003317 return NULL;
3318}
3319
Alexander Belopolsky40018472011-02-26 01:02:56 +00003320PyObject *
3321PyUnicode_AsEncodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003322 const char *encoding,
3323 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003324{
3325 PyObject *v;
3326
3327 if (!PyUnicode_Check(unicode)) {
3328 PyErr_BadArgument();
3329 goto onError;
3330 }
3331
3332 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003333 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003334
3335 /* Encode via the codec registry */
3336 v = PyCodec_Encode(unicode, encoding, errors);
3337 if (v == NULL)
3338 goto onError;
3339 if (!PyUnicode_Check(v)) {
3340 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00003341 "encoder did not return an str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003342 Py_TYPE(v)->tp_name);
3343 Py_DECREF(v);
3344 goto onError;
3345 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003346 return v;
Tim Petersced69f82003-09-16 20:30:58 +00003347
Benjamin Peterson29060642009-01-31 22:14:21 +00003348 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003349 return NULL;
3350}
3351
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003352PyObject*
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003353PyUnicode_DecodeLocaleAndSize(const char *str, Py_ssize_t len,
3354 int surrogateescape)
3355{
3356 wchar_t smallbuf[256];
3357 size_t smallbuf_len = Py_ARRAY_LENGTH(smallbuf);
3358 wchar_t *wstr;
3359 size_t wlen, wlen2;
3360 PyObject *unicode;
3361
3362 if (str[len] != '\0' || len != strlen(str)) {
3363 PyErr_SetString(PyExc_TypeError, "embedded null character");
3364 return NULL;
3365 }
3366
3367 if (surrogateescape)
3368 {
3369 wstr = _Py_char2wchar(str, &wlen);
3370 if (wstr == NULL) {
3371 if (wlen == (size_t)-1)
3372 PyErr_NoMemory();
3373 else
3374 PyErr_SetFromErrno(PyExc_OSError);
3375 return NULL;
3376 }
3377
3378 unicode = PyUnicode_FromWideChar(wstr, wlen);
3379 PyMem_Free(wstr);
3380 }
3381 else {
3382#ifndef HAVE_BROKEN_MBSTOWCS
3383 wlen = mbstowcs(NULL, str, 0);
3384#else
3385 wlen = len;
3386#endif
3387 if (wlen == (size_t)-1) {
3388 PyErr_SetFromErrno(PyExc_OSError);
3389 return NULL;
3390 }
3391 if (wlen+1 <= smallbuf_len) {
3392 wstr = smallbuf;
3393 }
3394 else {
3395 if (wlen > PY_SSIZE_T_MAX / sizeof(wchar_t) - 1)
3396 return PyErr_NoMemory();
3397
3398 wstr = PyMem_Malloc((wlen+1) * sizeof(wchar_t));
3399 if (!wstr)
3400 return PyErr_NoMemory();
3401 }
3402
3403 /* This shouldn't fail now */
3404 wlen2 = mbstowcs(wstr, str, wlen+1);
3405 if (wlen2 == (size_t)-1) {
3406 if (wstr != smallbuf)
3407 PyMem_Free(wstr);
3408 PyErr_SetFromErrno(PyExc_OSError);
3409 return NULL;
3410 }
3411#ifdef HAVE_BROKEN_MBSTOWCS
3412 assert(wlen2 == wlen);
3413#endif
3414 unicode = PyUnicode_FromWideChar(wstr, wlen2);
3415 if (wstr != smallbuf)
3416 PyMem_Free(wstr);
3417 }
3418 return unicode;
3419}
3420
3421PyObject*
3422PyUnicode_DecodeLocale(const char *str, int surrogateescape)
3423{
3424 Py_ssize_t size = (Py_ssize_t)strlen(str);
3425 return PyUnicode_DecodeLocaleAndSize(str, size, surrogateescape);
3426}
3427
3428
3429PyObject*
Christian Heimes5894ba72007-11-04 11:43:14 +00003430PyUnicode_DecodeFSDefault(const char *s) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003431 Py_ssize_t size = (Py_ssize_t)strlen(s);
Christian Heimes5894ba72007-11-04 11:43:14 +00003432 return PyUnicode_DecodeFSDefaultAndSize(s, size);
3433}
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003434
Christian Heimes5894ba72007-11-04 11:43:14 +00003435PyObject*
3436PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
3437{
Victor Stinner99b95382011-07-04 14:23:54 +02003438#ifdef HAVE_MBCS
Victor Stinnerad158722010-10-27 00:25:46 +00003439 return PyUnicode_DecodeMBCS(s, size, NULL);
3440#elif defined(__APPLE__)
Victor Stinnera1d12bb2011-12-11 21:53:09 +01003441 return PyUnicode_DecodeUTF8Stateful(s, size, "surrogateescape", NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003442#else
Victor Stinner793b5312011-04-27 00:24:21 +02003443 PyInterpreterState *interp = PyThreadState_GET()->interp;
3444 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3445 cannot use it to encode and decode filenames before it is loaded. Load
3446 the Python codec requires to encode at least its own filename. Use the C
3447 version of the locale codec until the codec registry is initialized and
3448 the Python codec is loaded.
3449
3450 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3451 cannot only rely on it: check also interp->fscodec_initialized for
3452 subinterpreters. */
3453 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003454 return PyUnicode_Decode(s, size,
3455 Py_FileSystemDefaultEncoding,
Victor Stinnerb9a20ad2010-04-30 16:37:52 +00003456 "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003457 }
3458 else {
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003459 return PyUnicode_DecodeLocaleAndSize(s, size, 1);
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003460 }
Victor Stinnerad158722010-10-27 00:25:46 +00003461#endif
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003462}
3463
Martin v. Löwis011e8422009-05-05 04:43:17 +00003464
3465int
3466PyUnicode_FSConverter(PyObject* arg, void* addr)
3467{
3468 PyObject *output = NULL;
3469 Py_ssize_t size;
3470 void *data;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003471 if (arg == NULL) {
3472 Py_DECREF(*(PyObject**)addr);
3473 return 1;
3474 }
Victor Stinnerdcb24032010-04-22 12:08:36 +00003475 if (PyBytes_Check(arg)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00003476 output = arg;
3477 Py_INCREF(output);
3478 }
3479 else {
3480 arg = PyUnicode_FromObject(arg);
3481 if (!arg)
3482 return 0;
Victor Stinnerae6265f2010-05-15 16:27:27 +00003483 output = PyUnicode_EncodeFSDefault(arg);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003484 Py_DECREF(arg);
3485 if (!output)
3486 return 0;
3487 if (!PyBytes_Check(output)) {
3488 Py_DECREF(output);
3489 PyErr_SetString(PyExc_TypeError, "encoder failed to return bytes");
3490 return 0;
3491 }
3492 }
Victor Stinner0ea2a462010-04-30 00:22:08 +00003493 size = PyBytes_GET_SIZE(output);
3494 data = PyBytes_AS_STRING(output);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003495 if (size != strlen(data)) {
Benjamin Peterson7a6b44a2011-08-18 13:51:47 -05003496 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
Martin v. Löwis011e8422009-05-05 04:43:17 +00003497 Py_DECREF(output);
3498 return 0;
3499 }
3500 *(PyObject**)addr = output;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003501 return Py_CLEANUP_SUPPORTED;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003502}
3503
3504
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003505int
3506PyUnicode_FSDecoder(PyObject* arg, void* addr)
3507{
3508 PyObject *output = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003509 if (arg == NULL) {
3510 Py_DECREF(*(PyObject**)addr);
3511 return 1;
3512 }
3513 if (PyUnicode_Check(arg)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003514 if (PyUnicode_READY(arg))
3515 return 0;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003516 output = arg;
3517 Py_INCREF(output);
3518 }
3519 else {
3520 arg = PyBytes_FromObject(arg);
3521 if (!arg)
3522 return 0;
3523 output = PyUnicode_DecodeFSDefaultAndSize(PyBytes_AS_STRING(arg),
3524 PyBytes_GET_SIZE(arg));
3525 Py_DECREF(arg);
3526 if (!output)
3527 return 0;
3528 if (!PyUnicode_Check(output)) {
3529 Py_DECREF(output);
3530 PyErr_SetString(PyExc_TypeError, "decoder failed to return unicode");
3531 return 0;
3532 }
3533 }
Victor Stinner065836e2011-10-27 01:56:33 +02003534 if (PyUnicode_READY(output) < 0) {
3535 Py_DECREF(output);
3536 return 0;
3537 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003538 if (findchar(PyUnicode_DATA(output), PyUnicode_KIND(output),
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02003539 PyUnicode_GET_LENGTH(output), 0, 1) >= 0) {
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003540 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
3541 Py_DECREF(output);
3542 return 0;
3543 }
3544 *(PyObject**)addr = output;
3545 return Py_CLEANUP_SUPPORTED;
3546}
3547
3548
Martin v. Löwis5b222132007-06-10 09:51:05 +00003549char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003550PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *psize)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003551{
Christian Heimesf3863112007-11-22 07:46:41 +00003552 PyObject *bytes;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003553
Neal Norwitze0a0a6e2007-08-25 01:04:21 +00003554 if (!PyUnicode_Check(unicode)) {
3555 PyErr_BadArgument();
3556 return NULL;
3557 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003558 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003559 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003560
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003561 if (PyUnicode_UTF8(unicode) == NULL) {
3562 assert(!PyUnicode_IS_COMPACT_ASCII(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003563 bytes = _PyUnicode_AsUTF8String(unicode, "strict");
3564 if (bytes == NULL)
3565 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003566 _PyUnicode_UTF8(unicode) = PyObject_MALLOC(PyBytes_GET_SIZE(bytes) + 1);
3567 if (_PyUnicode_UTF8(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003568 Py_DECREF(bytes);
3569 return NULL;
3570 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003571 _PyUnicode_UTF8_LENGTH(unicode) = PyBytes_GET_SIZE(bytes);
3572 Py_MEMCPY(_PyUnicode_UTF8(unicode),
3573 PyBytes_AS_STRING(bytes),
3574 _PyUnicode_UTF8_LENGTH(unicode) + 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003575 Py_DECREF(bytes);
3576 }
3577
3578 if (psize)
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003579 *psize = PyUnicode_UTF8_LENGTH(unicode);
3580 return PyUnicode_UTF8(unicode);
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003581}
3582
3583char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003584PyUnicode_AsUTF8(PyObject *unicode)
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003585{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003586 return PyUnicode_AsUTF8AndSize(unicode, NULL);
3587}
3588
3589#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +02003590static int unicode_as_unicode_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003591#endif
3592
3593
3594Py_UNICODE *
3595PyUnicode_AsUnicodeAndSize(PyObject *unicode, Py_ssize_t *size)
3596{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003597 const unsigned char *one_byte;
3598#if SIZEOF_WCHAR_T == 4
3599 const Py_UCS2 *two_bytes;
3600#else
3601 const Py_UCS4 *four_bytes;
3602 const Py_UCS4 *ucs4_end;
3603 Py_ssize_t num_surrogates;
3604#endif
3605 wchar_t *w;
3606 wchar_t *wchar_end;
3607
3608 if (!PyUnicode_Check(unicode)) {
3609 PyErr_BadArgument();
3610 return NULL;
3611 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003612 if (_PyUnicode_WSTR(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003613 /* Non-ASCII compact unicode object */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003614 assert(_PyUnicode_KIND(unicode) != 0);
3615 assert(PyUnicode_IS_READY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003616
3617#ifdef Py_DEBUG
3618 ++unicode_as_unicode_calls;
3619#endif
3620
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003621 if (PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003622#if SIZEOF_WCHAR_T == 2
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003623 four_bytes = PyUnicode_4BYTE_DATA(unicode);
3624 ucs4_end = four_bytes + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003625 num_surrogates = 0;
3626
3627 for (; four_bytes < ucs4_end; ++four_bytes) {
3628 if (*four_bytes > 0xFFFF)
3629 ++num_surrogates;
3630 }
3631
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003632 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(
3633 sizeof(wchar_t) * (_PyUnicode_LENGTH(unicode) + 1 + num_surrogates));
3634 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003635 PyErr_NoMemory();
3636 return NULL;
3637 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003638 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode) + num_surrogates;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003639
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003640 w = _PyUnicode_WSTR(unicode);
3641 wchar_end = w + _PyUnicode_WSTR_LENGTH(unicode);
3642 four_bytes = PyUnicode_4BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003643 for (; four_bytes < ucs4_end; ++four_bytes, ++w) {
3644 if (*four_bytes > 0xFFFF) {
Victor Stinner8faf8212011-12-08 22:14:11 +01003645 assert(*four_bytes <= MAX_UNICODE);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003646 /* encode surrogate pair in this case */
Victor Stinner551ac952011-11-29 22:58:13 +01003647 *w++ = Py_UNICODE_HIGH_SURROGATE(*four_bytes);
3648 *w = Py_UNICODE_LOW_SURROGATE(*four_bytes);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003649 }
3650 else
3651 *w = *four_bytes;
3652
3653 if (w > wchar_end) {
3654 assert(0 && "Miscalculated string end");
3655 }
3656 }
3657 *w = 0;
3658#else
3659 /* sizeof(wchar_t) == 4 */
3660 Py_FatalError("Impossible unicode object state, wstr and str "
3661 "should share memory already.");
3662 return NULL;
3663#endif
3664 }
3665 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003666 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(sizeof(wchar_t) *
3667 (_PyUnicode_LENGTH(unicode) + 1));
3668 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003669 PyErr_NoMemory();
3670 return NULL;
3671 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003672 if (!PyUnicode_IS_COMPACT_ASCII(unicode))
3673 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode);
3674 w = _PyUnicode_WSTR(unicode);
3675 wchar_end = w + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003676
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003677 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND) {
3678 one_byte = PyUnicode_1BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003679 for (; w < wchar_end; ++one_byte, ++w)
3680 *w = *one_byte;
3681 /* null-terminate the wstr */
3682 *w = 0;
3683 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003684 else if (PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003685#if SIZEOF_WCHAR_T == 4
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003686 two_bytes = PyUnicode_2BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003687 for (; w < wchar_end; ++two_bytes, ++w)
3688 *w = *two_bytes;
3689 /* null-terminate the wstr */
3690 *w = 0;
3691#else
3692 /* sizeof(wchar_t) == 2 */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003693 PyObject_FREE(_PyUnicode_WSTR(unicode));
3694 _PyUnicode_WSTR(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003695 Py_FatalError("Impossible unicode object state, wstr "
3696 "and str should share memory already.");
3697 return NULL;
3698#endif
3699 }
3700 else {
3701 assert(0 && "This should never happen.");
3702 }
3703 }
3704 }
3705 if (size != NULL)
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003706 *size = PyUnicode_WSTR_LENGTH(unicode);
3707 return _PyUnicode_WSTR(unicode);
Martin v. Löwis5b222132007-06-10 09:51:05 +00003708}
3709
Alexander Belopolsky40018472011-02-26 01:02:56 +00003710Py_UNICODE *
3711PyUnicode_AsUnicode(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003712{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003713 return PyUnicode_AsUnicodeAndSize(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003714}
3715
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003716
Alexander Belopolsky40018472011-02-26 01:02:56 +00003717Py_ssize_t
3718PyUnicode_GetSize(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003719{
3720 if (!PyUnicode_Check(unicode)) {
3721 PyErr_BadArgument();
3722 goto onError;
3723 }
3724 return PyUnicode_GET_SIZE(unicode);
3725
Benjamin Peterson29060642009-01-31 22:14:21 +00003726 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003727 return -1;
3728}
3729
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003730Py_ssize_t
3731PyUnicode_GetLength(PyObject *unicode)
3732{
Victor Stinner5a706cf2011-10-02 00:36:53 +02003733 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003734 PyErr_BadArgument();
3735 return -1;
3736 }
3737
3738 return PyUnicode_GET_LENGTH(unicode);
3739}
3740
3741Py_UCS4
3742PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
3743{
Victor Stinner2fe5ced2011-10-02 00:25:40 +02003744 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
3745 PyErr_BadArgument();
3746 return (Py_UCS4)-1;
3747 }
Victor Stinnerc4b49542011-12-11 22:44:26 +01003748 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinner2fe5ced2011-10-02 00:25:40 +02003749 PyErr_SetString(PyExc_IndexError, "string index out of range");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003750 return (Py_UCS4)-1;
3751 }
3752 return PyUnicode_READ_CHAR(unicode, index);
3753}
3754
3755int
3756PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 ch)
3757{
3758 if (!PyUnicode_Check(unicode) || !PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02003759 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003760 return -1;
3761 }
Victor Stinner488fa492011-12-12 00:01:39 +01003762 assert(PyUnicode_IS_READY(unicode));
Victor Stinnerc4b49542011-12-11 22:44:26 +01003763 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02003764 PyErr_SetString(PyExc_IndexError, "string index out of range");
3765 return -1;
3766 }
Victor Stinner488fa492011-12-12 00:01:39 +01003767 if (unicode_check_modifiable(unicode))
Victor Stinnercd9950f2011-10-02 00:34:53 +02003768 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003769 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
3770 index, ch);
3771 return 0;
3772}
3773
Alexander Belopolsky40018472011-02-26 01:02:56 +00003774const char *
3775PyUnicode_GetDefaultEncoding(void)
Fred Drakee4315f52000-05-09 19:53:39 +00003776{
Victor Stinner42cb4622010-09-01 19:39:01 +00003777 return "utf-8";
Fred Drakee4315f52000-05-09 19:53:39 +00003778}
3779
Victor Stinner554f3f02010-06-16 23:33:54 +00003780/* create or adjust a UnicodeDecodeError */
3781static void
3782make_decode_exception(PyObject **exceptionObject,
3783 const char *encoding,
3784 const char *input, Py_ssize_t length,
3785 Py_ssize_t startpos, Py_ssize_t endpos,
3786 const char *reason)
3787{
3788 if (*exceptionObject == NULL) {
3789 *exceptionObject = PyUnicodeDecodeError_Create(
3790 encoding, input, length, startpos, endpos, reason);
3791 }
3792 else {
3793 if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
3794 goto onError;
3795 if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
3796 goto onError;
3797 if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
3798 goto onError;
3799 }
3800 return;
3801
3802onError:
3803 Py_DECREF(*exceptionObject);
3804 *exceptionObject = NULL;
3805}
3806
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003807/* error handling callback helper:
3808 build arguments, call the callback and check the arguments,
Fred Drakedb390c12005-10-28 14:39:47 +00003809 if no exception occurred, copy the replacement to the output
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003810 and adjust various state variables.
3811 return 0 on success, -1 on error
3812*/
3813
Alexander Belopolsky40018472011-02-26 01:02:56 +00003814static int
3815unicode_decode_call_errorhandler(const char *errors, PyObject **errorHandler,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003816 const char *encoding, const char *reason,
3817 const char **input, const char **inend, Py_ssize_t *startinpos,
3818 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003819 PyObject **output, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003820{
Benjamin Peterson142957c2008-07-04 19:55:29 +00003821 static char *argparse = "O!n;decoding error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003822
3823 PyObject *restuple = NULL;
3824 PyObject *repunicode = NULL;
Victor Stinner596a6c42011-11-09 00:02:18 +01003825 Py_ssize_t outsize;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003826 Py_ssize_t insize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003827 Py_ssize_t requiredsize;
3828 Py_ssize_t newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003829 PyObject *inputobj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003830 int res = -1;
3831
Victor Stinner596a6c42011-11-09 00:02:18 +01003832 if (_PyUnicode_KIND(*output) != PyUnicode_WCHAR_KIND)
3833 outsize = PyUnicode_GET_LENGTH(*output);
3834 else
3835 outsize = _PyUnicode_WSTR_LENGTH(*output);
3836
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003837 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003838 *errorHandler = PyCodec_LookupError(errors);
3839 if (*errorHandler == NULL)
3840 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003841 }
3842
Victor Stinner554f3f02010-06-16 23:33:54 +00003843 make_decode_exception(exceptionObject,
3844 encoding,
3845 *input, *inend - *input,
3846 *startinpos, *endinpos,
3847 reason);
3848 if (*exceptionObject == NULL)
3849 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003850
3851 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
3852 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003853 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003854 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00003855 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00003856 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003857 }
3858 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00003859 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003860 if (PyUnicode_READY(repunicode) < 0)
3861 goto onError;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003862
3863 /* Copy back the bytes variables, which might have been modified by the
3864 callback */
3865 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
3866 if (!inputobj)
3867 goto onError;
Christian Heimes72b710a2008-05-26 13:28:38 +00003868 if (!PyBytes_Check(inputobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003869 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
Walter Dörwalde78178e2007-07-30 13:31:40 +00003870 }
Christian Heimes72b710a2008-05-26 13:28:38 +00003871 *input = PyBytes_AS_STRING(inputobj);
3872 insize = PyBytes_GET_SIZE(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00003873 *inend = *input + insize;
Walter Dörwald36f938f2007-08-10 10:11:43 +00003874 /* we can DECREF safely, as the exception has another reference,
3875 so the object won't go away. */
3876 Py_DECREF(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00003877
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003878 if (newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00003879 newpos = insize+newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00003880 if (newpos<0 || newpos>insize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003881 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
3882 goto onError;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00003883 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003884
Victor Stinner596a6c42011-11-09 00:02:18 +01003885 if (_PyUnicode_KIND(*output) != PyUnicode_WCHAR_KIND) {
3886 /* need more space? (at least enough for what we
3887 have+the replacement+the rest of the string (starting
3888 at the new input position), so we won't have to check space
3889 when there are no errors in the rest of the string) */
3890 Py_ssize_t replen = PyUnicode_GET_LENGTH(repunicode);
3891 requiredsize = *outpos + replen + insize-newpos;
3892 if (requiredsize > outsize) {
3893 if (requiredsize<2*outsize)
3894 requiredsize = 2*outsize;
3895 if (unicode_resize(output, requiredsize) < 0)
3896 goto onError;
3897 }
3898 if (unicode_widen(output, PyUnicode_MAX_CHAR_VALUE(repunicode)) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00003899 goto onError;
Victor Stinner596a6c42011-11-09 00:02:18 +01003900 copy_characters(*output, *outpos, repunicode, 0, replen);
3901 *outpos += replen;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003902 }
Victor Stinner596a6c42011-11-09 00:02:18 +01003903 else {
3904 wchar_t *repwstr;
3905 Py_ssize_t repwlen;
3906 repwstr = PyUnicode_AsUnicodeAndSize(repunicode, &repwlen);
3907 if (repwstr == NULL)
3908 goto onError;
3909 /* need more space? (at least enough for what we
3910 have+the replacement+the rest of the string (starting
3911 at the new input position), so we won't have to check space
3912 when there are no errors in the rest of the string) */
3913 requiredsize = *outpos + repwlen + insize-newpos;
3914 if (requiredsize > outsize) {
3915 if (requiredsize < 2*outsize)
3916 requiredsize = 2*outsize;
3917 if (unicode_resize(output, requiredsize) < 0)
3918 goto onError;
3919 }
3920 wcsncpy(_PyUnicode_WSTR(*output) + *outpos, repwstr, repwlen);
3921 *outpos += repwlen;
3922 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003923 *endinpos = newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003924 *inptr = *input + newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003925
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003926 /* we made it! */
3927 res = 0;
3928
Benjamin Peterson29060642009-01-31 22:14:21 +00003929 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003930 Py_XDECREF(restuple);
3931 return res;
3932}
3933
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003934/* --- UTF-7 Codec -------------------------------------------------------- */
3935
Antoine Pitrou244651a2009-05-04 18:56:13 +00003936/* See RFC2152 for details. We encode conservatively and decode liberally. */
3937
3938/* Three simple macros defining base-64. */
3939
3940/* Is c a base-64 character? */
3941
3942#define IS_BASE64(c) \
3943 (((c) >= 'A' && (c) <= 'Z') || \
3944 ((c) >= 'a' && (c) <= 'z') || \
3945 ((c) >= '0' && (c) <= '9') || \
3946 (c) == '+' || (c) == '/')
3947
3948/* given that c is a base-64 character, what is its base-64 value? */
3949
3950#define FROM_BASE64(c) \
3951 (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' : \
3952 ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 : \
3953 ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 : \
3954 (c) == '+' ? 62 : 63)
3955
3956/* What is the base-64 character of the bottom 6 bits of n? */
3957
3958#define TO_BASE64(n) \
3959 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
3960
3961/* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
3962 * decoded as itself. We are permissive on decoding; the only ASCII
3963 * byte not decoding to itself is the + which begins a base64
3964 * string. */
3965
3966#define DECODE_DIRECT(c) \
3967 ((c) <= 127 && (c) != '+')
3968
3969/* The UTF-7 encoder treats ASCII characters differently according to
3970 * whether they are Set D, Set O, Whitespace, or special (i.e. none of
3971 * the above). See RFC2152. This array identifies these different
3972 * sets:
3973 * 0 : "Set D"
3974 * alphanumeric and '(),-./:?
3975 * 1 : "Set O"
3976 * !"#$%&*;<=>@[]^_`{|}
3977 * 2 : "whitespace"
3978 * ht nl cr sp
3979 * 3 : special (must be base64 encoded)
3980 * everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
3981 */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003982
Tim Petersced69f82003-09-16 20:30:58 +00003983static
Antoine Pitrou244651a2009-05-04 18:56:13 +00003984char utf7_category[128] = {
3985/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
3986 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
3987/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
3988 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
3989/* sp ! " # $ % & ' ( ) * + , - . / */
3990 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
3991/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
3992 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
3993/* @ A B C D E F G H I J K L M N O */
3994 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
3995/* P Q R S T U V W X Y Z [ \ ] ^ _ */
3996 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
3997/* ` a b c d e f g h i j k l m n o */
3998 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
3999/* p q r s t u v w x y z { | } ~ del */
4000 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004001};
4002
Antoine Pitrou244651a2009-05-04 18:56:13 +00004003/* ENCODE_DIRECT: this character should be encoded as itself. The
4004 * answer depends on whether we are encoding set O as itself, and also
4005 * on whether we are encoding whitespace as itself. RFC2152 makes it
4006 * clear that the answers to these questions vary between
4007 * applications, so this code needs to be flexible. */
Marc-André Lemburge115ec82005-10-19 22:33:31 +00004008
Antoine Pitrou244651a2009-05-04 18:56:13 +00004009#define ENCODE_DIRECT(c, directO, directWS) \
4010 ((c) < 128 && (c) > 0 && \
4011 ((utf7_category[(c)] == 0) || \
4012 (directWS && (utf7_category[(c)] == 2)) || \
4013 (directO && (utf7_category[(c)] == 1))))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004014
Alexander Belopolsky40018472011-02-26 01:02:56 +00004015PyObject *
4016PyUnicode_DecodeUTF7(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004017 Py_ssize_t size,
4018 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004019{
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004020 return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
4021}
4022
Antoine Pitrou244651a2009-05-04 18:56:13 +00004023/* The decoder. The only state we preserve is our read position,
4024 * i.e. how many characters we have consumed. So if we end in the
4025 * middle of a shift sequence we have to back off the read position
4026 * and the output to the beginning of the sequence, otherwise we lose
4027 * all the shift state (seen bits, number of bits seen, high
4028 * surrogate). */
4029
Alexander Belopolsky40018472011-02-26 01:02:56 +00004030PyObject *
4031PyUnicode_DecodeUTF7Stateful(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004032 Py_ssize_t size,
4033 const char *errors,
4034 Py_ssize_t *consumed)
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004035{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004036 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004037 Py_ssize_t startinpos;
4038 Py_ssize_t endinpos;
4039 Py_ssize_t outpos;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004040 const char *e;
Victor Stinner7931d9a2011-11-04 00:22:48 +01004041 PyObject *unicode;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004042 const char *errmsg = "";
4043 int inShift = 0;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004044 Py_ssize_t shiftOutStart;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004045 unsigned int base64bits = 0;
4046 unsigned long base64buffer = 0;
Victor Stinner24729f32011-11-10 20:31:37 +01004047 Py_UCS4 surrogate = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004048 PyObject *errorHandler = NULL;
4049 PyObject *exc = NULL;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004050
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004051 /* Start off assuming it's all ASCII. Widen later as necessary. */
4052 unicode = PyUnicode_New(size, 127);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004053 if (!unicode)
4054 return NULL;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004055 if (size == 0) {
4056 if (consumed)
4057 *consumed = 0;
Victor Stinner7931d9a2011-11-04 00:22:48 +01004058 return unicode;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004059 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004060
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004061 shiftOutStart = outpos = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004062 e = s + size;
4063
4064 while (s < e) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004065 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00004066 restart:
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00004067 ch = (unsigned char) *s;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004068
Antoine Pitrou244651a2009-05-04 18:56:13 +00004069 if (inShift) { /* in a base-64 section */
4070 if (IS_BASE64(ch)) { /* consume a base-64 character */
4071 base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
4072 base64bits += 6;
4073 s++;
4074 if (base64bits >= 16) {
4075 /* we have enough bits for a UTF-16 value */
Victor Stinner24729f32011-11-10 20:31:37 +01004076 Py_UCS4 outCh = (Py_UCS4)(base64buffer >> (base64bits-16));
Antoine Pitrou244651a2009-05-04 18:56:13 +00004077 base64bits -= 16;
4078 base64buffer &= (1 << base64bits) - 1; /* clear high bits */
4079 if (surrogate) {
4080 /* expecting a second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004081 if (Py_UNICODE_IS_LOW_SURROGATE(outCh)) {
4082 Py_UCS4 ch2 = Py_UNICODE_JOIN_SURROGATES(surrogate, outCh);
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004083 if (unicode_putchar(&unicode, &outpos, ch2) < 0)
4084 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004085 surrogate = 0;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01004086 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004087 }
4088 else {
Antoine Pitrou78edf752011-11-15 01:44:16 +01004089 if (unicode_putchar(&unicode, &outpos, surrogate) < 0)
4090 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004091 surrogate = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004092 }
4093 }
Victor Stinner551ac952011-11-29 22:58:13 +01004094 if (Py_UNICODE_IS_HIGH_SURROGATE(outCh)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004095 /* first surrogate */
4096 surrogate = outCh;
4097 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004098 else {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004099 if (unicode_putchar(&unicode, &outpos, outCh) < 0)
4100 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004101 }
4102 }
4103 }
4104 else { /* now leaving a base-64 section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004105 inShift = 0;
4106 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004107 if (surrogate) {
Antoine Pitrou78edf752011-11-15 01:44:16 +01004108 if (unicode_putchar(&unicode, &outpos, surrogate) < 0)
4109 goto onError;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01004110 surrogate = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004111 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004112 if (base64bits > 0) { /* left-over bits */
4113 if (base64bits >= 6) {
4114 /* We've seen at least one base-64 character */
4115 errmsg = "partial character in shift sequence";
4116 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004117 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004118 else {
4119 /* Some bits remain; they should be zero */
4120 if (base64buffer != 0) {
4121 errmsg = "non-zero padding bits in shift sequence";
4122 goto utf7Error;
4123 }
4124 }
4125 }
4126 if (ch != '-') {
4127 /* '-' is absorbed; other terminating
4128 characters are preserved */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004129 if (unicode_putchar(&unicode, &outpos, ch) < 0)
4130 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004131 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004132 }
4133 }
4134 else if ( ch == '+' ) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004135 startinpos = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004136 s++; /* consume '+' */
4137 if (s < e && *s == '-') { /* '+-' encodes '+' */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004138 s++;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004139 if (unicode_putchar(&unicode, &outpos, '+') < 0)
4140 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004141 }
4142 else { /* begin base64-encoded section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004143 inShift = 1;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004144 shiftOutStart = outpos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004145 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004146 }
4147 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004148 else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004149 if (unicode_putchar(&unicode, &outpos, ch) < 0)
4150 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004151 s++;
4152 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004153 else {
4154 startinpos = s-starts;
4155 s++;
4156 errmsg = "unexpected special character";
4157 goto utf7Error;
4158 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004159 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004160utf7Error:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004161 endinpos = s-starts;
4162 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00004163 errors, &errorHandler,
4164 "utf7", errmsg,
4165 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004166 &unicode, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00004167 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004168 }
4169
Antoine Pitrou244651a2009-05-04 18:56:13 +00004170 /* end of string */
4171
4172 if (inShift && !consumed) { /* in shift sequence, no more to follow */
4173 /* if we're in an inconsistent state, that's an error */
4174 if (surrogate ||
4175 (base64bits >= 6) ||
4176 (base64bits > 0 && base64buffer != 0)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004177 endinpos = size;
4178 if (unicode_decode_call_errorhandler(
4179 errors, &errorHandler,
4180 "utf7", "unterminated shift sequence",
4181 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004182 &unicode, &outpos))
Antoine Pitrou244651a2009-05-04 18:56:13 +00004183 goto onError;
4184 if (s < e)
4185 goto restart;
4186 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004187 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004188
4189 /* return state */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004190 if (consumed) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004191 if (inShift) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004192 outpos = shiftOutStart; /* back off output */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004193 *consumed = startinpos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004194 }
4195 else {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004196 *consumed = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004197 }
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004198 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004199
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004200 if (unicode_resize(&unicode, outpos) < 0)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004201 goto onError;
4202
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004203 Py_XDECREF(errorHandler);
4204 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01004205 return unicode_result(unicode);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004206
Benjamin Peterson29060642009-01-31 22:14:21 +00004207 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004208 Py_XDECREF(errorHandler);
4209 Py_XDECREF(exc);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004210 Py_DECREF(unicode);
4211 return NULL;
4212}
4213
4214
Alexander Belopolsky40018472011-02-26 01:02:56 +00004215PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004216_PyUnicode_EncodeUTF7(PyObject *str,
4217 int base64SetO,
4218 int base64WhiteSpace,
4219 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004220{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004221 int kind;
4222 void *data;
4223 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004224 PyObject *v;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004225 Py_ssize_t allocated;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004226 int inShift = 0;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004227 Py_ssize_t i;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004228 unsigned int base64bits = 0;
4229 unsigned long base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004230 char * out;
4231 char * start;
4232
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004233 if (PyUnicode_READY(str) < 0)
4234 return NULL;
4235 kind = PyUnicode_KIND(str);
4236 data = PyUnicode_DATA(str);
4237 len = PyUnicode_GET_LENGTH(str);
4238
4239 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004240 return PyBytes_FromStringAndSize(NULL, 0);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004241
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004242 /* It might be possible to tighten this worst case */
4243 allocated = 8 * len;
4244 if (allocated / 8 != len)
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004245 return PyErr_NoMemory();
4246
Antoine Pitrou244651a2009-05-04 18:56:13 +00004247 v = PyBytes_FromStringAndSize(NULL, allocated);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004248 if (v == NULL)
4249 return NULL;
4250
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004251 start = out = PyBytes_AS_STRING(v);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004252 for (i = 0; i < len; ++i) {
Victor Stinner0e368262011-11-10 20:12:49 +01004253 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004254
Antoine Pitrou244651a2009-05-04 18:56:13 +00004255 if (inShift) {
4256 if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4257 /* shifting out */
4258 if (base64bits) { /* output remaining bits */
4259 *out++ = TO_BASE64(base64buffer << (6-base64bits));
4260 base64buffer = 0;
4261 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004262 }
4263 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004264 /* Characters not in the BASE64 set implicitly unshift the sequence
4265 so no '-' is required, except if the character is itself a '-' */
4266 if (IS_BASE64(ch) || ch == '-') {
4267 *out++ = '-';
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004268 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004269 *out++ = (char) ch;
4270 }
4271 else {
4272 goto encode_char;
Tim Petersced69f82003-09-16 20:30:58 +00004273 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004274 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004275 else { /* not in a shift sequence */
4276 if (ch == '+') {
4277 *out++ = '+';
4278 *out++ = '-';
4279 }
4280 else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4281 *out++ = (char) ch;
4282 }
4283 else {
4284 *out++ = '+';
4285 inShift = 1;
4286 goto encode_char;
4287 }
4288 }
4289 continue;
4290encode_char:
Antoine Pitrou244651a2009-05-04 18:56:13 +00004291 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01004292 assert(ch <= MAX_UNICODE);
Victor Stinner0d3721d2011-11-22 03:27:53 +01004293
Antoine Pitrou244651a2009-05-04 18:56:13 +00004294 /* code first surrogate */
4295 base64bits += 16;
4296 base64buffer = (base64buffer << 16) | 0xd800 | ((ch-0x10000) >> 10);
4297 while (base64bits >= 6) {
4298 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4299 base64bits -= 6;
4300 }
4301 /* prepare second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004302 ch = Py_UNICODE_LOW_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004303 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004304 base64bits += 16;
4305 base64buffer = (base64buffer << 16) | ch;
4306 while (base64bits >= 6) {
4307 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4308 base64bits -= 6;
4309 }
Hye-Shik Chang1bc09b72004-01-03 19:35:43 +00004310 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004311 if (base64bits)
4312 *out++= TO_BASE64(base64buffer << (6-base64bits) );
4313 if (inShift)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004314 *out++ = '-';
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004315 if (_PyBytes_Resize(&v, out - start) < 0)
4316 return NULL;
4317 return v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004318}
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004319PyObject *
4320PyUnicode_EncodeUTF7(const Py_UNICODE *s,
4321 Py_ssize_t size,
4322 int base64SetO,
4323 int base64WhiteSpace,
4324 const char *errors)
4325{
4326 PyObject *result;
4327 PyObject *tmp = PyUnicode_FromUnicode(s, size);
4328 if (tmp == NULL)
4329 return NULL;
Victor Stinner0e368262011-11-10 20:12:49 +01004330 result = _PyUnicode_EncodeUTF7(tmp, base64SetO,
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004331 base64WhiteSpace, errors);
4332 Py_DECREF(tmp);
4333 return result;
4334}
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004335
Antoine Pitrou244651a2009-05-04 18:56:13 +00004336#undef IS_BASE64
4337#undef FROM_BASE64
4338#undef TO_BASE64
4339#undef DECODE_DIRECT
4340#undef ENCODE_DIRECT
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004341
Guido van Rossumd57fd912000-03-10 22:53:23 +00004342/* --- UTF-8 Codec -------------------------------------------------------- */
4343
Tim Petersced69f82003-09-16 20:30:58 +00004344static
Guido van Rossumd57fd912000-03-10 22:53:23 +00004345char utf8_code_length[256] = {
Ezio Melotti57221d02010-07-01 07:32:02 +00004346 /* Map UTF-8 encoded prefix byte to sequence length. Zero means
4347 illegal prefix. See RFC 3629 for details */
4348 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 00-0F */
4349 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Victor Stinner4a2b7a12010-08-13 14:03:48 +00004350 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Guido van Rossumd57fd912000-03-10 22:53:23 +00004351 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
4352 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
4353 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
4354 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Ezio Melotti57221d02010-07-01 07:32:02 +00004355 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 70-7F */
4356 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 +00004357 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4358 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
Ezio Melotti57221d02010-07-01 07:32:02 +00004359 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* B0-BF */
4360 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* C0-C1 + C2-CF */
4361 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* D0-DF */
4362 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, /* E0-EF */
4363 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 +00004364};
4365
Alexander Belopolsky40018472011-02-26 01:02:56 +00004366PyObject *
4367PyUnicode_DecodeUTF8(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004368 Py_ssize_t size,
4369 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004370{
Walter Dörwald69652032004-09-07 20:24:22 +00004371 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
4372}
4373
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004374#include "stringlib/ucs1lib.h"
4375#include "stringlib/codecs.h"
4376#include "stringlib/undef.h"
4377
4378#include "stringlib/ucs2lib.h"
4379#include "stringlib/codecs.h"
4380#include "stringlib/undef.h"
4381
4382#include "stringlib/ucs4lib.h"
4383#include "stringlib/codecs.h"
4384#include "stringlib/undef.h"
4385
Antoine Pitrouab868312009-01-10 15:40:25 +00004386/* Mask to check or force alignment of a pointer to C 'long' boundaries */
4387#define LONG_PTR_MASK (size_t) (SIZEOF_LONG - 1)
4388
4389/* Mask to quickly check whether a C 'long' contains a
4390 non-ASCII, UTF8-encoded char. */
4391#if (SIZEOF_LONG == 8)
4392# define ASCII_CHAR_MASK 0x8080808080808080L
4393#elif (SIZEOF_LONG == 4)
4394# define ASCII_CHAR_MASK 0x80808080L
4395#else
4396# error C 'long' size should be either 4 or 8!
4397#endif
4398
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004399/* Scans a UTF-8 string and returns the maximum character to be expected
4400 and the size of the decoded unicode string.
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004401
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004402 This function doesn't check for errors, these checks are performed in
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004403 PyUnicode_DecodeUTF8Stateful.
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004404 */
4405static Py_UCS4
Victor Stinnera1d12bb2011-12-11 21:53:09 +01004406utf8_scanner(const unsigned char *p, Py_ssize_t string_size, Py_ssize_t *unicode_size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004407{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004408 Py_ssize_t char_count = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004409 const unsigned char *end = p + string_size;
4410 const unsigned char *aligned_end = (const unsigned char *) ((size_t) end & ~LONG_PTR_MASK);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004411
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004412 assert(unicode_size != NULL);
4413
4414 /* By having a cascade of independent loops which fallback onto each
4415 other, we minimize the amount of work done in the average loop
4416 iteration, and we also maximize the CPU's ability to predict
4417 branches correctly (because a given condition will have always the
4418 same boolean outcome except perhaps in the last iteration of the
4419 corresponding loop).
4420 In the general case this brings us rather close to decoding
4421 performance pre-PEP 393, despite the two-pass decoding.
4422
4423 Note that the pure ASCII loop is not duplicated once a non-ASCII
4424 character has been encountered. It is actually a pessimization (by
4425 a significant factor) to use this loop on text with many non-ASCII
4426 characters, and it is important to avoid bad performance on valid
4427 utf-8 data (invalid utf-8 being a different can of worms).
4428 */
4429
4430 /* ASCII */
4431 for (; p < end; ++p) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004432 /* Only check value if it's not a ASCII char... */
4433 if (*p < 0x80) {
4434 /* Fast path, see below in PyUnicode_DecodeUTF8Stateful for
4435 an explanation. */
4436 if (!((size_t) p & LONG_PTR_MASK)) {
4437 /* Help register allocation */
4438 register const unsigned char *_p = p;
4439 while (_p < aligned_end) {
4440 unsigned long value = *(unsigned long *) _p;
4441 if (value & ASCII_CHAR_MASK)
4442 break;
4443 _p += SIZEOF_LONG;
4444 char_count += SIZEOF_LONG;
4445 }
4446 p = _p;
4447 if (p == end)
4448 break;
4449 }
4450 }
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004451 if (*p < 0x80)
4452 ++char_count;
4453 else
4454 goto _ucs1loop;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004455 }
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004456 *unicode_size = char_count;
4457 return 127;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004458
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004459_ucs1loop:
4460 for (; p < end; ++p) {
4461 if (*p < 0xc4)
4462 char_count += ((*p & 0xc0) != 0x80);
4463 else
4464 goto _ucs2loop;
4465 }
4466 *unicode_size = char_count;
4467 return 255;
4468
4469_ucs2loop:
4470 for (; p < end; ++p) {
4471 if (*p < 0xf0)
4472 char_count += ((*p & 0xc0) != 0x80);
4473 else
4474 goto _ucs4loop;
4475 }
4476 *unicode_size = char_count;
4477 return 65535;
4478
4479_ucs4loop:
4480 for (; p < end; ++p) {
4481 char_count += ((*p & 0xc0) != 0x80);
4482 }
4483 *unicode_size = char_count;
4484 return 65537;
4485}
4486
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004487/* Similar to PyUnicode_WRITE but may attempt to widen and resize the string
Victor Stinner785938e2011-12-11 20:09:03 +01004488 in case of errors. Implicit parameters: unicode, kind, data, onError.
4489 Potential resizing overallocates, so the result needs to shrink at the end.
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004490*/
Victor Stinner785938e2011-12-11 20:09:03 +01004491#define WRITE_MAYBE_FAIL(index, value) \
4492 do { \
4493 Py_ssize_t pos = index; \
4494 if (pos > PyUnicode_GET_LENGTH(unicode) && \
4495 unicode_resize(&unicode, pos + pos/8) < 0) \
4496 goto onError; \
4497 if (unicode_putchar(&unicode, &pos, value) < 0) \
4498 goto onError; \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004499 } while (0)
4500
Victor Stinnerbf6e5602011-12-12 01:53:47 +01004501static PyObject *
Victor Stinner785938e2011-12-11 20:09:03 +01004502decode_utf8_errors(const char *starts,
4503 Py_ssize_t size,
4504 const char *errors,
4505 Py_ssize_t *consumed,
4506 const char *s,
4507 PyObject *unicode,
4508 Py_ssize_t i)
Walter Dörwald69652032004-09-07 20:24:22 +00004509{
Guido van Rossumd57fd912000-03-10 22:53:23 +00004510 int n;
Ezio Melotti57221d02010-07-01 07:32:02 +00004511 int k;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004512 Py_ssize_t startinpos;
4513 Py_ssize_t endinpos;
Victor Stinner785938e2011-12-11 20:09:03 +01004514 const char *e = starts + size;
4515 const char *aligned_end;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004516 const char *errmsg = "";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004517 PyObject *errorHandler = NULL;
4518 PyObject *exc = NULL;
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004519
Antoine Pitrouab868312009-01-10 15:40:25 +00004520 aligned_end = (const char *) ((size_t) e & ~LONG_PTR_MASK);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004521
4522 while (s < e) {
Marc-André Lemburge12896e2000-07-07 17:51:08 +00004523 Py_UCS4 ch = (unsigned char)*s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004524
4525 if (ch < 0x80) {
Antoine Pitrouab868312009-01-10 15:40:25 +00004526 /* Fast path for runs of ASCII characters. Given that common UTF-8
4527 input will consist of an overwhelming majority of ASCII
4528 characters, we try to optimize for this case by checking
4529 as many characters as a C 'long' can contain.
4530 First, check if we can do an aligned read, as most CPUs have
4531 a penalty for unaligned reads.
4532 */
4533 if (!((size_t) s & LONG_PTR_MASK)) {
4534 /* Help register allocation */
4535 register const char *_s = s;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004536 register Py_ssize_t _i = i;
Antoine Pitrouab868312009-01-10 15:40:25 +00004537 while (_s < aligned_end) {
4538 /* Read a whole long at a time (either 4 or 8 bytes),
4539 and do a fast unrolled copy if it only contains ASCII
4540 characters. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004541 unsigned long value = *(unsigned long *) _s;
4542 if (value & ASCII_CHAR_MASK)
Antoine Pitrouab868312009-01-10 15:40:25 +00004543 break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004544 WRITE_MAYBE_FAIL(_i+0, _s[0]);
4545 WRITE_MAYBE_FAIL(_i+1, _s[1]);
4546 WRITE_MAYBE_FAIL(_i+2, _s[2]);
4547 WRITE_MAYBE_FAIL(_i+3, _s[3]);
Antoine Pitrouab868312009-01-10 15:40:25 +00004548#if (SIZEOF_LONG == 8)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004549 WRITE_MAYBE_FAIL(_i+4, _s[4]);
4550 WRITE_MAYBE_FAIL(_i+5, _s[5]);
4551 WRITE_MAYBE_FAIL(_i+6, _s[6]);
4552 WRITE_MAYBE_FAIL(_i+7, _s[7]);
Antoine Pitrouab868312009-01-10 15:40:25 +00004553#endif
4554 _s += SIZEOF_LONG;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004555 _i += SIZEOF_LONG;
Antoine Pitrouab868312009-01-10 15:40:25 +00004556 }
4557 s = _s;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004558 i = _i;
Antoine Pitrouab868312009-01-10 15:40:25 +00004559 if (s == e)
4560 break;
4561 ch = (unsigned char)*s;
4562 }
4563 }
4564
4565 if (ch < 0x80) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004566 WRITE_MAYBE_FAIL(i++, ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004567 s++;
4568 continue;
4569 }
4570
4571 n = utf8_code_length[ch];
4572
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004573 if (s + n > e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004574 if (consumed)
4575 break;
4576 else {
4577 errmsg = "unexpected end of data";
4578 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004579 endinpos = startinpos+1;
4580 for (k=1; (k < size-startinpos) && ((s[k]&0xC0) == 0x80); k++)
4581 endinpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00004582 goto utf8Error;
4583 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00004584 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004585
4586 switch (n) {
4587
4588 case 0:
Ezio Melotti57221d02010-07-01 07:32:02 +00004589 errmsg = "invalid start byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004590 startinpos = s-starts;
4591 endinpos = startinpos+1;
4592 goto utf8Error;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004593
4594 case 1:
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004595 errmsg = "internal error";
Benjamin Peterson29060642009-01-31 22:14:21 +00004596 startinpos = s-starts;
4597 endinpos = startinpos+1;
4598 goto utf8Error;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004599
4600 case 2:
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004601 if ((s[1] & 0xc0) != 0x80) {
Ezio Melotti57221d02010-07-01 07:32:02 +00004602 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004603 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004604 endinpos = startinpos + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00004605 goto utf8Error;
4606 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004607 ch = ((s[0] & 0x1f) << 6) + (s[1] & 0x3f);
Ezio Melotti57221d02010-07-01 07:32:02 +00004608 assert ((ch > 0x007F) && (ch <= 0x07FF));
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004609 WRITE_MAYBE_FAIL(i++, ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004610 break;
4611
4612 case 3:
Ezio Melotti9bf2b3a2010-07-03 04:52:19 +00004613 /* Decoding UTF-8 sequences in range \xed\xa0\x80-\xed\xbf\xbf
4614 will result in surrogates in range d800-dfff. Surrogates are
4615 not valid UTF-8 so they are rejected.
4616 See http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf
4617 (table 3-7) and http://www.rfc-editor.org/rfc/rfc3629.txt */
Tim Petersced69f82003-09-16 20:30:58 +00004618 if ((s[1] & 0xc0) != 0x80 ||
Ezio Melotti57221d02010-07-01 07:32:02 +00004619 (s[2] & 0xc0) != 0x80 ||
4620 ((unsigned char)s[0] == 0xE0 &&
4621 (unsigned char)s[1] < 0xA0) ||
4622 ((unsigned char)s[0] == 0xED &&
4623 (unsigned char)s[1] > 0x9F)) {
4624 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004625 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004626 endinpos = startinpos + 1;
4627
4628 /* if s[1] first two bits are 1 and 0, then the invalid
4629 continuation byte is s[2], so increment endinpos by 1,
4630 if not, s[1] is invalid and endinpos doesn't need to
4631 be incremented. */
4632 if ((s[1] & 0xC0) == 0x80)
4633 endinpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00004634 goto utf8Error;
4635 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004636 ch = ((s[0] & 0x0f) << 12) + ((s[1] & 0x3f) << 6) + (s[2] & 0x3f);
Ezio Melotti57221d02010-07-01 07:32:02 +00004637 assert ((ch > 0x07FF) && (ch <= 0xFFFF));
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004638 WRITE_MAYBE_FAIL(i++, ch);
Marc-André Lemburge12896e2000-07-07 17:51:08 +00004639 break;
4640
4641 case 4:
4642 if ((s[1] & 0xc0) != 0x80 ||
4643 (s[2] & 0xc0) != 0x80 ||
Ezio Melotti57221d02010-07-01 07:32:02 +00004644 (s[3] & 0xc0) != 0x80 ||
4645 ((unsigned char)s[0] == 0xF0 &&
4646 (unsigned char)s[1] < 0x90) ||
4647 ((unsigned char)s[0] == 0xF4 &&
4648 (unsigned char)s[1] > 0x8F)) {
4649 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004650 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004651 endinpos = startinpos + 1;
4652 if ((s[1] & 0xC0) == 0x80) {
4653 endinpos++;
4654 if ((s[2] & 0xC0) == 0x80)
4655 endinpos++;
4656 }
Benjamin Peterson29060642009-01-31 22:14:21 +00004657 goto utf8Error;
4658 }
Marc-André Lemburge12896e2000-07-07 17:51:08 +00004659 ch = ((s[0] & 0x7) << 18) + ((s[1] & 0x3f) << 12) +
Ezio Melotti57221d02010-07-01 07:32:02 +00004660 ((s[2] & 0x3f) << 6) + (s[3] & 0x3f);
Victor Stinner8faf8212011-12-08 22:14:11 +01004661 assert ((ch > 0xFFFF) && (ch <= MAX_UNICODE));
Ezio Melotti57221d02010-07-01 07:32:02 +00004662
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004663 WRITE_MAYBE_FAIL(i++, ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004664 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004665 }
4666 s += n;
Benjamin Peterson29060642009-01-31 22:14:21 +00004667 continue;
Tim Petersced69f82003-09-16 20:30:58 +00004668
Benjamin Peterson29060642009-01-31 22:14:21 +00004669 utf8Error:
Benjamin Peterson29060642009-01-31 22:14:21 +00004670 if (unicode_decode_call_errorhandler(
4671 errors, &errorHandler,
4672 "utf8", errmsg,
4673 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004674 &unicode, &i))
Benjamin Peterson29060642009-01-31 22:14:21 +00004675 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004676 /* Update data because unicode_decode_call_errorhandler might have
4677 re-created or resized the unicode object. */
Benjamin Peterson29060642009-01-31 22:14:21 +00004678 aligned_end = (const char *) ((size_t) e & ~LONG_PTR_MASK);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004679 }
Walter Dörwald69652032004-09-07 20:24:22 +00004680 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00004681 *consumed = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004682
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004683 /* Adjust length and ready string when it contained errors and
4684 is of the old resizable kind. */
Victor Stinner785938e2011-12-11 20:09:03 +01004685 if (unicode_resize(&unicode, i) < 0)
4686 goto onError;
4687 unicode_adjust_maxchar(&unicode);
4688 if (unicode == NULL)
4689 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004690
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004691 Py_XDECREF(errorHandler);
4692 Py_XDECREF(exc);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02004693 assert(_PyUnicode_CheckConsistency(unicode, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01004694 return unicode;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004695
Benjamin Peterson29060642009-01-31 22:14:21 +00004696 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004697 Py_XDECREF(errorHandler);
4698 Py_XDECREF(exc);
Victor Stinner785938e2011-12-11 20:09:03 +01004699 Py_XDECREF(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004700 return NULL;
4701}
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004702#undef WRITE_MAYBE_FAIL
Antoine Pitrouab868312009-01-10 15:40:25 +00004703
Victor Stinner785938e2011-12-11 20:09:03 +01004704PyObject *
4705PyUnicode_DecodeUTF8Stateful(const char *s,
4706 Py_ssize_t size,
4707 const char *errors,
4708 Py_ssize_t *consumed)
4709{
4710 Py_UCS4 maxchar = 0;
4711 Py_ssize_t unicode_size;
4712 int has_errors = 0;
4713 PyObject *unicode;
4714 int kind;
4715 void *data;
4716 const char *starts = s;
4717 const char *e;
4718 Py_ssize_t i;
4719
4720 if (size == 0) {
4721 if (consumed)
4722 *consumed = 0;
Victor Stinner382955f2011-12-11 21:44:00 +01004723 Py_INCREF(unicode_empty);
4724 return unicode_empty;
Victor Stinner785938e2011-12-11 20:09:03 +01004725 }
4726
Victor Stinnera1d12bb2011-12-11 21:53:09 +01004727 maxchar = utf8_scanner((const unsigned char *)s, size, &unicode_size);
Victor Stinner785938e2011-12-11 20:09:03 +01004728
4729 /* When the string is ASCII only, just use memcpy and return.
4730 unicode_size may be != size if there is an incomplete UTF-8
4731 sequence at the end of the ASCII block. */
4732 if (maxchar < 128 && size == unicode_size) {
4733 if (consumed)
4734 *consumed = size;
4735 return unicode_fromascii(s, size);
4736 }
4737
4738 unicode = PyUnicode_New(unicode_size, maxchar);
4739 if (!unicode)
4740 return NULL;
4741 kind = PyUnicode_KIND(unicode);
4742 data = PyUnicode_DATA(unicode);
4743
4744 /* Unpack UTF-8 encoded data */
4745 i = 0;
4746 e = starts + size;
4747 switch (kind) {
4748 case PyUnicode_1BYTE_KIND:
4749 has_errors = ucs1lib_utf8_try_decode(s, e, (Py_UCS1 *) data, &s, &i);
4750 break;
4751 case PyUnicode_2BYTE_KIND:
4752 has_errors = ucs2lib_utf8_try_decode(s, e, (Py_UCS2 *) data, &s, &i);
4753 break;
4754 case PyUnicode_4BYTE_KIND:
4755 has_errors = ucs4lib_utf8_try_decode(s, e, (Py_UCS4 *) data, &s, &i);
4756 break;
4757 }
4758 if (!has_errors) {
4759 /* Ensure the unicode size calculation was correct */
4760 assert(i == unicode_size);
4761 assert(s == e);
4762 if (consumed)
4763 *consumed = size;
4764 return unicode;
4765 }
4766
4767 /* In case of errors, maxchar and size computation might be incorrect;
4768 code below refits and resizes as necessary. */
4769 return decode_utf8_errors(starts, size, errors, consumed, s, unicode, i);
4770}
4771
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004772#ifdef __APPLE__
4773
4774/* Simplified UTF-8 decoder using surrogateescape error handler,
4775 used to decode the command line arguments on Mac OS X. */
4776
4777wchar_t*
4778_Py_DecodeUTF8_surrogateescape(const char *s, Py_ssize_t size)
4779{
4780 int n;
4781 const char *e;
4782 wchar_t *unicode, *p;
4783
4784 /* Note: size will always be longer than the resulting Unicode
4785 character count */
4786 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < (size + 1)) {
4787 PyErr_NoMemory();
4788 return NULL;
4789 }
4790 unicode = PyMem_Malloc((size + 1) * sizeof(wchar_t));
4791 if (!unicode)
4792 return NULL;
4793
4794 /* Unpack UTF-8 encoded data */
4795 p = unicode;
4796 e = s + size;
4797 while (s < e) {
4798 Py_UCS4 ch = (unsigned char)*s;
4799
4800 if (ch < 0x80) {
4801 *p++ = (wchar_t)ch;
4802 s++;
4803 continue;
4804 }
4805
4806 n = utf8_code_length[ch];
4807 if (s + n > e) {
4808 goto surrogateescape;
4809 }
4810
4811 switch (n) {
4812 case 0:
4813 case 1:
4814 goto surrogateescape;
4815
4816 case 2:
4817 if ((s[1] & 0xc0) != 0x80)
4818 goto surrogateescape;
4819 ch = ((s[0] & 0x1f) << 6) + (s[1] & 0x3f);
4820 assert ((ch > 0x007F) && (ch <= 0x07FF));
4821 *p++ = (wchar_t)ch;
4822 break;
4823
4824 case 3:
4825 /* Decoding UTF-8 sequences in range \xed\xa0\x80-\xed\xbf\xbf
4826 will result in surrogates in range d800-dfff. Surrogates are
4827 not valid UTF-8 so they are rejected.
4828 See http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf
4829 (table 3-7) and http://www.rfc-editor.org/rfc/rfc3629.txt */
4830 if ((s[1] & 0xc0) != 0x80 ||
4831 (s[2] & 0xc0) != 0x80 ||
4832 ((unsigned char)s[0] == 0xE0 &&
4833 (unsigned char)s[1] < 0xA0) ||
4834 ((unsigned char)s[0] == 0xED &&
4835 (unsigned char)s[1] > 0x9F)) {
4836
4837 goto surrogateescape;
4838 }
4839 ch = ((s[0] & 0x0f) << 12) + ((s[1] & 0x3f) << 6) + (s[2] & 0x3f);
4840 assert ((ch > 0x07FF) && (ch <= 0xFFFF));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004841 *p++ = (wchar_t)ch;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004842 break;
4843
4844 case 4:
4845 if ((s[1] & 0xc0) != 0x80 ||
4846 (s[2] & 0xc0) != 0x80 ||
4847 (s[3] & 0xc0) != 0x80 ||
4848 ((unsigned char)s[0] == 0xF0 &&
4849 (unsigned char)s[1] < 0x90) ||
4850 ((unsigned char)s[0] == 0xF4 &&
4851 (unsigned char)s[1] > 0x8F)) {
4852 goto surrogateescape;
4853 }
4854 ch = ((s[0] & 0x7) << 18) + ((s[1] & 0x3f) << 12) +
4855 ((s[2] & 0x3f) << 6) + (s[3] & 0x3f);
Victor Stinner8faf8212011-12-08 22:14:11 +01004856 assert ((ch > 0xFFFF) && (ch <= MAX_UNICODE));
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004857
4858#if SIZEOF_WCHAR_T == 4
4859 *p++ = (wchar_t)ch;
4860#else
4861 /* compute and append the two surrogates: */
Victor Stinner551ac952011-11-29 22:58:13 +01004862 *p++ = (wchar_t)Py_UNICODE_HIGH_SURROGATE(ch);
4863 *p++ = (wchar_t)Py_UNICODE_LOW_SURROGATE(ch);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004864#endif
4865 break;
4866 }
4867 s += n;
4868 continue;
4869
4870 surrogateescape:
4871 *p++ = 0xDC00 + ch;
4872 s++;
4873 }
4874 *p = L'\0';
4875 return unicode;
4876}
4877
4878#endif /* __APPLE__ */
Antoine Pitrouab868312009-01-10 15:40:25 +00004879
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004880/* Primary internal function which creates utf8 encoded bytes objects.
4881
4882 Allocation strategy: if the string is short, convert into a stack buffer
Tim Peters602f7402002-04-27 18:03:26 +00004883 and allocate exactly as much space needed at the end. Else allocate the
4884 maximum possible needed (4 result bytes per Unicode character), and return
4885 the excess memory at the end.
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004886*/
Tim Peters7e3d9612002-04-21 03:26:37 +00004887PyObject *
Victor Stinner7931d9a2011-11-04 00:22:48 +01004888_PyUnicode_AsUTF8String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004889{
Tim Peters602f7402002-04-27 18:03:26 +00004890#define MAX_SHORT_UNICHARS 300 /* largest size we'll do on the stack */
Tim Peters0eca65c2002-04-21 17:28:06 +00004891
Guido van Rossum98297ee2007-11-06 21:34:58 +00004892 Py_ssize_t i; /* index into s of next input byte */
4893 PyObject *result; /* result string object */
4894 char *p; /* next free byte in output buffer */
4895 Py_ssize_t nallocated; /* number of result bytes allocated */
4896 Py_ssize_t nneeded; /* number of result bytes needed */
Tim Peters602f7402002-04-27 18:03:26 +00004897 char stackbuf[MAX_SHORT_UNICHARS * 4];
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004898 PyObject *errorHandler = NULL;
4899 PyObject *exc = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004900 int kind;
4901 void *data;
4902 Py_ssize_t size;
Antoine Pitrou31b92a52011-11-12 18:35:19 +01004903 PyObject *rep = NULL;
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00004904
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004905 if (!PyUnicode_Check(unicode)) {
4906 PyErr_BadArgument();
4907 return NULL;
4908 }
4909
4910 if (PyUnicode_READY(unicode) == -1)
4911 return NULL;
4912
Victor Stinnere90fe6a2011-10-01 16:48:13 +02004913 if (PyUnicode_UTF8(unicode))
4914 return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode),
4915 PyUnicode_UTF8_LENGTH(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004916
4917 kind = PyUnicode_KIND(unicode);
4918 data = PyUnicode_DATA(unicode);
4919 size = PyUnicode_GET_LENGTH(unicode);
4920
Tim Peters602f7402002-04-27 18:03:26 +00004921 assert(size >= 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004922
Tim Peters602f7402002-04-27 18:03:26 +00004923 if (size <= MAX_SHORT_UNICHARS) {
4924 /* Write into the stack buffer; nallocated can't overflow.
4925 * At the end, we'll allocate exactly as much heap space as it
4926 * turns out we need.
4927 */
4928 nallocated = Py_SAFE_DOWNCAST(sizeof(stackbuf), size_t, int);
Guido van Rossum98297ee2007-11-06 21:34:58 +00004929 result = NULL; /* will allocate after we're done */
Tim Peters602f7402002-04-27 18:03:26 +00004930 p = stackbuf;
4931 }
4932 else {
4933 /* Overallocate on the heap, and give the excess back at the end. */
4934 nallocated = size * 4;
4935 if (nallocated / 4 != size) /* overflow! */
4936 return PyErr_NoMemory();
Christian Heimes72b710a2008-05-26 13:28:38 +00004937 result = PyBytes_FromStringAndSize(NULL, nallocated);
Guido van Rossum98297ee2007-11-06 21:34:58 +00004938 if (result == NULL)
Tim Peters602f7402002-04-27 18:03:26 +00004939 return NULL;
Christian Heimes72b710a2008-05-26 13:28:38 +00004940 p = PyBytes_AS_STRING(result);
Tim Peters602f7402002-04-27 18:03:26 +00004941 }
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004942
Tim Peters602f7402002-04-27 18:03:26 +00004943 for (i = 0; i < size;) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004944 Py_UCS4 ch = PyUnicode_READ(kind, data, i++);
Marc-André Lemburg3688a882002-02-06 18:09:02 +00004945
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004946 if (ch < 0x80)
Tim Peters602f7402002-04-27 18:03:26 +00004947 /* Encode ASCII */
Guido van Rossumd57fd912000-03-10 22:53:23 +00004948 *p++ = (char) ch;
Marc-André Lemburg3688a882002-02-06 18:09:02 +00004949
Guido van Rossumd57fd912000-03-10 22:53:23 +00004950 else if (ch < 0x0800) {
Tim Peters602f7402002-04-27 18:03:26 +00004951 /* Encode Latin-1 */
Marc-André Lemburgdc724d62002-02-06 18:20:19 +00004952 *p++ = (char)(0xc0 | (ch >> 6));
4953 *p++ = (char)(0x80 | (ch & 0x3f));
Victor Stinner551ac952011-11-29 22:58:13 +01004954 } else if (Py_UNICODE_IS_SURROGATE(ch)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004955 Py_ssize_t newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004956 Py_ssize_t repsize, k, startpos;
4957 startpos = i-1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004958 rep = unicode_encode_call_errorhandler(
4959 errors, &errorHandler, "utf-8", "surrogates not allowed",
Victor Stinner7931d9a2011-11-04 00:22:48 +01004960 unicode, &exc, startpos, startpos+1, &newpos);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004961 if (!rep)
4962 goto error;
Victor Stinner31be90b2010-04-22 19:38:16 +00004963
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004964 if (PyBytes_Check(rep))
4965 repsize = PyBytes_GET_SIZE(rep);
4966 else
Victor Stinner9e30aa52011-11-21 02:49:52 +01004967 repsize = PyUnicode_GET_LENGTH(rep);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004968
4969 if (repsize > 4) {
4970 Py_ssize_t offset;
4971
4972 if (result == NULL)
4973 offset = p - stackbuf;
Victor Stinner31be90b2010-04-22 19:38:16 +00004974 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004975 offset = p - PyBytes_AS_STRING(result);
Victor Stinner31be90b2010-04-22 19:38:16 +00004976
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004977 if (nallocated > PY_SSIZE_T_MAX - repsize + 4) {
4978 /* integer overflow */
4979 PyErr_NoMemory();
4980 goto error;
4981 }
4982 nallocated += repsize - 4;
4983 if (result != NULL) {
4984 if (_PyBytes_Resize(&result, nallocated) < 0)
4985 goto error;
4986 } else {
4987 result = PyBytes_FromStringAndSize(NULL, nallocated);
Victor Stinner31be90b2010-04-22 19:38:16 +00004988 if (result == NULL)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004989 goto error;
4990 Py_MEMCPY(PyBytes_AS_STRING(result), stackbuf, offset);
4991 }
4992 p = PyBytes_AS_STRING(result) + offset;
4993 }
Victor Stinner31be90b2010-04-22 19:38:16 +00004994
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004995 if (PyBytes_Check(rep)) {
4996 char *prep = PyBytes_AS_STRING(rep);
4997 for(k = repsize; k > 0; k--)
4998 *p++ = *prep++;
4999 } else /* rep is unicode */ {
Victor Stinnera98b28c2011-11-10 20:21:49 +01005000 enum PyUnicode_Kind repkind;
5001 void *repdata;
5002
Antoine Pitrou31b92a52011-11-12 18:35:19 +01005003 if (PyUnicode_READY(rep) < 0)
Victor Stinnera98b28c2011-11-10 20:21:49 +01005004 goto error;
Victor Stinnera98b28c2011-11-10 20:21:49 +01005005 repkind = PyUnicode_KIND(rep);
5006 repdata = PyUnicode_DATA(rep);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005007
5008 for(k=0; k<repsize; k++) {
Victor Stinnera98b28c2011-11-10 20:21:49 +01005009 Py_UCS4 c = PyUnicode_READ(repkind, repdata, k);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005010 if (0x80 <= c) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01005011 raise_encode_exception(&exc, "utf-8",
Victor Stinner7931d9a2011-11-04 00:22:48 +01005012 unicode,
Martin v. Löwis9e816682011-11-02 12:45:42 +01005013 i-1, i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005014 "surrogates not allowed");
Victor Stinner31be90b2010-04-22 19:38:16 +00005015 goto error;
5016 }
Victor Stinnera98b28c2011-11-10 20:21:49 +01005017 *p++ = (char)c;
Victor Stinner31be90b2010-04-22 19:38:16 +00005018 }
Victor Stinner31be90b2010-04-22 19:38:16 +00005019 }
Antoine Pitrou31b92a52011-11-12 18:35:19 +01005020 Py_CLEAR(rep);
Victor Stinner31be90b2010-04-22 19:38:16 +00005021 } else if (ch < 0x10000) {
5022 *p++ = (char)(0xe0 | (ch >> 12));
5023 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
5024 *p++ = (char)(0x80 | (ch & 0x3f));
5025 } else /* ch >= 0x10000 */ {
Victor Stinner8faf8212011-12-08 22:14:11 +01005026 assert(ch <= MAX_UNICODE);
Tim Peters602f7402002-04-27 18:03:26 +00005027 /* Encode UCS4 Unicode ordinals */
5028 *p++ = (char)(0xf0 | (ch >> 18));
5029 *p++ = (char)(0x80 | ((ch >> 12) & 0x3f));
5030 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
5031 *p++ = (char)(0x80 | (ch & 0x3f));
5032 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005033 }
Tim Peters0eca65c2002-04-21 17:28:06 +00005034
Guido van Rossum98297ee2007-11-06 21:34:58 +00005035 if (result == NULL) {
Tim Peters602f7402002-04-27 18:03:26 +00005036 /* This was stack allocated. */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005037 nneeded = p - stackbuf;
Tim Peters602f7402002-04-27 18:03:26 +00005038 assert(nneeded <= nallocated);
Christian Heimes72b710a2008-05-26 13:28:38 +00005039 result = PyBytes_FromStringAndSize(stackbuf, nneeded);
Tim Peters602f7402002-04-27 18:03:26 +00005040 }
5041 else {
Christian Heimesf3863112007-11-22 07:46:41 +00005042 /* Cut back to size actually needed. */
Christian Heimes72b710a2008-05-26 13:28:38 +00005043 nneeded = p - PyBytes_AS_STRING(result);
Tim Peters602f7402002-04-27 18:03:26 +00005044 assert(nneeded <= nallocated);
Christian Heimes72b710a2008-05-26 13:28:38 +00005045 _PyBytes_Resize(&result, nneeded);
Tim Peters602f7402002-04-27 18:03:26 +00005046 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005047
Martin v. Löwisdb12d452009-05-02 18:52:14 +00005048 Py_XDECREF(errorHandler);
5049 Py_XDECREF(exc);
Guido van Rossum98297ee2007-11-06 21:34:58 +00005050 return result;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00005051 error:
Antoine Pitrou31b92a52011-11-12 18:35:19 +01005052 Py_XDECREF(rep);
Martin v. Löwisdb12d452009-05-02 18:52:14 +00005053 Py_XDECREF(errorHandler);
5054 Py_XDECREF(exc);
5055 Py_XDECREF(result);
5056 return NULL;
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00005057
Tim Peters602f7402002-04-27 18:03:26 +00005058#undef MAX_SHORT_UNICHARS
Guido van Rossumd57fd912000-03-10 22:53:23 +00005059}
5060
Alexander Belopolsky40018472011-02-26 01:02:56 +00005061PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005062PyUnicode_EncodeUTF8(const Py_UNICODE *s,
5063 Py_ssize_t size,
5064 const char *errors)
5065{
5066 PyObject *v, *unicode;
5067
5068 unicode = PyUnicode_FromUnicode(s, size);
5069 if (unicode == NULL)
5070 return NULL;
5071 v = _PyUnicode_AsUTF8String(unicode, errors);
5072 Py_DECREF(unicode);
5073 return v;
5074}
5075
5076PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005077PyUnicode_AsUTF8String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005078{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005079 return _PyUnicode_AsUTF8String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005080}
5081
Walter Dörwald41980ca2007-08-16 21:55:45 +00005082/* --- UTF-32 Codec ------------------------------------------------------- */
5083
5084PyObject *
5085PyUnicode_DecodeUTF32(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005086 Py_ssize_t size,
5087 const char *errors,
5088 int *byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005089{
5090 return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
5091}
5092
5093PyObject *
5094PyUnicode_DecodeUTF32Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005095 Py_ssize_t size,
5096 const char *errors,
5097 int *byteorder,
5098 Py_ssize_t *consumed)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005099{
5100 const char *starts = s;
5101 Py_ssize_t startinpos;
5102 Py_ssize_t endinpos;
5103 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01005104 PyObject *unicode;
Mark Dickinson7db923c2010-06-12 09:10:14 +00005105 const unsigned char *q, *e;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005106 int bo = 0; /* assume native ordering by default */
5107 const char *errmsg = "";
Walter Dörwald41980ca2007-08-16 21:55:45 +00005108 /* Offsets from q for retrieving bytes in the right order. */
5109#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5110 int iorder[] = {0, 1, 2, 3};
5111#else
5112 int iorder[] = {3, 2, 1, 0};
5113#endif
5114 PyObject *errorHandler = NULL;
5115 PyObject *exc = NULL;
Victor Stinner313a1202010-06-11 23:56:51 +00005116
Walter Dörwald41980ca2007-08-16 21:55:45 +00005117 q = (unsigned char *)s;
5118 e = q + size;
5119
5120 if (byteorder)
5121 bo = *byteorder;
5122
5123 /* Check for BOM marks (U+FEFF) in the input and adjust current
5124 byte order setting accordingly. In native mode, the leading BOM
5125 mark is skipped, in all other modes, it is copied to the output
5126 stream as-is (giving a ZWNBSP character). */
5127 if (bo == 0) {
5128 if (size >= 4) {
5129 const Py_UCS4 bom = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
Benjamin Peterson29060642009-01-31 22:14:21 +00005130 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00005131#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Benjamin Peterson29060642009-01-31 22:14:21 +00005132 if (bom == 0x0000FEFF) {
5133 q += 4;
5134 bo = -1;
5135 }
5136 else if (bom == 0xFFFE0000) {
5137 q += 4;
5138 bo = 1;
5139 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00005140#else
Benjamin Peterson29060642009-01-31 22:14:21 +00005141 if (bom == 0x0000FEFF) {
5142 q += 4;
5143 bo = 1;
5144 }
5145 else if (bom == 0xFFFE0000) {
5146 q += 4;
5147 bo = -1;
5148 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00005149#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00005150 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00005151 }
5152
5153 if (bo == -1) {
5154 /* force LE */
5155 iorder[0] = 0;
5156 iorder[1] = 1;
5157 iorder[2] = 2;
5158 iorder[3] = 3;
5159 }
5160 else if (bo == 1) {
5161 /* force BE */
5162 iorder[0] = 3;
5163 iorder[1] = 2;
5164 iorder[2] = 1;
5165 iorder[3] = 0;
5166 }
5167
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005168 /* This might be one to much, because of a BOM */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005169 unicode = PyUnicode_New((size+3)/4, 127);
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005170 if (!unicode)
5171 return NULL;
5172 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01005173 return unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005174 outpos = 0;
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005175
Walter Dörwald41980ca2007-08-16 21:55:45 +00005176 while (q < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005177 Py_UCS4 ch;
5178 /* remaining bytes at the end? (size should be divisible by 4) */
5179 if (e-q<4) {
5180 if (consumed)
5181 break;
5182 errmsg = "truncated data";
5183 startinpos = ((const char *)q)-starts;
5184 endinpos = ((const char *)e)-starts;
5185 goto utf32Error;
5186 /* The remaining input chars are ignored if the callback
5187 chooses to skip the input */
5188 }
5189 ch = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
5190 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00005191
Benjamin Peterson29060642009-01-31 22:14:21 +00005192 if (ch >= 0x110000)
5193 {
5194 errmsg = "codepoint not in range(0x110000)";
5195 startinpos = ((const char *)q)-starts;
5196 endinpos = startinpos+4;
5197 goto utf32Error;
5198 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005199 if (unicode_putchar(&unicode, &outpos, ch) < 0)
5200 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005201 q += 4;
5202 continue;
5203 utf32Error:
Benjamin Peterson29060642009-01-31 22:14:21 +00005204 if (unicode_decode_call_errorhandler(
5205 errors, &errorHandler,
5206 "utf32", errmsg,
5207 &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005208 &unicode, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00005209 goto onError;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005210 }
5211
5212 if (byteorder)
5213 *byteorder = bo;
5214
5215 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005216 *consumed = (const char *)q-starts;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005217
5218 /* Adjust length */
Victor Stinner16e6a802011-12-12 13:24:15 +01005219 if (unicode_resize(&unicode, outpos) < 0)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005220 goto onError;
5221
5222 Py_XDECREF(errorHandler);
5223 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01005224 return unicode_result(unicode);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005225
Benjamin Peterson29060642009-01-31 22:14:21 +00005226 onError:
Walter Dörwald41980ca2007-08-16 21:55:45 +00005227 Py_DECREF(unicode);
5228 Py_XDECREF(errorHandler);
5229 Py_XDECREF(exc);
5230 return NULL;
5231}
5232
5233PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005234_PyUnicode_EncodeUTF32(PyObject *str,
5235 const char *errors,
5236 int byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005237{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005238 int kind;
5239 void *data;
5240 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005241 PyObject *v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005242 unsigned char *p;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005243 Py_ssize_t nsize, bytesize, i;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005244 /* Offsets from p for storing byte pairs in the right order. */
5245#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5246 int iorder[] = {0, 1, 2, 3};
5247#else
5248 int iorder[] = {3, 2, 1, 0};
5249#endif
5250
Benjamin Peterson29060642009-01-31 22:14:21 +00005251#define STORECHAR(CH) \
5252 do { \
5253 p[iorder[3]] = ((CH) >> 24) & 0xff; \
5254 p[iorder[2]] = ((CH) >> 16) & 0xff; \
5255 p[iorder[1]] = ((CH) >> 8) & 0xff; \
5256 p[iorder[0]] = (CH) & 0xff; \
5257 p += 4; \
Walter Dörwald41980ca2007-08-16 21:55:45 +00005258 } while(0)
5259
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005260 if (!PyUnicode_Check(str)) {
5261 PyErr_BadArgument();
5262 return NULL;
5263 }
5264 if (PyUnicode_READY(str) < 0)
5265 return NULL;
5266 kind = PyUnicode_KIND(str);
5267 data = PyUnicode_DATA(str);
5268 len = PyUnicode_GET_LENGTH(str);
5269
5270 nsize = len + (byteorder == 0);
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005271 bytesize = nsize * 4;
5272 if (bytesize / 4 != nsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005273 return PyErr_NoMemory();
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005274 v = PyBytes_FromStringAndSize(NULL, bytesize);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005275 if (v == NULL)
5276 return NULL;
5277
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005278 p = (unsigned char *)PyBytes_AS_STRING(v);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005279 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005280 STORECHAR(0xFEFF);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005281 if (len == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005282 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005283
5284 if (byteorder == -1) {
5285 /* force LE */
5286 iorder[0] = 0;
5287 iorder[1] = 1;
5288 iorder[2] = 2;
5289 iorder[3] = 3;
5290 }
5291 else if (byteorder == 1) {
5292 /* force BE */
5293 iorder[0] = 3;
5294 iorder[1] = 2;
5295 iorder[2] = 1;
5296 iorder[3] = 0;
5297 }
5298
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005299 for (i = 0; i < len; i++)
5300 STORECHAR(PyUnicode_READ(kind, data, i));
Guido van Rossum98297ee2007-11-06 21:34:58 +00005301
5302 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005303 return v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005304#undef STORECHAR
5305}
5306
Alexander Belopolsky40018472011-02-26 01:02:56 +00005307PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005308PyUnicode_EncodeUTF32(const Py_UNICODE *s,
5309 Py_ssize_t size,
5310 const char *errors,
5311 int byteorder)
5312{
5313 PyObject *result;
5314 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5315 if (tmp == NULL)
5316 return NULL;
5317 result = _PyUnicode_EncodeUTF32(tmp, errors, byteorder);
5318 Py_DECREF(tmp);
5319 return result;
5320}
5321
5322PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005323PyUnicode_AsUTF32String(PyObject *unicode)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005324{
Victor Stinnerb960b342011-11-20 19:12:52 +01005325 return _PyUnicode_EncodeUTF32(unicode, NULL, 0);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005326}
5327
Guido van Rossumd57fd912000-03-10 22:53:23 +00005328/* --- UTF-16 Codec ------------------------------------------------------- */
5329
Tim Peters772747b2001-08-09 22:21:55 +00005330PyObject *
5331PyUnicode_DecodeUTF16(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005332 Py_ssize_t size,
5333 const char *errors,
5334 int *byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005335{
Walter Dörwald69652032004-09-07 20:24:22 +00005336 return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
5337}
5338
Antoine Pitrouab868312009-01-10 15:40:25 +00005339/* Two masks for fast checking of whether a C 'long' may contain
5340 UTF16-encoded surrogate characters. This is an efficient heuristic,
5341 assuming that non-surrogate characters with a code point >= 0x8000 are
5342 rare in most input.
5343 FAST_CHAR_MASK is used when the input is in native byte ordering,
5344 SWAPPED_FAST_CHAR_MASK when the input is in byteswapped ordering.
Benjamin Peterson29060642009-01-31 22:14:21 +00005345*/
Antoine Pitrouab868312009-01-10 15:40:25 +00005346#if (SIZEOF_LONG == 8)
5347# define FAST_CHAR_MASK 0x8000800080008000L
5348# define SWAPPED_FAST_CHAR_MASK 0x0080008000800080L
5349#elif (SIZEOF_LONG == 4)
5350# define FAST_CHAR_MASK 0x80008000L
5351# define SWAPPED_FAST_CHAR_MASK 0x00800080L
5352#else
5353# error C 'long' size should be either 4 or 8!
5354#endif
5355
Walter Dörwald69652032004-09-07 20:24:22 +00005356PyObject *
5357PyUnicode_DecodeUTF16Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005358 Py_ssize_t size,
5359 const char *errors,
5360 int *byteorder,
5361 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00005362{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005363 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005364 Py_ssize_t startinpos;
5365 Py_ssize_t endinpos;
5366 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01005367 PyObject *unicode;
Antoine Pitrouab868312009-01-10 15:40:25 +00005368 const unsigned char *q, *e, *aligned_end;
Tim Peters772747b2001-08-09 22:21:55 +00005369 int bo = 0; /* assume native ordering by default */
Antoine Pitrouab868312009-01-10 15:40:25 +00005370 int native_ordering = 0;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00005371 const char *errmsg = "";
Tim Peters772747b2001-08-09 22:21:55 +00005372 /* Offsets from q for retrieving byte pairs in the right order. */
5373#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5374 int ihi = 1, ilo = 0;
5375#else
5376 int ihi = 0, ilo = 1;
5377#endif
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005378 PyObject *errorHandler = NULL;
5379 PyObject *exc = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005380
5381 /* Note: size will always be longer than the resulting Unicode
5382 character count */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005383 unicode = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005384 if (!unicode)
5385 return NULL;
5386 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01005387 return unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005388 outpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005389
Tim Peters772747b2001-08-09 22:21:55 +00005390 q = (unsigned char *)s;
Antoine Pitrouab868312009-01-10 15:40:25 +00005391 e = q + size - 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005392
5393 if (byteorder)
Tim Peters772747b2001-08-09 22:21:55 +00005394 bo = *byteorder;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005395
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005396 /* Check for BOM marks (U+FEFF) in the input and adjust current
5397 byte order setting accordingly. In native mode, the leading BOM
5398 mark is skipped, in all other modes, it is copied to the output
5399 stream as-is (giving a ZWNBSP character). */
5400 if (bo == 0) {
Walter Dörwald69652032004-09-07 20:24:22 +00005401 if (size >= 2) {
Victor Stinner24729f32011-11-10 20:31:37 +01005402 const Py_UCS4 bom = (q[ihi] << 8) | q[ilo];
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005403#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Benjamin Peterson29060642009-01-31 22:14:21 +00005404 if (bom == 0xFEFF) {
5405 q += 2;
5406 bo = -1;
5407 }
5408 else if (bom == 0xFFFE) {
5409 q += 2;
5410 bo = 1;
5411 }
Tim Petersced69f82003-09-16 20:30:58 +00005412#else
Benjamin Peterson29060642009-01-31 22:14:21 +00005413 if (bom == 0xFEFF) {
5414 q += 2;
5415 bo = 1;
5416 }
5417 else if (bom == 0xFFFE) {
5418 q += 2;
5419 bo = -1;
5420 }
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005421#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00005422 }
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005423 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005424
Tim Peters772747b2001-08-09 22:21:55 +00005425 if (bo == -1) {
5426 /* force LE */
5427 ihi = 1;
5428 ilo = 0;
5429 }
5430 else if (bo == 1) {
5431 /* force BE */
5432 ihi = 0;
5433 ilo = 1;
5434 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005435#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5436 native_ordering = ilo < ihi;
5437#else
5438 native_ordering = ilo > ihi;
5439#endif
Tim Peters772747b2001-08-09 22:21:55 +00005440
Antoine Pitrouab868312009-01-10 15:40:25 +00005441 aligned_end = (const unsigned char *) ((size_t) e & ~LONG_PTR_MASK);
Tim Peters772747b2001-08-09 22:21:55 +00005442 while (q < e) {
Victor Stinner24729f32011-11-10 20:31:37 +01005443 Py_UCS4 ch;
Antoine Pitrouab868312009-01-10 15:40:25 +00005444 /* First check for possible aligned read of a C 'long'. Unaligned
5445 reads are more expensive, better to defer to another iteration. */
5446 if (!((size_t) q & LONG_PTR_MASK)) {
5447 /* Fast path for runs of non-surrogate chars. */
5448 register const unsigned char *_q = q;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005449 int kind = PyUnicode_KIND(unicode);
5450 void *data = PyUnicode_DATA(unicode);
5451 while (_q < aligned_end) {
5452 unsigned long block = * (unsigned long *) _q;
5453 unsigned short *pblock = (unsigned short*)&block;
5454 Py_UCS4 maxch;
5455 if (native_ordering) {
5456 /* Can use buffer directly */
5457 if (block & FAST_CHAR_MASK)
Antoine Pitrouab868312009-01-10 15:40:25 +00005458 break;
Antoine Pitrouab868312009-01-10 15:40:25 +00005459 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005460 else {
5461 /* Need to byte-swap */
5462 unsigned char *_p = (unsigned char*)pblock;
5463 if (block & SWAPPED_FAST_CHAR_MASK)
Antoine Pitrouab868312009-01-10 15:40:25 +00005464 break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005465 _p[0] = _q[1];
5466 _p[1] = _q[0];
5467 _p[2] = _q[3];
5468 _p[3] = _q[2];
Antoine Pitrouab868312009-01-10 15:40:25 +00005469#if (SIZEOF_LONG == 8)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005470 _p[4] = _q[5];
5471 _p[5] = _q[4];
5472 _p[6] = _q[7];
5473 _p[7] = _q[6];
Antoine Pitrouab868312009-01-10 15:40:25 +00005474#endif
Antoine Pitrouab868312009-01-10 15:40:25 +00005475 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005476 maxch = Py_MAX(pblock[0], pblock[1]);
5477#if SIZEOF_LONG == 8
5478 maxch = Py_MAX(maxch, Py_MAX(pblock[2], pblock[3]));
5479#endif
5480 if (maxch > PyUnicode_MAX_CHAR_VALUE(unicode)) {
5481 if (unicode_widen(&unicode, maxch) < 0)
5482 goto onError;
5483 kind = PyUnicode_KIND(unicode);
5484 data = PyUnicode_DATA(unicode);
5485 }
5486 PyUnicode_WRITE(kind, data, outpos++, pblock[0]);
5487 PyUnicode_WRITE(kind, data, outpos++, pblock[1]);
5488#if SIZEOF_LONG == 8
5489 PyUnicode_WRITE(kind, data, outpos++, pblock[2]);
5490 PyUnicode_WRITE(kind, data, outpos++, pblock[3]);
5491#endif
5492 _q += SIZEOF_LONG;
Antoine Pitrouab868312009-01-10 15:40:25 +00005493 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005494 q = _q;
5495 if (q >= e)
5496 break;
5497 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005498 ch = (q[ihi] << 8) | q[ilo];
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005499
Benjamin Peterson14339b62009-01-31 16:36:08 +00005500 q += 2;
Benjamin Peterson29060642009-01-31 22:14:21 +00005501
Victor Stinner551ac952011-11-29 22:58:13 +01005502 if (!Py_UNICODE_IS_SURROGATE(ch)) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005503 if (unicode_putchar(&unicode, &outpos, ch) < 0)
5504 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005505 continue;
5506 }
5507
5508 /* UTF-16 code pair: */
5509 if (q > e) {
5510 errmsg = "unexpected end of data";
5511 startinpos = (((const char *)q) - 2) - starts;
5512 endinpos = ((const char *)e) + 1 - starts;
5513 goto utf16Error;
5514 }
Victor Stinner2e9cfad2011-11-20 18:40:27 +01005515 if (Py_UNICODE_IS_HIGH_SURROGATE(ch)) {
5516 Py_UCS4 ch2 = (q[ihi] << 8) | q[ilo];
Benjamin Peterson29060642009-01-31 22:14:21 +00005517 q += 2;
Victor Stinner2e9cfad2011-11-20 18:40:27 +01005518 if (Py_UNICODE_IS_LOW_SURROGATE(ch2)) {
Victor Stinner62aa4d02011-11-09 00:03:45 +01005519 if (unicode_putchar(&unicode, &outpos,
Victor Stinner2e9cfad2011-11-20 18:40:27 +01005520 Py_UNICODE_JOIN_SURROGATES(ch, ch2)) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005521 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005522 continue;
5523 }
5524 else {
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005525 errmsg = "illegal UTF-16 surrogate";
Benjamin Peterson29060642009-01-31 22:14:21 +00005526 startinpos = (((const char *)q)-4)-starts;
5527 endinpos = startinpos+2;
5528 goto utf16Error;
5529 }
5530
Benjamin Peterson14339b62009-01-31 16:36:08 +00005531 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005532 errmsg = "illegal encoding";
5533 startinpos = (((const char *)q)-2)-starts;
5534 endinpos = startinpos+2;
5535 /* Fall through to report the error */
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005536
Benjamin Peterson29060642009-01-31 22:14:21 +00005537 utf16Error:
Benjamin Peterson29060642009-01-31 22:14:21 +00005538 if (unicode_decode_call_errorhandler(
Antoine Pitrouab868312009-01-10 15:40:25 +00005539 errors,
5540 &errorHandler,
5541 "utf16", errmsg,
5542 &starts,
5543 (const char **)&e,
5544 &startinpos,
5545 &endinpos,
5546 &exc,
5547 (const char **)&q,
5548 &unicode,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005549 &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00005550 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005551 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005552 /* remaining byte at the end? (size should be even) */
5553 if (e == q) {
5554 if (!consumed) {
5555 errmsg = "truncated data";
5556 startinpos = ((const char *)q) - starts;
5557 endinpos = ((const char *)e) + 1 - starts;
Antoine Pitrouab868312009-01-10 15:40:25 +00005558 if (unicode_decode_call_errorhandler(
5559 errors,
5560 &errorHandler,
5561 "utf16", errmsg,
5562 &starts,
5563 (const char **)&e,
5564 &startinpos,
5565 &endinpos,
5566 &exc,
5567 (const char **)&q,
5568 &unicode,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005569 &outpos))
Antoine Pitrouab868312009-01-10 15:40:25 +00005570 goto onError;
5571 /* The remaining input chars are ignored if the callback
5572 chooses to skip the input */
5573 }
5574 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005575
5576 if (byteorder)
5577 *byteorder = bo;
5578
Walter Dörwald69652032004-09-07 20:24:22 +00005579 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005580 *consumed = (const char *)q-starts;
Walter Dörwald69652032004-09-07 20:24:22 +00005581
Guido van Rossumd57fd912000-03-10 22:53:23 +00005582 /* Adjust length */
Victor Stinner16e6a802011-12-12 13:24:15 +01005583 if (unicode_resize(&unicode, outpos) < 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005584 goto onError;
5585
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005586 Py_XDECREF(errorHandler);
5587 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01005588 return unicode_result(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005589
Benjamin Peterson29060642009-01-31 22:14:21 +00005590 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00005591 Py_DECREF(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005592 Py_XDECREF(errorHandler);
5593 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005594 return NULL;
5595}
5596
Antoine Pitrouab868312009-01-10 15:40:25 +00005597#undef FAST_CHAR_MASK
5598#undef SWAPPED_FAST_CHAR_MASK
5599
Tim Peters772747b2001-08-09 22:21:55 +00005600PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005601_PyUnicode_EncodeUTF16(PyObject *str,
5602 const char *errors,
5603 int byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005604{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005605 int kind;
5606 void *data;
5607 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005608 PyObject *v;
Tim Peters772747b2001-08-09 22:21:55 +00005609 unsigned char *p;
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005610 Py_ssize_t nsize, bytesize;
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005611 Py_ssize_t i, pairs;
Tim Peters772747b2001-08-09 22:21:55 +00005612 /* Offsets from p for storing byte pairs in the right order. */
5613#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5614 int ihi = 1, ilo = 0;
5615#else
5616 int ihi = 0, ilo = 1;
5617#endif
5618
Benjamin Peterson29060642009-01-31 22:14:21 +00005619#define STORECHAR(CH) \
5620 do { \
5621 p[ihi] = ((CH) >> 8) & 0xff; \
5622 p[ilo] = (CH) & 0xff; \
5623 p += 2; \
Tim Peters772747b2001-08-09 22:21:55 +00005624 } while(0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005625
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005626 if (!PyUnicode_Check(str)) {
5627 PyErr_BadArgument();
5628 return NULL;
5629 }
5630 if (PyUnicode_READY(str) < 0)
5631 return NULL;
5632 kind = PyUnicode_KIND(str);
5633 data = PyUnicode_DATA(str);
5634 len = PyUnicode_GET_LENGTH(str);
Victor Stinner0e368262011-11-10 20:12:49 +01005635
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005636 pairs = 0;
5637 if (kind == PyUnicode_4BYTE_KIND)
5638 for (i = 0; i < len; i++)
5639 if (PyUnicode_READ(kind, data, i) >= 0x10000)
5640 pairs++;
5641 /* 2 * (len + pairs + (byteorder == 0)) */
5642 if (len > PY_SSIZE_T_MAX - pairs - (byteorder == 0))
Benjamin Peterson29060642009-01-31 22:14:21 +00005643 return PyErr_NoMemory();
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005644 nsize = len + pairs + (byteorder == 0);
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005645 bytesize = nsize * 2;
5646 if (bytesize / 2 != nsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005647 return PyErr_NoMemory();
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005648 v = PyBytes_FromStringAndSize(NULL, bytesize);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005649 if (v == NULL)
5650 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005651
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005652 p = (unsigned char *)PyBytes_AS_STRING(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005653 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005654 STORECHAR(0xFEFF);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005655 if (len == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005656 goto done;
Tim Peters772747b2001-08-09 22:21:55 +00005657
5658 if (byteorder == -1) {
5659 /* force LE */
5660 ihi = 1;
5661 ilo = 0;
5662 }
5663 else if (byteorder == 1) {
5664 /* force BE */
5665 ihi = 0;
5666 ilo = 1;
5667 }
5668
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005669 for (i = 0; i < len; i++) {
5670 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
5671 Py_UCS4 ch2 = 0;
Benjamin Peterson29060642009-01-31 22:14:21 +00005672 if (ch >= 0x10000) {
Victor Stinner551ac952011-11-29 22:58:13 +01005673 ch2 = Py_UNICODE_LOW_SURROGATE(ch);
5674 ch = Py_UNICODE_HIGH_SURROGATE(ch);
Benjamin Peterson29060642009-01-31 22:14:21 +00005675 }
Tim Peters772747b2001-08-09 22:21:55 +00005676 STORECHAR(ch);
5677 if (ch2)
5678 STORECHAR(ch2);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005679 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005680
5681 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005682 return v;
Tim Peters772747b2001-08-09 22:21:55 +00005683#undef STORECHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00005684}
5685
Alexander Belopolsky40018472011-02-26 01:02:56 +00005686PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005687PyUnicode_EncodeUTF16(const Py_UNICODE *s,
5688 Py_ssize_t size,
5689 const char *errors,
5690 int byteorder)
5691{
5692 PyObject *result;
5693 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5694 if (tmp == NULL)
5695 return NULL;
5696 result = _PyUnicode_EncodeUTF16(tmp, errors, byteorder);
5697 Py_DECREF(tmp);
5698 return result;
5699}
5700
5701PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005702PyUnicode_AsUTF16String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005703{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005704 return _PyUnicode_EncodeUTF16(unicode, NULL, 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005705}
5706
5707/* --- Unicode Escape Codec ----------------------------------------------- */
5708
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005709/* Helper function for PyUnicode_DecodeUnicodeEscape, determines
5710 if all the escapes in the string make it still a valid ASCII string.
5711 Returns -1 if any escapes were found which cause the string to
5712 pop out of ASCII range. Otherwise returns the length of the
5713 required buffer to hold the string.
5714 */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02005715static Py_ssize_t
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005716length_of_escaped_ascii_string(const char *s, Py_ssize_t size)
5717{
5718 const unsigned char *p = (const unsigned char *)s;
5719 const unsigned char *end = p + size;
5720 Py_ssize_t length = 0;
5721
5722 if (size < 0)
5723 return -1;
5724
5725 for (; p < end; ++p) {
5726 if (*p > 127) {
5727 /* Non-ASCII */
5728 return -1;
5729 }
5730 else if (*p != '\\') {
5731 /* Normal character */
5732 ++length;
5733 }
5734 else {
5735 /* Backslash-escape, check next char */
5736 ++p;
5737 /* Escape sequence reaches till end of string or
5738 non-ASCII follow-up. */
5739 if (p >= end || *p > 127)
5740 return -1;
5741 switch (*p) {
5742 case '\n':
5743 /* backslash + \n result in zero characters */
5744 break;
5745 case '\\': case '\'': case '\"':
5746 case 'b': case 'f': case 't':
5747 case 'n': case 'r': case 'v': case 'a':
5748 ++length;
5749 break;
5750 case '0': case '1': case '2': case '3':
5751 case '4': case '5': case '6': case '7':
5752 case 'x': case 'u': case 'U': case 'N':
5753 /* these do not guarantee ASCII characters */
5754 return -1;
5755 default:
5756 /* count the backslash + the other character */
5757 length += 2;
5758 }
5759 }
5760 }
5761 return length;
5762}
5763
Fredrik Lundh06d12682001-01-24 07:59:11 +00005764static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
Marc-André Lemburg0f774e32000-06-28 16:43:35 +00005765
Alexander Belopolsky40018472011-02-26 01:02:56 +00005766PyObject *
5767PyUnicode_DecodeUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005768 Py_ssize_t size,
Victor Stinnerc17f5402011-09-29 00:16:58 +02005769 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005770{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005771 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005772 Py_ssize_t startinpos;
5773 Py_ssize_t endinpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005774 int j;
Victor Stinner7931d9a2011-11-04 00:22:48 +01005775 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005776 const char *end;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005777 char* message;
5778 Py_UCS4 chr = 0xffffffff; /* in case 'getcode' messes up */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005779 PyObject *errorHandler = NULL;
5780 PyObject *exc = NULL;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005781 Py_ssize_t len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005782 Py_ssize_t i;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005783
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005784 len = length_of_escaped_ascii_string(s, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005785
5786 /* After length_of_escaped_ascii_string() there are two alternatives,
5787 either the string is pure ASCII with named escapes like \n, etc.
5788 and we determined it's exact size (common case)
5789 or it contains \x, \u, ... escape sequences. then we create a
5790 legacy wchar string and resize it at the end of this function. */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005791 if (len >= 0) {
5792 v = PyUnicode_New(len, 127);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005793 if (!v)
5794 goto onError;
5795 assert(PyUnicode_KIND(v) == PyUnicode_1BYTE_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005796 }
5797 else {
5798 /* Escaped strings will always be longer than the resulting
5799 Unicode string, so we start with size here and then reduce the
5800 length after conversion to the true value.
5801 (but if the error callback returns a long replacement string
5802 we'll have to allocate more space) */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005803 v = PyUnicode_New(size, 127);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005804 if (!v)
5805 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005806 len = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005807 }
5808
Guido van Rossumd57fd912000-03-10 22:53:23 +00005809 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01005810 return v;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005811 i = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005812 end = s + size;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005813
Guido van Rossumd57fd912000-03-10 22:53:23 +00005814 while (s < end) {
5815 unsigned char c;
Victor Stinner24729f32011-11-10 20:31:37 +01005816 Py_UCS4 x;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005817 int digits;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005818
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005819 /* The only case in which i == ascii_length is a backslash
5820 followed by a newline. */
5821 assert(i <= len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005822
Guido van Rossumd57fd912000-03-10 22:53:23 +00005823 /* Non-escape characters are interpreted as Unicode ordinals */
5824 if (*s != '\\') {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005825 if (unicode_putchar(&v, &i, (unsigned char) *s++) < 0)
5826 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005827 continue;
5828 }
5829
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005830 startinpos = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005831 /* \ - Escapes */
5832 s++;
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005833 c = *s++;
5834 if (s > end)
5835 c = '\0'; /* Invalid after \ */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005836
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005837 /* The only case in which i == ascii_length is a backslash
5838 followed by a newline. */
5839 assert(i < len || (i == len && c == '\n'));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005840
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005841 switch (c) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005842
Benjamin Peterson29060642009-01-31 22:14:21 +00005843 /* \x escapes */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005844#define WRITECHAR(ch) \
5845 do { \
5846 if (unicode_putchar(&v, &i, ch) < 0) \
5847 goto onError; \
5848 }while(0)
5849
Guido van Rossumd57fd912000-03-10 22:53:23 +00005850 case '\n': break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005851 case '\\': WRITECHAR('\\'); break;
5852 case '\'': WRITECHAR('\''); break;
5853 case '\"': WRITECHAR('\"'); break;
5854 case 'b': WRITECHAR('\b'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005855 /* FF */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005856 case 'f': WRITECHAR('\014'); break;
5857 case 't': WRITECHAR('\t'); break;
5858 case 'n': WRITECHAR('\n'); break;
5859 case 'r': WRITECHAR('\r'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005860 /* VT */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005861 case 'v': WRITECHAR('\013'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005862 /* BEL, not classic C */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005863 case 'a': WRITECHAR('\007'); break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005864
Benjamin Peterson29060642009-01-31 22:14:21 +00005865 /* \OOO (octal) escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005866 case '0': case '1': case '2': case '3':
5867 case '4': case '5': case '6': case '7':
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005868 x = s[-1] - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005869 if (s < end && '0' <= *s && *s <= '7') {
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005870 x = (x<<3) + *s++ - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005871 if (s < end && '0' <= *s && *s <= '7')
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005872 x = (x<<3) + *s++ - '0';
Guido van Rossumd57fd912000-03-10 22:53:23 +00005873 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005874 WRITECHAR(x);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005875 break;
5876
Benjamin Peterson29060642009-01-31 22:14:21 +00005877 /* hex escapes */
5878 /* \xXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005879 case 'x':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005880 digits = 2;
5881 message = "truncated \\xXX escape";
5882 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005883
Benjamin Peterson29060642009-01-31 22:14:21 +00005884 /* \uXXXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005885 case 'u':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005886 digits = 4;
5887 message = "truncated \\uXXXX escape";
5888 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005889
Benjamin Peterson29060642009-01-31 22:14:21 +00005890 /* \UXXXXXXXX */
Fredrik Lundhdf846752000-09-03 11:29:49 +00005891 case 'U':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005892 digits = 8;
5893 message = "truncated \\UXXXXXXXX escape";
5894 hexescape:
5895 chr = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005896 if (s+digits>end) {
5897 endinpos = size;
5898 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005899 errors, &errorHandler,
5900 "unicodeescape", "end of string in escape sequence",
5901 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005902 &v, &i))
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005903 goto onError;
5904 goto nextByte;
5905 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005906 for (j = 0; j < digits; ++j) {
5907 c = (unsigned char) s[j];
David Malcolm96960882010-11-05 17:23:41 +00005908 if (!Py_ISXDIGIT(c)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005909 endinpos = (s+j+1)-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005910 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005911 errors, &errorHandler,
5912 "unicodeescape", message,
5913 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005914 &v, &i))
Fredrik Lundhdf846752000-09-03 11:29:49 +00005915 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005916 len = PyUnicode_GET_LENGTH(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005917 goto nextByte;
Fredrik Lundhdf846752000-09-03 11:29:49 +00005918 }
5919 chr = (chr<<4) & ~0xF;
5920 if (c >= '0' && c <= '9')
5921 chr += c - '0';
5922 else if (c >= 'a' && c <= 'f')
5923 chr += 10 + c - 'a';
5924 else
5925 chr += 10 + c - 'A';
5926 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005927 s += j;
Jeremy Hylton504de6b2003-10-06 05:08:26 +00005928 if (chr == 0xffffffff && PyErr_Occurred())
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005929 /* _decoding_error will have already written into the
5930 target buffer. */
5931 break;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005932 store:
Fredrik Lundhdf846752000-09-03 11:29:49 +00005933 /* when we get here, chr is a 32-bit unicode character */
Victor Stinner8faf8212011-12-08 22:14:11 +01005934 if (chr <= MAX_UNICODE) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005935 WRITECHAR(chr);
Fredrik Lundhdf846752000-09-03 11:29:49 +00005936 } else {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005937 endinpos = s-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005938 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005939 errors, &errorHandler,
5940 "unicodeescape", "illegal Unicode character",
5941 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005942 &v, &i))
Fredrik Lundhdf846752000-09-03 11:29:49 +00005943 goto onError;
5944 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00005945 break;
5946
Benjamin Peterson29060642009-01-31 22:14:21 +00005947 /* \N{name} */
Fredrik Lundhccc74732001-02-18 22:13:49 +00005948 case 'N':
5949 message = "malformed \\N character escape";
5950 if (ucnhash_CAPI == NULL) {
5951 /* load the unicode data module */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005952 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
5953 PyUnicodeData_CAPSULE_NAME, 1);
Fredrik Lundhccc74732001-02-18 22:13:49 +00005954 if (ucnhash_CAPI == NULL)
5955 goto ucnhashError;
5956 }
5957 if (*s == '{') {
5958 const char *start = s+1;
5959 /* look for the closing brace */
5960 while (*s != '}' && s < end)
5961 s++;
5962 if (s > start && s < end && *s == '}') {
5963 /* found a name. look it up in the unicode database */
5964 message = "unknown Unicode character name";
5965 s++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005966 if (ucnhash_CAPI->getcode(NULL, start, (int)(s-start-1),
Ezio Melotti931b8aa2011-10-21 21:57:36 +03005967 &chr, 0))
Fredrik Lundhccc74732001-02-18 22:13:49 +00005968 goto store;
5969 }
5970 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005971 endinpos = s-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005972 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005973 errors, &errorHandler,
5974 "unicodeescape", message,
5975 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005976 &v, &i))
Fredrik Lundhccc74732001-02-18 22:13:49 +00005977 goto onError;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005978 break;
5979
5980 default:
Walter Dörwald8c077222002-03-25 11:16:18 +00005981 if (s > end) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005982 message = "\\ at end of string";
5983 s--;
5984 endinpos = s-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005985 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005986 errors, &errorHandler,
5987 "unicodeescape", message,
5988 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005989 &v, &i))
Walter Dörwald8c077222002-03-25 11:16:18 +00005990 goto onError;
5991 }
5992 else {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005993 WRITECHAR('\\');
5994 WRITECHAR(s[-1]);
Walter Dörwald8c077222002-03-25 11:16:18 +00005995 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00005996 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005997 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005998 nextByte:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005999 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006000 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006001#undef WRITECHAR
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006002
Victor Stinner16e6a802011-12-12 13:24:15 +01006003 if (unicode_resize(&v, i) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006004 goto onError;
Walter Dörwaldd4ade082003-08-15 15:00:26 +00006005 Py_XDECREF(errorHandler);
6006 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006007 return unicode_result(v);
Walter Dörwald8c077222002-03-25 11:16:18 +00006008
Benjamin Peterson29060642009-01-31 22:14:21 +00006009 ucnhashError:
Fredrik Lundh06d12682001-01-24 07:59:11 +00006010 PyErr_SetString(
6011 PyExc_UnicodeError,
6012 "\\N escapes not supported (can't load unicodedata module)"
6013 );
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00006014 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006015 Py_XDECREF(errorHandler);
6016 Py_XDECREF(exc);
Fredrik Lundhf6056062001-01-20 11:15:25 +00006017 return NULL;
6018
Benjamin Peterson29060642009-01-31 22:14:21 +00006019 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00006020 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006021 Py_XDECREF(errorHandler);
6022 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006023 return NULL;
6024}
6025
6026/* Return a Unicode-Escape string version of the Unicode object.
6027
6028 If quotes is true, the string is enclosed in u"" or u'' quotes as
6029 appropriate.
6030
6031*/
6032
Alexander Belopolsky40018472011-02-26 01:02:56 +00006033PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006034PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006035{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006036 Py_ssize_t i, len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006037 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006038 char *p;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006039 int kind;
6040 void *data;
6041 Py_ssize_t expandsize = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006042
Thomas Wouters89f507f2006-12-13 04:49:30 +00006043 /* Initial allocation is based on the longest-possible unichr
6044 escape.
6045
6046 In wide (UTF-32) builds '\U00xxxxxx' is 10 chars per source
6047 unichr, so in this case it's the longest unichr escape. In
6048 narrow (UTF-16) builds this is five chars per source unichr
6049 since there are two unichrs in the surrogate pair, so in narrow
6050 (UTF-16) builds it's not the longest unichr escape.
6051
6052 In wide or narrow builds '\uxxxx' is 6 chars per source unichr,
6053 so in the narrow (UTF-16) build case it's the longest unichr
6054 escape.
6055 */
6056
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006057 if (!PyUnicode_Check(unicode)) {
6058 PyErr_BadArgument();
6059 return NULL;
6060 }
6061 if (PyUnicode_READY(unicode) < 0)
6062 return NULL;
6063 len = PyUnicode_GET_LENGTH(unicode);
6064 kind = PyUnicode_KIND(unicode);
6065 data = PyUnicode_DATA(unicode);
6066 switch(kind) {
6067 case PyUnicode_1BYTE_KIND: expandsize = 4; break;
6068 case PyUnicode_2BYTE_KIND: expandsize = 6; break;
6069 case PyUnicode_4BYTE_KIND: expandsize = 10; break;
6070 }
6071
6072 if (len == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006073 return PyBytes_FromStringAndSize(NULL, 0);
6074
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006075 if (len > (PY_SSIZE_T_MAX - 2 - 1) / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00006076 return PyErr_NoMemory();
Neal Norwitz3ce5d922008-08-24 07:08:55 +00006077
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006078 repr = PyBytes_FromStringAndSize(NULL,
Benjamin Peterson29060642009-01-31 22:14:21 +00006079 2
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006080 + expandsize*len
Benjamin Peterson29060642009-01-31 22:14:21 +00006081 + 1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006082 if (repr == NULL)
6083 return NULL;
6084
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006085 p = PyBytes_AS_STRING(repr);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006086
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006087 for (i = 0; i < len; i++) {
Victor Stinner3326cb62011-11-10 20:15:25 +01006088 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006089
Walter Dörwald79e913e2007-05-12 11:08:06 +00006090 /* Escape backslashes */
6091 if (ch == '\\') {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006092 *p++ = '\\';
6093 *p++ = (char) ch;
Walter Dörwald79e913e2007-05-12 11:08:06 +00006094 continue;
Tim Petersced69f82003-09-16 20:30:58 +00006095 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006096
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00006097 /* Map 21-bit characters to '\U00xxxxxx' */
6098 else if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01006099 assert(ch <= MAX_UNICODE);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00006100 *p++ = '\\';
6101 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006102 *p++ = Py_hexdigits[(ch >> 28) & 0x0000000F];
6103 *p++ = Py_hexdigits[(ch >> 24) & 0x0000000F];
6104 *p++ = Py_hexdigits[(ch >> 20) & 0x0000000F];
6105 *p++ = Py_hexdigits[(ch >> 16) & 0x0000000F];
6106 *p++ = Py_hexdigits[(ch >> 12) & 0x0000000F];
6107 *p++ = Py_hexdigits[(ch >> 8) & 0x0000000F];
6108 *p++ = Py_hexdigits[(ch >> 4) & 0x0000000F];
6109 *p++ = Py_hexdigits[ch & 0x0000000F];
Benjamin Peterson29060642009-01-31 22:14:21 +00006110 continue;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00006111 }
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00006112
Guido van Rossumd57fd912000-03-10 22:53:23 +00006113 /* Map 16-bit characters to '\uxxxx' */
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00006114 if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006115 *p++ = '\\';
6116 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006117 *p++ = Py_hexdigits[(ch >> 12) & 0x000F];
6118 *p++ = Py_hexdigits[(ch >> 8) & 0x000F];
6119 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6120 *p++ = Py_hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006121 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006122
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006123 /* Map special whitespace to '\t', \n', '\r' */
6124 else if (ch == '\t') {
6125 *p++ = '\\';
6126 *p++ = 't';
6127 }
6128 else if (ch == '\n') {
6129 *p++ = '\\';
6130 *p++ = 'n';
6131 }
6132 else if (ch == '\r') {
6133 *p++ = '\\';
6134 *p++ = 'r';
6135 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006136
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006137 /* Map non-printable US ASCII to '\xhh' */
Marc-André Lemburg11326de2001-11-28 12:56:20 +00006138 else if (ch < ' ' || ch >= 0x7F) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006139 *p++ = '\\';
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006140 *p++ = 'x';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006141 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6142 *p++ = Py_hexdigits[ch & 0x000F];
Tim Petersced69f82003-09-16 20:30:58 +00006143 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006144
Guido van Rossumd57fd912000-03-10 22:53:23 +00006145 /* Copy everything else as-is */
6146 else
6147 *p++ = (char) ch;
6148 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006149
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006150 assert(p - PyBytes_AS_STRING(repr) > 0);
6151 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0)
6152 return NULL;
6153 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006154}
6155
Alexander Belopolsky40018472011-02-26 01:02:56 +00006156PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006157PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
6158 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006159{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006160 PyObject *result;
6161 PyObject *tmp = PyUnicode_FromUnicode(s, size);
6162 if (tmp == NULL)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006163 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006164 result = PyUnicode_AsUnicodeEscapeString(tmp);
6165 Py_DECREF(tmp);
6166 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006167}
6168
6169/* --- Raw Unicode Escape Codec ------------------------------------------- */
6170
Alexander Belopolsky40018472011-02-26 01:02:56 +00006171PyObject *
6172PyUnicode_DecodeRawUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006173 Py_ssize_t size,
6174 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006175{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006176 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006177 Py_ssize_t startinpos;
6178 Py_ssize_t endinpos;
6179 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01006180 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006181 const char *end;
6182 const char *bs;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006183 PyObject *errorHandler = NULL;
6184 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006185
Guido van Rossumd57fd912000-03-10 22:53:23 +00006186 /* Escaped strings will always be longer than the resulting
6187 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006188 length after conversion to the true value. (But decoding error
6189 handler might have to resize the string) */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006190 v = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006191 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006192 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006193 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01006194 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006195 outpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006196 end = s + size;
6197 while (s < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006198 unsigned char c;
6199 Py_UCS4 x;
6200 int i;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006201 int count;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006202
Benjamin Peterson29060642009-01-31 22:14:21 +00006203 /* Non-escape characters are interpreted as Unicode ordinals */
6204 if (*s != '\\') {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006205 if (unicode_putchar(&v, &outpos, (unsigned char)*s++) < 0)
6206 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00006207 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006208 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006209 startinpos = s-starts;
6210
6211 /* \u-escapes are only interpreted iff the number of leading
6212 backslashes if odd */
6213 bs = s;
6214 for (;s < end;) {
6215 if (*s != '\\')
6216 break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006217 if (unicode_putchar(&v, &outpos, (unsigned char)*s++) < 0)
6218 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00006219 }
6220 if (((s - bs) & 1) == 0 ||
6221 s >= end ||
6222 (*s != 'u' && *s != 'U')) {
6223 continue;
6224 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006225 outpos--;
Benjamin Peterson29060642009-01-31 22:14:21 +00006226 count = *s=='u' ? 4 : 8;
6227 s++;
6228
6229 /* \uXXXX with 4 hex digits, \Uxxxxxxxx with 8 */
Benjamin Peterson29060642009-01-31 22:14:21 +00006230 for (x = 0, i = 0; i < count; ++i, ++s) {
6231 c = (unsigned char)*s;
David Malcolm96960882010-11-05 17:23:41 +00006232 if (!Py_ISXDIGIT(c)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006233 endinpos = s-starts;
6234 if (unicode_decode_call_errorhandler(
6235 errors, &errorHandler,
6236 "rawunicodeescape", "truncated \\uXXXX",
6237 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006238 &v, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00006239 goto onError;
6240 goto nextByte;
6241 }
6242 x = (x<<4) & ~0xF;
6243 if (c >= '0' && c <= '9')
6244 x += c - '0';
6245 else if (c >= 'a' && c <= 'f')
6246 x += 10 + c - 'a';
6247 else
6248 x += 10 + c - 'A';
6249 }
Victor Stinner8faf8212011-12-08 22:14:11 +01006250 if (x <= MAX_UNICODE) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006251 if (unicode_putchar(&v, &outpos, x) < 0)
6252 goto onError;
Christian Heimesfe337bf2008-03-23 21:54:12 +00006253 } else {
6254 endinpos = s-starts;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006255 if (unicode_decode_call_errorhandler(
6256 errors, &errorHandler,
6257 "rawunicodeescape", "\\Uxxxxxxxx out of range",
Benjamin Peterson29060642009-01-31 22:14:21 +00006258 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006259 &v, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00006260 goto onError;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006261 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006262 nextByte:
6263 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006264 }
Victor Stinner16e6a802011-12-12 13:24:15 +01006265 if (unicode_resize(&v, outpos) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006266 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006267 Py_XDECREF(errorHandler);
6268 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006269 return unicode_result(v);
Tim Petersced69f82003-09-16 20:30:58 +00006270
Benjamin Peterson29060642009-01-31 22:14:21 +00006271 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00006272 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006273 Py_XDECREF(errorHandler);
6274 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006275 return NULL;
6276}
6277
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006278
Alexander Belopolsky40018472011-02-26 01:02:56 +00006279PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006280PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006281{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006282 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006283 char *p;
6284 char *q;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006285 Py_ssize_t expandsize, pos;
6286 int kind;
6287 void *data;
6288 Py_ssize_t len;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006289
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006290 if (!PyUnicode_Check(unicode)) {
6291 PyErr_BadArgument();
6292 return NULL;
6293 }
6294 if (PyUnicode_READY(unicode) < 0)
6295 return NULL;
6296 kind = PyUnicode_KIND(unicode);
6297 data = PyUnicode_DATA(unicode);
6298 len = PyUnicode_GET_LENGTH(unicode);
Benjamin Peterson1518e872011-11-23 10:44:52 -06006299 /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6
6300 bytes, and 1 byte characters 4. */
6301 expandsize = kind * 2 + 2;
Victor Stinner0e368262011-11-10 20:12:49 +01006302
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006303 if (len > PY_SSIZE_T_MAX / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00006304 return PyErr_NoMemory();
Benjamin Peterson14339b62009-01-31 16:36:08 +00006305
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006306 repr = PyBytes_FromStringAndSize(NULL, expandsize * len);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006307 if (repr == NULL)
6308 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006309 if (len == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006310 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006311
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006312 p = q = PyBytes_AS_STRING(repr);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006313 for (pos = 0; pos < len; pos++) {
6314 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Benjamin Peterson29060642009-01-31 22:14:21 +00006315 /* Map 32-bit characters to '\Uxxxxxxxx' */
6316 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01006317 assert(ch <= MAX_UNICODE);
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006318 *p++ = '\\';
6319 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006320 *p++ = Py_hexdigits[(ch >> 28) & 0xf];
6321 *p++ = Py_hexdigits[(ch >> 24) & 0xf];
6322 *p++ = Py_hexdigits[(ch >> 20) & 0xf];
6323 *p++ = Py_hexdigits[(ch >> 16) & 0xf];
6324 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6325 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6326 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6327 *p++ = Py_hexdigits[ch & 15];
Tim Petersced69f82003-09-16 20:30:58 +00006328 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006329 /* Map 16-bit characters to '\uxxxx' */
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006330 else if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006331 *p++ = '\\';
6332 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006333 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6334 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6335 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6336 *p++ = Py_hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006337 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006338 /* Copy everything else as-is */
6339 else
Guido van Rossumd57fd912000-03-10 22:53:23 +00006340 *p++ = (char) ch;
6341 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00006342
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006343 assert(p > q);
6344 if (_PyBytes_Resize(&repr, p - q) < 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006345 return NULL;
6346 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006347}
6348
Alexander Belopolsky40018472011-02-26 01:02:56 +00006349PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006350PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
6351 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006352{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006353 PyObject *result;
6354 PyObject *tmp = PyUnicode_FromUnicode(s, size);
6355 if (tmp == NULL)
Walter Dörwald711005d2007-05-12 12:03:26 +00006356 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006357 result = PyUnicode_AsRawUnicodeEscapeString(tmp);
6358 Py_DECREF(tmp);
6359 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006360}
6361
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006362/* --- Unicode Internal Codec ------------------------------------------- */
6363
Alexander Belopolsky40018472011-02-26 01:02:56 +00006364PyObject *
6365_PyUnicode_DecodeUnicodeInternal(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006366 Py_ssize_t size,
6367 const char *errors)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006368{
6369 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006370 Py_ssize_t startinpos;
6371 Py_ssize_t endinpos;
6372 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01006373 PyObject *v;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006374 const char *end;
6375 const char *reason;
6376 PyObject *errorHandler = NULL;
6377 PyObject *exc = NULL;
6378
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006379 if (PyErr_WarnEx(PyExc_DeprecationWarning,
Ezio Melotti11060a42011-11-16 09:39:10 +02006380 "unicode_internal codec has been deprecated",
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006381 1))
6382 return NULL;
6383
Thomas Wouters89f507f2006-12-13 04:49:30 +00006384 /* XXX overflow detection missing */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006385 v = PyUnicode_New((size+Py_UNICODE_SIZE-1)/ Py_UNICODE_SIZE, 127);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006386 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006387 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006388 if (PyUnicode_GET_LENGTH(v) == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01006389 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006390 outpos = 0;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006391 end = s + size;
6392
6393 while (s < end) {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006394 Py_UNICODE uch;
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006395 Py_UCS4 ch;
6396 /* We copy the raw representation one byte at a time because the
6397 pointer may be unaligned (see test_codeccallbacks). */
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006398 ((char *) &uch)[0] = s[0];
6399 ((char *) &uch)[1] = s[1];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006400#ifdef Py_UNICODE_WIDE
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006401 ((char *) &uch)[2] = s[2];
6402 ((char *) &uch)[3] = s[3];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006403#endif
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006404 ch = uch;
6405
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006406 /* We have to sanity check the raw data, otherwise doom looms for
6407 some malformed UCS-4 data. */
6408 if (
Benjamin Peterson29060642009-01-31 22:14:21 +00006409#ifdef Py_UNICODE_WIDE
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006410 ch > 0x10ffff ||
Benjamin Peterson29060642009-01-31 22:14:21 +00006411#endif
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006412 end-s < Py_UNICODE_SIZE
6413 )
Benjamin Peterson29060642009-01-31 22:14:21 +00006414 {
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006415 startinpos = s - starts;
6416 if (end-s < Py_UNICODE_SIZE) {
6417 endinpos = end-starts;
6418 reason = "truncated input";
6419 }
6420 else {
6421 endinpos = s - starts + Py_UNICODE_SIZE;
6422 reason = "illegal code point (> 0x10FFFF)";
6423 }
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006424 if (unicode_decode_call_errorhandler(
6425 errors, &errorHandler,
6426 "unicode_internal", reason,
Walter Dörwalde78178e2007-07-30 13:31:40 +00006427 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006428 &v, &outpos))
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006429 goto onError;
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006430 continue;
6431 }
6432
6433 s += Py_UNICODE_SIZE;
6434#ifndef Py_UNICODE_WIDE
Victor Stinner551ac952011-11-29 22:58:13 +01006435 if (Py_UNICODE_IS_HIGH_SURROGATE(ch) && s < end)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006436 {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006437 Py_UNICODE uch2;
6438 ((char *) &uch2)[0] = s[0];
6439 ((char *) &uch2)[1] = s[1];
Victor Stinner551ac952011-11-29 22:58:13 +01006440 if (Py_UNICODE_IS_LOW_SURROGATE(uch2))
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006441 {
Victor Stinner551ac952011-11-29 22:58:13 +01006442 ch = Py_UNICODE_JOIN_SURROGATES(uch, uch2);
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006443 s += Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006444 }
6445 }
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006446#endif
6447
6448 if (unicode_putchar(&v, &outpos, ch) < 0)
6449 goto onError;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006450 }
6451
Victor Stinner16e6a802011-12-12 13:24:15 +01006452 if (unicode_resize(&v, outpos) < 0)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006453 goto onError;
6454 Py_XDECREF(errorHandler);
6455 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006456 return unicode_result(v);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006457
Benjamin Peterson29060642009-01-31 22:14:21 +00006458 onError:
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006459 Py_XDECREF(v);
6460 Py_XDECREF(errorHandler);
6461 Py_XDECREF(exc);
6462 return NULL;
6463}
6464
Guido van Rossumd57fd912000-03-10 22:53:23 +00006465/* --- Latin-1 Codec ------------------------------------------------------ */
6466
Alexander Belopolsky40018472011-02-26 01:02:56 +00006467PyObject *
6468PyUnicode_DecodeLatin1(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006469 Py_ssize_t size,
6470 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006471{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006472 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Victor Stinnere57b1c02011-09-28 22:20:48 +02006473 return _PyUnicode_FromUCS1((unsigned char*)s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006474}
6475
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006476/* create or adjust a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006477static void
6478make_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006479 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006480 PyObject *unicode,
6481 Py_ssize_t startpos, Py_ssize_t endpos,
6482 const char *reason)
6483{
6484 if (*exceptionObject == NULL) {
6485 *exceptionObject = PyObject_CallFunction(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006486 PyExc_UnicodeEncodeError, "sOnns",
Martin v. Löwis9e816682011-11-02 12:45:42 +01006487 encoding, unicode, startpos, endpos, reason);
6488 }
6489 else {
6490 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
6491 goto onError;
6492 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
6493 goto onError;
6494 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
6495 goto onError;
6496 return;
6497 onError:
6498 Py_DECREF(*exceptionObject);
6499 *exceptionObject = NULL;
6500 }
6501}
6502
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006503/* raises a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006504static void
6505raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006506 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006507 PyObject *unicode,
6508 Py_ssize_t startpos, Py_ssize_t endpos,
6509 const char *reason)
6510{
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006511 make_encode_exception(exceptionObject,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006512 encoding, unicode, startpos, endpos, reason);
6513 if (*exceptionObject != NULL)
6514 PyCodec_StrictErrors(*exceptionObject);
6515}
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006516
6517/* error handling callback helper:
6518 build arguments, call the callback and check the arguments,
6519 put the result into newpos and return the replacement string, which
6520 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006521static PyObject *
6522unicode_encode_call_errorhandler(const char *errors,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006523 PyObject **errorHandler,
6524 const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006525 PyObject *unicode, PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006526 Py_ssize_t startpos, Py_ssize_t endpos,
6527 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006528{
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006529 static char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006530 Py_ssize_t len;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006531 PyObject *restuple;
6532 PyObject *resunicode;
6533
6534 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006535 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006536 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006537 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006538 }
6539
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006540 if (PyUnicode_READY(unicode) < 0)
6541 return NULL;
6542 len = PyUnicode_GET_LENGTH(unicode);
6543
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006544 make_encode_exception(exceptionObject,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006545 encoding, unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006546 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006547 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006548
6549 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00006550 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006551 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006552 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006553 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006554 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00006555 Py_DECREF(restuple);
6556 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006557 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006558 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00006559 &resunicode, newpos)) {
6560 Py_DECREF(restuple);
6561 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006562 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006563 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
6564 PyErr_SetString(PyExc_TypeError, &argparse[3]);
6565 Py_DECREF(restuple);
6566 return NULL;
6567 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006568 if (*newpos<0)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006569 *newpos = len + *newpos;
6570 if (*newpos<0 || *newpos>len) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006571 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
6572 Py_DECREF(restuple);
6573 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00006574 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006575 Py_INCREF(resunicode);
6576 Py_DECREF(restuple);
6577 return resunicode;
6578}
6579
Alexander Belopolsky40018472011-02-26 01:02:56 +00006580static PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006581unicode_encode_ucs1(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006582 const char *errors,
Victor Stinnerfcd96532011-11-04 00:28:50 +01006583 unsigned int limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006584{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006585 /* input state */
6586 Py_ssize_t pos=0, size;
6587 int kind;
6588 void *data;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006589 /* output object */
6590 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006591 /* pointer into the output */
6592 char *str;
6593 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00006594 Py_ssize_t ressize;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006595 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
6596 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006597 PyObject *errorHandler = NULL;
6598 PyObject *exc = NULL;
6599 /* the following variable is used for caching string comparisons
6600 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
6601 int known_errorHandler = -1;
6602
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006603 if (PyUnicode_READY(unicode) < 0)
6604 return NULL;
6605 size = PyUnicode_GET_LENGTH(unicode);
6606 kind = PyUnicode_KIND(unicode);
6607 data = PyUnicode_DATA(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006608 /* allocate enough for a simple encoding without
6609 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00006610 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00006611 return PyBytes_FromStringAndSize(NULL, 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006612 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006613 if (res == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00006614 return NULL;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006615 str = PyBytes_AS_STRING(res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006616 ressize = size;
6617
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006618 while (pos < size) {
6619 Py_UCS4 c = PyUnicode_READ(kind, data, pos);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006620
Benjamin Peterson29060642009-01-31 22:14:21 +00006621 /* can we encode this? */
6622 if (c<limit) {
6623 /* no overflow check, because we know that the space is enough */
6624 *str++ = (char)c;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006625 ++pos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006626 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006627 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006628 Py_ssize_t requiredsize;
6629 PyObject *repunicode;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006630 Py_ssize_t repsize, newpos, respos, i;
Benjamin Peterson29060642009-01-31 22:14:21 +00006631 /* startpos for collecting unencodable chars */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006632 Py_ssize_t collstart = pos;
6633 Py_ssize_t collend = pos;
Benjamin Peterson29060642009-01-31 22:14:21 +00006634 /* find all unecodable characters */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006635 while ((collend < size) && (PyUnicode_READ(kind, data, collend)>=limit))
Benjamin Peterson29060642009-01-31 22:14:21 +00006636 ++collend;
6637 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
6638 if (known_errorHandler==-1) {
6639 if ((errors==NULL) || (!strcmp(errors, "strict")))
6640 known_errorHandler = 1;
6641 else if (!strcmp(errors, "replace"))
6642 known_errorHandler = 2;
6643 else if (!strcmp(errors, "ignore"))
6644 known_errorHandler = 3;
6645 else if (!strcmp(errors, "xmlcharrefreplace"))
6646 known_errorHandler = 4;
6647 else
6648 known_errorHandler = 0;
6649 }
6650 switch (known_errorHandler) {
6651 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006652 raise_encode_exception(&exc, encoding, unicode, collstart, collend, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006653 goto onError;
6654 case 2: /* replace */
6655 while (collstart++<collend)
6656 *str++ = '?'; /* fall through */
6657 case 3: /* ignore */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006658 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006659 break;
6660 case 4: /* xmlcharrefreplace */
6661 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006662 /* determine replacement size */
6663 for (i = collstart, repsize = 0; i < collend; ++i) {
6664 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
6665 if (ch < 10)
Benjamin Peterson29060642009-01-31 22:14:21 +00006666 repsize += 2+1+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006667 else if (ch < 100)
Benjamin Peterson29060642009-01-31 22:14:21 +00006668 repsize += 2+2+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006669 else if (ch < 1000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006670 repsize += 2+3+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006671 else if (ch < 10000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006672 repsize += 2+4+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006673 else if (ch < 100000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006674 repsize += 2+5+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006675 else if (ch < 1000000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006676 repsize += 2+6+1;
Victor Stinner0d3721d2011-11-22 03:27:53 +01006677 else {
Victor Stinner8faf8212011-12-08 22:14:11 +01006678 assert(ch <= MAX_UNICODE);
Benjamin Peterson29060642009-01-31 22:14:21 +00006679 repsize += 2+7+1;
Victor Stinner0d3721d2011-11-22 03:27:53 +01006680 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006681 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006682 requiredsize = respos+repsize+(size-collend);
Benjamin Peterson29060642009-01-31 22:14:21 +00006683 if (requiredsize > ressize) {
6684 if (requiredsize<2*ressize)
6685 requiredsize = 2*ressize;
6686 if (_PyBytes_Resize(&res, requiredsize))
6687 goto onError;
6688 str = PyBytes_AS_STRING(res) + respos;
6689 ressize = requiredsize;
6690 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006691 /* generate replacement */
6692 for (i = collstart; i < collend; ++i) {
6693 str += sprintf(str, "&#%d;", PyUnicode_READ(kind, data, i));
Benjamin Peterson29060642009-01-31 22:14:21 +00006694 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006695 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006696 break;
6697 default:
6698 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006699 encoding, reason, unicode, &exc,
6700 collstart, collend, &newpos);
6701 if (repunicode == NULL || (PyUnicode_Check(repunicode) &&
6702 PyUnicode_READY(repunicode) < 0))
Benjamin Peterson29060642009-01-31 22:14:21 +00006703 goto onError;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006704 if (PyBytes_Check(repunicode)) {
6705 /* Directly copy bytes result to output. */
6706 repsize = PyBytes_Size(repunicode);
6707 if (repsize > 1) {
6708 /* Make room for all additional bytes. */
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006709 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006710 if (_PyBytes_Resize(&res, ressize+repsize-1)) {
6711 Py_DECREF(repunicode);
6712 goto onError;
6713 }
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006714 str = PyBytes_AS_STRING(res) + respos;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006715 ressize += repsize-1;
6716 }
6717 memcpy(str, PyBytes_AsString(repunicode), repsize);
6718 str += repsize;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006719 pos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006720 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006721 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006722 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006723 /* need more space? (at least enough for what we
6724 have+the replacement+the rest of the string, so
6725 we won't have to check space for encodable characters) */
6726 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006727 repsize = PyUnicode_GET_LENGTH(repunicode);
6728 requiredsize = respos+repsize+(size-collend);
Benjamin Peterson29060642009-01-31 22:14:21 +00006729 if (requiredsize > ressize) {
6730 if (requiredsize<2*ressize)
6731 requiredsize = 2*ressize;
6732 if (_PyBytes_Resize(&res, requiredsize)) {
6733 Py_DECREF(repunicode);
6734 goto onError;
6735 }
6736 str = PyBytes_AS_STRING(res) + respos;
6737 ressize = requiredsize;
6738 }
6739 /* check if there is anything unencodable in the replacement
6740 and copy it to the output */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006741 for (i = 0; repsize-->0; ++i, ++str) {
6742 c = PyUnicode_READ_CHAR(repunicode, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00006743 if (c >= limit) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006744 raise_encode_exception(&exc, encoding, unicode,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006745 pos, pos+1, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006746 Py_DECREF(repunicode);
6747 goto onError;
6748 }
6749 *str = (char)c;
6750 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006751 pos = newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006752 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006753 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00006754 }
6755 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006756 /* Resize if we allocated to much */
6757 size = str - PyBytes_AS_STRING(res);
6758 if (size < ressize) { /* If this falls res will be NULL */
Alexandre Vassalottibad1b922008-12-27 09:49:09 +00006759 assert(size >= 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006760 if (_PyBytes_Resize(&res, size) < 0)
6761 goto onError;
6762 }
6763
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006764 Py_XDECREF(errorHandler);
6765 Py_XDECREF(exc);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006766 return res;
6767
6768 onError:
6769 Py_XDECREF(res);
6770 Py_XDECREF(errorHandler);
6771 Py_XDECREF(exc);
6772 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006773}
6774
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006775/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006776PyObject *
6777PyUnicode_EncodeLatin1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006778 Py_ssize_t size,
6779 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006780{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006781 PyObject *result;
6782 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6783 if (unicode == NULL)
6784 return NULL;
6785 result = unicode_encode_ucs1(unicode, errors, 256);
6786 Py_DECREF(unicode);
6787 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006788}
6789
Alexander Belopolsky40018472011-02-26 01:02:56 +00006790PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006791_PyUnicode_AsLatin1String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006792{
6793 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006794 PyErr_BadArgument();
6795 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006796 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006797 if (PyUnicode_READY(unicode) == -1)
6798 return NULL;
6799 /* Fast path: if it is a one-byte string, construct
6800 bytes object directly. */
6801 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND)
6802 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6803 PyUnicode_GET_LENGTH(unicode));
6804 /* Non-Latin-1 characters present. Defer to above function to
6805 raise the exception. */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006806 return unicode_encode_ucs1(unicode, errors, 256);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006807}
6808
6809PyObject*
6810PyUnicode_AsLatin1String(PyObject *unicode)
6811{
6812 return _PyUnicode_AsLatin1String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006813}
6814
6815/* --- 7-bit ASCII Codec -------------------------------------------------- */
6816
Alexander Belopolsky40018472011-02-26 01:02:56 +00006817PyObject *
6818PyUnicode_DecodeASCII(const char *s,
6819 Py_ssize_t size,
6820 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006821{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006822 const char *starts = s;
Victor Stinner7931d9a2011-11-04 00:22:48 +01006823 PyObject *v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006824 int kind;
6825 void *data;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006826 Py_ssize_t startinpos;
6827 Py_ssize_t endinpos;
6828 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006829 const char *e;
Victor Stinner702c7342011-10-05 13:50:52 +02006830 int has_error;
6831 const unsigned char *p = (const unsigned char *)s;
6832 const unsigned char *end = p + size;
6833 const unsigned char *aligned_end = (const unsigned char *) ((size_t) end & ~LONG_PTR_MASK);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006834 PyObject *errorHandler = NULL;
6835 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006836
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006837 if (size == 0) {
6838 Py_INCREF(unicode_empty);
6839 return unicode_empty;
6840 }
6841
Guido van Rossumd57fd912000-03-10 22:53:23 +00006842 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Victor Stinner702c7342011-10-05 13:50:52 +02006843 if (size == 1 && (unsigned char)s[0] < 128)
6844 return get_latin1_char((unsigned char)s[0]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006845
Victor Stinner702c7342011-10-05 13:50:52 +02006846 has_error = 0;
6847 while (p < end && !has_error) {
6848 /* Fast path, see below in PyUnicode_DecodeUTF8Stateful for
6849 an explanation. */
6850 if (!((size_t) p & LONG_PTR_MASK)) {
6851 /* Help register allocation */
6852 register const unsigned char *_p = p;
6853 while (_p < aligned_end) {
6854 unsigned long value = *(unsigned long *) _p;
6855 if (value & ASCII_CHAR_MASK) {
6856 has_error = 1;
6857 break;
6858 }
6859 _p += SIZEOF_LONG;
6860 }
6861 if (_p == end)
6862 break;
6863 if (has_error)
6864 break;
6865 p = _p;
6866 }
6867 if (*p & 0x80) {
6868 has_error = 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006869 break;
Victor Stinner702c7342011-10-05 13:50:52 +02006870 }
6871 else {
6872 ++p;
6873 }
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00006874 }
Victor Stinner702c7342011-10-05 13:50:52 +02006875 if (!has_error)
6876 return unicode_fromascii((const unsigned char *)s, size);
Tim Petersced69f82003-09-16 20:30:58 +00006877
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006878 v = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006879 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006880 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006881 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01006882 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006883 kind = PyUnicode_KIND(v);
6884 data = PyUnicode_DATA(v);
6885 outpos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006886 e = s + size;
6887 while (s < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006888 register unsigned char c = (unsigned char)*s;
6889 if (c < 128) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006890 PyUnicode_WRITE(kind, data, outpos++, c);
Benjamin Peterson29060642009-01-31 22:14:21 +00006891 ++s;
6892 }
6893 else {
6894 startinpos = s-starts;
6895 endinpos = startinpos + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00006896 if (unicode_decode_call_errorhandler(
6897 errors, &errorHandler,
6898 "ascii", "ordinal not in range(128)",
6899 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006900 &v, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00006901 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006902 kind = PyUnicode_KIND(v);
6903 data = PyUnicode_DATA(v);
Benjamin Peterson29060642009-01-31 22:14:21 +00006904 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006905 }
Victor Stinner16e6a802011-12-12 13:24:15 +01006906 if (unicode_resize(&v, outpos) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006907 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006908 Py_XDECREF(errorHandler);
6909 Py_XDECREF(exc);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02006910 assert(_PyUnicode_CheckConsistency(v, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01006911 return v;
Tim Petersced69f82003-09-16 20:30:58 +00006912
Benjamin Peterson29060642009-01-31 22:14:21 +00006913 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00006914 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006915 Py_XDECREF(errorHandler);
6916 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006917 return NULL;
6918}
6919
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006920/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006921PyObject *
6922PyUnicode_EncodeASCII(const Py_UNICODE *p,
6923 Py_ssize_t size,
6924 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006925{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006926 PyObject *result;
6927 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6928 if (unicode == NULL)
6929 return NULL;
6930 result = unicode_encode_ucs1(unicode, errors, 128);
6931 Py_DECREF(unicode);
6932 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006933}
6934
Alexander Belopolsky40018472011-02-26 01:02:56 +00006935PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006936_PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006937{
6938 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006939 PyErr_BadArgument();
6940 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006941 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006942 if (PyUnicode_READY(unicode) == -1)
6943 return NULL;
6944 /* Fast path: if it is an ASCII-only string, construct bytes object
6945 directly. Else defer to above function to raise the exception. */
6946 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
6947 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6948 PyUnicode_GET_LENGTH(unicode));
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006949 return unicode_encode_ucs1(unicode, errors, 128);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006950}
6951
6952PyObject *
6953PyUnicode_AsASCIIString(PyObject *unicode)
6954{
6955 return _PyUnicode_AsASCIIString(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006956}
6957
Victor Stinner99b95382011-07-04 14:23:54 +02006958#ifdef HAVE_MBCS
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006959
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006960/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006961
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00006962#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006963#define NEED_RETRY
6964#endif
6965
Victor Stinner3a50e702011-10-18 21:21:00 +02006966#ifndef WC_ERR_INVALID_CHARS
6967# define WC_ERR_INVALID_CHARS 0x0080
6968#endif
6969
6970static char*
6971code_page_name(UINT code_page, PyObject **obj)
6972{
6973 *obj = NULL;
6974 if (code_page == CP_ACP)
6975 return "mbcs";
6976 if (code_page == CP_UTF7)
6977 return "CP_UTF7";
6978 if (code_page == CP_UTF8)
6979 return "CP_UTF8";
6980
6981 *obj = PyBytes_FromFormat("cp%u", code_page);
6982 if (*obj == NULL)
6983 return NULL;
6984 return PyBytes_AS_STRING(*obj);
6985}
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006986
Alexander Belopolsky40018472011-02-26 01:02:56 +00006987static int
Victor Stinner3a50e702011-10-18 21:21:00 +02006988is_dbcs_lead_byte(UINT code_page, const char *s, int offset)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006989{
6990 const char *curr = s + offset;
Victor Stinner3a50e702011-10-18 21:21:00 +02006991 const char *prev;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006992
Victor Stinner3a50e702011-10-18 21:21:00 +02006993 if (!IsDBCSLeadByteEx(code_page, *curr))
6994 return 0;
6995
6996 prev = CharPrevExA(code_page, s, curr, 0);
6997 if (prev == curr)
6998 return 1;
6999 /* FIXME: This code is limited to "true" double-byte encodings,
7000 as it assumes an incomplete character consists of a single
7001 byte. */
7002 if (curr - prev == 2)
7003 return 1;
7004 if (!IsDBCSLeadByteEx(code_page, *prev))
7005 return 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007006 return 0;
7007}
7008
Victor Stinner3a50e702011-10-18 21:21:00 +02007009static DWORD
7010decode_code_page_flags(UINT code_page)
7011{
7012 if (code_page == CP_UTF7) {
7013 /* The CP_UTF7 decoder only supports flags=0 */
7014 return 0;
7015 }
7016 else
7017 return MB_ERR_INVALID_CHARS;
7018}
7019
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007020/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007021 * Decode a byte string from a Windows code page into unicode object in strict
7022 * mode.
7023 *
7024 * Returns consumed size if succeed, returns -2 on decode error, or raise a
7025 * WindowsError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007026 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007027static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007028decode_code_page_strict(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007029 PyObject **v,
Victor Stinner3a50e702011-10-18 21:21:00 +02007030 const char *in,
7031 int insize)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007032{
Victor Stinner3a50e702011-10-18 21:21:00 +02007033 const DWORD flags = decode_code_page_flags(code_page);
Victor Stinner24729f32011-11-10 20:31:37 +01007034 wchar_t *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007035 DWORD outsize;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007036
7037 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007038 assert(insize > 0);
7039 outsize = MultiByteToWideChar(code_page, flags, in, insize, NULL, 0);
7040 if (outsize <= 0)
7041 goto error;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007042
7043 if (*v == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007044 /* Create unicode object */
Victor Stinnerab595942011-12-17 04:59:06 +01007045 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01007046 *v = (PyObject*)_PyUnicode_New(outsize);
Benjamin Peterson29060642009-01-31 22:14:21 +00007047 if (*v == NULL)
7048 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007049 out = PyUnicode_AS_UNICODE(*v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007050 }
7051 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007052 /* Extend unicode object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007053 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
Victor Stinner16e6a802011-12-12 13:24:15 +01007054 if (unicode_resize(v, n + outsize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007055 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007056 out = PyUnicode_AS_UNICODE(*v) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007057 }
7058
7059 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007060 outsize = MultiByteToWideChar(code_page, flags, in, insize, out, outsize);
7061 if (outsize <= 0)
7062 goto error;
7063 return insize;
Victor Stinner554f3f02010-06-16 23:33:54 +00007064
Victor Stinner3a50e702011-10-18 21:21:00 +02007065error:
7066 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7067 return -2;
7068 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007069 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007070}
7071
Victor Stinner3a50e702011-10-18 21:21:00 +02007072/*
7073 * Decode a byte string from a code page into unicode object with an error
7074 * handler.
7075 *
7076 * Returns consumed size if succeed, or raise a WindowsError or
7077 * UnicodeDecodeError exception and returns -1 on error.
7078 */
7079static int
7080decode_code_page_errors(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007081 PyObject **v,
7082 const char *in, const int size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007083 const char *errors)
7084{
7085 const char *startin = in;
7086 const char *endin = in + size;
7087 const DWORD flags = decode_code_page_flags(code_page);
7088 /* Ideally, we should get reason from FormatMessage. This is the Windows
7089 2000 English version of the message. */
7090 const char *reason = "No mapping for the Unicode character exists "
7091 "in the target code page.";
7092 /* each step cannot decode more than 1 character, but a character can be
7093 represented as a surrogate pair */
7094 wchar_t buffer[2], *startout, *out;
7095 int insize, outsize;
7096 PyObject *errorHandler = NULL;
7097 PyObject *exc = NULL;
7098 PyObject *encoding_obj = NULL;
7099 char *encoding;
7100 DWORD err;
7101 int ret = -1;
7102
7103 assert(size > 0);
7104
7105 encoding = code_page_name(code_page, &encoding_obj);
7106 if (encoding == NULL)
7107 return -1;
7108
7109 if (errors == NULL || strcmp(errors, "strict") == 0) {
7110 /* The last error was ERROR_NO_UNICODE_TRANSLATION, then we raise a
7111 UnicodeDecodeError. */
7112 make_decode_exception(&exc, encoding, in, size, 0, 0, reason);
7113 if (exc != NULL) {
7114 PyCodec_StrictErrors(exc);
7115 Py_CLEAR(exc);
7116 }
7117 goto error;
7118 }
7119
7120 if (*v == NULL) {
7121 /* Create unicode object */
7122 if (size > PY_SSIZE_T_MAX / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
7123 PyErr_NoMemory();
7124 goto error;
7125 }
Victor Stinnerab595942011-12-17 04:59:06 +01007126 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01007127 *v = (PyObject*)_PyUnicode_New(size * Py_ARRAY_LENGTH(buffer));
Victor Stinner3a50e702011-10-18 21:21:00 +02007128 if (*v == NULL)
7129 goto error;
7130 startout = PyUnicode_AS_UNICODE(*v);
7131 }
7132 else {
7133 /* Extend unicode object */
7134 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
7135 if (size > (PY_SSIZE_T_MAX - n) / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
7136 PyErr_NoMemory();
7137 goto error;
7138 }
Victor Stinner16e6a802011-12-12 13:24:15 +01007139 if (unicode_resize(v, n + size * Py_ARRAY_LENGTH(buffer)) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007140 goto error;
7141 startout = PyUnicode_AS_UNICODE(*v) + n;
7142 }
7143
7144 /* Decode the byte string character per character */
7145 out = startout;
7146 while (in < endin)
7147 {
7148 /* Decode a character */
7149 insize = 1;
7150 do
7151 {
7152 outsize = MultiByteToWideChar(code_page, flags,
7153 in, insize,
7154 buffer, Py_ARRAY_LENGTH(buffer));
7155 if (outsize > 0)
7156 break;
7157 err = GetLastError();
7158 if (err != ERROR_NO_UNICODE_TRANSLATION
7159 && err != ERROR_INSUFFICIENT_BUFFER)
7160 {
7161 PyErr_SetFromWindowsErr(0);
7162 goto error;
7163 }
7164 insize++;
7165 }
7166 /* 4=maximum length of a UTF-8 sequence */
7167 while (insize <= 4 && (in + insize) <= endin);
7168
7169 if (outsize <= 0) {
7170 Py_ssize_t startinpos, endinpos, outpos;
7171
7172 startinpos = in - startin;
7173 endinpos = startinpos + 1;
7174 outpos = out - PyUnicode_AS_UNICODE(*v);
7175 if (unicode_decode_call_errorhandler(
7176 errors, &errorHandler,
7177 encoding, reason,
7178 &startin, &endin, &startinpos, &endinpos, &exc, &in,
Victor Stinner596a6c42011-11-09 00:02:18 +01007179 v, &outpos))
Victor Stinner3a50e702011-10-18 21:21:00 +02007180 {
7181 goto error;
7182 }
Victor Stinner596a6c42011-11-09 00:02:18 +01007183 out = PyUnicode_AS_UNICODE(*v) + outpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007184 }
7185 else {
7186 in += insize;
7187 memcpy(out, buffer, outsize * sizeof(wchar_t));
7188 out += outsize;
7189 }
7190 }
7191
7192 /* write a NUL character at the end */
7193 *out = 0;
7194
7195 /* Extend unicode object */
7196 outsize = out - startout;
7197 assert(outsize <= PyUnicode_WSTR_LENGTH(*v));
Victor Stinner16e6a802011-12-12 13:24:15 +01007198 if (unicode_resize(v, outsize) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007199 goto error;
Victor Stinner76a31a62011-11-04 00:05:13 +01007200 ret = size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007201
7202error:
7203 Py_XDECREF(encoding_obj);
7204 Py_XDECREF(errorHandler);
7205 Py_XDECREF(exc);
7206 return ret;
7207}
7208
Victor Stinner3a50e702011-10-18 21:21:00 +02007209static PyObject *
7210decode_code_page_stateful(int code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007211 const char *s, Py_ssize_t size,
7212 const char *errors, Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007213{
Victor Stinner76a31a62011-11-04 00:05:13 +01007214 PyObject *v = NULL;
7215 int chunk_size, final, converted, done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007216
Victor Stinner3a50e702011-10-18 21:21:00 +02007217 if (code_page < 0) {
7218 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7219 return NULL;
7220 }
7221
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007222 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00007223 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007224
Victor Stinner76a31a62011-11-04 00:05:13 +01007225 do
7226 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007227#ifdef NEED_RETRY
Victor Stinner76a31a62011-11-04 00:05:13 +01007228 if (size > INT_MAX) {
7229 chunk_size = INT_MAX;
7230 final = 0;
7231 done = 0;
7232 }
7233 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007234#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007235 {
7236 chunk_size = (int)size;
7237 final = (consumed == NULL);
7238 done = 1;
7239 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007240
Victor Stinner76a31a62011-11-04 00:05:13 +01007241 /* Skip trailing lead-byte unless 'final' is set */
7242 if (!final && is_dbcs_lead_byte(code_page, s, chunk_size - 1))
7243 --chunk_size;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007244
Victor Stinner76a31a62011-11-04 00:05:13 +01007245 if (chunk_size == 0 && done) {
7246 if (v != NULL)
7247 break;
7248 Py_INCREF(unicode_empty);
7249 return unicode_empty;
7250 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007251
Victor Stinner76a31a62011-11-04 00:05:13 +01007252
7253 converted = decode_code_page_strict(code_page, &v,
7254 s, chunk_size);
7255 if (converted == -2)
7256 converted = decode_code_page_errors(code_page, &v,
7257 s, chunk_size,
7258 errors);
7259 assert(converted != 0);
7260
7261 if (converted < 0) {
7262 Py_XDECREF(v);
7263 return NULL;
7264 }
7265
7266 if (consumed)
7267 *consumed += converted;
7268
7269 s += converted;
7270 size -= converted;
7271 } while (!done);
Victor Stinner3a50e702011-10-18 21:21:00 +02007272
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01007273 return unicode_result(v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007274}
7275
Alexander Belopolsky40018472011-02-26 01:02:56 +00007276PyObject *
Victor Stinner3a50e702011-10-18 21:21:00 +02007277PyUnicode_DecodeCodePageStateful(int code_page,
7278 const char *s,
7279 Py_ssize_t size,
7280 const char *errors,
7281 Py_ssize_t *consumed)
7282{
7283 return decode_code_page_stateful(code_page, s, size, errors, consumed);
7284}
7285
7286PyObject *
7287PyUnicode_DecodeMBCSStateful(const char *s,
7288 Py_ssize_t size,
7289 const char *errors,
7290 Py_ssize_t *consumed)
7291{
7292 return decode_code_page_stateful(CP_ACP, s, size, errors, consumed);
7293}
7294
7295PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00007296PyUnicode_DecodeMBCS(const char *s,
7297 Py_ssize_t size,
7298 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007299{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007300 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
7301}
7302
Victor Stinner3a50e702011-10-18 21:21:00 +02007303static DWORD
7304encode_code_page_flags(UINT code_page, const char *errors)
7305{
7306 if (code_page == CP_UTF8) {
7307 if (winver.dwMajorVersion >= 6)
7308 /* CP_UTF8 supports WC_ERR_INVALID_CHARS on Windows Vista
7309 and later */
7310 return WC_ERR_INVALID_CHARS;
7311 else
7312 /* CP_UTF8 only supports flags=0 on Windows older than Vista */
7313 return 0;
7314 }
7315 else if (code_page == CP_UTF7) {
7316 /* CP_UTF7 only supports flags=0 */
7317 return 0;
7318 }
7319 else {
7320 if (errors != NULL && strcmp(errors, "replace") == 0)
7321 return 0;
7322 else
7323 return WC_NO_BEST_FIT_CHARS;
7324 }
7325}
7326
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007327/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007328 * Encode a Unicode string to a Windows code page into a byte string in strict
7329 * mode.
7330 *
7331 * Returns consumed characters if succeed, returns -2 on encode error, or raise
7332 * a WindowsError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007333 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007334static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007335encode_code_page_strict(UINT code_page, PyObject **outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007336 PyObject *unicode, Py_ssize_t offset, int len,
Victor Stinner3a50e702011-10-18 21:21:00 +02007337 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007338{
Victor Stinner554f3f02010-06-16 23:33:54 +00007339 BOOL usedDefaultChar = FALSE;
Victor Stinner3a50e702011-10-18 21:21:00 +02007340 BOOL *pusedDefaultChar = &usedDefaultChar;
7341 int outsize;
Victor Stinner554f3f02010-06-16 23:33:54 +00007342 PyObject *exc = NULL;
Victor Stinner24729f32011-11-10 20:31:37 +01007343 wchar_t *p;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007344 Py_ssize_t size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007345 const DWORD flags = encode_code_page_flags(code_page, NULL);
7346 char *out;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007347 /* Create a substring so that we can get the UTF-16 representation
7348 of just the slice under consideration. */
7349 PyObject *substring;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007350
Martin v. Löwis3d325192011-11-04 18:23:06 +01007351 assert(len > 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007352
Victor Stinner3a50e702011-10-18 21:21:00 +02007353 if (code_page != CP_UTF8 && code_page != CP_UTF7)
Victor Stinner554f3f02010-06-16 23:33:54 +00007354 pusedDefaultChar = &usedDefaultChar;
Victor Stinner3a50e702011-10-18 21:21:00 +02007355 else
Victor Stinner554f3f02010-06-16 23:33:54 +00007356 pusedDefaultChar = NULL;
Victor Stinner554f3f02010-06-16 23:33:54 +00007357
Victor Stinner2fc507f2011-11-04 20:06:39 +01007358 substring = PyUnicode_Substring(unicode, offset, offset+len);
7359 if (substring == NULL)
7360 return -1;
7361 p = PyUnicode_AsUnicodeAndSize(substring, &size);
7362 if (p == NULL) {
7363 Py_DECREF(substring);
7364 return -1;
7365 }
Martin v. Löwis3d325192011-11-04 18:23:06 +01007366
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007367 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007368 outsize = WideCharToMultiByte(code_page, flags,
7369 p, size,
7370 NULL, 0,
7371 NULL, pusedDefaultChar);
7372 if (outsize <= 0)
7373 goto error;
7374 /* If we used a default char, then we failed! */
Victor Stinner2fc507f2011-11-04 20:06:39 +01007375 if (pusedDefaultChar && *pusedDefaultChar) {
7376 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007377 return -2;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007378 }
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007379
Victor Stinner3a50e702011-10-18 21:21:00 +02007380 if (*outbytes == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007381 /* Create string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007382 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007383 if (*outbytes == NULL) {
7384 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007385 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007386 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007387 out = PyBytes_AS_STRING(*outbytes);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007388 }
7389 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007390 /* Extend string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007391 const Py_ssize_t n = PyBytes_Size(*outbytes);
7392 if (outsize > PY_SSIZE_T_MAX - n) {
7393 PyErr_NoMemory();
Victor Stinner2fc507f2011-11-04 20:06:39 +01007394 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007395 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007396 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007397 if (_PyBytes_Resize(outbytes, n + outsize) < 0) {
7398 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007399 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007400 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007401 out = PyBytes_AS_STRING(*outbytes) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007402 }
7403
7404 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007405 outsize = WideCharToMultiByte(code_page, flags,
7406 p, size,
7407 out, outsize,
7408 NULL, pusedDefaultChar);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007409 Py_CLEAR(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007410 if (outsize <= 0)
7411 goto error;
7412 if (pusedDefaultChar && *pusedDefaultChar)
7413 return -2;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007414 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00007415
Victor Stinner3a50e702011-10-18 21:21:00 +02007416error:
Victor Stinner2fc507f2011-11-04 20:06:39 +01007417 Py_XDECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007418 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7419 return -2;
7420 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007421 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007422}
7423
Victor Stinner3a50e702011-10-18 21:21:00 +02007424/*
7425 * Encode a Unicode string to a Windows code page into a byte string using a
7426 * error handler.
7427 *
7428 * Returns consumed characters if succeed, or raise a WindowsError and returns
7429 * -1 on other error.
7430 */
7431static int
7432encode_code_page_errors(UINT code_page, PyObject **outbytes,
Victor Stinner7581cef2011-11-03 22:32:33 +01007433 PyObject *unicode, Py_ssize_t unicode_offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007434 Py_ssize_t insize, const char* errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007435{
Victor Stinner3a50e702011-10-18 21:21:00 +02007436 const DWORD flags = encode_code_page_flags(code_page, errors);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007437 Py_ssize_t pos = unicode_offset;
7438 Py_ssize_t endin = unicode_offset + insize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007439 /* Ideally, we should get reason from FormatMessage. This is the Windows
7440 2000 English version of the message. */
7441 const char *reason = "invalid character";
7442 /* 4=maximum length of a UTF-8 sequence */
7443 char buffer[4];
7444 BOOL usedDefaultChar = FALSE, *pusedDefaultChar;
7445 Py_ssize_t outsize;
7446 char *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007447 PyObject *errorHandler = NULL;
7448 PyObject *exc = NULL;
7449 PyObject *encoding_obj = NULL;
7450 char *encoding;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007451 Py_ssize_t newpos, newoutsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007452 PyObject *rep;
7453 int ret = -1;
7454
7455 assert(insize > 0);
7456
7457 encoding = code_page_name(code_page, &encoding_obj);
7458 if (encoding == NULL)
7459 return -1;
7460
7461 if (errors == NULL || strcmp(errors, "strict") == 0) {
7462 /* The last error was ERROR_NO_UNICODE_TRANSLATION,
7463 then we raise a UnicodeEncodeError. */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007464 make_encode_exception(&exc, encoding, unicode, 0, 0, reason);
Victor Stinner3a50e702011-10-18 21:21:00 +02007465 if (exc != NULL) {
7466 PyCodec_StrictErrors(exc);
7467 Py_DECREF(exc);
7468 }
7469 Py_XDECREF(encoding_obj);
7470 return -1;
7471 }
7472
7473 if (code_page != CP_UTF8 && code_page != CP_UTF7)
7474 pusedDefaultChar = &usedDefaultChar;
7475 else
7476 pusedDefaultChar = NULL;
7477
7478 if (Py_ARRAY_LENGTH(buffer) > PY_SSIZE_T_MAX / insize) {
7479 PyErr_NoMemory();
7480 goto error;
7481 }
7482 outsize = insize * Py_ARRAY_LENGTH(buffer);
7483
7484 if (*outbytes == NULL) {
7485 /* Create string object */
7486 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
7487 if (*outbytes == NULL)
7488 goto error;
7489 out = PyBytes_AS_STRING(*outbytes);
7490 }
7491 else {
7492 /* Extend string object */
7493 Py_ssize_t n = PyBytes_Size(*outbytes);
7494 if (n > PY_SSIZE_T_MAX - outsize) {
7495 PyErr_NoMemory();
7496 goto error;
7497 }
7498 if (_PyBytes_Resize(outbytes, n + outsize) < 0)
7499 goto error;
7500 out = PyBytes_AS_STRING(*outbytes) + n;
7501 }
7502
7503 /* Encode the string character per character */
Martin v. Löwis3d325192011-11-04 18:23:06 +01007504 while (pos < endin)
Victor Stinner3a50e702011-10-18 21:21:00 +02007505 {
Victor Stinner2fc507f2011-11-04 20:06:39 +01007506 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, pos);
7507 wchar_t chars[2];
7508 int charsize;
7509 if (ch < 0x10000) {
7510 chars[0] = (wchar_t)ch;
7511 charsize = 1;
7512 }
7513 else {
7514 ch -= 0x10000;
7515 chars[0] = 0xd800 + (ch >> 10);
7516 chars[1] = 0xdc00 + (ch & 0x3ff);
7517 charsize = 2;
7518 }
7519
Victor Stinner3a50e702011-10-18 21:21:00 +02007520 outsize = WideCharToMultiByte(code_page, flags,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007521 chars, charsize,
Victor Stinner3a50e702011-10-18 21:21:00 +02007522 buffer, Py_ARRAY_LENGTH(buffer),
7523 NULL, pusedDefaultChar);
7524 if (outsize > 0) {
7525 if (pusedDefaultChar == NULL || !(*pusedDefaultChar))
7526 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007527 pos++;
Victor Stinner3a50e702011-10-18 21:21:00 +02007528 memcpy(out, buffer, outsize);
7529 out += outsize;
7530 continue;
7531 }
7532 }
7533 else if (GetLastError() != ERROR_NO_UNICODE_TRANSLATION) {
7534 PyErr_SetFromWindowsErr(0);
7535 goto error;
7536 }
7537
Victor Stinner3a50e702011-10-18 21:21:00 +02007538 rep = unicode_encode_call_errorhandler(
7539 errors, &errorHandler, encoding, reason,
Victor Stinner7581cef2011-11-03 22:32:33 +01007540 unicode, &exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007541 pos, pos + 1, &newpos);
Victor Stinner3a50e702011-10-18 21:21:00 +02007542 if (rep == NULL)
7543 goto error;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007544 pos = newpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007545
7546 if (PyBytes_Check(rep)) {
7547 outsize = PyBytes_GET_SIZE(rep);
7548 if (outsize != 1) {
7549 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7550 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7551 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7552 Py_DECREF(rep);
7553 goto error;
7554 }
7555 out = PyBytes_AS_STRING(*outbytes) + offset;
7556 }
7557 memcpy(out, PyBytes_AS_STRING(rep), outsize);
7558 out += outsize;
7559 }
7560 else {
7561 Py_ssize_t i;
7562 enum PyUnicode_Kind kind;
7563 void *data;
7564
7565 if (PyUnicode_READY(rep) < 0) {
7566 Py_DECREF(rep);
7567 goto error;
7568 }
7569
7570 outsize = PyUnicode_GET_LENGTH(rep);
7571 if (outsize != 1) {
7572 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7573 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7574 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7575 Py_DECREF(rep);
7576 goto error;
7577 }
7578 out = PyBytes_AS_STRING(*outbytes) + offset;
7579 }
7580 kind = PyUnicode_KIND(rep);
7581 data = PyUnicode_DATA(rep);
7582 for (i=0; i < outsize; i++) {
7583 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7584 if (ch > 127) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007585 raise_encode_exception(&exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007586 encoding, unicode,
7587 pos, pos + 1,
Victor Stinner3a50e702011-10-18 21:21:00 +02007588 "unable to encode error handler result to ASCII");
7589 Py_DECREF(rep);
7590 goto error;
7591 }
7592 *out = (unsigned char)ch;
7593 out++;
7594 }
7595 }
7596 Py_DECREF(rep);
7597 }
7598 /* write a NUL byte */
7599 *out = 0;
7600 outsize = out - PyBytes_AS_STRING(*outbytes);
7601 assert(outsize <= PyBytes_GET_SIZE(*outbytes));
7602 if (_PyBytes_Resize(outbytes, outsize) < 0)
7603 goto error;
7604 ret = 0;
7605
7606error:
7607 Py_XDECREF(encoding_obj);
7608 Py_XDECREF(errorHandler);
7609 Py_XDECREF(exc);
7610 return ret;
7611}
7612
Victor Stinner3a50e702011-10-18 21:21:00 +02007613static PyObject *
7614encode_code_page(int code_page,
Victor Stinner7581cef2011-11-03 22:32:33 +01007615 PyObject *unicode,
Victor Stinner3a50e702011-10-18 21:21:00 +02007616 const char *errors)
7617{
Martin v. Löwis3d325192011-11-04 18:23:06 +01007618 Py_ssize_t len;
Victor Stinner3a50e702011-10-18 21:21:00 +02007619 PyObject *outbytes = NULL;
Victor Stinner7581cef2011-11-03 22:32:33 +01007620 Py_ssize_t offset;
Victor Stinner76a31a62011-11-04 00:05:13 +01007621 int chunk_len, ret, done;
Victor Stinner7581cef2011-11-03 22:32:33 +01007622
Victor Stinner2fc507f2011-11-04 20:06:39 +01007623 if (PyUnicode_READY(unicode) < 0)
7624 return NULL;
7625 len = PyUnicode_GET_LENGTH(unicode);
Guido van Rossum03e29f12000-05-04 15:52:20 +00007626
Victor Stinner3a50e702011-10-18 21:21:00 +02007627 if (code_page < 0) {
7628 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7629 return NULL;
7630 }
7631
Martin v. Löwis3d325192011-11-04 18:23:06 +01007632 if (len == 0)
Victor Stinner76a31a62011-11-04 00:05:13 +01007633 return PyBytes_FromStringAndSize(NULL, 0);
7634
Victor Stinner7581cef2011-11-03 22:32:33 +01007635 offset = 0;
7636 do
7637 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007638#ifdef NEED_RETRY
Victor Stinner2fc507f2011-11-04 20:06:39 +01007639 /* UTF-16 encoding may double the size, so use only INT_MAX/2
Martin v. Löwis3d325192011-11-04 18:23:06 +01007640 chunks. */
7641 if (len > INT_MAX/2) {
7642 chunk_len = INT_MAX/2;
Victor Stinner76a31a62011-11-04 00:05:13 +01007643 done = 0;
7644 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007645 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007646#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007647 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007648 chunk_len = (int)len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007649 done = 1;
7650 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007651
Victor Stinner76a31a62011-11-04 00:05:13 +01007652 ret = encode_code_page_strict(code_page, &outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007653 unicode, offset, chunk_len,
Victor Stinner76a31a62011-11-04 00:05:13 +01007654 errors);
7655 if (ret == -2)
7656 ret = encode_code_page_errors(code_page, &outbytes,
7657 unicode, offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007658 chunk_len, errors);
Victor Stinner7581cef2011-11-03 22:32:33 +01007659 if (ret < 0) {
7660 Py_XDECREF(outbytes);
7661 return NULL;
7662 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007663
Victor Stinner7581cef2011-11-03 22:32:33 +01007664 offset += chunk_len;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007665 len -= chunk_len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007666 } while (!done);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007667
Victor Stinner3a50e702011-10-18 21:21:00 +02007668 return outbytes;
7669}
7670
7671PyObject *
7672PyUnicode_EncodeMBCS(const Py_UNICODE *p,
7673 Py_ssize_t size,
7674 const char *errors)
7675{
Victor Stinner7581cef2011-11-03 22:32:33 +01007676 PyObject *unicode, *res;
7677 unicode = PyUnicode_FromUnicode(p, size);
7678 if (unicode == NULL)
7679 return NULL;
7680 res = encode_code_page(CP_ACP, unicode, errors);
7681 Py_DECREF(unicode);
7682 return res;
Victor Stinner3a50e702011-10-18 21:21:00 +02007683}
7684
7685PyObject *
7686PyUnicode_EncodeCodePage(int code_page,
7687 PyObject *unicode,
7688 const char *errors)
7689{
Victor Stinner7581cef2011-11-03 22:32:33 +01007690 return encode_code_page(code_page, unicode, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007691}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007692
Alexander Belopolsky40018472011-02-26 01:02:56 +00007693PyObject *
7694PyUnicode_AsMBCSString(PyObject *unicode)
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007695{
7696 if (!PyUnicode_Check(unicode)) {
7697 PyErr_BadArgument();
7698 return NULL;
7699 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007700 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007701}
7702
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007703#undef NEED_RETRY
7704
Victor Stinner99b95382011-07-04 14:23:54 +02007705#endif /* HAVE_MBCS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007706
Guido van Rossumd57fd912000-03-10 22:53:23 +00007707/* --- Character Mapping Codec -------------------------------------------- */
7708
Alexander Belopolsky40018472011-02-26 01:02:56 +00007709PyObject *
7710PyUnicode_DecodeCharmap(const char *s,
7711 Py_ssize_t size,
7712 PyObject *mapping,
7713 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007714{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007715 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007716 Py_ssize_t startinpos;
7717 Py_ssize_t endinpos;
7718 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007719 const char *e;
Victor Stinner7931d9a2011-11-04 00:22:48 +01007720 PyObject *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007721 Py_ssize_t extrachars = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007722 PyObject *errorHandler = NULL;
7723 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00007724
Guido van Rossumd57fd912000-03-10 22:53:23 +00007725 /* Default to Latin-1 */
7726 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007727 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007728
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007729 v = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007730 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007731 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007732 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01007733 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007734 outpos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007735 e = s + size;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007736 if (PyUnicode_CheckExact(mapping)) {
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007737 Py_ssize_t maplen;
7738 enum PyUnicode_Kind kind;
7739 void *data;
7740 Py_UCS4 x;
7741
7742 if (PyUnicode_READY(mapping) < 0)
7743 return NULL;
7744
7745 maplen = PyUnicode_GET_LENGTH(mapping);
7746 data = PyUnicode_DATA(mapping);
7747 kind = PyUnicode_KIND(mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00007748 while (s < e) {
7749 unsigned char ch = *s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007750
Benjamin Peterson29060642009-01-31 22:14:21 +00007751 if (ch < maplen)
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007752 x = PyUnicode_READ(kind, data, ch);
7753 else
7754 x = 0xfffe; /* invalid value */
Guido van Rossumd57fd912000-03-10 22:53:23 +00007755
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007756 if (x == 0xfffe)
7757 {
Benjamin Peterson29060642009-01-31 22:14:21 +00007758 /* undefined mapping */
Benjamin Peterson29060642009-01-31 22:14:21 +00007759 startinpos = s-starts;
7760 endinpos = startinpos+1;
7761 if (unicode_decode_call_errorhandler(
7762 errors, &errorHandler,
7763 "charmap", "character maps to <undefined>",
7764 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007765 &v, &outpos)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007766 goto onError;
7767 }
7768 continue;
7769 }
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007770
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007771 if (unicode_putchar(&v, &outpos, x) < 0)
7772 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00007773 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007774 }
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007775 }
7776 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007777 while (s < e) {
7778 unsigned char ch = *s;
7779 PyObject *w, *x;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007780
Benjamin Peterson29060642009-01-31 22:14:21 +00007781 /* Get mapping (char ordinal -> integer, Unicode char or None) */
7782 w = PyLong_FromLong((long)ch);
7783 if (w == NULL)
7784 goto onError;
7785 x = PyObject_GetItem(mapping, w);
7786 Py_DECREF(w);
7787 if (x == NULL) {
7788 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7789 /* No mapping found means: mapping is undefined. */
7790 PyErr_Clear();
7791 x = Py_None;
7792 Py_INCREF(x);
7793 } else
7794 goto onError;
7795 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007796
Benjamin Peterson29060642009-01-31 22:14:21 +00007797 /* Apply mapping */
7798 if (PyLong_Check(x)) {
7799 long value = PyLong_AS_LONG(x);
7800 if (value < 0 || value > 65535) {
7801 PyErr_SetString(PyExc_TypeError,
7802 "character mapping must be in range(65536)");
7803 Py_DECREF(x);
7804 goto onError;
7805 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007806 if (unicode_putchar(&v, &outpos, value) < 0)
7807 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00007808 }
7809 else if (x == Py_None) {
7810 /* undefined mapping */
Benjamin Peterson29060642009-01-31 22:14:21 +00007811 startinpos = s-starts;
7812 endinpos = startinpos+1;
7813 if (unicode_decode_call_errorhandler(
7814 errors, &errorHandler,
7815 "charmap", "character maps to <undefined>",
7816 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007817 &v, &outpos)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007818 Py_DECREF(x);
7819 goto onError;
7820 }
7821 Py_DECREF(x);
7822 continue;
7823 }
7824 else if (PyUnicode_Check(x)) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007825 Py_ssize_t targetsize;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007826
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007827 if (PyUnicode_READY(x) < 0)
7828 goto onError;
7829 targetsize = PyUnicode_GET_LENGTH(x);
7830
7831 if (targetsize == 1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007832 /* 1-1 mapping */
Victor Stinner62aa4d02011-11-09 00:03:45 +01007833 if (unicode_putchar(&v, &outpos,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007834 PyUnicode_READ_CHAR(x, 0)) < 0)
7835 goto onError;
7836 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007837 else if (targetsize > 1) {
7838 /* 1-n mapping */
7839 if (targetsize > extrachars) {
7840 /* resize first */
Benjamin Peterson29060642009-01-31 22:14:21 +00007841 Py_ssize_t needed = (targetsize - extrachars) + \
7842 (targetsize << 2);
7843 extrachars += needed;
7844 /* XXX overflow detection missing */
Victor Stinner16e6a802011-12-12 13:24:15 +01007845 if (unicode_resize(&v,
7846 PyUnicode_GET_LENGTH(v) + needed) < 0)
7847 {
Benjamin Peterson29060642009-01-31 22:14:21 +00007848 Py_DECREF(x);
7849 goto onError;
7850 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007851 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007852 if (unicode_widen(&v, PyUnicode_MAX_CHAR_VALUE(x)) < 0)
7853 goto onError;
7854 PyUnicode_CopyCharacters(v, outpos, x, 0, targetsize);
7855 outpos += targetsize;
Benjamin Peterson29060642009-01-31 22:14:21 +00007856 extrachars -= targetsize;
7857 }
7858 /* 1-0 mapping: skip the character */
7859 }
7860 else {
7861 /* wrong return value */
7862 PyErr_SetString(PyExc_TypeError,
7863 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00007864 Py_DECREF(x);
7865 goto onError;
7866 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007867 Py_DECREF(x);
7868 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007869 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00007870 }
Victor Stinner16e6a802011-12-12 13:24:15 +01007871 if (unicode_resize(&v, outpos) < 0)
Antoine Pitroua8f63c02011-11-08 18:37:16 +01007872 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007873 Py_XDECREF(errorHandler);
7874 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01007875 return unicode_result(v);
Tim Petersced69f82003-09-16 20:30:58 +00007876
Benjamin Peterson29060642009-01-31 22:14:21 +00007877 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007878 Py_XDECREF(errorHandler);
7879 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007880 Py_XDECREF(v);
7881 return NULL;
7882}
7883
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007884/* Charmap encoding: the lookup table */
7885
Alexander Belopolsky40018472011-02-26 01:02:56 +00007886struct encoding_map {
Benjamin Peterson29060642009-01-31 22:14:21 +00007887 PyObject_HEAD
7888 unsigned char level1[32];
7889 int count2, count3;
7890 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007891};
7892
7893static PyObject*
7894encoding_map_size(PyObject *obj, PyObject* args)
7895{
7896 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007897 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00007898 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007899}
7900
7901static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007902 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00007903 PyDoc_STR("Return the size (in bytes) of this object") },
7904 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007905};
7906
7907static void
7908encoding_map_dealloc(PyObject* o)
7909{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007910 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007911}
7912
7913static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007914 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007915 "EncodingMap", /*tp_name*/
7916 sizeof(struct encoding_map), /*tp_basicsize*/
7917 0, /*tp_itemsize*/
7918 /* methods */
7919 encoding_map_dealloc, /*tp_dealloc*/
7920 0, /*tp_print*/
7921 0, /*tp_getattr*/
7922 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00007923 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00007924 0, /*tp_repr*/
7925 0, /*tp_as_number*/
7926 0, /*tp_as_sequence*/
7927 0, /*tp_as_mapping*/
7928 0, /*tp_hash*/
7929 0, /*tp_call*/
7930 0, /*tp_str*/
7931 0, /*tp_getattro*/
7932 0, /*tp_setattro*/
7933 0, /*tp_as_buffer*/
7934 Py_TPFLAGS_DEFAULT, /*tp_flags*/
7935 0, /*tp_doc*/
7936 0, /*tp_traverse*/
7937 0, /*tp_clear*/
7938 0, /*tp_richcompare*/
7939 0, /*tp_weaklistoffset*/
7940 0, /*tp_iter*/
7941 0, /*tp_iternext*/
7942 encoding_map_methods, /*tp_methods*/
7943 0, /*tp_members*/
7944 0, /*tp_getset*/
7945 0, /*tp_base*/
7946 0, /*tp_dict*/
7947 0, /*tp_descr_get*/
7948 0, /*tp_descr_set*/
7949 0, /*tp_dictoffset*/
7950 0, /*tp_init*/
7951 0, /*tp_alloc*/
7952 0, /*tp_new*/
7953 0, /*tp_free*/
7954 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007955};
7956
7957PyObject*
7958PyUnicode_BuildEncodingMap(PyObject* string)
7959{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007960 PyObject *result;
7961 struct encoding_map *mresult;
7962 int i;
7963 int need_dict = 0;
7964 unsigned char level1[32];
7965 unsigned char level2[512];
7966 unsigned char *mlevel1, *mlevel2, *mlevel3;
7967 int count2 = 0, count3 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007968 int kind;
7969 void *data;
7970 Py_UCS4 ch;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007971
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007972 if (!PyUnicode_Check(string) || PyUnicode_GET_LENGTH(string) != 256) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007973 PyErr_BadArgument();
7974 return NULL;
7975 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007976 kind = PyUnicode_KIND(string);
7977 data = PyUnicode_DATA(string);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007978 memset(level1, 0xFF, sizeof level1);
7979 memset(level2, 0xFF, sizeof level2);
7980
7981 /* If there isn't a one-to-one mapping of NULL to \0,
7982 or if there are non-BMP characters, we need to use
7983 a mapping dictionary. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007984 if (PyUnicode_READ(kind, data, 0) != 0)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007985 need_dict = 1;
7986 for (i = 1; i < 256; i++) {
7987 int l1, l2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007988 ch = PyUnicode_READ(kind, data, i);
7989 if (ch == 0 || ch > 0xFFFF) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007990 need_dict = 1;
7991 break;
7992 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007993 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007994 /* unmapped character */
7995 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007996 l1 = ch >> 11;
7997 l2 = ch >> 7;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007998 if (level1[l1] == 0xFF)
7999 level1[l1] = count2++;
8000 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00008001 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008002 }
8003
8004 if (count2 >= 0xFF || count3 >= 0xFF)
8005 need_dict = 1;
8006
8007 if (need_dict) {
8008 PyObject *result = PyDict_New();
8009 PyObject *key, *value;
8010 if (!result)
8011 return NULL;
8012 for (i = 0; i < 256; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008013 key = PyLong_FromLong(PyUnicode_READ(kind, data, i));
Christian Heimes217cfd12007-12-02 14:31:20 +00008014 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008015 if (!key || !value)
8016 goto failed1;
8017 if (PyDict_SetItem(result, key, value) == -1)
8018 goto failed1;
8019 Py_DECREF(key);
8020 Py_DECREF(value);
8021 }
8022 return result;
8023 failed1:
8024 Py_XDECREF(key);
8025 Py_XDECREF(value);
8026 Py_DECREF(result);
8027 return NULL;
8028 }
8029
8030 /* Create a three-level trie */
8031 result = PyObject_MALLOC(sizeof(struct encoding_map) +
8032 16*count2 + 128*count3 - 1);
8033 if (!result)
8034 return PyErr_NoMemory();
8035 PyObject_Init(result, &EncodingMapType);
8036 mresult = (struct encoding_map*)result;
8037 mresult->count2 = count2;
8038 mresult->count3 = count3;
8039 mlevel1 = mresult->level1;
8040 mlevel2 = mresult->level23;
8041 mlevel3 = mresult->level23 + 16*count2;
8042 memcpy(mlevel1, level1, 32);
8043 memset(mlevel2, 0xFF, 16*count2);
8044 memset(mlevel3, 0, 128*count3);
8045 count3 = 0;
8046 for (i = 1; i < 256; i++) {
8047 int o1, o2, o3, i2, i3;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008048 if (PyUnicode_READ(kind, data, i) == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008049 /* unmapped character */
8050 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008051 o1 = PyUnicode_READ(kind, data, i)>>11;
8052 o2 = (PyUnicode_READ(kind, data, i)>>7) & 0xF;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008053 i2 = 16*mlevel1[o1] + o2;
8054 if (mlevel2[i2] == 0xFF)
8055 mlevel2[i2] = count3++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008056 o3 = PyUnicode_READ(kind, data, i) & 0x7F;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008057 i3 = 128*mlevel2[i2] + o3;
8058 mlevel3[i3] = i;
8059 }
8060 return result;
8061}
8062
8063static int
Victor Stinner22168992011-11-20 17:09:18 +01008064encoding_map_lookup(Py_UCS4 c, PyObject *mapping)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008065{
8066 struct encoding_map *map = (struct encoding_map*)mapping;
8067 int l1 = c>>11;
8068 int l2 = (c>>7) & 0xF;
8069 int l3 = c & 0x7F;
8070 int i;
8071
Victor Stinner22168992011-11-20 17:09:18 +01008072 if (c > 0xFFFF)
Benjamin Peterson29060642009-01-31 22:14:21 +00008073 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008074 if (c == 0)
8075 return 0;
8076 /* level 1*/
8077 i = map->level1[l1];
8078 if (i == 0xFF) {
8079 return -1;
8080 }
8081 /* level 2*/
8082 i = map->level23[16*i+l2];
8083 if (i == 0xFF) {
8084 return -1;
8085 }
8086 /* level 3 */
8087 i = map->level23[16*map->count2 + 128*i + l3];
8088 if (i == 0) {
8089 return -1;
8090 }
8091 return i;
8092}
8093
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008094/* Lookup the character ch in the mapping. If the character
8095 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00008096 error occurred). */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008097static PyObject *
Victor Stinner22168992011-11-20 17:09:18 +01008098charmapencode_lookup(Py_UCS4 c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008099{
Christian Heimes217cfd12007-12-02 14:31:20 +00008100 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008101 PyObject *x;
8102
8103 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008104 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008105 x = PyObject_GetItem(mapping, w);
8106 Py_DECREF(w);
8107 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008108 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8109 /* No mapping found means: mapping is undefined. */
8110 PyErr_Clear();
8111 x = Py_None;
8112 Py_INCREF(x);
8113 return x;
8114 } else
8115 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008116 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00008117 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008118 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00008119 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008120 long value = PyLong_AS_LONG(x);
8121 if (value < 0 || value > 255) {
8122 PyErr_SetString(PyExc_TypeError,
8123 "character mapping must be in range(256)");
8124 Py_DECREF(x);
8125 return NULL;
8126 }
8127 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008128 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008129 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008130 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008131 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008132 /* wrong return value */
8133 PyErr_Format(PyExc_TypeError,
8134 "character mapping must return integer, bytes or None, not %.400s",
8135 x->ob_type->tp_name);
8136 Py_DECREF(x);
8137 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008138 }
8139}
8140
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008141static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00008142charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008143{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008144 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
8145 /* exponentially overallocate to minimize reallocations */
8146 if (requiredsize < 2*outsize)
8147 requiredsize = 2*outsize;
8148 if (_PyBytes_Resize(outobj, requiredsize))
8149 return -1;
8150 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008151}
8152
Benjamin Peterson14339b62009-01-31 16:36:08 +00008153typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00008154 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Alexander Belopolsky40018472011-02-26 01:02:56 +00008155} charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008156/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00008157 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008158 space is available. Return a new reference to the object that
8159 was put in the output buffer, or Py_None, if the mapping was undefined
8160 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00008161 reallocation error occurred. The caller must decref the result */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008162static charmapencode_result
Victor Stinner22168992011-11-20 17:09:18 +01008163charmapencode_output(Py_UCS4 c, PyObject *mapping,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008164 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008165{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008166 PyObject *rep;
8167 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00008168 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008169
Christian Heimes90aa7642007-12-19 02:45:37 +00008170 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008171 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008172 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008173 if (res == -1)
8174 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00008175 if (outsize<requiredsize)
8176 if (charmapencode_resize(outobj, outpos, requiredsize))
8177 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00008178 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008179 outstart[(*outpos)++] = (char)res;
8180 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008181 }
8182
8183 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008184 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008185 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008186 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008187 Py_DECREF(rep);
8188 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008189 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008190 if (PyLong_Check(rep)) {
8191 Py_ssize_t requiredsize = *outpos+1;
8192 if (outsize<requiredsize)
8193 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8194 Py_DECREF(rep);
8195 return enc_EXCEPTION;
8196 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008197 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008198 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008199 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008200 else {
8201 const char *repchars = PyBytes_AS_STRING(rep);
8202 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
8203 Py_ssize_t requiredsize = *outpos+repsize;
8204 if (outsize<requiredsize)
8205 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8206 Py_DECREF(rep);
8207 return enc_EXCEPTION;
8208 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008209 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008210 memcpy(outstart + *outpos, repchars, repsize);
8211 *outpos += repsize;
8212 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008213 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008214 Py_DECREF(rep);
8215 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008216}
8217
8218/* handle an error in PyUnicode_EncodeCharmap
8219 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008220static int
8221charmap_encoding_error(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008222 PyObject *unicode, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008223 PyObject **exceptionObject,
Walter Dörwalde5402fb2003-08-14 20:25:29 +00008224 int *known_errorHandler, PyObject **errorHandler, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00008225 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008226{
8227 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008228 Py_ssize_t size, repsize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008229 Py_ssize_t newpos;
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008230 enum PyUnicode_Kind kind;
8231 void *data;
8232 Py_ssize_t index;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008233 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008234 Py_ssize_t collstartpos = *inpos;
8235 Py_ssize_t collendpos = *inpos+1;
8236 Py_ssize_t collpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008237 char *encoding = "charmap";
8238 char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008239 charmapencode_result x;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008240 Py_UCS4 ch;
Brian Curtin2787ea42011-11-02 15:09:37 -05008241 int val;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008242
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008243 if (PyUnicode_READY(unicode) < 0)
8244 return -1;
8245 size = PyUnicode_GET_LENGTH(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008246 /* find all unencodable characters */
8247 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008248 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00008249 if (Py_TYPE(mapping) == &EncodingMapType) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008250 ch = PyUnicode_READ_CHAR(unicode, collendpos);
Brian Curtin2787ea42011-11-02 15:09:37 -05008251 val = encoding_map_lookup(ch, mapping);
8252 if (val != -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008253 break;
8254 ++collendpos;
8255 continue;
8256 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008257
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008258 ch = PyUnicode_READ_CHAR(unicode, collendpos);
8259 rep = charmapencode_lookup(ch, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008260 if (rep==NULL)
8261 return -1;
8262 else if (rep!=Py_None) {
8263 Py_DECREF(rep);
8264 break;
8265 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008266 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00008267 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008268 }
8269 /* cache callback name lookup
8270 * (if not done yet, i.e. it's the first error) */
8271 if (*known_errorHandler==-1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008272 if ((errors==NULL) || (!strcmp(errors, "strict")))
8273 *known_errorHandler = 1;
8274 else if (!strcmp(errors, "replace"))
8275 *known_errorHandler = 2;
8276 else if (!strcmp(errors, "ignore"))
8277 *known_errorHandler = 3;
8278 else if (!strcmp(errors, "xmlcharrefreplace"))
8279 *known_errorHandler = 4;
8280 else
8281 *known_errorHandler = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008282 }
8283 switch (*known_errorHandler) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008284 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008285 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008286 return -1;
8287 case 2: /* replace */
8288 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008289 x = charmapencode_output('?', mapping, res, respos);
8290 if (x==enc_EXCEPTION) {
8291 return -1;
8292 }
8293 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008294 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008295 return -1;
8296 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008297 }
8298 /* fall through */
8299 case 3: /* ignore */
8300 *inpos = collendpos;
8301 break;
8302 case 4: /* xmlcharrefreplace */
8303 /* generate replacement (temporarily (mis)uses p) */
8304 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008305 char buffer[2+29+1+1];
8306 char *cp;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008307 sprintf(buffer, "&#%d;", (int)PyUnicode_READ_CHAR(unicode, collpos));
Benjamin Peterson29060642009-01-31 22:14:21 +00008308 for (cp = buffer; *cp; ++cp) {
8309 x = charmapencode_output(*cp, mapping, res, respos);
8310 if (x==enc_EXCEPTION)
8311 return -1;
8312 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008313 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008314 return -1;
8315 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008316 }
8317 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008318 *inpos = collendpos;
8319 break;
8320 default:
8321 repunicode = unicode_encode_call_errorhandler(errors, errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008322 encoding, reason, unicode, exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00008323 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008324 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008325 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00008326 if (PyBytes_Check(repunicode)) {
8327 /* Directly copy bytes result to output. */
8328 Py_ssize_t outsize = PyBytes_Size(*res);
8329 Py_ssize_t requiredsize;
8330 repsize = PyBytes_Size(repunicode);
8331 requiredsize = *respos + repsize;
8332 if (requiredsize > outsize)
8333 /* Make room for all additional bytes. */
8334 if (charmapencode_resize(res, respos, requiredsize)) {
8335 Py_DECREF(repunicode);
8336 return -1;
8337 }
8338 memcpy(PyBytes_AsString(*res) + *respos,
8339 PyBytes_AsString(repunicode), repsize);
8340 *respos += repsize;
8341 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008342 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00008343 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008344 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008345 /* generate replacement */
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008346 if (PyUnicode_READY(repunicode) < 0) {
8347 Py_DECREF(repunicode);
8348 return -1;
8349 }
Victor Stinner9e30aa52011-11-21 02:49:52 +01008350 repsize = PyUnicode_GET_LENGTH(repunicode);
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008351 data = PyUnicode_DATA(repunicode);
8352 kind = PyUnicode_KIND(repunicode);
8353 for (index = 0; index < repsize; index++) {
8354 Py_UCS4 repch = PyUnicode_READ(kind, data, index);
8355 x = charmapencode_output(repch, mapping, res, respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008356 if (x==enc_EXCEPTION) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008357 Py_DECREF(repunicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00008358 return -1;
8359 }
8360 else if (x==enc_FAILED) {
8361 Py_DECREF(repunicode);
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008362 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008363 return -1;
8364 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008365 }
8366 *inpos = newpos;
8367 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008368 }
8369 return 0;
8370}
8371
Alexander Belopolsky40018472011-02-26 01:02:56 +00008372PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008373_PyUnicode_EncodeCharmap(PyObject *unicode,
8374 PyObject *mapping,
8375 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008376{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008377 /* output object */
8378 PyObject *res = NULL;
8379 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008380 Py_ssize_t inpos = 0;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008381 Py_ssize_t size;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008382 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008383 Py_ssize_t respos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008384 PyObject *errorHandler = NULL;
8385 PyObject *exc = NULL;
8386 /* the following variable is used for caching string comparisons
8387 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8388 * 3=ignore, 4=xmlcharrefreplace */
8389 int known_errorHandler = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008390
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008391 if (PyUnicode_READY(unicode) < 0)
8392 return NULL;
8393 size = PyUnicode_GET_LENGTH(unicode);
8394
Guido van Rossumd57fd912000-03-10 22:53:23 +00008395 /* Default to Latin-1 */
8396 if (mapping == NULL)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008397 return unicode_encode_ucs1(unicode, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008398
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008399 /* allocate enough for a simple encoding without
8400 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00008401 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008402 if (res == NULL)
8403 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00008404 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008405 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008406
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008407 while (inpos<size) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008408 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, inpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008409 /* try to encode it */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008410 charmapencode_result x = charmapencode_output(ch, mapping, &res, &respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008411 if (x==enc_EXCEPTION) /* error */
8412 goto onError;
8413 if (x==enc_FAILED) { /* unencodable character */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008414 if (charmap_encoding_error(unicode, &inpos, mapping,
Benjamin Peterson29060642009-01-31 22:14:21 +00008415 &exc,
8416 &known_errorHandler, &errorHandler, errors,
8417 &res, &respos)) {
8418 goto onError;
8419 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008420 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008421 else
8422 /* done with this character => adjust input position */
8423 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008424 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008425
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008426 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00008427 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00008428 if (_PyBytes_Resize(&res, respos) < 0)
8429 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00008430
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008431 Py_XDECREF(exc);
8432 Py_XDECREF(errorHandler);
8433 return res;
8434
Benjamin Peterson29060642009-01-31 22:14:21 +00008435 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008436 Py_XDECREF(res);
8437 Py_XDECREF(exc);
8438 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008439 return NULL;
8440}
8441
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008442/* Deprecated */
8443PyObject *
8444PyUnicode_EncodeCharmap(const Py_UNICODE *p,
8445 Py_ssize_t size,
8446 PyObject *mapping,
8447 const char *errors)
8448{
8449 PyObject *result;
8450 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8451 if (unicode == NULL)
8452 return NULL;
8453 result = _PyUnicode_EncodeCharmap(unicode, mapping, errors);
8454 Py_DECREF(unicode);
Victor Stinnerfc026c92011-11-04 00:24:51 +01008455 return result;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008456}
8457
Alexander Belopolsky40018472011-02-26 01:02:56 +00008458PyObject *
8459PyUnicode_AsCharmapString(PyObject *unicode,
8460 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008461{
8462 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008463 PyErr_BadArgument();
8464 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008465 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008466 return _PyUnicode_EncodeCharmap(unicode, mapping, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008467}
8468
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008469/* create or adjust a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008470static void
8471make_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008472 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008473 Py_ssize_t startpos, Py_ssize_t endpos,
8474 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008475{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008476 if (*exceptionObject == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008477 *exceptionObject = _PyUnicodeTranslateError_Create(
8478 unicode, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008479 }
8480 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008481 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
8482 goto onError;
8483 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
8484 goto onError;
8485 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
8486 goto onError;
8487 return;
8488 onError:
8489 Py_DECREF(*exceptionObject);
8490 *exceptionObject = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008491 }
8492}
8493
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008494/* raises a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008495static void
8496raise_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008497 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008498 Py_ssize_t startpos, Py_ssize_t endpos,
8499 const char *reason)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008500{
8501 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008502 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008503 if (*exceptionObject != NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008504 PyCodec_StrictErrors(*exceptionObject);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008505}
8506
8507/* error handling callback helper:
8508 build arguments, call the callback and check the arguments,
8509 put the result into newpos and return the replacement string, which
8510 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008511static PyObject *
8512unicode_translate_call_errorhandler(const char *errors,
8513 PyObject **errorHandler,
8514 const char *reason,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008515 PyObject *unicode, PyObject **exceptionObject,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008516 Py_ssize_t startpos, Py_ssize_t endpos,
8517 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008518{
Benjamin Peterson142957c2008-07-04 19:55:29 +00008519 static char *argparse = "O!n;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008520
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008521 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008522 PyObject *restuple;
8523 PyObject *resunicode;
8524
8525 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008526 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008527 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008528 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008529 }
8530
8531 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008532 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008533 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008534 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008535
8536 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00008537 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008538 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008539 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008540 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00008541 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00008542 Py_DECREF(restuple);
8543 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008544 }
8545 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type,
Benjamin Peterson29060642009-01-31 22:14:21 +00008546 &resunicode, &i_newpos)) {
8547 Py_DECREF(restuple);
8548 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008549 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00008550 if (i_newpos<0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008551 *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008552 else
8553 *newpos = i_newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008554 if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008555 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
8556 Py_DECREF(restuple);
8557 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00008558 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008559 Py_INCREF(resunicode);
8560 Py_DECREF(restuple);
8561 return resunicode;
8562}
8563
8564/* Lookup the character ch in the mapping and put the result in result,
8565 which must be decrefed by the caller.
8566 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008567static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008568charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008569{
Christian Heimes217cfd12007-12-02 14:31:20 +00008570 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008571 PyObject *x;
8572
8573 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008574 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008575 x = PyObject_GetItem(mapping, w);
8576 Py_DECREF(w);
8577 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008578 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8579 /* No mapping found means: use 1:1 mapping. */
8580 PyErr_Clear();
8581 *result = NULL;
8582 return 0;
8583 } else
8584 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008585 }
8586 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008587 *result = x;
8588 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008589 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008590 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008591 long value = PyLong_AS_LONG(x);
8592 long max = PyUnicode_GetMax();
8593 if (value < 0 || value > max) {
8594 PyErr_Format(PyExc_TypeError,
Guido van Rossum5a2f7e602007-10-24 21:13:09 +00008595 "character mapping must be in range(0x%x)", max+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00008596 Py_DECREF(x);
8597 return -1;
8598 }
8599 *result = x;
8600 return 0;
8601 }
8602 else if (PyUnicode_Check(x)) {
8603 *result = x;
8604 return 0;
8605 }
8606 else {
8607 /* wrong return value */
8608 PyErr_SetString(PyExc_TypeError,
8609 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00008610 Py_DECREF(x);
8611 return -1;
8612 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008613}
8614/* ensure that *outobj is at least requiredsize characters long,
Benjamin Peterson29060642009-01-31 22:14:21 +00008615 if not reallocate and adjust various state variables.
8616 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008617static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008618charmaptranslate_makespace(Py_UCS4 **outobj, Py_ssize_t *psize,
Benjamin Peterson29060642009-01-31 22:14:21 +00008619 Py_ssize_t requiredsize)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008620{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008621 Py_ssize_t oldsize = *psize;
Walter Dörwald4894c302003-10-24 14:25:28 +00008622 if (requiredsize > oldsize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008623 /* exponentially overallocate to minimize reallocations */
8624 if (requiredsize < 2 * oldsize)
8625 requiredsize = 2 * oldsize;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008626 *outobj = PyMem_Realloc(*outobj, requiredsize * sizeof(Py_UCS4));
8627 if (*outobj == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008628 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008629 *psize = requiredsize;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008630 }
8631 return 0;
8632}
8633/* lookup the character, put the result in the output string and adjust
8634 various state variables. Return a new reference to the object that
8635 was put in the output buffer in *result, or Py_None, if the mapping was
8636 undefined (in which case no character was written).
8637 The called must decref result.
8638 Return 0 on success, -1 on error. */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008639static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008640charmaptranslate_output(PyObject *input, Py_ssize_t ipos,
8641 PyObject *mapping, Py_UCS4 **output,
8642 Py_ssize_t *osize, Py_ssize_t *opos,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008643 PyObject **res)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008644{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008645 Py_UCS4 curinp = PyUnicode_READ_CHAR(input, ipos);
8646 if (charmaptranslate_lookup(curinp, mapping, res))
Benjamin Peterson29060642009-01-31 22:14:21 +00008647 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008648 if (*res==NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008649 /* not found => default to 1:1 mapping */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008650 (*output)[(*opos)++] = curinp;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008651 }
8652 else if (*res==Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008653 ;
Christian Heimes217cfd12007-12-02 14:31:20 +00008654 else if (PyLong_Check(*res)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008655 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008656 (*output)[(*opos)++] = (Py_UCS4)PyLong_AS_LONG(*res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008657 }
8658 else if (PyUnicode_Check(*res)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008659 Py_ssize_t repsize;
8660 if (PyUnicode_READY(*res) == -1)
8661 return -1;
8662 repsize = PyUnicode_GET_LENGTH(*res);
Benjamin Peterson29060642009-01-31 22:14:21 +00008663 if (repsize==1) {
8664 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008665 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +00008666 }
8667 else if (repsize!=0) {
8668 /* more than one character */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008669 Py_ssize_t requiredsize = *opos +
8670 (PyUnicode_GET_LENGTH(input) - ipos) +
Benjamin Peterson29060642009-01-31 22:14:21 +00008671 repsize - 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008672 Py_ssize_t i;
8673 if (charmaptranslate_makespace(output, osize, requiredsize))
Benjamin Peterson29060642009-01-31 22:14:21 +00008674 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008675 for(i = 0; i < repsize; i++)
8676 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00008677 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008678 }
8679 else
Benjamin Peterson29060642009-01-31 22:14:21 +00008680 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008681 return 0;
8682}
8683
Alexander Belopolsky40018472011-02-26 01:02:56 +00008684PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008685_PyUnicode_TranslateCharmap(PyObject *input,
8686 PyObject *mapping,
8687 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008688{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008689 /* input object */
8690 char *idata;
8691 Py_ssize_t size, i;
8692 int kind;
8693 /* output buffer */
8694 Py_UCS4 *output = NULL;
8695 Py_ssize_t osize;
8696 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008697 /* current output position */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008698 Py_ssize_t opos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008699 char *reason = "character maps to <undefined>";
8700 PyObject *errorHandler = NULL;
8701 PyObject *exc = NULL;
8702 /* the following variable is used for caching string comparisons
8703 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8704 * 3=ignore, 4=xmlcharrefreplace */
8705 int known_errorHandler = -1;
8706
Guido van Rossumd57fd912000-03-10 22:53:23 +00008707 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008708 PyErr_BadArgument();
8709 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008710 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008711
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008712 if (PyUnicode_READY(input) == -1)
8713 return NULL;
8714 idata = (char*)PyUnicode_DATA(input);
8715 kind = PyUnicode_KIND(input);
8716 size = PyUnicode_GET_LENGTH(input);
8717 i = 0;
8718
8719 if (size == 0) {
8720 Py_INCREF(input);
8721 return input;
8722 }
8723
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008724 /* allocate enough for a simple 1:1 translation without
8725 replacements, if we need more, we'll resize */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008726 osize = size;
8727 output = PyMem_Malloc(osize * sizeof(Py_UCS4));
8728 opos = 0;
8729 if (output == NULL) {
8730 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00008731 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008732 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008733
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008734 while (i<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008735 /* try to encode it */
8736 PyObject *x = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008737 if (charmaptranslate_output(input, i, mapping,
8738 &output, &osize, &opos, &x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008739 Py_XDECREF(x);
8740 goto onError;
8741 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008742 Py_XDECREF(x);
Benjamin Peterson29060642009-01-31 22:14:21 +00008743 if (x!=Py_None) /* it worked => adjust input pointer */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008744 ++i;
Benjamin Peterson29060642009-01-31 22:14:21 +00008745 else { /* untranslatable character */
8746 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
8747 Py_ssize_t repsize;
8748 Py_ssize_t newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008749 Py_ssize_t uni2;
Benjamin Peterson29060642009-01-31 22:14:21 +00008750 /* startpos for collecting untranslatable chars */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008751 Py_ssize_t collstart = i;
8752 Py_ssize_t collend = i+1;
8753 Py_ssize_t coll;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008754
Benjamin Peterson29060642009-01-31 22:14:21 +00008755 /* find all untranslatable characters */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008756 while (collend < size) {
8757 if (charmaptranslate_lookup(PyUnicode_READ(kind,idata, collend), mapping, &x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008758 goto onError;
8759 Py_XDECREF(x);
8760 if (x!=Py_None)
8761 break;
8762 ++collend;
8763 }
8764 /* cache callback name lookup
8765 * (if not done yet, i.e. it's the first error) */
8766 if (known_errorHandler==-1) {
8767 if ((errors==NULL) || (!strcmp(errors, "strict")))
8768 known_errorHandler = 1;
8769 else if (!strcmp(errors, "replace"))
8770 known_errorHandler = 2;
8771 else if (!strcmp(errors, "ignore"))
8772 known_errorHandler = 3;
8773 else if (!strcmp(errors, "xmlcharrefreplace"))
8774 known_errorHandler = 4;
8775 else
8776 known_errorHandler = 0;
8777 }
8778 switch (known_errorHandler) {
8779 case 1: /* strict */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008780 raise_translate_exception(&exc, input, collstart,
8781 collend, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008782 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00008783 case 2: /* replace */
8784 /* No need to check for space, this is a 1:1 replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008785 for (coll = collstart; coll<collend; coll++)
8786 output[opos++] = '?';
Benjamin Peterson29060642009-01-31 22:14:21 +00008787 /* fall through */
8788 case 3: /* ignore */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008789 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008790 break;
8791 case 4: /* xmlcharrefreplace */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008792 /* generate replacement (temporarily (mis)uses i) */
8793 for (i = collstart; i < collend; ++i) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008794 char buffer[2+29+1+1];
8795 char *cp;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008796 sprintf(buffer, "&#%d;", PyUnicode_READ(kind, idata, i));
8797 if (charmaptranslate_makespace(&output, &osize,
8798 opos+strlen(buffer)+(size-collend)))
Benjamin Peterson29060642009-01-31 22:14:21 +00008799 goto onError;
8800 for (cp = buffer; *cp; ++cp)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008801 output[opos++] = *cp;
Benjamin Peterson29060642009-01-31 22:14:21 +00008802 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008803 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008804 break;
8805 default:
8806 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008807 reason, input, &exc,
8808 collstart, collend, &newpos);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008809 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008810 goto onError;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008811 if (PyUnicode_READY(repunicode) < 0) {
8812 Py_DECREF(repunicode);
8813 goto onError;
8814 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008815 /* generate replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008816 repsize = PyUnicode_GET_LENGTH(repunicode);
8817 if (charmaptranslate_makespace(&output, &osize,
8818 opos+repsize+(size-collend))) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008819 Py_DECREF(repunicode);
8820 goto onError;
8821 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008822 for (uni2 = 0; repsize-->0; ++uni2)
8823 output[opos++] = PyUnicode_READ_CHAR(repunicode, uni2);
8824 i = newpos;
Benjamin Peterson29060642009-01-31 22:14:21 +00008825 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008826 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008827 }
8828 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008829 res = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND, output, opos);
8830 if (!res)
8831 goto onError;
8832 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008833 Py_XDECREF(exc);
8834 Py_XDECREF(errorHandler);
8835 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008836
Benjamin Peterson29060642009-01-31 22:14:21 +00008837 onError:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008838 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008839 Py_XDECREF(exc);
8840 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008841 return NULL;
8842}
8843
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008844/* Deprecated. Use PyUnicode_Translate instead. */
8845PyObject *
8846PyUnicode_TranslateCharmap(const Py_UNICODE *p,
8847 Py_ssize_t size,
8848 PyObject *mapping,
8849 const char *errors)
8850{
8851 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8852 if (!unicode)
8853 return NULL;
8854 return _PyUnicode_TranslateCharmap(unicode, mapping, errors);
8855}
8856
Alexander Belopolsky40018472011-02-26 01:02:56 +00008857PyObject *
8858PyUnicode_Translate(PyObject *str,
8859 PyObject *mapping,
8860 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008861{
8862 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +00008863
Guido van Rossumd57fd912000-03-10 22:53:23 +00008864 str = PyUnicode_FromObject(str);
8865 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008866 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008867 result = _PyUnicode_TranslateCharmap(str, mapping, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008868 Py_DECREF(str);
8869 return result;
Tim Petersced69f82003-09-16 20:30:58 +00008870
Benjamin Peterson29060642009-01-31 22:14:21 +00008871 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00008872 Py_XDECREF(str);
8873 return NULL;
8874}
Tim Petersced69f82003-09-16 20:30:58 +00008875
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008876static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02008877fix_decimal_and_space_to_ascii(PyObject *self)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008878{
8879 /* No need to call PyUnicode_READY(self) because this function is only
8880 called as a callback from fixup() which does it already. */
8881 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
8882 const int kind = PyUnicode_KIND(self);
8883 void *data = PyUnicode_DATA(self);
8884 Py_UCS4 maxchar = 0, ch, fixed;
8885 Py_ssize_t i;
8886
8887 for (i = 0; i < len; ++i) {
8888 ch = PyUnicode_READ(kind, data, i);
8889 fixed = 0;
8890 if (ch > 127) {
8891 if (Py_UNICODE_ISSPACE(ch))
8892 fixed = ' ';
8893 else {
8894 const int decimal = Py_UNICODE_TODECIMAL(ch);
8895 if (decimal >= 0)
8896 fixed = '0' + decimal;
8897 }
8898 if (fixed != 0) {
8899 if (fixed > maxchar)
8900 maxchar = fixed;
8901 PyUnicode_WRITE(kind, data, i, fixed);
8902 }
8903 else if (ch > maxchar)
8904 maxchar = ch;
8905 }
8906 else if (ch > maxchar)
8907 maxchar = ch;
8908 }
8909
8910 return maxchar;
8911}
8912
8913PyObject *
8914_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
8915{
8916 if (!PyUnicode_Check(unicode)) {
8917 PyErr_BadInternalCall();
8918 return NULL;
8919 }
8920 if (PyUnicode_READY(unicode) == -1)
8921 return NULL;
8922 if (PyUnicode_MAX_CHAR_VALUE(unicode) <= 127) {
8923 /* If the string is already ASCII, just return the same string */
8924 Py_INCREF(unicode);
8925 return unicode;
8926 }
Victor Stinner9310abb2011-10-05 00:59:23 +02008927 return fixup(unicode, fix_decimal_and_space_to_ascii);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008928}
8929
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008930PyObject *
8931PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
8932 Py_ssize_t length)
8933{
Victor Stinnerf0124502011-11-21 23:12:56 +01008934 PyObject *decimal;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008935 Py_ssize_t i;
Victor Stinnerf0124502011-11-21 23:12:56 +01008936 Py_UCS4 maxchar;
8937 enum PyUnicode_Kind kind;
8938 void *data;
8939
8940 maxchar = 0;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008941 for (i = 0; i < length; i++) {
Victor Stinnerf0124502011-11-21 23:12:56 +01008942 Py_UNICODE ch = s[i];
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008943 if (ch > 127) {
8944 int decimal = Py_UNICODE_TODECIMAL(ch);
8945 if (decimal >= 0)
Victor Stinnerf0124502011-11-21 23:12:56 +01008946 ch = '0' + decimal;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008947 }
Victor Stinnerf0124502011-11-21 23:12:56 +01008948 maxchar = Py_MAX(maxchar, ch);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008949 }
Victor Stinnerf0124502011-11-21 23:12:56 +01008950
8951 /* Copy to a new string */
8952 decimal = PyUnicode_New(length, maxchar);
8953 if (decimal == NULL)
8954 return decimal;
8955 kind = PyUnicode_KIND(decimal);
8956 data = PyUnicode_DATA(decimal);
8957 /* Iterate over code points */
8958 for (i = 0; i < length; i++) {
8959 Py_UNICODE ch = s[i];
8960 if (ch > 127) {
8961 int decimal = Py_UNICODE_TODECIMAL(ch);
8962 if (decimal >= 0)
8963 ch = '0' + decimal;
8964 }
8965 PyUnicode_WRITE(kind, data, i, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008966 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008967 return unicode_result(decimal);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008968}
Guido van Rossum9e896b32000-04-05 20:11:21 +00008969/* --- Decimal Encoder ---------------------------------------------------- */
8970
Alexander Belopolsky40018472011-02-26 01:02:56 +00008971int
8972PyUnicode_EncodeDecimal(Py_UNICODE *s,
8973 Py_ssize_t length,
8974 char *output,
8975 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00008976{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008977 PyObject *unicode;
Victor Stinner6345be92011-11-25 20:09:01 +01008978 Py_ssize_t i;
Victor Stinner42bf7752011-11-21 22:52:58 +01008979 enum PyUnicode_Kind kind;
8980 void *data;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008981
8982 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008983 PyErr_BadArgument();
8984 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008985 }
8986
Victor Stinner42bf7752011-11-21 22:52:58 +01008987 unicode = PyUnicode_FromUnicode(s, length);
8988 if (unicode == NULL)
8989 return -1;
8990
Victor Stinner6345be92011-11-25 20:09:01 +01008991 if (PyUnicode_READY(unicode) < 0) {
8992 Py_DECREF(unicode);
8993 return -1;
8994 }
Victor Stinner42bf7752011-11-21 22:52:58 +01008995 kind = PyUnicode_KIND(unicode);
8996 data = PyUnicode_DATA(unicode);
8997
Victor Stinnerb84d7232011-11-22 01:50:07 +01008998 for (i=0; i < length; ) {
Victor Stinner6345be92011-11-25 20:09:01 +01008999 PyObject *exc;
9000 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00009001 int decimal;
Victor Stinner6345be92011-11-25 20:09:01 +01009002 Py_ssize_t startpos;
9003
9004 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +00009005
Benjamin Peterson29060642009-01-31 22:14:21 +00009006 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009007 *output++ = ' ';
Victor Stinnerb84d7232011-11-22 01:50:07 +01009008 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009009 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009010 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009011 decimal = Py_UNICODE_TODECIMAL(ch);
9012 if (decimal >= 0) {
9013 *output++ = '0' + decimal;
Victor Stinnerb84d7232011-11-22 01:50:07 +01009014 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009015 continue;
9016 }
9017 if (0 < ch && ch < 256) {
9018 *output++ = (char)ch;
Victor Stinnerb84d7232011-11-22 01:50:07 +01009019 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009020 continue;
9021 }
Victor Stinner6345be92011-11-25 20:09:01 +01009022
Victor Stinner42bf7752011-11-21 22:52:58 +01009023 startpos = i;
Victor Stinner6345be92011-11-25 20:09:01 +01009024 exc = NULL;
9025 raise_encode_exception(&exc, "decimal", unicode,
9026 startpos, startpos+1,
9027 "invalid decimal Unicode string");
9028 Py_XDECREF(exc);
9029 Py_DECREF(unicode);
9030 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009031 }
9032 /* 0-terminate the output string */
9033 *output++ = '\0';
Victor Stinner42bf7752011-11-21 22:52:58 +01009034 Py_DECREF(unicode);
Guido van Rossum9e896b32000-04-05 20:11:21 +00009035 return 0;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009036}
9037
Guido van Rossumd57fd912000-03-10 22:53:23 +00009038/* --- Helpers ------------------------------------------------------------ */
9039
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009040static Py_ssize_t
Victor Stinner794d5672011-10-10 03:21:36 +02009041any_find_slice(int direction, PyObject* s1, PyObject* s2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009042 Py_ssize_t start,
9043 Py_ssize_t end)
9044{
9045 int kind1, kind2, kind;
9046 void *buf1, *buf2;
9047 Py_ssize_t len1, len2, result;
9048
9049 kind1 = PyUnicode_KIND(s1);
9050 kind2 = PyUnicode_KIND(s2);
9051 kind = kind1 > kind2 ? kind1 : kind2;
9052 buf1 = PyUnicode_DATA(s1);
9053 buf2 = PyUnicode_DATA(s2);
9054 if (kind1 != kind)
9055 buf1 = _PyUnicode_AsKind(s1, kind);
9056 if (!buf1)
9057 return -2;
9058 if (kind2 != kind)
9059 buf2 = _PyUnicode_AsKind(s2, kind);
9060 if (!buf2) {
9061 if (kind1 != kind) PyMem_Free(buf1);
9062 return -2;
9063 }
9064 len1 = PyUnicode_GET_LENGTH(s1);
9065 len2 = PyUnicode_GET_LENGTH(s2);
9066
Victor Stinner794d5672011-10-10 03:21:36 +02009067 if (direction > 0) {
9068 switch(kind) {
9069 case PyUnicode_1BYTE_KIND:
9070 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9071 result = asciilib_find_slice(buf1, len1, buf2, len2, start, end);
9072 else
9073 result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end);
9074 break;
9075 case PyUnicode_2BYTE_KIND:
9076 result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end);
9077 break;
9078 case PyUnicode_4BYTE_KIND:
9079 result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end);
9080 break;
9081 default:
9082 assert(0); result = -2;
9083 }
9084 }
9085 else {
9086 switch(kind) {
9087 case PyUnicode_1BYTE_KIND:
9088 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9089 result = asciilib_rfind_slice(buf1, len1, buf2, len2, start, end);
9090 else
9091 result = ucs1lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9092 break;
9093 case PyUnicode_2BYTE_KIND:
9094 result = ucs2lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9095 break;
9096 case PyUnicode_4BYTE_KIND:
9097 result = ucs4lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9098 break;
9099 default:
9100 assert(0); result = -2;
9101 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009102 }
9103
9104 if (kind1 != kind)
9105 PyMem_Free(buf1);
9106 if (kind2 != kind)
9107 PyMem_Free(buf2);
9108
9109 return result;
9110}
9111
9112Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +02009113_PyUnicode_InsertThousandsGrouping(PyObject *unicode, int kind, void *data,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009114 Py_ssize_t n_buffer,
9115 void *digits, Py_ssize_t n_digits,
9116 Py_ssize_t min_width,
9117 const char *grouping,
9118 const char *thousands_sep)
9119{
9120 switch(kind) {
9121 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009122 if (unicode != NULL && PyUnicode_IS_ASCII(unicode))
9123 return _PyUnicode_ascii_InsertThousandsGrouping(
9124 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
9125 min_width, grouping, thousands_sep);
9126 else
9127 return _PyUnicode_ucs1_InsertThousandsGrouping(
9128 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
9129 min_width, grouping, thousands_sep);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009130 case PyUnicode_2BYTE_KIND:
9131 return _PyUnicode_ucs2_InsertThousandsGrouping(
9132 (Py_UCS2*)data, n_buffer, (Py_UCS2*)digits, n_digits,
9133 min_width, grouping, thousands_sep);
9134 case PyUnicode_4BYTE_KIND:
9135 return _PyUnicode_ucs4_InsertThousandsGrouping(
9136 (Py_UCS4*)data, n_buffer, (Py_UCS4*)digits, n_digits,
9137 min_width, grouping, thousands_sep);
9138 }
9139 assert(0);
9140 return -1;
9141}
9142
9143
Thomas Wouters477c8d52006-05-27 19:21:47 +00009144/* helper macro to fixup start/end slice values */
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009145#define ADJUST_INDICES(start, end, len) \
9146 if (end > len) \
9147 end = len; \
9148 else if (end < 0) { \
9149 end += len; \
9150 if (end < 0) \
9151 end = 0; \
9152 } \
9153 if (start < 0) { \
9154 start += len; \
9155 if (start < 0) \
9156 start = 0; \
9157 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009158
Alexander Belopolsky40018472011-02-26 01:02:56 +00009159Py_ssize_t
9160PyUnicode_Count(PyObject *str,
9161 PyObject *substr,
9162 Py_ssize_t start,
9163 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009164{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009165 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009166 PyObject* str_obj;
9167 PyObject* sub_obj;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009168 int kind1, kind2, kind;
9169 void *buf1 = NULL, *buf2 = NULL;
9170 Py_ssize_t len1, len2;
Tim Petersced69f82003-09-16 20:30:58 +00009171
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009172 str_obj = PyUnicode_FromObject(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009173 if (!str_obj || PyUnicode_READY(str_obj) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00009174 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009175 sub_obj = PyUnicode_FromObject(substr);
Victor Stinnere9a29352011-10-01 02:14:59 +02009176 if (!sub_obj || PyUnicode_READY(sub_obj) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009177 Py_DECREF(str_obj);
9178 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009179 }
Tim Petersced69f82003-09-16 20:30:58 +00009180
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009181 kind1 = PyUnicode_KIND(str_obj);
9182 kind2 = PyUnicode_KIND(sub_obj);
9183 kind = kind1 > kind2 ? kind1 : kind2;
9184 buf1 = PyUnicode_DATA(str_obj);
9185 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009186 buf1 = _PyUnicode_AsKind(str_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009187 if (!buf1)
9188 goto onError;
9189 buf2 = PyUnicode_DATA(sub_obj);
9190 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009191 buf2 = _PyUnicode_AsKind(sub_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009192 if (!buf2)
9193 goto onError;
9194 len1 = PyUnicode_GET_LENGTH(str_obj);
9195 len2 = PyUnicode_GET_LENGTH(sub_obj);
9196
9197 ADJUST_INDICES(start, end, len1);
9198 switch(kind) {
9199 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009200 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sub_obj))
9201 result = asciilib_count(
9202 ((Py_UCS1*)buf1) + start, end - start,
9203 buf2, len2, PY_SSIZE_T_MAX
9204 );
9205 else
9206 result = ucs1lib_count(
9207 ((Py_UCS1*)buf1) + start, end - start,
9208 buf2, len2, PY_SSIZE_T_MAX
9209 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009210 break;
9211 case PyUnicode_2BYTE_KIND:
9212 result = ucs2lib_count(
9213 ((Py_UCS2*)buf1) + start, end - start,
9214 buf2, len2, PY_SSIZE_T_MAX
9215 );
9216 break;
9217 case PyUnicode_4BYTE_KIND:
9218 result = ucs4lib_count(
9219 ((Py_UCS4*)buf1) + start, end - start,
9220 buf2, len2, PY_SSIZE_T_MAX
9221 );
9222 break;
9223 default:
9224 assert(0); result = 0;
9225 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009226
9227 Py_DECREF(sub_obj);
9228 Py_DECREF(str_obj);
9229
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009230 if (kind1 != kind)
9231 PyMem_Free(buf1);
9232 if (kind2 != kind)
9233 PyMem_Free(buf2);
9234
Guido van Rossumd57fd912000-03-10 22:53:23 +00009235 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009236 onError:
9237 Py_DECREF(sub_obj);
9238 Py_DECREF(str_obj);
9239 if (kind1 != kind && buf1)
9240 PyMem_Free(buf1);
9241 if (kind2 != kind && buf2)
9242 PyMem_Free(buf2);
9243 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009244}
9245
Alexander Belopolsky40018472011-02-26 01:02:56 +00009246Py_ssize_t
9247PyUnicode_Find(PyObject *str,
9248 PyObject *sub,
9249 Py_ssize_t start,
9250 Py_ssize_t end,
9251 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009252{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009253 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009254
Guido van Rossumd57fd912000-03-10 22:53:23 +00009255 str = PyUnicode_FromObject(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009256 if (!str || PyUnicode_READY(str) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00009257 return -2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009258 sub = PyUnicode_FromObject(sub);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009259 if (!sub || PyUnicode_READY(sub) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009260 Py_DECREF(str);
9261 return -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009262 }
Tim Petersced69f82003-09-16 20:30:58 +00009263
Victor Stinner794d5672011-10-10 03:21:36 +02009264 result = any_find_slice(direction,
9265 str, sub, start, end
9266 );
Thomas Wouters477c8d52006-05-27 19:21:47 +00009267
Guido van Rossumd57fd912000-03-10 22:53:23 +00009268 Py_DECREF(str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009269 Py_DECREF(sub);
9270
Guido van Rossumd57fd912000-03-10 22:53:23 +00009271 return result;
9272}
9273
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009274Py_ssize_t
9275PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
9276 Py_ssize_t start, Py_ssize_t end,
9277 int direction)
9278{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009279 int kind;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009280 Py_ssize_t result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009281 if (PyUnicode_READY(str) == -1)
9282 return -2;
Victor Stinner267aa242011-10-02 01:08:37 +02009283 if (start < 0 || end < 0) {
9284 PyErr_SetString(PyExc_IndexError, "string index out of range");
9285 return -2;
9286 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009287 if (end > PyUnicode_GET_LENGTH(str))
9288 end = PyUnicode_GET_LENGTH(str);
9289 kind = PyUnicode_KIND(str);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009290 result = findchar(PyUnicode_1BYTE_DATA(str) + kind*start,
9291 kind, end-start, ch, direction);
9292 if (result == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009293 return -1;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009294 else
9295 return start + result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009296}
9297
Alexander Belopolsky40018472011-02-26 01:02:56 +00009298static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009299tailmatch(PyObject *self,
9300 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009301 Py_ssize_t start,
9302 Py_ssize_t end,
9303 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009304{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009305 int kind_self;
9306 int kind_sub;
9307 void *data_self;
9308 void *data_sub;
9309 Py_ssize_t offset;
9310 Py_ssize_t i;
9311 Py_ssize_t end_sub;
9312
9313 if (PyUnicode_READY(self) == -1 ||
9314 PyUnicode_READY(substring) == -1)
9315 return 0;
9316
9317 if (PyUnicode_GET_LENGTH(substring) == 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009318 return 1;
9319
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009320 ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
9321 end -= PyUnicode_GET_LENGTH(substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009322 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00009323 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009324
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009325 kind_self = PyUnicode_KIND(self);
9326 data_self = PyUnicode_DATA(self);
9327 kind_sub = PyUnicode_KIND(substring);
9328 data_sub = PyUnicode_DATA(substring);
9329 end_sub = PyUnicode_GET_LENGTH(substring) - 1;
9330
9331 if (direction > 0)
9332 offset = end;
9333 else
9334 offset = start;
9335
9336 if (PyUnicode_READ(kind_self, data_self, offset) ==
9337 PyUnicode_READ(kind_sub, data_sub, 0) &&
9338 PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
9339 PyUnicode_READ(kind_sub, data_sub, end_sub)) {
9340 /* If both are of the same kind, memcmp is sufficient */
9341 if (kind_self == kind_sub) {
9342 return ! memcmp((char *)data_self +
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009343 (offset * PyUnicode_KIND(substring)),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009344 data_sub,
9345 PyUnicode_GET_LENGTH(substring) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009346 PyUnicode_KIND(substring));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009347 }
9348 /* otherwise we have to compare each character by first accesing it */
9349 else {
9350 /* We do not need to compare 0 and len(substring)-1 because
9351 the if statement above ensured already that they are equal
9352 when we end up here. */
9353 // TODO: honor direction and do a forward or backwards search
9354 for (i = 1; i < end_sub; ++i) {
9355 if (PyUnicode_READ(kind_self, data_self, offset + i) !=
9356 PyUnicode_READ(kind_sub, data_sub, i))
9357 return 0;
9358 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009359 return 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009360 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009361 }
9362
9363 return 0;
9364}
9365
Alexander Belopolsky40018472011-02-26 01:02:56 +00009366Py_ssize_t
9367PyUnicode_Tailmatch(PyObject *str,
9368 PyObject *substr,
9369 Py_ssize_t start,
9370 Py_ssize_t end,
9371 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009372{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009373 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009374
Guido van Rossumd57fd912000-03-10 22:53:23 +00009375 str = PyUnicode_FromObject(str);
9376 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009377 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009378 substr = PyUnicode_FromObject(substr);
9379 if (substr == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009380 Py_DECREF(str);
9381 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009382 }
Tim Petersced69f82003-09-16 20:30:58 +00009383
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009384 result = tailmatch(str, substr,
Benjamin Peterson29060642009-01-31 22:14:21 +00009385 start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009386 Py_DECREF(str);
9387 Py_DECREF(substr);
9388 return result;
9389}
9390
Guido van Rossumd57fd912000-03-10 22:53:23 +00009391/* Apply fixfct filter to the Unicode object self and return a
9392 reference to the modified object */
9393
Alexander Belopolsky40018472011-02-26 01:02:56 +00009394static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009395fixup(PyObject *self,
9396 Py_UCS4 (*fixfct)(PyObject *s))
Guido van Rossumd57fd912000-03-10 22:53:23 +00009397{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009398 PyObject *u;
9399 Py_UCS4 maxchar_old, maxchar_new = 0;
Victor Stinnereaab6042011-12-11 22:22:39 +01009400 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009401
Victor Stinnerbf6e5602011-12-12 01:53:47 +01009402 u = _PyUnicode_Copy(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009403 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009404 return NULL;
Victor Stinner87af4f22011-11-21 23:03:47 +01009405 maxchar_old = PyUnicode_MAX_CHAR_VALUE(u);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009406
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009407 /* fix functions return the new maximum character in a string,
9408 if the kind of the resulting unicode object does not change,
9409 everything is fine. Otherwise we need to change the string kind
9410 and re-run the fix function. */
Victor Stinner9310abb2011-10-05 00:59:23 +02009411 maxchar_new = fixfct(u);
Victor Stinnereaab6042011-12-11 22:22:39 +01009412
9413 if (maxchar_new == 0) {
9414 /* no changes */;
9415 if (PyUnicode_CheckExact(self)) {
9416 Py_DECREF(u);
9417 Py_INCREF(self);
9418 return self;
9419 }
9420 else
9421 return u;
9422 }
9423
9424 if (maxchar_new <= 127)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009425 maxchar_new = 127;
9426 else if (maxchar_new <= 255)
9427 maxchar_new = 255;
9428 else if (maxchar_new <= 65535)
9429 maxchar_new = 65535;
9430 else
Victor Stinner8faf8212011-12-08 22:14:11 +01009431 maxchar_new = MAX_UNICODE;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009432
Victor Stinnereaab6042011-12-11 22:22:39 +01009433 if (maxchar_new == maxchar_old)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009434 return u;
Victor Stinnereaab6042011-12-11 22:22:39 +01009435
9436 /* In case the maximum character changed, we need to
9437 convert the string to the new category. */
9438 v = PyUnicode_New(PyUnicode_GET_LENGTH(self), maxchar_new);
9439 if (v == NULL) {
9440 Py_DECREF(u);
9441 return NULL;
9442 }
9443 if (maxchar_new > maxchar_old) {
9444 /* If the maxchar increased so that the kind changed, not all
9445 characters are representable anymore and we need to fix the
9446 string again. This only happens in very few cases. */
9447 copy_characters(v, 0, self, 0, PyUnicode_GET_LENGTH(self));
9448 maxchar_old = fixfct(v);
9449 assert(maxchar_old > 0 && maxchar_old <= maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009450 }
9451 else {
Victor Stinnereaab6042011-12-11 22:22:39 +01009452 copy_characters(v, 0, u, 0, PyUnicode_GET_LENGTH(self));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009453 }
Victor Stinnereaab6042011-12-11 22:22:39 +01009454 Py_DECREF(u);
9455 assert(_PyUnicode_CheckConsistency(v, 1));
9456 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009457}
9458
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009459static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009460fixupper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009461{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009462 /* No need to call PyUnicode_READY(self) because this function is only
9463 called as a callback from fixup() which does it already. */
9464 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9465 const int kind = PyUnicode_KIND(self);
9466 void *data = PyUnicode_DATA(self);
9467 int touched = 0;
9468 Py_UCS4 maxchar = 0;
9469 Py_ssize_t i;
Tim Petersced69f82003-09-16 20:30:58 +00009470
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009471 for (i = 0; i < len; ++i) {
9472 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9473 const Py_UCS4 up = Py_UNICODE_TOUPPER(ch);
9474 if (up != ch) {
9475 if (up > maxchar)
9476 maxchar = up;
9477 PyUnicode_WRITE(kind, data, i, up);
9478 touched = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00009479 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009480 else if (ch > maxchar)
9481 maxchar = ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009482 }
9483
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009484 if (touched)
9485 return maxchar;
9486 else
9487 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009488}
9489
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009490static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009491fixlower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009492{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009493 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
9494 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9495 const int kind = PyUnicode_KIND(self);
9496 void *data = PyUnicode_DATA(self);
9497 int touched = 0;
9498 Py_UCS4 maxchar = 0;
9499 Py_ssize_t i;
Tim Petersced69f82003-09-16 20:30:58 +00009500
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009501 for(i = 0; i < len; ++i) {
9502 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9503 const Py_UCS4 lo = Py_UNICODE_TOLOWER(ch);
9504 if (lo != ch) {
9505 if (lo > maxchar)
9506 maxchar = lo;
9507 PyUnicode_WRITE(kind, data, i, lo);
9508 touched = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00009509 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009510 else if (ch > maxchar)
9511 maxchar = ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009512 }
9513
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009514 if (touched)
9515 return maxchar;
9516 else
9517 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009518}
9519
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009520static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009521fixswapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009522{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009523 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
9524 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9525 const int kind = PyUnicode_KIND(self);
9526 void *data = PyUnicode_DATA(self);
9527 int touched = 0;
9528 Py_UCS4 maxchar = 0;
9529 Py_ssize_t i;
Tim Petersced69f82003-09-16 20:30:58 +00009530
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009531 for(i = 0; i < len; ++i) {
9532 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9533 Py_UCS4 nu = 0;
9534
9535 if (Py_UNICODE_ISUPPER(ch))
9536 nu = Py_UNICODE_TOLOWER(ch);
9537 else if (Py_UNICODE_ISLOWER(ch))
9538 nu = Py_UNICODE_TOUPPER(ch);
9539
9540 if (nu != 0) {
9541 if (nu > maxchar)
9542 maxchar = nu;
9543 PyUnicode_WRITE(kind, data, i, nu);
9544 touched = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009545 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009546 else if (ch > maxchar)
9547 maxchar = ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009548 }
9549
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009550 if (touched)
9551 return maxchar;
9552 else
9553 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009554}
9555
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009556static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009557fixcapitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009558{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009559 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
9560 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9561 const int kind = PyUnicode_KIND(self);
9562 void *data = PyUnicode_DATA(self);
9563 int touched = 0;
9564 Py_UCS4 maxchar = 0;
9565 Py_ssize_t i = 0;
9566 Py_UCS4 ch;
Tim Petersced69f82003-09-16 20:30:58 +00009567
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009568 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009569 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009570
9571 ch = PyUnicode_READ(kind, data, i);
9572 if (!Py_UNICODE_ISUPPER(ch)) {
9573 maxchar = Py_UNICODE_TOUPPER(ch);
9574 PyUnicode_WRITE(kind, data, i, maxchar);
9575 touched = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009576 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009577 ++i;
9578 for(; i < len; ++i) {
9579 ch = PyUnicode_READ(kind, data, i);
9580 if (!Py_UNICODE_ISLOWER(ch)) {
9581 const Py_UCS4 lo = Py_UNICODE_TOLOWER(ch);
9582 if (lo > maxchar)
9583 maxchar = lo;
9584 PyUnicode_WRITE(kind, data, i, lo);
9585 touched = 1;
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009586 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009587 else if (ch > maxchar)
9588 maxchar = ch;
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009589 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009590
9591 if (touched)
9592 return maxchar;
9593 else
9594 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009595}
9596
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009597static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009598fixtitle(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009599{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009600 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
9601 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9602 const int kind = PyUnicode_KIND(self);
9603 void *data = PyUnicode_DATA(self);
9604 Py_UCS4 maxchar = 0;
9605 Py_ssize_t i = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009606 int previous_is_cased;
9607
9608 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009609 if (len == 1) {
9610 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9611 const Py_UCS4 ti = Py_UNICODE_TOTITLE(ch);
9612 if (ti != ch) {
9613 PyUnicode_WRITE(kind, data, i, ti);
9614 return ti;
Benjamin Peterson29060642009-01-31 22:14:21 +00009615 }
9616 else
9617 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009618 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009619 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009620 for(; i < len; ++i) {
9621 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9622 Py_UCS4 nu;
Tim Petersced69f82003-09-16 20:30:58 +00009623
Benjamin Peterson29060642009-01-31 22:14:21 +00009624 if (previous_is_cased)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009625 nu = Py_UNICODE_TOLOWER(ch);
Benjamin Peterson29060642009-01-31 22:14:21 +00009626 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009627 nu = Py_UNICODE_TOTITLE(ch);
9628
9629 if (nu > maxchar)
9630 maxchar = nu;
9631 PyUnicode_WRITE(kind, data, i, nu);
Tim Petersced69f82003-09-16 20:30:58 +00009632
Benjamin Peterson29060642009-01-31 22:14:21 +00009633 if (Py_UNICODE_ISLOWER(ch) ||
9634 Py_UNICODE_ISUPPER(ch) ||
9635 Py_UNICODE_ISTITLE(ch))
9636 previous_is_cased = 1;
9637 else
9638 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009639 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009640 return maxchar;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009641}
9642
Tim Peters8ce9f162004-08-27 01:49:32 +00009643PyObject *
9644PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009645{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009646 PyObject *sep = NULL;
Victor Stinnerdd077322011-10-07 17:02:31 +02009647 Py_ssize_t seplen;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009648 PyObject *res = NULL; /* the result */
Tim Peters05eba1f2004-08-27 21:32:02 +00009649 PyObject *fseq; /* PySequence_Fast(seq) */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009650 Py_ssize_t seqlen; /* len(fseq) -- number of items in sequence */
9651 PyObject **items;
Tim Peters8ce9f162004-08-27 01:49:32 +00009652 PyObject *item;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009653 Py_ssize_t sz, i, res_offset;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009654 Py_UCS4 maxchar;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009655 Py_UCS4 item_maxchar;
Victor Stinnerdd077322011-10-07 17:02:31 +02009656 int use_memcpy;
9657 unsigned char *res_data = NULL, *sep_data = NULL;
9658 PyObject *last_obj;
9659 unsigned int kind = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009660
Tim Peters05eba1f2004-08-27 21:32:02 +00009661 fseq = PySequence_Fast(seq, "");
9662 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009663 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00009664 }
9665
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009666 /* NOTE: the following code can't call back into Python code,
9667 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00009668 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009669
Tim Peters05eba1f2004-08-27 21:32:02 +00009670 seqlen = PySequence_Fast_GET_SIZE(fseq);
9671 /* If empty sequence, return u"". */
9672 if (seqlen == 0) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009673 Py_DECREF(fseq);
9674 Py_INCREF(unicode_empty);
9675 res = unicode_empty;
9676 return res;
Tim Peters05eba1f2004-08-27 21:32:02 +00009677 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009678
Tim Peters05eba1f2004-08-27 21:32:02 +00009679 /* If singleton sequence with an exact Unicode, return that. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009680 last_obj = NULL;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009681 items = PySequence_Fast_ITEMS(fseq);
Victor Stinneracf47b82011-10-06 12:32:37 +02009682 if (seqlen == 1) {
9683 if (PyUnicode_CheckExact(items[0])) {
9684 res = items[0];
9685 Py_INCREF(res);
9686 Py_DECREF(fseq);
9687 return res;
9688 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009689 seplen = 0;
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009690 maxchar = 0;
Tim Peters8ce9f162004-08-27 01:49:32 +00009691 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009692 else {
Victor Stinneracf47b82011-10-06 12:32:37 +02009693 /* Set up sep and seplen */
9694 if (separator == NULL) {
9695 /* fall back to a blank space separator */
9696 sep = PyUnicode_FromOrdinal(' ');
9697 if (!sep)
9698 goto onError;
Victor Stinnerdd077322011-10-07 17:02:31 +02009699 seplen = 1;
Victor Stinneracf47b82011-10-06 12:32:37 +02009700 maxchar = 32;
Tim Peters05eba1f2004-08-27 21:32:02 +00009701 }
Victor Stinneracf47b82011-10-06 12:32:37 +02009702 else {
9703 if (!PyUnicode_Check(separator)) {
9704 PyErr_Format(PyExc_TypeError,
9705 "separator: expected str instance,"
9706 " %.80s found",
9707 Py_TYPE(separator)->tp_name);
9708 goto onError;
9709 }
9710 if (PyUnicode_READY(separator))
9711 goto onError;
9712 sep = separator;
9713 seplen = PyUnicode_GET_LENGTH(separator);
9714 maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
9715 /* inc refcount to keep this code path symmetric with the
9716 above case of a blank separator */
9717 Py_INCREF(sep);
9718 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009719 last_obj = sep;
Tim Peters05eba1f2004-08-27 21:32:02 +00009720 }
9721
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009722 /* There are at least two things to join, or else we have a subclass
9723 * of str in the sequence.
9724 * Do a pre-pass to figure out the total amount of space we'll
9725 * need (sz), and see whether all argument are strings.
9726 */
9727 sz = 0;
Victor Stinnerdd077322011-10-07 17:02:31 +02009728#ifdef Py_DEBUG
9729 use_memcpy = 0;
9730#else
9731 use_memcpy = 1;
9732#endif
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009733 for (i = 0; i < seqlen; i++) {
9734 const Py_ssize_t old_sz = sz;
9735 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009736 if (!PyUnicode_Check(item)) {
9737 PyErr_Format(PyExc_TypeError,
9738 "sequence item %zd: expected str instance,"
9739 " %.80s found",
9740 i, Py_TYPE(item)->tp_name);
9741 goto onError;
9742 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009743 if (PyUnicode_READY(item) == -1)
9744 goto onError;
9745 sz += PyUnicode_GET_LENGTH(item);
9746 item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009747 maxchar = Py_MAX(maxchar, item_maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009748 if (i != 0)
9749 sz += seplen;
9750 if (sz < old_sz || sz > PY_SSIZE_T_MAX) {
9751 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009752 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009753 goto onError;
9754 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009755 if (use_memcpy && last_obj != NULL) {
9756 if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
9757 use_memcpy = 0;
9758 }
9759 last_obj = item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009760 }
Tim Petersced69f82003-09-16 20:30:58 +00009761
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009762 res = PyUnicode_New(sz, maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009763 if (res == NULL)
9764 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +00009765
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009766 /* Catenate everything. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009767#ifdef Py_DEBUG
9768 use_memcpy = 0;
9769#else
9770 if (use_memcpy) {
9771 res_data = PyUnicode_1BYTE_DATA(res);
9772 kind = PyUnicode_KIND(res);
9773 if (seplen != 0)
9774 sep_data = PyUnicode_1BYTE_DATA(sep);
9775 }
9776#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009777 for (i = 0, res_offset = 0; i < seqlen; ++i) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009778 Py_ssize_t itemlen;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009779 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009780 /* Copy item, and maybe the separator. */
Victor Stinner9ce5a832011-10-03 23:36:02 +02009781 if (i && seplen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009782 if (use_memcpy) {
9783 Py_MEMCPY(res_data,
9784 sep_data,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009785 kind * seplen);
9786 res_data += kind * seplen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009787 }
9788 else {
9789 copy_characters(res, res_offset, sep, 0, seplen);
9790 res_offset += seplen;
9791 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009792 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009793 itemlen = PyUnicode_GET_LENGTH(item);
9794 if (itemlen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009795 if (use_memcpy) {
9796 Py_MEMCPY(res_data,
9797 PyUnicode_DATA(item),
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009798 kind * itemlen);
9799 res_data += kind * itemlen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009800 }
9801 else {
9802 copy_characters(res, res_offset, item, 0, itemlen);
9803 res_offset += itemlen;
9804 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009805 }
Tim Peters05eba1f2004-08-27 21:32:02 +00009806 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009807 if (use_memcpy)
9808 assert(res_data == PyUnicode_1BYTE_DATA(res)
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009809 + kind * PyUnicode_GET_LENGTH(res));
Victor Stinnerdd077322011-10-07 17:02:31 +02009810 else
9811 assert(res_offset == PyUnicode_GET_LENGTH(res));
Tim Peters8ce9f162004-08-27 01:49:32 +00009812
Tim Peters05eba1f2004-08-27 21:32:02 +00009813 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009814 Py_XDECREF(sep);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009815 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009816 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009817
Benjamin Peterson29060642009-01-31 22:14:21 +00009818 onError:
Tim Peters05eba1f2004-08-27 21:32:02 +00009819 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009820 Py_XDECREF(sep);
Tim Peters8ce9f162004-08-27 01:49:32 +00009821 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009822 return NULL;
9823}
9824
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009825#define FILL(kind, data, value, start, length) \
9826 do { \
9827 Py_ssize_t i_ = 0; \
9828 assert(kind != PyUnicode_WCHAR_KIND); \
9829 switch ((kind)) { \
9830 case PyUnicode_1BYTE_KIND: { \
9831 unsigned char * to_ = (unsigned char *)((data)) + (start); \
9832 memset(to_, (unsigned char)value, length); \
9833 break; \
9834 } \
9835 case PyUnicode_2BYTE_KIND: { \
9836 Py_UCS2 * to_ = (Py_UCS2 *)((data)) + (start); \
9837 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9838 break; \
9839 } \
9840 default: { \
9841 Py_UCS4 * to_ = (Py_UCS4 *)((data)) + (start); \
9842 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9843 break; \
9844 } \
9845 } \
9846 } while (0)
9847
Victor Stinner9310abb2011-10-05 00:59:23 +02009848static PyObject *
9849pad(PyObject *self,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009850 Py_ssize_t left,
9851 Py_ssize_t right,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009852 Py_UCS4 fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009853{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009854 PyObject *u;
9855 Py_UCS4 maxchar;
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009856 int kind;
9857 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009858
9859 if (left < 0)
9860 left = 0;
9861 if (right < 0)
9862 right = 0;
9863
Victor Stinnerc4b49542011-12-11 22:44:26 +01009864 if (left == 0 && right == 0)
9865 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009866
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009867 if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
9868 right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +00009869 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
9870 return NULL;
9871 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009872 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
9873 if (fill > maxchar)
9874 maxchar = fill;
9875 u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009876 if (!u)
9877 return NULL;
9878
9879 kind = PyUnicode_KIND(u);
9880 data = PyUnicode_DATA(u);
9881 if (left)
9882 FILL(kind, data, fill, 0, left);
9883 if (right)
9884 FILL(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009885 copy_characters(u, left, self, 0, _PyUnicode_LENGTH(self));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009886 assert(_PyUnicode_CheckConsistency(u, 1));
9887 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009888}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009889#undef FILL
Guido van Rossumd57fd912000-03-10 22:53:23 +00009890
Alexander Belopolsky40018472011-02-26 01:02:56 +00009891PyObject *
9892PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009893{
Guido van Rossumd57fd912000-03-10 22:53:23 +00009894 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009895
9896 string = PyUnicode_FromObject(string);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009897 if (string == NULL || PyUnicode_READY(string) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00009898 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009899
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009900 switch(PyUnicode_KIND(string)) {
9901 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009902 if (PyUnicode_IS_ASCII(string))
9903 list = asciilib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009904 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009905 PyUnicode_GET_LENGTH(string), keepends);
9906 else
9907 list = ucs1lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009908 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009909 PyUnicode_GET_LENGTH(string), keepends);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009910 break;
9911 case PyUnicode_2BYTE_KIND:
9912 list = ucs2lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009913 string, PyUnicode_2BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009914 PyUnicode_GET_LENGTH(string), keepends);
9915 break;
9916 case PyUnicode_4BYTE_KIND:
9917 list = ucs4lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009918 string, PyUnicode_4BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009919 PyUnicode_GET_LENGTH(string), keepends);
9920 break;
9921 default:
9922 assert(0);
9923 list = 0;
9924 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009925 Py_DECREF(string);
9926 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009927}
9928
Alexander Belopolsky40018472011-02-26 01:02:56 +00009929static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009930split(PyObject *self,
9931 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009932 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009933{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009934 int kind1, kind2, kind;
9935 void *buf1, *buf2;
9936 Py_ssize_t len1, len2;
9937 PyObject* out;
9938
Guido van Rossumd57fd912000-03-10 22:53:23 +00009939 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00009940 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009941
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009942 if (PyUnicode_READY(self) == -1)
9943 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009944
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009945 if (substring == NULL)
9946 switch(PyUnicode_KIND(self)) {
9947 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009948 if (PyUnicode_IS_ASCII(self))
9949 return asciilib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009950 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009951 PyUnicode_GET_LENGTH(self), maxcount
9952 );
9953 else
9954 return ucs1lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009955 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009956 PyUnicode_GET_LENGTH(self), maxcount
9957 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009958 case PyUnicode_2BYTE_KIND:
9959 return ucs2lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009960 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009961 PyUnicode_GET_LENGTH(self), maxcount
9962 );
9963 case PyUnicode_4BYTE_KIND:
9964 return ucs4lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009965 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009966 PyUnicode_GET_LENGTH(self), maxcount
9967 );
9968 default:
9969 assert(0);
9970 return NULL;
9971 }
9972
9973 if (PyUnicode_READY(substring) == -1)
9974 return NULL;
9975
9976 kind1 = PyUnicode_KIND(self);
9977 kind2 = PyUnicode_KIND(substring);
9978 kind = kind1 > kind2 ? kind1 : kind2;
9979 buf1 = PyUnicode_DATA(self);
9980 buf2 = PyUnicode_DATA(substring);
9981 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009982 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009983 if (!buf1)
9984 return NULL;
9985 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009986 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009987 if (!buf2) {
9988 if (kind1 != kind) PyMem_Free(buf1);
9989 return NULL;
9990 }
9991 len1 = PyUnicode_GET_LENGTH(self);
9992 len2 = PyUnicode_GET_LENGTH(substring);
9993
9994 switch(kind) {
9995 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009996 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
9997 out = asciilib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009998 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +02009999 else
10000 out = ucs1lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010001 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010002 break;
10003 case PyUnicode_2BYTE_KIND:
10004 out = ucs2lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010005 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010006 break;
10007 case PyUnicode_4BYTE_KIND:
10008 out = ucs4lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010009 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010010 break;
10011 default:
10012 out = NULL;
10013 }
10014 if (kind1 != kind)
10015 PyMem_Free(buf1);
10016 if (kind2 != kind)
10017 PyMem_Free(buf2);
10018 return out;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010019}
10020
Alexander Belopolsky40018472011-02-26 01:02:56 +000010021static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010022rsplit(PyObject *self,
10023 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010024 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010025{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010026 int kind1, kind2, kind;
10027 void *buf1, *buf2;
10028 Py_ssize_t len1, len2;
10029 PyObject* out;
10030
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010031 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010032 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010033
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010034 if (PyUnicode_READY(self) == -1)
10035 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010036
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010037 if (substring == NULL)
10038 switch(PyUnicode_KIND(self)) {
10039 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010040 if (PyUnicode_IS_ASCII(self))
10041 return asciilib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010042 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010043 PyUnicode_GET_LENGTH(self), maxcount
10044 );
10045 else
10046 return ucs1lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010047 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010048 PyUnicode_GET_LENGTH(self), maxcount
10049 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010050 case PyUnicode_2BYTE_KIND:
10051 return ucs2lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010052 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010053 PyUnicode_GET_LENGTH(self), maxcount
10054 );
10055 case PyUnicode_4BYTE_KIND:
10056 return ucs4lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010057 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010058 PyUnicode_GET_LENGTH(self), maxcount
10059 );
10060 default:
10061 assert(0);
10062 return NULL;
10063 }
10064
10065 if (PyUnicode_READY(substring) == -1)
10066 return NULL;
10067
10068 kind1 = PyUnicode_KIND(self);
10069 kind2 = PyUnicode_KIND(substring);
10070 kind = kind1 > kind2 ? kind1 : kind2;
10071 buf1 = PyUnicode_DATA(self);
10072 buf2 = PyUnicode_DATA(substring);
10073 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010074 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010075 if (!buf1)
10076 return NULL;
10077 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010078 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010079 if (!buf2) {
10080 if (kind1 != kind) PyMem_Free(buf1);
10081 return NULL;
10082 }
10083 len1 = PyUnicode_GET_LENGTH(self);
10084 len2 = PyUnicode_GET_LENGTH(substring);
10085
10086 switch(kind) {
10087 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010088 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10089 out = asciilib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010090 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010091 else
10092 out = ucs1lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010093 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010094 break;
10095 case PyUnicode_2BYTE_KIND:
10096 out = ucs2lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010097 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010098 break;
10099 case PyUnicode_4BYTE_KIND:
10100 out = ucs4lib_rsplit(
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 default:
10104 out = NULL;
10105 }
10106 if (kind1 != kind)
10107 PyMem_Free(buf1);
10108 if (kind2 != kind)
10109 PyMem_Free(buf2);
10110 return out;
10111}
10112
10113static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010114anylib_find(int kind, PyObject *str1, void *buf1, Py_ssize_t len1,
10115 PyObject *str2, void *buf2, Py_ssize_t len2, Py_ssize_t offset)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010116{
10117 switch(kind) {
10118 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010119 if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
10120 return asciilib_find(buf1, len1, buf2, len2, offset);
10121 else
10122 return ucs1lib_find(buf1, len1, buf2, len2, offset);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010123 case PyUnicode_2BYTE_KIND:
10124 return ucs2lib_find(buf1, len1, buf2, len2, offset);
10125 case PyUnicode_4BYTE_KIND:
10126 return ucs4lib_find(buf1, len1, buf2, len2, offset);
10127 }
10128 assert(0);
10129 return -1;
10130}
10131
10132static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010133anylib_count(int kind, PyObject *sstr, void* sbuf, Py_ssize_t slen,
10134 PyObject *str1, void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010135{
10136 switch(kind) {
10137 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010138 if (PyUnicode_IS_ASCII(sstr) && PyUnicode_IS_ASCII(str1))
10139 return asciilib_count(sbuf, slen, buf1, len1, maxcount);
10140 else
10141 return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010142 case PyUnicode_2BYTE_KIND:
10143 return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
10144 case PyUnicode_4BYTE_KIND:
10145 return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
10146 }
10147 assert(0);
10148 return 0;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010149}
10150
Alexander Belopolsky40018472011-02-26 01:02:56 +000010151static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010152replace(PyObject *self, PyObject *str1,
10153 PyObject *str2, Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010154{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010155 PyObject *u;
10156 char *sbuf = PyUnicode_DATA(self);
10157 char *buf1 = PyUnicode_DATA(str1);
10158 char *buf2 = PyUnicode_DATA(str2);
10159 int srelease = 0, release1 = 0, release2 = 0;
10160 int skind = PyUnicode_KIND(self);
10161 int kind1 = PyUnicode_KIND(str1);
10162 int kind2 = PyUnicode_KIND(str2);
10163 Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
10164 Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
10165 Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010166 int mayshrink;
10167 Py_UCS4 maxchar, maxchar_str2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010168
10169 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010170 maxcount = PY_SSIZE_T_MAX;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010171 else if (maxcount == 0 || slen == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010172 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010173
Victor Stinner59de0ee2011-10-07 10:01:28 +020010174 if (str1 == str2)
10175 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010176 if (skind < kind1)
10177 /* substring too wide to be present */
10178 goto nothing;
10179
Victor Stinner49a0a212011-10-12 23:46:10 +020010180 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
10181 maxchar_str2 = PyUnicode_MAX_CHAR_VALUE(str2);
10182 /* Replacing str1 with str2 may cause a maxchar reduction in the
10183 result string. */
10184 mayshrink = (maxchar_str2 < maxchar);
10185 maxchar = Py_MAX(maxchar, maxchar_str2);
10186
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010187 if (len1 == len2) {
Antoine Pitroucbfdee32010-01-13 08:58:08 +000010188 Py_ssize_t i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010189 /* same length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010190 if (len1 == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010191 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010192 if (len1 == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010193 /* replace characters */
Victor Stinner49a0a212011-10-12 23:46:10 +020010194 Py_UCS4 u1, u2;
10195 int rkind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010196 u1 = PyUnicode_READ_CHAR(str1, 0);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +020010197 if (findchar(sbuf, PyUnicode_KIND(self),
10198 slen, u1, 1) < 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010199 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010200 u2 = PyUnicode_READ_CHAR(str2, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010201 u = PyUnicode_New(slen, maxchar);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010202 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010203 goto error;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020010204 copy_characters(u, 0, self, 0, slen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010205 rkind = PyUnicode_KIND(u);
10206 for (i = 0; i < PyUnicode_GET_LENGTH(u); i++)
10207 if (PyUnicode_READ(rkind, PyUnicode_DATA(u), i) == u1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010208 if (--maxcount < 0)
10209 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010210 PyUnicode_WRITE(rkind, PyUnicode_DATA(u), i, u2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010211 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010212 }
10213 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010214 int rkind = skind;
10215 char *res;
Victor Stinner25a4b292011-10-06 12:31:55 +020010216
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010217 if (kind1 < rkind) {
10218 /* widen substring */
10219 buf1 = _PyUnicode_AsKind(str1, rkind);
10220 if (!buf1) goto error;
10221 release1 = 1;
10222 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010223 i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010224 if (i < 0)
10225 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010226 if (rkind > kind2) {
10227 /* widen replacement */
10228 buf2 = _PyUnicode_AsKind(str2, rkind);
10229 if (!buf2) goto error;
10230 release2 = 1;
10231 }
10232 else if (rkind < kind2) {
10233 /* widen self and buf1 */
10234 rkind = kind2;
10235 if (release1) PyMem_Free(buf1);
10236 sbuf = _PyUnicode_AsKind(self, rkind);
10237 if (!sbuf) goto error;
10238 srelease = 1;
10239 buf1 = _PyUnicode_AsKind(str1, rkind);
10240 if (!buf1) goto error;
10241 release1 = 1;
10242 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010243 u = PyUnicode_New(slen, maxchar);
10244 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010245 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010246 assert(PyUnicode_KIND(u) == rkind);
10247 res = PyUnicode_DATA(u);
Victor Stinner25a4b292011-10-06 12:31:55 +020010248
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010249 memcpy(res, sbuf, rkind * slen);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010250 /* change everything in-place, starting with this one */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010251 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010252 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010253 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010254 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010255
10256 while ( --maxcount > 0) {
Victor Stinnerc3cec782011-10-05 21:24:08 +020010257 i = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010258 sbuf+rkind*i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010259 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010260 if (i == -1)
10261 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010262 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010263 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010264 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010265 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010266 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010267 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010268 }
10269 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010270 Py_ssize_t n, i, j, ires;
10271 Py_ssize_t product, new_size;
10272 int rkind = skind;
10273 char *res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010274
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010275 if (kind1 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010276 /* widen substring */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010277 buf1 = _PyUnicode_AsKind(str1, rkind);
10278 if (!buf1) goto error;
10279 release1 = 1;
10280 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010281 n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010282 if (n == 0)
10283 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010284 if (kind2 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010285 /* widen replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010286 buf2 = _PyUnicode_AsKind(str2, rkind);
10287 if (!buf2) goto error;
10288 release2 = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010289 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010290 else if (kind2 > rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010291 /* widen self and buf1 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010292 rkind = kind2;
10293 sbuf = _PyUnicode_AsKind(self, rkind);
10294 if (!sbuf) goto error;
10295 srelease = 1;
10296 if (release1) PyMem_Free(buf1);
10297 buf1 = _PyUnicode_AsKind(str1, rkind);
10298 if (!buf1) goto error;
10299 release1 = 1;
10300 }
10301 /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
10302 PyUnicode_GET_LENGTH(str1))); */
10303 product = n * (len2-len1);
10304 if ((product / (len2-len1)) != n) {
10305 PyErr_SetString(PyExc_OverflowError,
10306 "replace string is too long");
10307 goto error;
10308 }
10309 new_size = slen + product;
Victor Stinner49a0a212011-10-12 23:46:10 +020010310 if (new_size == 0) {
10311 Py_INCREF(unicode_empty);
10312 u = unicode_empty;
10313 goto done;
10314 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010315 if (new_size < 0 || new_size > (PY_SSIZE_T_MAX >> (rkind-1))) {
10316 PyErr_SetString(PyExc_OverflowError,
10317 "replace string is too long");
10318 goto error;
10319 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010320 u = PyUnicode_New(new_size, maxchar);
10321 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010322 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010323 assert(PyUnicode_KIND(u) == rkind);
10324 res = PyUnicode_DATA(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010325 ires = i = 0;
10326 if (len1 > 0) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010327 while (n-- > 0) {
10328 /* look for next match */
Victor Stinnerc3cec782011-10-05 21:24:08 +020010329 j = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010330 sbuf + rkind * i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010331 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010332 if (j == -1)
10333 break;
10334 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010335 /* copy unchanged part [i:j] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010336 memcpy(res + rkind * ires,
10337 sbuf + rkind * i,
10338 rkind * (j-i));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010339 ires += j - i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010340 }
10341 /* copy substitution string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010342 if (len2 > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010343 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010344 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010345 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010346 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010347 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010348 i = j + len1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010349 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010350 if (i < slen)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010351 /* copy tail [i:] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010352 memcpy(res + rkind * ires,
10353 sbuf + rkind * i,
10354 rkind * (slen-i));
Victor Stinner49a0a212011-10-12 23:46:10 +020010355 }
10356 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010357 /* interleave */
10358 while (n > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010359 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010360 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010361 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010362 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010363 if (--n <= 0)
10364 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010365 memcpy(res + rkind * ires,
10366 sbuf + rkind * i,
10367 rkind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010368 ires++;
10369 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010370 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010371 memcpy(res + rkind * ires,
10372 sbuf + rkind * i,
10373 rkind * (slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +000010374 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010375 }
10376
10377 if (mayshrink) {
Victor Stinner25a4b292011-10-06 12:31:55 +020010378 unicode_adjust_maxchar(&u);
10379 if (u == NULL)
10380 goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010381 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010382
10383 done:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010384 if (srelease)
10385 PyMem_FREE(sbuf);
10386 if (release1)
10387 PyMem_FREE(buf1);
10388 if (release2)
10389 PyMem_FREE(buf2);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010390 assert(_PyUnicode_CheckConsistency(u, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010391 return u;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010392
Benjamin Peterson29060642009-01-31 22:14:21 +000010393 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +000010394 /* nothing to replace; return original string (when possible) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010395 if (srelease)
10396 PyMem_FREE(sbuf);
10397 if (release1)
10398 PyMem_FREE(buf1);
10399 if (release2)
10400 PyMem_FREE(buf2);
Victor Stinnerc4b49542011-12-11 22:44:26 +010010401 return unicode_result_unchanged(self);
10402
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010403 error:
10404 if (srelease && sbuf)
10405 PyMem_FREE(sbuf);
10406 if (release1 && buf1)
10407 PyMem_FREE(buf1);
10408 if (release2 && buf2)
10409 PyMem_FREE(buf2);
10410 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010411}
10412
10413/* --- Unicode Object Methods --------------------------------------------- */
10414
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010415PyDoc_STRVAR(title__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010416 "S.title() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010417\n\
10418Return a titlecased version of S, i.e. words start with title case\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010419characters, all remaining cased characters have lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010420
10421static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010422unicode_title(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010423{
Guido van Rossumd57fd912000-03-10 22:53:23 +000010424 return fixup(self, fixtitle);
10425}
10426
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010427PyDoc_STRVAR(capitalize__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010428 "S.capitalize() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010429\n\
10430Return a capitalized version of S, i.e. make the first character\n\
Senthil Kumarane51ee8a2010-07-05 12:00:56 +000010431have upper case and the rest lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010432
10433static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010434unicode_capitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010435{
Guido van Rossumd57fd912000-03-10 22:53:23 +000010436 return fixup(self, fixcapitalize);
10437}
10438
10439#if 0
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010440PyDoc_STRVAR(capwords__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010441 "S.capwords() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010442\n\
10443Apply .capitalize() to all words in S and return the result with\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010444normalized whitespace (all whitespace strings are replaced by ' ').");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010445
10446static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010447unicode_capwords(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010448{
10449 PyObject *list;
10450 PyObject *item;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010451 Py_ssize_t i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010452
Guido van Rossumd57fd912000-03-10 22:53:23 +000010453 /* Split into words */
10454 list = split(self, NULL, -1);
10455 if (!list)
10456 return NULL;
10457
10458 /* Capitalize each word */
10459 for (i = 0; i < PyList_GET_SIZE(list); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010460 item = fixup(PyList_GET_ITEM(list, i),
Benjamin Peterson29060642009-01-31 22:14:21 +000010461 fixcapitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010462 if (item == NULL)
10463 goto onError;
10464 Py_DECREF(PyList_GET_ITEM(list, i));
10465 PyList_SET_ITEM(list, i, item);
10466 }
10467
10468 /* Join the words to form a new string */
10469 item = PyUnicode_Join(NULL, list);
10470
Benjamin Peterson29060642009-01-31 22:14:21 +000010471 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000010472 Py_DECREF(list);
Victor Stinner7931d9a2011-11-04 00:22:48 +010010473 return item;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010474}
10475#endif
10476
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010477/* Argument converter. Coerces to a single unicode character */
10478
10479static int
10480convert_uc(PyObject *obj, void *addr)
10481{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010482 Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010483 PyObject *uniobj;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010484
Benjamin Peterson14339b62009-01-31 16:36:08 +000010485 uniobj = PyUnicode_FromObject(obj);
10486 if (uniobj == NULL) {
10487 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010488 "The fill character cannot be converted to Unicode");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010489 return 0;
10490 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010491 if (PyUnicode_GET_LENGTH(uniobj) != 1) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010492 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010493 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010494 Py_DECREF(uniobj);
10495 return 0;
10496 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010497 *fillcharloc = PyUnicode_READ_CHAR(uniobj, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010498 Py_DECREF(uniobj);
10499 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010500}
10501
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010502PyDoc_STRVAR(center__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010503 "S.center(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010504\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010505Return S centered in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010506done using the specified fill character (default is a space)");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010507
10508static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010509unicode_center(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010510{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010511 Py_ssize_t marg, left;
10512 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010513 Py_UCS4 fillchar = ' ';
10514
Victor Stinnere9a29352011-10-01 02:14:59 +020010515 if (!PyArg_ParseTuple(args, "n|O&:center", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010516 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010517
Victor Stinnerc4b49542011-12-11 22:44:26 +010010518 if (PyUnicode_READY(self) < 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010519 return NULL;
10520
Victor Stinnerc4b49542011-12-11 22:44:26 +010010521 if (PyUnicode_GET_LENGTH(self) >= width)
10522 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010523
Victor Stinnerc4b49542011-12-11 22:44:26 +010010524 marg = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010525 left = marg / 2 + (marg & width & 1);
10526
Victor Stinner9310abb2011-10-05 00:59:23 +020010527 return pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010528}
10529
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010530/* This function assumes that str1 and str2 are readied by the caller. */
10531
Marc-André Lemburge5034372000-08-08 08:04:29 +000010532static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010533unicode_compare(PyObject *str1, PyObject *str2)
Marc-André Lemburge5034372000-08-08 08:04:29 +000010534{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010535 int kind1, kind2;
10536 void *data1, *data2;
10537 Py_ssize_t len1, len2, i;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010538
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010539 kind1 = PyUnicode_KIND(str1);
10540 kind2 = PyUnicode_KIND(str2);
10541 data1 = PyUnicode_DATA(str1);
10542 data2 = PyUnicode_DATA(str2);
10543 len1 = PyUnicode_GET_LENGTH(str1);
10544 len2 = PyUnicode_GET_LENGTH(str2);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010545
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010546 for (i = 0; i < len1 && i < len2; ++i) {
10547 Py_UCS4 c1, c2;
10548 c1 = PyUnicode_READ(kind1, data1, i);
10549 c2 = PyUnicode_READ(kind2, data2, i);
Fredrik Lundh45714e92001-06-26 16:39:36 +000010550
10551 if (c1 != c2)
10552 return (c1 < c2) ? -1 : 1;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010553 }
10554
10555 return (len1 < len2) ? -1 : (len1 != len2);
10556}
10557
Alexander Belopolsky40018472011-02-26 01:02:56 +000010558int
10559PyUnicode_Compare(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010560{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010561 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10562 if (PyUnicode_READY(left) == -1 ||
10563 PyUnicode_READY(right) == -1)
10564 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010565 return unicode_compare(left, right);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010566 }
Guido van Rossum09dc34f2007-05-04 04:17:33 +000010567 PyErr_Format(PyExc_TypeError,
10568 "Can't compare %.100s and %.100s",
10569 left->ob_type->tp_name,
10570 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010571 return -1;
10572}
10573
Martin v. Löwis5b222132007-06-10 09:51:05 +000010574int
10575PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
10576{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010577 Py_ssize_t i;
10578 int kind;
10579 void *data;
10580 Py_UCS4 chr;
10581
Victor Stinner910337b2011-10-03 03:20:16 +020010582 assert(_PyUnicode_CHECK(uni));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010583 if (PyUnicode_READY(uni) == -1)
10584 return -1;
10585 kind = PyUnicode_KIND(uni);
10586 data = PyUnicode_DATA(uni);
Martin v. Löwis5b222132007-06-10 09:51:05 +000010587 /* Compare Unicode string and source character set string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010588 for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
10589 if (chr != str[i])
10590 return (chr < (unsigned char)(str[i])) ? -1 : 1;
Benjamin Peterson8667a9b2010-01-09 21:45:28 +000010591 /* This check keeps Python strings that end in '\0' from comparing equal
10592 to C strings identical up to that point. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010593 if (PyUnicode_GET_LENGTH(uni) != i || chr)
Benjamin Peterson29060642009-01-31 22:14:21 +000010594 return 1; /* uni is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010595 if (str[i])
Benjamin Peterson29060642009-01-31 22:14:21 +000010596 return -1; /* str is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010597 return 0;
10598}
10599
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010600
Benjamin Peterson29060642009-01-31 22:14:21 +000010601#define TEST_COND(cond) \
Benjamin Peterson14339b62009-01-31 16:36:08 +000010602 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010603
Alexander Belopolsky40018472011-02-26 01:02:56 +000010604PyObject *
10605PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010606{
10607 int result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010608
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010609 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10610 PyObject *v;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010611 if (PyUnicode_READY(left) == -1 ||
10612 PyUnicode_READY(right) == -1)
10613 return NULL;
10614 if (PyUnicode_GET_LENGTH(left) != PyUnicode_GET_LENGTH(right) ||
10615 PyUnicode_KIND(left) != PyUnicode_KIND(right)) {
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010616 if (op == Py_EQ) {
10617 Py_INCREF(Py_False);
10618 return Py_False;
10619 }
10620 if (op == Py_NE) {
10621 Py_INCREF(Py_True);
10622 return Py_True;
10623 }
10624 }
10625 if (left == right)
10626 result = 0;
10627 else
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010628 result = unicode_compare(left, right);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010629
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010630 /* Convert the return value to a Boolean */
10631 switch (op) {
10632 case Py_EQ:
10633 v = TEST_COND(result == 0);
10634 break;
10635 case Py_NE:
10636 v = TEST_COND(result != 0);
10637 break;
10638 case Py_LE:
10639 v = TEST_COND(result <= 0);
10640 break;
10641 case Py_GE:
10642 v = TEST_COND(result >= 0);
10643 break;
10644 case Py_LT:
10645 v = TEST_COND(result == -1);
10646 break;
10647 case Py_GT:
10648 v = TEST_COND(result == 1);
10649 break;
10650 default:
10651 PyErr_BadArgument();
10652 return NULL;
10653 }
10654 Py_INCREF(v);
10655 return v;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010656 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000010657
Brian Curtindfc80e32011-08-10 20:28:54 -050010658 Py_RETURN_NOTIMPLEMENTED;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010659}
10660
Alexander Belopolsky40018472011-02-26 01:02:56 +000010661int
10662PyUnicode_Contains(PyObject *container, PyObject *element)
Guido van Rossum403d68b2000-03-13 15:55:09 +000010663{
Thomas Wouters477c8d52006-05-27 19:21:47 +000010664 PyObject *str, *sub;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010665 int kind1, kind2, kind;
10666 void *buf1, *buf2;
10667 Py_ssize_t len1, len2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010668 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010669
10670 /* Coerce the two arguments */
Thomas Wouters477c8d52006-05-27 19:21:47 +000010671 sub = PyUnicode_FromObject(element);
10672 if (!sub) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010673 PyErr_Format(PyExc_TypeError,
10674 "'in <string>' requires string as left operand, not %s",
10675 element->ob_type->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010676 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010677 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010678 if (PyUnicode_READY(sub) == -1)
10679 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010680
Thomas Wouters477c8d52006-05-27 19:21:47 +000010681 str = PyUnicode_FromObject(container);
Victor Stinnere9a29352011-10-01 02:14:59 +020010682 if (!str || PyUnicode_READY(str) == -1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010683 Py_DECREF(sub);
10684 return -1;
10685 }
10686
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010687 kind1 = PyUnicode_KIND(str);
10688 kind2 = PyUnicode_KIND(sub);
10689 kind = kind1 > kind2 ? kind1 : kind2;
10690 buf1 = PyUnicode_DATA(str);
10691 buf2 = PyUnicode_DATA(sub);
10692 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010693 buf1 = _PyUnicode_AsKind(str, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010694 if (!buf1) {
10695 Py_DECREF(sub);
10696 return -1;
10697 }
10698 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010699 buf2 = _PyUnicode_AsKind(sub, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010700 if (!buf2) {
10701 Py_DECREF(sub);
10702 if (kind1 != kind) PyMem_Free(buf1);
10703 return -1;
10704 }
10705 len1 = PyUnicode_GET_LENGTH(str);
10706 len2 = PyUnicode_GET_LENGTH(sub);
10707
10708 switch(kind) {
10709 case PyUnicode_1BYTE_KIND:
10710 result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
10711 break;
10712 case PyUnicode_2BYTE_KIND:
10713 result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
10714 break;
10715 case PyUnicode_4BYTE_KIND:
10716 result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
10717 break;
10718 default:
10719 result = -1;
10720 assert(0);
10721 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000010722
10723 Py_DECREF(str);
10724 Py_DECREF(sub);
10725
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010726 if (kind1 != kind)
10727 PyMem_Free(buf1);
10728 if (kind2 != kind)
10729 PyMem_Free(buf2);
10730
Guido van Rossum403d68b2000-03-13 15:55:09 +000010731 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010732}
10733
Guido van Rossumd57fd912000-03-10 22:53:23 +000010734/* Concat to string or Unicode object giving a new Unicode object. */
10735
Alexander Belopolsky40018472011-02-26 01:02:56 +000010736PyObject *
10737PyUnicode_Concat(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010738{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010739 PyObject *u = NULL, *v = NULL, *w;
Victor Stinner127226b2011-10-13 01:12:34 +020010740 Py_UCS4 maxchar, maxchar2;
Victor Stinner488fa492011-12-12 00:01:39 +010010741 Py_ssize_t u_len, v_len, new_len;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010742
10743 /* Coerce the two arguments */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010744 u = PyUnicode_FromObject(left);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010745 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010746 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010747 v = PyUnicode_FromObject(right);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010748 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010749 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010750
10751 /* Shortcuts */
Victor Stinnera464fc12011-10-02 20:39:30 +020010752 if (v == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010753 Py_DECREF(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010754 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010755 }
Victor Stinnera464fc12011-10-02 20:39:30 +020010756 if (u == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010757 Py_DECREF(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010758 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010759 }
10760
Victor Stinner488fa492011-12-12 00:01:39 +010010761 u_len = PyUnicode_GET_LENGTH(u);
10762 v_len = PyUnicode_GET_LENGTH(v);
10763 if (u_len > PY_SSIZE_T_MAX - v_len) {
10764 PyErr_SetString(PyExc_OverflowError,
10765 "strings are too large to concat");
10766 goto onError;
10767 }
10768 new_len = u_len + v_len;
10769
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010770 maxchar = PyUnicode_MAX_CHAR_VALUE(u);
Victor Stinner127226b2011-10-13 01:12:34 +020010771 maxchar2 = PyUnicode_MAX_CHAR_VALUE(v);
10772 maxchar = Py_MAX(maxchar, maxchar2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010773
Guido van Rossumd57fd912000-03-10 22:53:23 +000010774 /* Concat the two Unicode strings */
Victor Stinner488fa492011-12-12 00:01:39 +010010775 w = PyUnicode_New(new_len, maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010776 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010777 goto onError;
Victor Stinner488fa492011-12-12 00:01:39 +010010778 copy_characters(w, 0, u, 0, u_len);
10779 copy_characters(w, u_len, v, 0, v_len);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010780 Py_DECREF(u);
10781 Py_DECREF(v);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010782 assert(_PyUnicode_CheckConsistency(w, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010783 return w;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010784
Benjamin Peterson29060642009-01-31 22:14:21 +000010785 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000010786 Py_XDECREF(u);
10787 Py_XDECREF(v);
10788 return NULL;
10789}
10790
Walter Dörwald1ab83302007-05-18 17:15:44 +000010791void
Victor Stinner23e56682011-10-03 03:54:37 +020010792PyUnicode_Append(PyObject **p_left, PyObject *right)
Walter Dörwald1ab83302007-05-18 17:15:44 +000010793{
Victor Stinner23e56682011-10-03 03:54:37 +020010794 PyObject *left, *res;
Victor Stinner488fa492011-12-12 00:01:39 +010010795 Py_UCS4 maxchar, maxchar2;
10796 Py_ssize_t left_len, right_len, new_len;
Victor Stinner23e56682011-10-03 03:54:37 +020010797
10798 if (p_left == NULL) {
10799 if (!PyErr_Occurred())
10800 PyErr_BadInternalCall();
Benjamin Peterson14339b62009-01-31 16:36:08 +000010801 return;
10802 }
Victor Stinner23e56682011-10-03 03:54:37 +020010803 left = *p_left;
10804 if (right == NULL || !PyUnicode_Check(left)) {
10805 if (!PyErr_Occurred())
10806 PyErr_BadInternalCall();
10807 goto error;
10808 }
10809
Victor Stinnere1335c72011-10-04 20:53:03 +020010810 if (PyUnicode_READY(left))
10811 goto error;
10812 if (PyUnicode_READY(right))
10813 goto error;
10814
Victor Stinner488fa492011-12-12 00:01:39 +010010815 /* Shortcuts */
10816 if (left == unicode_empty) {
10817 Py_DECREF(left);
10818 Py_INCREF(right);
10819 *p_left = right;
10820 return;
10821 }
10822 if (right == unicode_empty)
10823 return;
10824
10825 left_len = PyUnicode_GET_LENGTH(left);
10826 right_len = PyUnicode_GET_LENGTH(right);
10827 if (left_len > PY_SSIZE_T_MAX - right_len) {
10828 PyErr_SetString(PyExc_OverflowError,
10829 "strings are too large to concat");
10830 goto error;
10831 }
10832 new_len = left_len + right_len;
10833
10834 if (unicode_modifiable(left)
10835 && PyUnicode_CheckExact(right)
10836 && PyUnicode_KIND(right) <= PyUnicode_KIND(left)
Victor Stinnerb0923652011-10-04 01:17:31 +020010837 /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
10838 to change the structure size, but characters are stored just after
Georg Brandl7597add2011-10-05 16:36:47 +020010839 the structure, and so it requires to move all characters which is
Victor Stinnerb0923652011-10-04 01:17:31 +020010840 not so different than duplicating the string. */
Victor Stinner488fa492011-12-12 00:01:39 +010010841 && !(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
10842 {
10843 /* append inplace */
10844 if (unicode_resize(p_left, new_len) != 0) {
10845 /* XXX if _PyUnicode_Resize() fails, 'left' has been
10846 * deallocated so it cannot be put back into
10847 * 'variable'. The MemoryError is raised when there
10848 * is no value in 'variable', which might (very
10849 * remotely) be a cause of incompatibilities.
10850 */
10851 goto error;
Victor Stinner23e56682011-10-03 03:54:37 +020010852 }
Victor Stinner488fa492011-12-12 00:01:39 +010010853 /* copy 'right' into the newly allocated area of 'left' */
10854 copy_characters(*p_left, left_len, right, 0, right_len);
Victor Stinner23e56682011-10-03 03:54:37 +020010855 }
Victor Stinner488fa492011-12-12 00:01:39 +010010856 else {
10857 maxchar = PyUnicode_MAX_CHAR_VALUE(left);
10858 maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
10859 maxchar = Py_MAX(maxchar, maxchar2);
Victor Stinner23e56682011-10-03 03:54:37 +020010860
Victor Stinner488fa492011-12-12 00:01:39 +010010861 /* Concat the two Unicode strings */
10862 res = PyUnicode_New(new_len, maxchar);
10863 if (res == NULL)
10864 goto error;
10865 copy_characters(res, 0, left, 0, left_len);
10866 copy_characters(res, left_len, right, 0, right_len);
10867 Py_DECREF(left);
10868 *p_left = res;
10869 }
10870 assert(_PyUnicode_CheckConsistency(*p_left, 1));
Victor Stinner23e56682011-10-03 03:54:37 +020010871 return;
10872
10873error:
Victor Stinner488fa492011-12-12 00:01:39 +010010874 Py_CLEAR(*p_left);
Walter Dörwald1ab83302007-05-18 17:15:44 +000010875}
10876
10877void
10878PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
10879{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010880 PyUnicode_Append(pleft, right);
10881 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +000010882}
10883
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010884PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010885 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010886\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000010887Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010888string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010889interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010890
10891static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010892unicode_count(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010893{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010894 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010895 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010896 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010897 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010898 int kind1, kind2, kind;
10899 void *buf1, *buf2;
10900 Py_ssize_t len1, len2, iresult;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010901
Jesus Ceaac451502011-04-20 17:09:23 +020010902 if (!stringlib_parse_args_finds_unicode("count", args, &substring,
10903 &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000010904 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000010905
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010906 kind1 = PyUnicode_KIND(self);
10907 kind2 = PyUnicode_KIND(substring);
10908 kind = kind1 > kind2 ? kind1 : kind2;
10909 buf1 = PyUnicode_DATA(self);
10910 buf2 = PyUnicode_DATA(substring);
10911 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010912 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010913 if (!buf1) {
10914 Py_DECREF(substring);
10915 return NULL;
10916 }
10917 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010918 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010919 if (!buf2) {
10920 Py_DECREF(substring);
10921 if (kind1 != kind) PyMem_Free(buf1);
10922 return NULL;
10923 }
10924 len1 = PyUnicode_GET_LENGTH(self);
10925 len2 = PyUnicode_GET_LENGTH(substring);
10926
10927 ADJUST_INDICES(start, end, len1);
10928 switch(kind) {
10929 case PyUnicode_1BYTE_KIND:
10930 iresult = ucs1lib_count(
10931 ((Py_UCS1*)buf1) + start, end - start,
10932 buf2, len2, PY_SSIZE_T_MAX
10933 );
10934 break;
10935 case PyUnicode_2BYTE_KIND:
10936 iresult = ucs2lib_count(
10937 ((Py_UCS2*)buf1) + start, end - start,
10938 buf2, len2, PY_SSIZE_T_MAX
10939 );
10940 break;
10941 case PyUnicode_4BYTE_KIND:
10942 iresult = ucs4lib_count(
10943 ((Py_UCS4*)buf1) + start, end - start,
10944 buf2, len2, PY_SSIZE_T_MAX
10945 );
10946 break;
10947 default:
10948 assert(0); iresult = 0;
10949 }
10950
10951 result = PyLong_FromSsize_t(iresult);
10952
10953 if (kind1 != kind)
10954 PyMem_Free(buf1);
10955 if (kind2 != kind)
10956 PyMem_Free(buf2);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010957
10958 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010959
Guido van Rossumd57fd912000-03-10 22:53:23 +000010960 return result;
10961}
10962
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010963PyDoc_STRVAR(encode__doc__,
Victor Stinnerc911bbf2010-11-07 19:04:46 +000010964 "S.encode(encoding='utf-8', errors='strict') -> bytes\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010965\n\
Victor Stinnere14e2122010-11-07 18:41:46 +000010966Encode S using the codec registered for encoding. Default encoding\n\
10967is 'utf-8'. errors may be given to set a different error\n\
Fred Drakee4315f52000-05-09 19:53:39 +000010968handling scheme. Default is 'strict' meaning that encoding errors raise\n\
Walter Dörwald3aeb6322002-09-02 13:14:32 +000010969a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
10970'xmlcharrefreplace' as well as any other name registered with\n\
10971codecs.register_error that can handle UnicodeEncodeErrors.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010972
10973static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010974unicode_encode(PyObject *self, PyObject *args, PyObject *kwargs)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010975{
Benjamin Peterson308d6372009-09-18 21:42:35 +000010976 static char *kwlist[] = {"encoding", "errors", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000010977 char *encoding = NULL;
10978 char *errors = NULL;
Guido van Rossum35d94282007-08-27 18:20:11 +000010979
Benjamin Peterson308d6372009-09-18 21:42:35 +000010980 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:encode",
10981 kwlist, &encoding, &errors))
Guido van Rossumd57fd912000-03-10 22:53:23 +000010982 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010983 return PyUnicode_AsEncodedString(self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +000010984}
10985
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010986PyDoc_STRVAR(expandtabs__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010987 "S.expandtabs([tabsize]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010988\n\
10989Return a copy of S where all tab characters are expanded using spaces.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010990If tabsize is not given, a tab size of 8 characters is assumed.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010991
10992static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010993unicode_expandtabs(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010994{
Antoine Pitroue71d5742011-10-04 15:55:09 +020010995 Py_ssize_t i, j, line_pos, src_len, incr;
10996 Py_UCS4 ch;
10997 PyObject *u;
10998 void *src_data, *dest_data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010999 int tabsize = 8;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011000 int kind;
Antoine Pitroue19aa382011-10-04 16:04:01 +020011001 int found;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011002
11003 if (!PyArg_ParseTuple(args, "|i:expandtabs", &tabsize))
Benjamin Peterson29060642009-01-31 22:14:21 +000011004 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011005
Antoine Pitrou22425222011-10-04 19:10:51 +020011006 if (PyUnicode_READY(self) == -1)
11007 return NULL;
11008
Thomas Wouters7e474022000-07-16 12:04:32 +000011009 /* First pass: determine size of output string */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011010 src_len = PyUnicode_GET_LENGTH(self);
11011 i = j = line_pos = 0;
11012 kind = PyUnicode_KIND(self);
11013 src_data = PyUnicode_DATA(self);
Antoine Pitroue19aa382011-10-04 16:04:01 +020011014 found = 0;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011015 for (; i < src_len; i++) {
11016 ch = PyUnicode_READ(kind, src_data, i);
11017 if (ch == '\t') {
Antoine Pitroue19aa382011-10-04 16:04:01 +020011018 found = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000011019 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011020 incr = tabsize - (line_pos % tabsize); /* cannot overflow */
Benjamin Peterson29060642009-01-31 22:14:21 +000011021 if (j > PY_SSIZE_T_MAX - incr)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011022 goto overflow;
11023 line_pos += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011024 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011025 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011026 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011027 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000011028 if (j > PY_SSIZE_T_MAX - 1)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011029 goto overflow;
11030 line_pos++;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011031 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011032 if (ch == '\n' || ch == '\r')
11033 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011034 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011035 }
Victor Stinnerc4b49542011-12-11 22:44:26 +010011036 if (!found)
11037 return unicode_result_unchanged(self);
Guido van Rossumcd16bf62007-06-13 18:07:49 +000011038
Guido van Rossumd57fd912000-03-10 22:53:23 +000011039 /* Second pass: create output string and fill it */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011040 u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011041 if (!u)
11042 return NULL;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011043 dest_data = PyUnicode_DATA(u);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011044
Antoine Pitroue71d5742011-10-04 15:55:09 +020011045 i = j = line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011046
Antoine Pitroue71d5742011-10-04 15:55:09 +020011047 for (; i < src_len; i++) {
11048 ch = PyUnicode_READ(kind, src_data, i);
11049 if (ch == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +000011050 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011051 incr = tabsize - (line_pos % tabsize);
11052 line_pos += incr;
11053 while (incr--) {
11054 PyUnicode_WRITE(kind, dest_data, j, ' ');
11055 j++;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011056 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011057 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011058 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011059 else {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011060 line_pos++;
11061 PyUnicode_WRITE(kind, dest_data, j, ch);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011062 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011063 if (ch == '\n' || ch == '\r')
11064 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011065 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011066 }
11067 assert (j == PyUnicode_GET_LENGTH(u));
Victor Stinnerd3df8ab2011-11-22 01:22:34 +010011068 return unicode_result(u);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011069
Antoine Pitroue71d5742011-10-04 15:55:09 +020011070 overflow:
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011071 PyErr_SetString(PyExc_OverflowError, "new string is too long");
11072 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011073}
11074
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011075PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011076 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011077\n\
11078Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080011079such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011080arguments start and end are interpreted as in slice notation.\n\
11081\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011082Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011083
11084static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011085unicode_find(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011086{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011087 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011088 Py_ssize_t start;
11089 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011090 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011091
Jesus Ceaac451502011-04-20 17:09:23 +020011092 if (!stringlib_parse_args_finds_unicode("find", args, &substring,
11093 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011094 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011095
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011096 if (PyUnicode_READY(self) == -1)
11097 return NULL;
11098 if (PyUnicode_READY(substring) == -1)
11099 return NULL;
11100
Victor Stinner7931d9a2011-11-04 00:22:48 +010011101 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011102
11103 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011104
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011105 if (result == -2)
11106 return NULL;
11107
Christian Heimes217cfd12007-12-02 14:31:20 +000011108 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011109}
11110
11111static PyObject *
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011112unicode_getitem(PyObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011113{
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011114 Py_UCS4 ch = PyUnicode_ReadChar(self, index);
11115 if (ch == (Py_UCS4)-1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011116 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011117 return PyUnicode_FromOrdinal(ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011118}
11119
Guido van Rossumc2504932007-09-18 19:42:40 +000011120/* Believe it or not, this produces the same value for ASCII strings
Mark Dickinson57e683e2011-09-24 18:18:40 +010011121 as bytes_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +000011122static Py_hash_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011123unicode_hash(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011124{
Guido van Rossumc2504932007-09-18 19:42:40 +000011125 Py_ssize_t len;
Mark Dickinson57e683e2011-09-24 18:18:40 +010011126 Py_uhash_t x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011127
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011128 if (_PyUnicode_HASH(self) != -1)
11129 return _PyUnicode_HASH(self);
11130 if (PyUnicode_READY(self) == -1)
11131 return -1;
11132 len = PyUnicode_GET_LENGTH(self);
11133
11134 /* The hash function as a macro, gets expanded three times below. */
11135#define HASH(P) \
11136 x = (Py_uhash_t)*P << 7; \
11137 while (--len >= 0) \
11138 x = (1000003*x) ^ (Py_uhash_t)*P++;
11139
11140 switch (PyUnicode_KIND(self)) {
11141 case PyUnicode_1BYTE_KIND: {
11142 const unsigned char *c = PyUnicode_1BYTE_DATA(self);
11143 HASH(c);
11144 break;
11145 }
11146 case PyUnicode_2BYTE_KIND: {
11147 const Py_UCS2 *s = PyUnicode_2BYTE_DATA(self);
11148 HASH(s);
11149 break;
11150 }
11151 default: {
11152 Py_UCS4 *l;
11153 assert(PyUnicode_KIND(self) == PyUnicode_4BYTE_KIND &&
11154 "Impossible switch case in unicode_hash");
11155 l = PyUnicode_4BYTE_DATA(self);
11156 HASH(l);
11157 break;
11158 }
11159 }
11160 x ^= (Py_uhash_t)PyUnicode_GET_LENGTH(self);
11161
Guido van Rossumc2504932007-09-18 19:42:40 +000011162 if (x == -1)
11163 x = -2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011164 _PyUnicode_HASH(self) = x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011165 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011166}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011167#undef HASH
Guido van Rossumd57fd912000-03-10 22:53:23 +000011168
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011169PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011170 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011171\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011172Like S.find() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011173
11174static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011175unicode_index(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011176{
Martin v. Löwis18e16552006-02-15 17:27:45 +000011177 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011178 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011179 Py_ssize_t start;
11180 Py_ssize_t end;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011181
Jesus Ceaac451502011-04-20 17:09:23 +020011182 if (!stringlib_parse_args_finds_unicode("index", args, &substring,
11183 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011184 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011185
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011186 if (PyUnicode_READY(self) == -1)
11187 return NULL;
11188 if (PyUnicode_READY(substring) == -1)
11189 return NULL;
11190
Victor Stinner7931d9a2011-11-04 00:22:48 +010011191 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011192
11193 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011194
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011195 if (result == -2)
11196 return NULL;
11197
Guido van Rossumd57fd912000-03-10 22:53:23 +000011198 if (result < 0) {
11199 PyErr_SetString(PyExc_ValueError, "substring not found");
11200 return NULL;
11201 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011202
Christian Heimes217cfd12007-12-02 14:31:20 +000011203 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011204}
11205
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011206PyDoc_STRVAR(islower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011207 "S.islower() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011208\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011209Return True if all cased characters in S are lowercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011210at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011211
11212static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011213unicode_islower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011214{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011215 Py_ssize_t i, length;
11216 int kind;
11217 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011218 int cased;
11219
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011220 if (PyUnicode_READY(self) == -1)
11221 return NULL;
11222 length = PyUnicode_GET_LENGTH(self);
11223 kind = PyUnicode_KIND(self);
11224 data = PyUnicode_DATA(self);
11225
Guido van Rossumd57fd912000-03-10 22:53:23 +000011226 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011227 if (length == 1)
11228 return PyBool_FromLong(
11229 Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011230
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011231 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011232 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011233 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011234
Guido van Rossumd57fd912000-03-10 22:53:23 +000011235 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011236 for (i = 0; i < length; i++) {
11237 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011238
Benjamin Peterson29060642009-01-31 22:14:21 +000011239 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
11240 return PyBool_FromLong(0);
11241 else if (!cased && Py_UNICODE_ISLOWER(ch))
11242 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011243 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011244 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011245}
11246
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011247PyDoc_STRVAR(isupper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011248 "S.isupper() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011249\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011250Return True if all cased characters in S are uppercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011251at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011252
11253static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011254unicode_isupper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011255{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011256 Py_ssize_t i, length;
11257 int kind;
11258 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011259 int cased;
11260
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011261 if (PyUnicode_READY(self) == -1)
11262 return NULL;
11263 length = PyUnicode_GET_LENGTH(self);
11264 kind = PyUnicode_KIND(self);
11265 data = PyUnicode_DATA(self);
11266
Guido van Rossumd57fd912000-03-10 22:53:23 +000011267 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011268 if (length == 1)
11269 return PyBool_FromLong(
11270 Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011271
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011272 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011273 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011274 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011275
Guido van Rossumd57fd912000-03-10 22:53:23 +000011276 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011277 for (i = 0; i < length; i++) {
11278 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011279
Benjamin Peterson29060642009-01-31 22:14:21 +000011280 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
11281 return PyBool_FromLong(0);
11282 else if (!cased && Py_UNICODE_ISUPPER(ch))
11283 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011284 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011285 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011286}
11287
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011288PyDoc_STRVAR(istitle__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011289 "S.istitle() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011290\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011291Return True if S is a titlecased string and there is at least one\n\
11292character in S, i.e. upper- and titlecase characters may only\n\
11293follow uncased characters and lowercase characters only cased ones.\n\
11294Return False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011295
11296static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011297unicode_istitle(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011298{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011299 Py_ssize_t i, length;
11300 int kind;
11301 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011302 int cased, previous_is_cased;
11303
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011304 if (PyUnicode_READY(self) == -1)
11305 return NULL;
11306 length = PyUnicode_GET_LENGTH(self);
11307 kind = PyUnicode_KIND(self);
11308 data = PyUnicode_DATA(self);
11309
Guido van Rossumd57fd912000-03-10 22:53:23 +000011310 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011311 if (length == 1) {
11312 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11313 return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
11314 (Py_UNICODE_ISUPPER(ch) != 0));
11315 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011316
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011317 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011318 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011319 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011320
Guido van Rossumd57fd912000-03-10 22:53:23 +000011321 cased = 0;
11322 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011323 for (i = 0; i < length; i++) {
11324 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011325
Benjamin Peterson29060642009-01-31 22:14:21 +000011326 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
11327 if (previous_is_cased)
11328 return PyBool_FromLong(0);
11329 previous_is_cased = 1;
11330 cased = 1;
11331 }
11332 else if (Py_UNICODE_ISLOWER(ch)) {
11333 if (!previous_is_cased)
11334 return PyBool_FromLong(0);
11335 previous_is_cased = 1;
11336 cased = 1;
11337 }
11338 else
11339 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011340 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011341 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011342}
11343
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011344PyDoc_STRVAR(isspace__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011345 "S.isspace() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011346\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011347Return True if all characters in S are whitespace\n\
11348and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011349
11350static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011351unicode_isspace(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011352{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011353 Py_ssize_t i, length;
11354 int kind;
11355 void *data;
11356
11357 if (PyUnicode_READY(self) == -1)
11358 return NULL;
11359 length = PyUnicode_GET_LENGTH(self);
11360 kind = PyUnicode_KIND(self);
11361 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011362
Guido van Rossumd57fd912000-03-10 22:53:23 +000011363 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011364 if (length == 1)
11365 return PyBool_FromLong(
11366 Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011367
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011368 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011369 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011370 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011371
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011372 for (i = 0; i < length; i++) {
11373 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011374 if (!Py_UNICODE_ISSPACE(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011375 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011376 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011377 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011378}
11379
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011380PyDoc_STRVAR(isalpha__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011381 "S.isalpha() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011382\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011383Return True if all characters in S are alphabetic\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011384and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011385
11386static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011387unicode_isalpha(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011388{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011389 Py_ssize_t i, length;
11390 int kind;
11391 void *data;
11392
11393 if (PyUnicode_READY(self) == -1)
11394 return NULL;
11395 length = PyUnicode_GET_LENGTH(self);
11396 kind = PyUnicode_KIND(self);
11397 data = PyUnicode_DATA(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011398
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011399 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011400 if (length == 1)
11401 return PyBool_FromLong(
11402 Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011403
11404 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011405 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011406 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011407
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011408 for (i = 0; i < length; i++) {
11409 if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011410 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011411 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011412 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011413}
11414
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011415PyDoc_STRVAR(isalnum__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011416 "S.isalnum() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011417\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011418Return True if all characters in S are alphanumeric\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011419and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011420
11421static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011422unicode_isalnum(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011423{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011424 int kind;
11425 void *data;
11426 Py_ssize_t len, i;
11427
11428 if (PyUnicode_READY(self) == -1)
11429 return NULL;
11430
11431 kind = PyUnicode_KIND(self);
11432 data = PyUnicode_DATA(self);
11433 len = PyUnicode_GET_LENGTH(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011434
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011435 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011436 if (len == 1) {
11437 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11438 return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
11439 }
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011440
11441 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011442 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011443 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011444
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011445 for (i = 0; i < len; i++) {
11446 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011447 if (!Py_UNICODE_ISALNUM(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011448 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011449 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011450 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011451}
11452
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011453PyDoc_STRVAR(isdecimal__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011454 "S.isdecimal() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011455\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011456Return True if there are only decimal characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011457False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011458
11459static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011460unicode_isdecimal(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011461{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011462 Py_ssize_t i, length;
11463 int kind;
11464 void *data;
11465
11466 if (PyUnicode_READY(self) == -1)
11467 return NULL;
11468 length = PyUnicode_GET_LENGTH(self);
11469 kind = PyUnicode_KIND(self);
11470 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011471
Guido van Rossumd57fd912000-03-10 22:53:23 +000011472 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011473 if (length == 1)
11474 return PyBool_FromLong(
11475 Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011476
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011477 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011478 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011479 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011480
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011481 for (i = 0; i < length; i++) {
11482 if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011483 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011484 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011485 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011486}
11487
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011488PyDoc_STRVAR(isdigit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011489 "S.isdigit() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011490\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011491Return True if all characters in S are digits\n\
11492and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011493
11494static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011495unicode_isdigit(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011496{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011497 Py_ssize_t i, length;
11498 int kind;
11499 void *data;
11500
11501 if (PyUnicode_READY(self) == -1)
11502 return NULL;
11503 length = PyUnicode_GET_LENGTH(self);
11504 kind = PyUnicode_KIND(self);
11505 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011506
Guido van Rossumd57fd912000-03-10 22:53:23 +000011507 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011508 if (length == 1) {
11509 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11510 return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
11511 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011512
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011513 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011514 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011515 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011516
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011517 for (i = 0; i < length; i++) {
11518 if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011519 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011520 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011521 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011522}
11523
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011524PyDoc_STRVAR(isnumeric__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011525 "S.isnumeric() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011526\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011527Return True if there are only numeric characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011528False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011529
11530static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011531unicode_isnumeric(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011532{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011533 Py_ssize_t i, length;
11534 int kind;
11535 void *data;
11536
11537 if (PyUnicode_READY(self) == -1)
11538 return NULL;
11539 length = PyUnicode_GET_LENGTH(self);
11540 kind = PyUnicode_KIND(self);
11541 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011542
Guido van Rossumd57fd912000-03-10 22:53:23 +000011543 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011544 if (length == 1)
11545 return PyBool_FromLong(
11546 Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011547
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011548 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011549 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011550 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011551
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011552 for (i = 0; i < length; i++) {
11553 if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011554 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011555 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011556 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011557}
11558
Martin v. Löwis47383402007-08-15 07:32:56 +000011559int
11560PyUnicode_IsIdentifier(PyObject *self)
11561{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011562 int kind;
11563 void *data;
11564 Py_ssize_t i;
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011565 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +000011566
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011567 if (PyUnicode_READY(self) == -1) {
11568 Py_FatalError("identifier not ready");
Benjamin Peterson29060642009-01-31 22:14:21 +000011569 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011570 }
11571
11572 /* Special case for empty strings */
11573 if (PyUnicode_GET_LENGTH(self) == 0)
11574 return 0;
11575 kind = PyUnicode_KIND(self);
11576 data = PyUnicode_DATA(self);
Martin v. Löwis47383402007-08-15 07:32:56 +000011577
11578 /* PEP 3131 says that the first character must be in
11579 XID_Start and subsequent characters in XID_Continue,
11580 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +000011581 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +000011582 letters, digits, underscore). However, given the current
11583 definition of XID_Start and XID_Continue, it is sufficient
11584 to check just for these, except that _ must be allowed
11585 as starting an identifier. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011586 first = PyUnicode_READ(kind, data, 0);
Benjamin Petersonf413b802011-08-12 22:17:18 -050011587 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +000011588 return 0;
11589
Benjamin Peterson9c6e6a02011-09-28 08:09:05 -040011590 for (i = 1; i < PyUnicode_GET_LENGTH(self); i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011591 if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011592 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +000011593 return 1;
11594}
11595
11596PyDoc_STRVAR(isidentifier__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011597 "S.isidentifier() -> bool\n\
Martin v. Löwis47383402007-08-15 07:32:56 +000011598\n\
11599Return True if S is a valid identifier according\n\
11600to the language definition.");
11601
11602static PyObject*
11603unicode_isidentifier(PyObject *self)
11604{
11605 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
11606}
11607
Georg Brandl559e5d72008-06-11 18:37:52 +000011608PyDoc_STRVAR(isprintable__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011609 "S.isprintable() -> bool\n\
Georg Brandl559e5d72008-06-11 18:37:52 +000011610\n\
11611Return True if all characters in S are considered\n\
11612printable in repr() or S is empty, False otherwise.");
11613
11614static PyObject*
11615unicode_isprintable(PyObject *self)
11616{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011617 Py_ssize_t i, length;
11618 int kind;
11619 void *data;
11620
11621 if (PyUnicode_READY(self) == -1)
11622 return NULL;
11623 length = PyUnicode_GET_LENGTH(self);
11624 kind = PyUnicode_KIND(self);
11625 data = PyUnicode_DATA(self);
Georg Brandl559e5d72008-06-11 18:37:52 +000011626
11627 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011628 if (length == 1)
11629 return PyBool_FromLong(
11630 Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
Georg Brandl559e5d72008-06-11 18:37:52 +000011631
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011632 for (i = 0; i < length; i++) {
11633 if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
Georg Brandl559e5d72008-06-11 18:37:52 +000011634 Py_RETURN_FALSE;
11635 }
11636 }
11637 Py_RETURN_TRUE;
11638}
11639
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011640PyDoc_STRVAR(join__doc__,
Georg Brandl495f7b52009-10-27 15:28:25 +000011641 "S.join(iterable) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011642\n\
11643Return a string which is the concatenation of the strings in the\n\
Georg Brandl495f7b52009-10-27 15:28:25 +000011644iterable. The separator between elements is S.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011645
11646static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011647unicode_join(PyObject *self, PyObject *data)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011648{
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011649 return PyUnicode_Join(self, data);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011650}
11651
Martin v. Löwis18e16552006-02-15 17:27:45 +000011652static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011653unicode_length(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011654{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011655 if (PyUnicode_READY(self) == -1)
11656 return -1;
11657 return PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011658}
11659
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011660PyDoc_STRVAR(ljust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011661 "S.ljust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011662\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000011663Return S left-justified in a Unicode string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011664done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011665
11666static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020011667unicode_ljust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011668{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011669 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011670 Py_UCS4 fillchar = ' ';
11671
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011672 if (!PyArg_ParseTuple(args, "n|O&:ljust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011673 return NULL;
11674
Victor Stinnerc4b49542011-12-11 22:44:26 +010011675 if (PyUnicode_READY(self) < 0)
11676 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011677
Victor Stinnerc4b49542011-12-11 22:44:26 +010011678 if (PyUnicode_GET_LENGTH(self) >= width)
11679 return unicode_result_unchanged(self);
11680
11681 return pad(self, 0, width - PyUnicode_GET_LENGTH(self), fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011682}
11683
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011684PyDoc_STRVAR(lower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011685 "S.lower() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011686\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011687Return a copy of the string S converted to lowercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011688
11689static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020011690unicode_lower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011691{
Guido van Rossumd57fd912000-03-10 22:53:23 +000011692 return fixup(self, fixlower);
11693}
11694
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011695#define LEFTSTRIP 0
11696#define RIGHTSTRIP 1
11697#define BOTHSTRIP 2
11698
11699/* Arrays indexed by above */
11700static const char *stripformat[] = {"|O:lstrip", "|O:rstrip", "|O:strip"};
11701
11702#define STRIPNAME(i) (stripformat[i]+3)
11703
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011704/* externally visible for str.strip(unicode) */
11705PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011706_PyUnicode_XStrip(PyObject *self, int striptype, PyObject *sepobj)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011707{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011708 void *data;
11709 int kind;
11710 Py_ssize_t i, j, len;
11711 BLOOM_MASK sepmask;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011712
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011713 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
11714 return NULL;
11715
11716 kind = PyUnicode_KIND(self);
11717 data = PyUnicode_DATA(self);
11718 len = PyUnicode_GET_LENGTH(self);
11719 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
11720 PyUnicode_DATA(sepobj),
11721 PyUnicode_GET_LENGTH(sepobj));
Thomas Wouters477c8d52006-05-27 19:21:47 +000011722
Benjamin Peterson14339b62009-01-31 16:36:08 +000011723 i = 0;
11724 if (striptype != RIGHTSTRIP) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011725 while (i < len &&
11726 BLOOM_MEMBER(sepmask, PyUnicode_READ(kind, data, i), sepobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011727 i++;
11728 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011729 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011730
Benjamin Peterson14339b62009-01-31 16:36:08 +000011731 j = len;
11732 if (striptype != LEFTSTRIP) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011733 do {
11734 j--;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011735 } while (j >= i &&
11736 BLOOM_MEMBER(sepmask, PyUnicode_READ(kind, data, j), sepobj));
Benjamin Peterson29060642009-01-31 22:14:21 +000011737 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011738 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011739
Victor Stinner7931d9a2011-11-04 00:22:48 +010011740 return PyUnicode_Substring(self, i, j);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011741}
11742
11743PyObject*
11744PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
11745{
11746 unsigned char *data;
11747 int kind;
Victor Stinner12bab6d2011-10-01 01:53:49 +020011748 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011749
Victor Stinnerde636f32011-10-01 03:55:54 +020011750 if (PyUnicode_READY(self) == -1)
11751 return NULL;
11752
11753 end = Py_MIN(end, PyUnicode_GET_LENGTH(self));
11754
Victor Stinner12bab6d2011-10-01 01:53:49 +020011755 if (start == 0 && end == PyUnicode_GET_LENGTH(self))
Victor Stinnerc4b49542011-12-11 22:44:26 +010011756 return unicode_result_unchanged(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011757
Victor Stinner12bab6d2011-10-01 01:53:49 +020011758 length = end - start;
11759 if (length == 1)
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011760 return unicode_getitem(self, start);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011761
Victor Stinnerde636f32011-10-01 03:55:54 +020011762 if (start < 0 || end < 0) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020011763 PyErr_SetString(PyExc_IndexError, "string index out of range");
11764 return NULL;
11765 }
11766
Victor Stinnerb9275c12011-10-05 14:01:42 +020011767 if (PyUnicode_IS_ASCII(self)) {
11768 kind = PyUnicode_KIND(self);
11769 data = PyUnicode_1BYTE_DATA(self);
11770 return unicode_fromascii(data + start, length);
11771 }
11772 else {
11773 kind = PyUnicode_KIND(self);
11774 data = PyUnicode_1BYTE_DATA(self);
11775 return PyUnicode_FromKindAndData(kind,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020011776 data + kind * start,
Victor Stinnerb9275c12011-10-05 14:01:42 +020011777 length);
11778 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011779}
Guido van Rossumd57fd912000-03-10 22:53:23 +000011780
11781static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011782do_strip(PyObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011783{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011784 int kind;
11785 void *data;
11786 Py_ssize_t len, i, j;
11787
11788 if (PyUnicode_READY(self) == -1)
11789 return NULL;
11790
11791 kind = PyUnicode_KIND(self);
11792 data = PyUnicode_DATA(self);
11793 len = PyUnicode_GET_LENGTH(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011794
Benjamin Peterson14339b62009-01-31 16:36:08 +000011795 i = 0;
11796 if (striptype != RIGHTSTRIP) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011797 while (i < len && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, i))) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000011798 i++;
11799 }
11800 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011801
Benjamin Peterson14339b62009-01-31 16:36:08 +000011802 j = len;
11803 if (striptype != LEFTSTRIP) {
11804 do {
11805 j--;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011806 } while (j >= i && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, j)));
Benjamin Peterson14339b62009-01-31 16:36:08 +000011807 j++;
11808 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011809
Victor Stinner7931d9a2011-11-04 00:22:48 +010011810 return PyUnicode_Substring(self, i, j);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011811}
11812
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011813
11814static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011815do_argstrip(PyObject *self, int striptype, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011816{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011817 PyObject *sep = NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011818
Benjamin Peterson14339b62009-01-31 16:36:08 +000011819 if (!PyArg_ParseTuple(args, (char *)stripformat[striptype], &sep))
11820 return NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011821
Benjamin Peterson14339b62009-01-31 16:36:08 +000011822 if (sep != NULL && sep != Py_None) {
11823 if (PyUnicode_Check(sep))
11824 return _PyUnicode_XStrip(self, striptype, sep);
11825 else {
11826 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000011827 "%s arg must be None or str",
11828 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +000011829 return NULL;
11830 }
11831 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011832
Benjamin Peterson14339b62009-01-31 16:36:08 +000011833 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011834}
11835
11836
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011837PyDoc_STRVAR(strip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011838 "S.strip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011839\n\
11840Return a copy of the string S with leading and trailing\n\
11841whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011842If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011843
11844static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011845unicode_strip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011846{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011847 if (PyTuple_GET_SIZE(args) == 0)
11848 return do_strip(self, BOTHSTRIP); /* Common case */
11849 else
11850 return do_argstrip(self, BOTHSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011851}
11852
11853
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011854PyDoc_STRVAR(lstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011855 "S.lstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011856\n\
11857Return a copy of the string S with leading whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011858If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011859
11860static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011861unicode_lstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011862{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011863 if (PyTuple_GET_SIZE(args) == 0)
11864 return do_strip(self, LEFTSTRIP); /* Common case */
11865 else
11866 return do_argstrip(self, LEFTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011867}
11868
11869
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011870PyDoc_STRVAR(rstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011871 "S.rstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011872\n\
11873Return a copy of the string S with trailing whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011874If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011875
11876static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011877unicode_rstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011878{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011879 if (PyTuple_GET_SIZE(args) == 0)
11880 return do_strip(self, RIGHTSTRIP); /* Common case */
11881 else
11882 return do_argstrip(self, RIGHTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011883}
11884
11885
Guido van Rossumd57fd912000-03-10 22:53:23 +000011886static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011887unicode_repeat(PyObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011888{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011889 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011890 Py_ssize_t nchars, n;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011891
Georg Brandl222de0f2009-04-12 12:01:50 +000011892 if (len < 1) {
11893 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +020011894 return unicode_empty;
Georg Brandl222de0f2009-04-12 12:01:50 +000011895 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011896
Victor Stinnerc4b49542011-12-11 22:44:26 +010011897 /* no repeat, return original string */
11898 if (len == 1)
11899 return unicode_result_unchanged(str);
Tim Peters8f422462000-09-09 06:13:41 +000011900
Victor Stinnerc4b49542011-12-11 22:44:26 +010011901 if (PyUnicode_READY(str) < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011902 return NULL;
11903
Victor Stinnerc759f3e2011-10-01 03:09:58 +020011904 if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
Victor Stinner67ca64c2011-10-01 02:47:29 +020011905 PyErr_SetString(PyExc_OverflowError,
11906 "repeated string is too long");
11907 return NULL;
11908 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011909 nchars = len * PyUnicode_GET_LENGTH(str);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011910
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011911 u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011912 if (!u)
11913 return NULL;
Victor Stinner67ca64c2011-10-01 02:47:29 +020011914 assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011915
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011916 if (PyUnicode_GET_LENGTH(str) == 1) {
11917 const int kind = PyUnicode_KIND(str);
11918 const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
11919 void *to = PyUnicode_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011920 if (kind == PyUnicode_1BYTE_KIND)
11921 memset(to, (unsigned char)fill_char, len);
11922 else {
11923 for (n = 0; n < len; ++n)
11924 PyUnicode_WRITE(kind, to, n, fill_char);
11925 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011926 }
11927 else {
11928 /* number of characters copied this far */
11929 Py_ssize_t done = PyUnicode_GET_LENGTH(str);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020011930 const Py_ssize_t char_size = PyUnicode_KIND(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011931 char *to = (char *) PyUnicode_DATA(u);
11932 Py_MEMCPY(to, PyUnicode_DATA(str),
11933 PyUnicode_GET_LENGTH(str) * char_size);
Benjamin Peterson29060642009-01-31 22:14:21 +000011934 while (done < nchars) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011935 n = (done <= nchars-done) ? done : nchars-done;
11936 Py_MEMCPY(to + (done * char_size), to, n * char_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011937 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +000011938 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011939 }
11940
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020011941 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011942 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011943}
11944
Alexander Belopolsky40018472011-02-26 01:02:56 +000011945PyObject *
11946PyUnicode_Replace(PyObject *obj,
11947 PyObject *subobj,
11948 PyObject *replobj,
11949 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011950{
11951 PyObject *self;
11952 PyObject *str1;
11953 PyObject *str2;
11954 PyObject *result;
11955
11956 self = PyUnicode_FromObject(obj);
Victor Stinnere9a29352011-10-01 02:14:59 +020011957 if (self == NULL || PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000011958 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011959 str1 = PyUnicode_FromObject(subobj);
Victor Stinnere9a29352011-10-01 02:14:59 +020011960 if (str1 == NULL || PyUnicode_READY(str1) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011961 Py_DECREF(self);
11962 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011963 }
11964 str2 = PyUnicode_FromObject(replobj);
Victor Stinnere9a29352011-10-01 02:14:59 +020011965 if (str2 == NULL || PyUnicode_READY(str2)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011966 Py_DECREF(self);
11967 Py_DECREF(str1);
11968 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011969 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011970 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011971 Py_DECREF(self);
11972 Py_DECREF(str1);
11973 Py_DECREF(str2);
11974 return result;
11975}
11976
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011977PyDoc_STRVAR(replace__doc__,
Ezio Melottic1897e72010-06-26 18:50:39 +000011978 "S.replace(old, new[, count]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011979\n\
11980Return a copy of S with all occurrences of substring\n\
Georg Brandlf08a9dd2008-06-10 16:57:31 +000011981old replaced by new. If the optional argument count is\n\
11982given, only the first count occurrences are replaced.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011983
11984static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011985unicode_replace(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011986{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011987 PyObject *str1;
11988 PyObject *str2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011989 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011990 PyObject *result;
11991
Martin v. Löwis18e16552006-02-15 17:27:45 +000011992 if (!PyArg_ParseTuple(args, "OO|n:replace", &str1, &str2, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011993 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011994 if (!PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000011995 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011996 str1 = PyUnicode_FromObject(str1);
11997 if (str1 == NULL || PyUnicode_READY(str1) == -1)
11998 return NULL;
11999 str2 = PyUnicode_FromObject(str2);
Victor Stinnere9a29352011-10-01 02:14:59 +020012000 if (str2 == NULL || PyUnicode_READY(str2) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012001 Py_DECREF(str1);
12002 return NULL;
Walter Dörwaldf6b56ae2003-02-09 23:42:56 +000012003 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012004
12005 result = replace(self, str1, str2, maxcount);
12006
12007 Py_DECREF(str1);
12008 Py_DECREF(str2);
12009 return result;
12010}
12011
Alexander Belopolsky40018472011-02-26 01:02:56 +000012012static PyObject *
12013unicode_repr(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012014{
Walter Dörwald79e913e2007-05-12 11:08:06 +000012015 PyObject *repr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012016 Py_ssize_t isize;
12017 Py_ssize_t osize, squote, dquote, i, o;
12018 Py_UCS4 max, quote;
12019 int ikind, okind;
12020 void *idata, *odata;
Walter Dörwald79e913e2007-05-12 11:08:06 +000012021
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012022 if (PyUnicode_READY(unicode) == -1)
Walter Dörwald79e913e2007-05-12 11:08:06 +000012023 return NULL;
12024
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012025 isize = PyUnicode_GET_LENGTH(unicode);
12026 idata = PyUnicode_DATA(unicode);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012027
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012028 /* Compute length of output, quote characters, and
12029 maximum character */
12030 osize = 2; /* quotes */
12031 max = 127;
12032 squote = dquote = 0;
12033 ikind = PyUnicode_KIND(unicode);
12034 for (i = 0; i < isize; i++) {
12035 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
12036 switch (ch) {
12037 case '\'': squote++; osize++; break;
12038 case '"': dquote++; osize++; break;
12039 case '\\': case '\t': case '\r': case '\n':
12040 osize += 2; break;
12041 default:
12042 /* Fast-path ASCII */
12043 if (ch < ' ' || ch == 0x7f)
12044 osize += 4; /* \xHH */
12045 else if (ch < 0x7f)
12046 osize++;
12047 else if (Py_UNICODE_ISPRINTABLE(ch)) {
12048 osize++;
12049 max = ch > max ? ch : max;
12050 }
12051 else if (ch < 0x100)
12052 osize += 4; /* \xHH */
12053 else if (ch < 0x10000)
12054 osize += 6; /* \uHHHH */
12055 else
12056 osize += 10; /* \uHHHHHHHH */
12057 }
12058 }
12059
12060 quote = '\'';
12061 if (squote) {
12062 if (dquote)
12063 /* Both squote and dquote present. Use squote,
12064 and escape them */
12065 osize += squote;
12066 else
12067 quote = '"';
12068 }
12069
12070 repr = PyUnicode_New(osize, max);
12071 if (repr == NULL)
12072 return NULL;
12073 okind = PyUnicode_KIND(repr);
12074 odata = PyUnicode_DATA(repr);
12075
12076 PyUnicode_WRITE(okind, odata, 0, quote);
12077 PyUnicode_WRITE(okind, odata, osize-1, quote);
12078
12079 for (i = 0, o = 1; i < isize; i++) {
12080 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012081
12082 /* Escape quotes and backslashes */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012083 if ((ch == quote) || (ch == '\\')) {
12084 PyUnicode_WRITE(okind, odata, o++, '\\');
12085 PyUnicode_WRITE(okind, odata, o++, ch);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012086 continue;
12087 }
12088
Benjamin Peterson29060642009-01-31 22:14:21 +000012089 /* Map special whitespace to '\t', \n', '\r' */
Georg Brandl559e5d72008-06-11 18:37:52 +000012090 if (ch == '\t') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012091 PyUnicode_WRITE(okind, odata, o++, '\\');
12092 PyUnicode_WRITE(okind, odata, o++, 't');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012093 }
12094 else if (ch == '\n') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012095 PyUnicode_WRITE(okind, odata, o++, '\\');
12096 PyUnicode_WRITE(okind, odata, o++, 'n');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012097 }
12098 else if (ch == '\r') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012099 PyUnicode_WRITE(okind, odata, o++, '\\');
12100 PyUnicode_WRITE(okind, odata, o++, 'r');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012101 }
12102
12103 /* Map non-printable US ASCII to '\xhh' */
Georg Brandl559e5d72008-06-11 18:37:52 +000012104 else if (ch < ' ' || ch == 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012105 PyUnicode_WRITE(okind, odata, o++, '\\');
12106 PyUnicode_WRITE(okind, odata, o++, 'x');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012107 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12108 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012109 }
12110
Georg Brandl559e5d72008-06-11 18:37:52 +000012111 /* Copy ASCII characters as-is */
12112 else if (ch < 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012113 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000012114 }
12115
Benjamin Peterson29060642009-01-31 22:14:21 +000012116 /* Non-ASCII characters */
Georg Brandl559e5d72008-06-11 18:37:52 +000012117 else {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012118 /* Map Unicode whitespace and control characters
Georg Brandl559e5d72008-06-11 18:37:52 +000012119 (categories Z* and C* except ASCII space)
12120 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012121 if (!Py_UNICODE_ISPRINTABLE(ch)) {
Georg Brandl559e5d72008-06-11 18:37:52 +000012122 /* Map 8-bit characters to '\xhh' */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012123 if (ch <= 0xff) {
12124 PyUnicode_WRITE(okind, odata, o++, '\\');
12125 PyUnicode_WRITE(okind, odata, o++, 'x');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012126 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12127 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012128 }
12129 /* Map 21-bit characters to '\U00xxxxxx' */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012130 else if (ch >= 0x10000) {
12131 PyUnicode_WRITE(okind, odata, o++, '\\');
12132 PyUnicode_WRITE(okind, odata, o++, 'U');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012133 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 28) & 0xF]);
12134 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 24) & 0xF]);
12135 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 20) & 0xF]);
12136 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 16) & 0xF]);
12137 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12138 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12139 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12140 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012141 }
12142 /* Map 16-bit characters to '\uxxxx' */
12143 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012144 PyUnicode_WRITE(okind, odata, o++, '\\');
12145 PyUnicode_WRITE(okind, odata, o++, 'u');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012146 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12147 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12148 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12149 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012150 }
12151 }
12152 /* Copy characters as-is */
12153 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012154 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000012155 }
12156 }
Walter Dörwald79e913e2007-05-12 11:08:06 +000012157 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012158 /* Closing quote already added at the beginning */
Victor Stinner05d11892011-10-06 01:13:58 +020012159 assert(_PyUnicode_CheckConsistency(repr, 1));
Walter Dörwald79e913e2007-05-12 11:08:06 +000012160 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012161}
12162
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012163PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012164 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012165\n\
12166Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080012167such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012168arguments start and end are interpreted as in slice notation.\n\
12169\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012170Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012171
12172static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012173unicode_rfind(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012174{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012175 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012176 Py_ssize_t start;
12177 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012178 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012179
Jesus Ceaac451502011-04-20 17:09:23 +020012180 if (!stringlib_parse_args_finds_unicode("rfind", args, &substring,
12181 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012182 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012183
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012184 if (PyUnicode_READY(self) == -1)
12185 return NULL;
12186 if (PyUnicode_READY(substring) == -1)
12187 return NULL;
12188
Victor Stinner7931d9a2011-11-04 00:22:48 +010012189 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012190
12191 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012192
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012193 if (result == -2)
12194 return NULL;
12195
Christian Heimes217cfd12007-12-02 14:31:20 +000012196 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012197}
12198
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012199PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012200 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012201\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012202Like S.rfind() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012203
12204static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012205unicode_rindex(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012206{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012207 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012208 Py_ssize_t start;
12209 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012210 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012211
Jesus Ceaac451502011-04-20 17:09:23 +020012212 if (!stringlib_parse_args_finds_unicode("rindex", args, &substring,
12213 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012214 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012215
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012216 if (PyUnicode_READY(self) == -1)
12217 return NULL;
12218 if (PyUnicode_READY(substring) == -1)
12219 return NULL;
12220
Victor Stinner7931d9a2011-11-04 00:22:48 +010012221 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012222
12223 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012224
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012225 if (result == -2)
12226 return NULL;
12227
Guido van Rossumd57fd912000-03-10 22:53:23 +000012228 if (result < 0) {
12229 PyErr_SetString(PyExc_ValueError, "substring not found");
12230 return NULL;
12231 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012232
Christian Heimes217cfd12007-12-02 14:31:20 +000012233 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012234}
12235
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012236PyDoc_STRVAR(rjust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012237 "S.rjust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012238\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012239Return S right-justified in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012240done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012241
12242static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012243unicode_rjust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012244{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012245 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012246 Py_UCS4 fillchar = ' ';
12247
Victor Stinnere9a29352011-10-01 02:14:59 +020012248 if (!PyArg_ParseTuple(args, "n|O&:rjust", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012249 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012250
Victor Stinnerc4b49542011-12-11 22:44:26 +010012251 if (PyUnicode_READY(self) < 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012252 return NULL;
12253
Victor Stinnerc4b49542011-12-11 22:44:26 +010012254 if (PyUnicode_GET_LENGTH(self) >= width)
12255 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012256
Victor Stinnerc4b49542011-12-11 22:44:26 +010012257 return pad(self, width - PyUnicode_GET_LENGTH(self), 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012258}
12259
Alexander Belopolsky40018472011-02-26 01:02:56 +000012260PyObject *
12261PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012262{
12263 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +000012264
Guido van Rossumd57fd912000-03-10 22:53:23 +000012265 s = PyUnicode_FromObject(s);
12266 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012267 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012268 if (sep != NULL) {
12269 sep = PyUnicode_FromObject(sep);
12270 if (sep == NULL) {
12271 Py_DECREF(s);
12272 return NULL;
12273 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012274 }
12275
Victor Stinner9310abb2011-10-05 00:59:23 +020012276 result = split(s, sep, maxsplit);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012277
12278 Py_DECREF(s);
12279 Py_XDECREF(sep);
12280 return result;
12281}
12282
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012283PyDoc_STRVAR(split__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012284 "S.split([sep[, maxsplit]]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012285\n\
12286Return a list of the words in S, using sep as the\n\
12287delimiter string. If maxsplit is given, at most maxsplit\n\
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000012288splits are done. If sep is not specified or is None, any\n\
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +000012289whitespace string is a separator and empty strings are\n\
12290removed from the result.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012291
12292static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012293unicode_split(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012294{
12295 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012296 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012297
Martin v. Löwis18e16552006-02-15 17:27:45 +000012298 if (!PyArg_ParseTuple(args, "|On:split", &substring, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012299 return NULL;
12300
12301 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012302 return split(self, NULL, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012303 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012304 return split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012305 else
Victor Stinner7931d9a2011-11-04 00:22:48 +010012306 return PyUnicode_Split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012307}
12308
Thomas Wouters477c8d52006-05-27 19:21:47 +000012309PyObject *
12310PyUnicode_Partition(PyObject *str_in, PyObject *sep_in)
12311{
12312 PyObject* str_obj;
12313 PyObject* sep_obj;
12314 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012315 int kind1, kind2, kind;
12316 void *buf1 = NULL, *buf2 = NULL;
12317 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012318
12319 str_obj = PyUnicode_FromObject(str_in);
Victor Stinnere9a29352011-10-01 02:14:59 +020012320 if (!str_obj || PyUnicode_READY(str_obj) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000012321 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012322 sep_obj = PyUnicode_FromObject(sep_in);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012323 if (!sep_obj || PyUnicode_READY(sep_obj) == -1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000012324 Py_DECREF(str_obj);
12325 return NULL;
12326 }
12327
Victor Stinner14f8f022011-10-05 20:58:25 +020012328 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012329 kind2 = PyUnicode_KIND(sep_obj);
Victor Stinner14f8f022011-10-05 20:58:25 +020012330 kind = Py_MAX(kind1, kind2);
12331 buf1 = PyUnicode_DATA(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012332 if (kind1 != kind)
Victor Stinner14f8f022011-10-05 20:58:25 +020012333 buf1 = _PyUnicode_AsKind(str_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012334 if (!buf1)
12335 goto onError;
12336 buf2 = PyUnicode_DATA(sep_obj);
12337 if (kind2 != kind)
12338 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12339 if (!buf2)
12340 goto onError;
12341 len1 = PyUnicode_GET_LENGTH(str_obj);
12342 len2 = PyUnicode_GET_LENGTH(sep_obj);
12343
Victor Stinner14f8f022011-10-05 20:58:25 +020012344 switch(PyUnicode_KIND(str_obj)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012345 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012346 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12347 out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12348 else
12349 out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012350 break;
12351 case PyUnicode_2BYTE_KIND:
12352 out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12353 break;
12354 case PyUnicode_4BYTE_KIND:
12355 out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12356 break;
12357 default:
12358 assert(0);
12359 out = 0;
12360 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012361
12362 Py_DECREF(sep_obj);
12363 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012364 if (kind1 != kind)
12365 PyMem_Free(buf1);
12366 if (kind2 != kind)
12367 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012368
12369 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012370 onError:
12371 Py_DECREF(sep_obj);
12372 Py_DECREF(str_obj);
12373 if (kind1 != kind && buf1)
12374 PyMem_Free(buf1);
12375 if (kind2 != kind && buf2)
12376 PyMem_Free(buf2);
12377 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012378}
12379
12380
12381PyObject *
12382PyUnicode_RPartition(PyObject *str_in, PyObject *sep_in)
12383{
12384 PyObject* str_obj;
12385 PyObject* sep_obj;
12386 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012387 int kind1, kind2, kind;
12388 void *buf1 = NULL, *buf2 = NULL;
12389 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012390
12391 str_obj = PyUnicode_FromObject(str_in);
12392 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012393 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012394 sep_obj = PyUnicode_FromObject(sep_in);
12395 if (!sep_obj) {
12396 Py_DECREF(str_obj);
12397 return NULL;
12398 }
12399
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012400 kind1 = PyUnicode_KIND(str_in);
12401 kind2 = PyUnicode_KIND(sep_obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +020012402 kind = Py_MAX(kind1, kind2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012403 buf1 = PyUnicode_DATA(str_in);
12404 if (kind1 != kind)
12405 buf1 = _PyUnicode_AsKind(str_in, kind);
12406 if (!buf1)
12407 goto onError;
12408 buf2 = PyUnicode_DATA(sep_obj);
12409 if (kind2 != kind)
12410 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12411 if (!buf2)
12412 goto onError;
12413 len1 = PyUnicode_GET_LENGTH(str_obj);
12414 len2 = PyUnicode_GET_LENGTH(sep_obj);
12415
12416 switch(PyUnicode_KIND(str_in)) {
12417 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012418 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12419 out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12420 else
12421 out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012422 break;
12423 case PyUnicode_2BYTE_KIND:
12424 out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12425 break;
12426 case PyUnicode_4BYTE_KIND:
12427 out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12428 break;
12429 default:
12430 assert(0);
12431 out = 0;
12432 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012433
12434 Py_DECREF(sep_obj);
12435 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012436 if (kind1 != kind)
12437 PyMem_Free(buf1);
12438 if (kind2 != kind)
12439 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012440
12441 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012442 onError:
12443 Py_DECREF(sep_obj);
12444 Py_DECREF(str_obj);
12445 if (kind1 != kind && buf1)
12446 PyMem_Free(buf1);
12447 if (kind2 != kind && buf2)
12448 PyMem_Free(buf2);
12449 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012450}
12451
12452PyDoc_STRVAR(partition__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012453 "S.partition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012454\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012455Search for the separator sep in S, and return the part before it,\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012456the separator itself, and the part after it. If the separator is not\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012457found, return S and two empty strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012458
12459static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012460unicode_partition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012461{
Victor Stinner9310abb2011-10-05 00:59:23 +020012462 return PyUnicode_Partition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012463}
12464
12465PyDoc_STRVAR(rpartition__doc__,
Ezio Melotti5b2b2422010-01-25 11:58:28 +000012466 "S.rpartition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012467\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012468Search for the separator sep in S, starting at the end of S, and return\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012469the part before it, the separator itself, and the part after it. If the\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012470separator is not found, return two empty strings and S.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012471
12472static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012473unicode_rpartition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012474{
Victor Stinner9310abb2011-10-05 00:59:23 +020012475 return PyUnicode_RPartition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012476}
12477
Alexander Belopolsky40018472011-02-26 01:02:56 +000012478PyObject *
12479PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012480{
12481 PyObject *result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012482
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012483 s = PyUnicode_FromObject(s);
12484 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012485 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012486 if (sep != NULL) {
12487 sep = PyUnicode_FromObject(sep);
12488 if (sep == NULL) {
12489 Py_DECREF(s);
12490 return NULL;
12491 }
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012492 }
12493
Victor Stinner9310abb2011-10-05 00:59:23 +020012494 result = rsplit(s, sep, maxsplit);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012495
12496 Py_DECREF(s);
12497 Py_XDECREF(sep);
12498 return result;
12499}
12500
12501PyDoc_STRVAR(rsplit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012502 "S.rsplit([sep[, maxsplit]]) -> list of strings\n\
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012503\n\
12504Return a list of the words in S, using sep as the\n\
12505delimiter string, starting at the end of the string and\n\
12506working to the front. If maxsplit is given, at most maxsplit\n\
12507splits are done. If sep is not specified, any whitespace string\n\
12508is a separator.");
12509
12510static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012511unicode_rsplit(PyObject *self, PyObject *args)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012512{
12513 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012514 Py_ssize_t maxcount = -1;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012515
Martin v. Löwis18e16552006-02-15 17:27:45 +000012516 if (!PyArg_ParseTuple(args, "|On:rsplit", &substring, &maxcount))
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012517 return NULL;
12518
12519 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012520 return rsplit(self, NULL, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012521 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012522 return rsplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012523 else
Victor Stinner9310abb2011-10-05 00:59:23 +020012524 return PyUnicode_RSplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012525}
12526
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012527PyDoc_STRVAR(splitlines__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012528 "S.splitlines([keepends]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012529\n\
12530Return a list of the lines in S, breaking at line boundaries.\n\
Guido van Rossum86662912000-04-11 15:38:46 +000012531Line breaks are not included in the resulting list unless keepends\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012532is given and true.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012533
12534static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012535unicode_splitlines(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012536{
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012537 static char *kwlist[] = {"keepends", 0};
Guido van Rossum86662912000-04-11 15:38:46 +000012538 int keepends = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012539
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012540 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:splitlines",
12541 kwlist, &keepends))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012542 return NULL;
12543
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012544 return PyUnicode_Splitlines(self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012545}
12546
12547static
Guido van Rossumf15a29f2007-05-04 00:41:39 +000012548PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012549{
Victor Stinnerc4b49542011-12-11 22:44:26 +010012550 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012551}
12552
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012553PyDoc_STRVAR(swapcase__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012554 "S.swapcase() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012555\n\
12556Return a copy of S with uppercase characters converted to lowercase\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012557and vice versa.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012558
12559static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012560unicode_swapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012561{
Guido van Rossumd57fd912000-03-10 22:53:23 +000012562 return fixup(self, fixswapcase);
12563}
12564
Georg Brandlceee0772007-11-27 23:48:05 +000012565PyDoc_STRVAR(maketrans__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012566 "str.maketrans(x[, y[, z]]) -> dict (static method)\n\
Georg Brandlceee0772007-11-27 23:48:05 +000012567\n\
12568Return a translation table usable for str.translate().\n\
12569If there is only one argument, it must be a dictionary mapping Unicode\n\
12570ordinals (integers) or characters to Unicode ordinals, strings or None.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012571Character keys will be then converted to ordinals.\n\
Georg Brandlceee0772007-11-27 23:48:05 +000012572If there are two arguments, they must be strings of equal length, and\n\
12573in the resulting dictionary, each character in x will be mapped to the\n\
12574character at the same position in y. If there is a third argument, it\n\
12575must be a string, whose characters will be mapped to None in the result.");
12576
12577static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012578unicode_maketrans(PyObject *null, PyObject *args)
Georg Brandlceee0772007-11-27 23:48:05 +000012579{
12580 PyObject *x, *y = NULL, *z = NULL;
12581 PyObject *new = NULL, *key, *value;
12582 Py_ssize_t i = 0;
12583 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012584
Georg Brandlceee0772007-11-27 23:48:05 +000012585 if (!PyArg_ParseTuple(args, "O|UU:maketrans", &x, &y, &z))
12586 return NULL;
12587 new = PyDict_New();
12588 if (!new)
12589 return NULL;
12590 if (y != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012591 int x_kind, y_kind, z_kind;
12592 void *x_data, *y_data, *z_data;
12593
Georg Brandlceee0772007-11-27 23:48:05 +000012594 /* x must be a string too, of equal length */
Georg Brandlceee0772007-11-27 23:48:05 +000012595 if (!PyUnicode_Check(x)) {
12596 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
12597 "be a string if there is a second argument");
12598 goto err;
12599 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012600 if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012601 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
12602 "arguments must have equal length");
12603 goto err;
12604 }
12605 /* create entries for translating chars in x to those in y */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012606 x_kind = PyUnicode_KIND(x);
12607 y_kind = PyUnicode_KIND(y);
12608 x_data = PyUnicode_DATA(x);
12609 y_data = PyUnicode_DATA(y);
12610 for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
12611 key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
12612 value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000012613 if (!key || !value)
12614 goto err;
12615 res = PyDict_SetItem(new, key, value);
12616 Py_DECREF(key);
12617 Py_DECREF(value);
12618 if (res < 0)
12619 goto err;
12620 }
12621 /* create entries for deleting chars in z */
12622 if (z != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012623 z_kind = PyUnicode_KIND(z);
12624 z_data = PyUnicode_DATA(z);
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012625 for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012626 key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000012627 if (!key)
12628 goto err;
12629 res = PyDict_SetItem(new, key, Py_None);
12630 Py_DECREF(key);
12631 if (res < 0)
12632 goto err;
12633 }
12634 }
12635 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012636 int kind;
12637 void *data;
12638
Georg Brandlceee0772007-11-27 23:48:05 +000012639 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +000012640 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012641 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
12642 "to maketrans it must be a dict");
12643 goto err;
12644 }
12645 /* copy entries into the new dict, converting string keys to int keys */
12646 while (PyDict_Next(x, &i, &key, &value)) {
12647 if (PyUnicode_Check(key)) {
12648 /* convert string keys to integer keys */
12649 PyObject *newkey;
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012650 if (PyUnicode_GET_LENGTH(key) != 1) {
Georg Brandlceee0772007-11-27 23:48:05 +000012651 PyErr_SetString(PyExc_ValueError, "string keys in translate "
12652 "table must be of length 1");
12653 goto err;
12654 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012655 kind = PyUnicode_KIND(key);
12656 data = PyUnicode_DATA(key);
12657 newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
Georg Brandlceee0772007-11-27 23:48:05 +000012658 if (!newkey)
12659 goto err;
12660 res = PyDict_SetItem(new, newkey, value);
12661 Py_DECREF(newkey);
12662 if (res < 0)
12663 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +000012664 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012665 /* just keep integer keys */
12666 if (PyDict_SetItem(new, key, value) < 0)
12667 goto err;
12668 } else {
12669 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
12670 "be strings or integers");
12671 goto err;
12672 }
12673 }
12674 }
12675 return new;
12676 err:
12677 Py_DECREF(new);
12678 return NULL;
12679}
12680
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012681PyDoc_STRVAR(translate__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012682 "S.translate(table) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012683\n\
12684Return a copy of the string S, where all characters have been mapped\n\
12685through the given translation table, which must be a mapping of\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012686Unicode ordinals to Unicode ordinals, strings, or None.\n\
Walter Dörwald5c1ee172002-09-04 20:31:32 +000012687Unmapped characters are left untouched. Characters mapped to None\n\
12688are deleted.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012689
12690static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012691unicode_translate(PyObject *self, PyObject *table)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012692{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012693 return _PyUnicode_TranslateCharmap(self, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012694}
12695
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012696PyDoc_STRVAR(upper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012697 "S.upper() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012698\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012699Return a copy of S converted to uppercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012700
12701static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012702unicode_upper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012703{
Guido van Rossumd57fd912000-03-10 22:53:23 +000012704 return fixup(self, fixupper);
12705}
12706
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012707PyDoc_STRVAR(zfill__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012708 "S.zfill(width) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012709\n\
Benjamin Peterson9aa42992008-09-10 21:57:34 +000012710Pad a numeric string S with zeros on the left, to fill a field\n\
12711of the specified width. The string S is never truncated.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012712
12713static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012714unicode_zfill(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012715{
Martin v. Löwis18e16552006-02-15 17:27:45 +000012716 Py_ssize_t fill;
Victor Stinner9310abb2011-10-05 00:59:23 +020012717 PyObject *u;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012718 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012719 int kind;
12720 void *data;
12721 Py_UCS4 chr;
12722
Martin v. Löwis18e16552006-02-15 17:27:45 +000012723 if (!PyArg_ParseTuple(args, "n:zfill", &width))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012724 return NULL;
12725
Victor Stinnerc4b49542011-12-11 22:44:26 +010012726 if (PyUnicode_READY(self) < 0)
12727 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012728
Victor Stinnerc4b49542011-12-11 22:44:26 +010012729 if (PyUnicode_GET_LENGTH(self) >= width)
12730 return unicode_result_unchanged(self);
12731
12732 fill = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012733
12734 u = pad(self, fill, 0, '0');
12735
Walter Dörwald068325e2002-04-15 13:36:47 +000012736 if (u == NULL)
12737 return NULL;
12738
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012739 kind = PyUnicode_KIND(u);
12740 data = PyUnicode_DATA(u);
12741 chr = PyUnicode_READ(kind, data, fill);
12742
12743 if (chr == '+' || chr == '-') {
Guido van Rossumd57fd912000-03-10 22:53:23 +000012744 /* move sign to beginning of string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012745 PyUnicode_WRITE(kind, data, 0, chr);
12746 PyUnicode_WRITE(kind, data, fill, '0');
Guido van Rossumd57fd912000-03-10 22:53:23 +000012747 }
12748
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012749 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +010012750 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012751}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012752
12753#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012754static PyObject *
12755unicode__decimal2ascii(PyObject *self)
12756{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012757 return PyUnicode_TransformDecimalAndSpaceToASCII(self);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012758}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012759#endif
12760
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012761PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012762 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012763\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000012764Return True if S starts with the specified prefix, False otherwise.\n\
12765With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012766With optional end, stop comparing S at that position.\n\
12767prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012768
12769static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012770unicode_startswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000012771 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012772{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012773 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012774 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012775 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012776 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012777 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012778
Jesus Ceaac451502011-04-20 17:09:23 +020012779 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000012780 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012781 if (PyTuple_Check(subobj)) {
12782 Py_ssize_t i;
12783 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012784 substring = PyUnicode_FromObject(PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012785 if (substring == NULL)
12786 return NULL;
12787 result = tailmatch(self, substring, start, end, -1);
12788 Py_DECREF(substring);
12789 if (result) {
12790 Py_RETURN_TRUE;
12791 }
12792 }
12793 /* nothing matched */
12794 Py_RETURN_FALSE;
12795 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012796 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030012797 if (substring == NULL) {
12798 if (PyErr_ExceptionMatches(PyExc_TypeError))
12799 PyErr_Format(PyExc_TypeError, "startswith first arg must be str or "
12800 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000012801 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030012802 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012803 result = tailmatch(self, substring, start, end, -1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012804 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012805 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012806}
12807
12808
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012809PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012810 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012811\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000012812Return True if S ends with the specified suffix, False otherwise.\n\
12813With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012814With optional end, stop comparing S at that position.\n\
12815suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012816
12817static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012818unicode_endswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000012819 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012820{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012821 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012822 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012823 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012824 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012825 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012826
Jesus Ceaac451502011-04-20 17:09:23 +020012827 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000012828 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012829 if (PyTuple_Check(subobj)) {
12830 Py_ssize_t i;
12831 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012832 substring = PyUnicode_FromObject(
Benjamin Peterson29060642009-01-31 22:14:21 +000012833 PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012834 if (substring == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000012835 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012836 result = tailmatch(self, substring, start, end, +1);
12837 Py_DECREF(substring);
12838 if (result) {
12839 Py_RETURN_TRUE;
12840 }
12841 }
12842 Py_RETURN_FALSE;
12843 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012844 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030012845 if (substring == NULL) {
12846 if (PyErr_ExceptionMatches(PyExc_TypeError))
12847 PyErr_Format(PyExc_TypeError, "endswith first arg must be str or "
12848 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000012849 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030012850 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012851 result = tailmatch(self, substring, start, end, +1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012852 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012853 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012854}
12855
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012856#include "stringlib/unicode_format.h"
Eric Smith8c663262007-08-25 02:26:07 +000012857
12858PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012859 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000012860\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012861Return a formatted version of S, using substitutions from args and kwargs.\n\
12862The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +000012863
Eric Smith27bbca62010-11-04 17:06:58 +000012864PyDoc_STRVAR(format_map__doc__,
12865 "S.format_map(mapping) -> str\n\
12866\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012867Return a formatted version of S, using substitutions from mapping.\n\
12868The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +000012869
Eric Smith4a7d76d2008-05-30 18:10:19 +000012870static PyObject *
12871unicode__format__(PyObject* self, PyObject* args)
12872{
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012873 PyObject *format_spec, *out;
Eric Smith4a7d76d2008-05-30 18:10:19 +000012874
12875 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
12876 return NULL;
12877
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012878 out = _PyUnicode_FormatAdvanced(self, format_spec, 0,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012879 PyUnicode_GET_LENGTH(format_spec));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012880 return out;
Eric Smith4a7d76d2008-05-30 18:10:19 +000012881}
12882
Eric Smith8c663262007-08-25 02:26:07 +000012883PyDoc_STRVAR(p_format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012884 "S.__format__(format_spec) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000012885\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012886Return a formatted version of S as described by format_spec.");
Eric Smith8c663262007-08-25 02:26:07 +000012887
12888static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012889unicode__sizeof__(PyObject *v)
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012890{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012891 Py_ssize_t size;
12892
12893 /* If it's a compact object, account for base structure +
12894 character data. */
12895 if (PyUnicode_IS_COMPACT_ASCII(v))
12896 size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(v) + 1;
12897 else if (PyUnicode_IS_COMPACT(v))
12898 size = sizeof(PyCompactUnicodeObject) +
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012899 (PyUnicode_GET_LENGTH(v) + 1) * PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012900 else {
12901 /* If it is a two-block object, account for base object, and
12902 for character block if present. */
12903 size = sizeof(PyUnicodeObject);
Victor Stinnerc3c74152011-10-02 20:39:55 +020012904 if (_PyUnicode_DATA_ANY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012905 size += (PyUnicode_GET_LENGTH(v) + 1) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012906 PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012907 }
12908 /* If the wstr pointer is present, account for it unless it is shared
Victor Stinnera3be6132011-10-03 02:16:37 +020012909 with the data pointer. Check if the data is not shared. */
Victor Stinner03490912011-10-03 23:45:12 +020012910 if (_PyUnicode_HAS_WSTR_MEMORY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012911 size += (PyUnicode_WSTR_LENGTH(v) + 1) * sizeof(wchar_t);
Victor Stinner829c0ad2011-10-03 01:08:02 +020012912 if (_PyUnicode_HAS_UTF8_MEMORY(v))
Victor Stinnere90fe6a2011-10-01 16:48:13 +020012913 size += PyUnicode_UTF8_LENGTH(v) + 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012914
12915 return PyLong_FromSsize_t(size);
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012916}
12917
12918PyDoc_STRVAR(sizeof__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012919 "S.__sizeof__() -> size of S in memory, in bytes");
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012920
12921static PyObject *
Victor Stinner034f6cf2011-09-30 02:26:44 +020012922unicode_getnewargs(PyObject *v)
Guido van Rossum5d9113d2003-01-29 17:58:45 +000012923{
Victor Stinnerbf6e5602011-12-12 01:53:47 +010012924 PyObject *copy = _PyUnicode_Copy(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012925 if (!copy)
12926 return NULL;
12927 return Py_BuildValue("(N)", copy);
Guido van Rossum5d9113d2003-01-29 17:58:45 +000012928}
12929
Guido van Rossumd57fd912000-03-10 22:53:23 +000012930static PyMethodDef unicode_methods[] = {
12931
12932 /* Order is according to common usage: often used methods should
12933 appear first, since lookup is done sequentially. */
12934
Benjamin Peterson28a4dce2010-12-12 01:33:04 +000012935 {"encode", (PyCFunction) unicode_encode, METH_VARARGS | METH_KEYWORDS, encode__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012936 {"replace", (PyCFunction) unicode_replace, METH_VARARGS, replace__doc__},
12937 {"split", (PyCFunction) unicode_split, METH_VARARGS, split__doc__},
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012938 {"rsplit", (PyCFunction) unicode_rsplit, METH_VARARGS, rsplit__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012939 {"join", (PyCFunction) unicode_join, METH_O, join__doc__},
12940 {"capitalize", (PyCFunction) unicode_capitalize, METH_NOARGS, capitalize__doc__},
12941 {"title", (PyCFunction) unicode_title, METH_NOARGS, title__doc__},
12942 {"center", (PyCFunction) unicode_center, METH_VARARGS, center__doc__},
12943 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
12944 {"expandtabs", (PyCFunction) unicode_expandtabs, METH_VARARGS, expandtabs__doc__},
12945 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000012946 {"partition", (PyCFunction) unicode_partition, METH_O, partition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012947 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
12948 {"ljust", (PyCFunction) unicode_ljust, METH_VARARGS, ljust__doc__},
12949 {"lower", (PyCFunction) unicode_lower, METH_NOARGS, lower__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012950 {"lstrip", (PyCFunction) unicode_lstrip, METH_VARARGS, lstrip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012951 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
12952 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
12953 {"rjust", (PyCFunction) unicode_rjust, METH_VARARGS, rjust__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012954 {"rstrip", (PyCFunction) unicode_rstrip, METH_VARARGS, rstrip__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000012955 {"rpartition", (PyCFunction) unicode_rpartition, METH_O, rpartition__doc__},
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012956 {"splitlines", (PyCFunction) unicode_splitlines, METH_VARARGS | METH_KEYWORDS, splitlines__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012957 {"strip", (PyCFunction) unicode_strip, METH_VARARGS, strip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012958 {"swapcase", (PyCFunction) unicode_swapcase, METH_NOARGS, swapcase__doc__},
12959 {"translate", (PyCFunction) unicode_translate, METH_O, translate__doc__},
12960 {"upper", (PyCFunction) unicode_upper, METH_NOARGS, upper__doc__},
12961 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
12962 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
12963 {"islower", (PyCFunction) unicode_islower, METH_NOARGS, islower__doc__},
12964 {"isupper", (PyCFunction) unicode_isupper, METH_NOARGS, isupper__doc__},
12965 {"istitle", (PyCFunction) unicode_istitle, METH_NOARGS, istitle__doc__},
12966 {"isspace", (PyCFunction) unicode_isspace, METH_NOARGS, isspace__doc__},
12967 {"isdecimal", (PyCFunction) unicode_isdecimal, METH_NOARGS, isdecimal__doc__},
12968 {"isdigit", (PyCFunction) unicode_isdigit, METH_NOARGS, isdigit__doc__},
12969 {"isnumeric", (PyCFunction) unicode_isnumeric, METH_NOARGS, isnumeric__doc__},
12970 {"isalpha", (PyCFunction) unicode_isalpha, METH_NOARGS, isalpha__doc__},
12971 {"isalnum", (PyCFunction) unicode_isalnum, METH_NOARGS, isalnum__doc__},
Martin v. Löwis47383402007-08-15 07:32:56 +000012972 {"isidentifier", (PyCFunction) unicode_isidentifier, METH_NOARGS, isidentifier__doc__},
Georg Brandl559e5d72008-06-11 18:37:52 +000012973 {"isprintable", (PyCFunction) unicode_isprintable, METH_NOARGS, isprintable__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012974 {"zfill", (PyCFunction) unicode_zfill, METH_VARARGS, zfill__doc__},
Eric Smith9cd1e092007-08-31 18:39:38 +000012975 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +000012976 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
Eric Smith4a7d76d2008-05-30 18:10:19 +000012977 {"__format__", (PyCFunction) unicode__format__, METH_VARARGS, p_format__doc__},
Georg Brandlceee0772007-11-27 23:48:05 +000012978 {"maketrans", (PyCFunction) unicode_maketrans,
12979 METH_VARARGS | METH_STATIC, maketrans__doc__},
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012980 {"__sizeof__", (PyCFunction) unicode__sizeof__, METH_NOARGS, sizeof__doc__},
Walter Dörwald068325e2002-04-15 13:36:47 +000012981#if 0
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012982 {"capwords", (PyCFunction) unicode_capwords, METH_NOARGS, capwords__doc__},
Guido van Rossumd57fd912000-03-10 22:53:23 +000012983#endif
12984
12985#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012986 /* These methods are just used for debugging the implementation. */
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012987 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000012988#endif
12989
Benjamin Peterson14339b62009-01-31 16:36:08 +000012990 {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000012991 {NULL, NULL}
12992};
12993
Neil Schemenauerce30bc92002-11-18 16:10:18 +000012994static PyObject *
12995unicode_mod(PyObject *v, PyObject *w)
12996{
Brian Curtindfc80e32011-08-10 20:28:54 -050012997 if (!PyUnicode_Check(v))
12998 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson29060642009-01-31 22:14:21 +000012999 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013000}
13001
13002static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013003 0, /*nb_add*/
13004 0, /*nb_subtract*/
13005 0, /*nb_multiply*/
13006 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013007};
13008
Guido van Rossumd57fd912000-03-10 22:53:23 +000013009static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013010 (lenfunc) unicode_length, /* sq_length */
13011 PyUnicode_Concat, /* sq_concat */
13012 (ssizeargfunc) unicode_repeat, /* sq_repeat */
13013 (ssizeargfunc) unicode_getitem, /* sq_item */
13014 0, /* sq_slice */
13015 0, /* sq_ass_item */
13016 0, /* sq_ass_slice */
13017 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013018};
13019
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013020static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013021unicode_subscript(PyObject* self, PyObject* item)
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013022{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013023 if (PyUnicode_READY(self) == -1)
13024 return NULL;
13025
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000013026 if (PyIndex_Check(item)) {
13027 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013028 if (i == -1 && PyErr_Occurred())
13029 return NULL;
13030 if (i < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013031 i += PyUnicode_GET_LENGTH(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013032 return unicode_getitem(self, i);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013033 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000013034 Py_ssize_t start, stop, step, slicelength, cur, i;
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013035 PyObject *result;
13036 void *src_data, *dest_data;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013037 int src_kind, dest_kind;
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013038 Py_UCS4 ch, max_char, kind_limit;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013039
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013040 if (PySlice_GetIndicesEx(item, PyUnicode_GET_LENGTH(self),
Benjamin Peterson29060642009-01-31 22:14:21 +000013041 &start, &stop, &step, &slicelength) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013042 return NULL;
13043 }
13044
13045 if (slicelength <= 0) {
Victor Stinner382955f2011-12-11 21:44:00 +010013046 Py_INCREF(unicode_empty);
13047 return unicode_empty;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013048 } else if (start == 0 && step == 1 &&
Victor Stinnerc4b49542011-12-11 22:44:26 +010013049 slicelength == PyUnicode_GET_LENGTH(self)) {
13050 return unicode_result_unchanged(self);
Thomas Woutersed03b412007-08-28 21:37:11 +000013051 } else if (step == 1) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013052 return PyUnicode_Substring(self,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013053 start, start + slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013054 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013055 /* General case */
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013056 src_kind = PyUnicode_KIND(self);
13057 src_data = PyUnicode_DATA(self);
Victor Stinner55c99112011-10-13 01:17:06 +020013058 if (!PyUnicode_IS_ASCII(self)) {
13059 kind_limit = kind_maxchar_limit(src_kind);
13060 max_char = 0;
13061 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
13062 ch = PyUnicode_READ(src_kind, src_data, cur);
13063 if (ch > max_char) {
13064 max_char = ch;
13065 if (max_char >= kind_limit)
13066 break;
13067 }
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013068 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013069 }
Victor Stinner55c99112011-10-13 01:17:06 +020013070 else
13071 max_char = 127;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013072 result = PyUnicode_New(slicelength, max_char);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013073 if (result == NULL)
13074 return NULL;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013075 dest_kind = PyUnicode_KIND(result);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013076 dest_data = PyUnicode_DATA(result);
13077
13078 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013079 Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
13080 PyUnicode_WRITE(dest_kind, dest_data, i, ch);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013081 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013082 assert(_PyUnicode_CheckConsistency(result, 1));
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013083 return result;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013084 } else {
13085 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
13086 return NULL;
13087 }
13088}
13089
13090static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013091 (lenfunc)unicode_length, /* mp_length */
13092 (binaryfunc)unicode_subscript, /* mp_subscript */
13093 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013094};
13095
Guido van Rossumd57fd912000-03-10 22:53:23 +000013096
Guido van Rossumd57fd912000-03-10 22:53:23 +000013097/* Helpers for PyUnicode_Format() */
13098
13099static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +000013100getnextarg(PyObject *args, Py_ssize_t arglen, Py_ssize_t *p_argidx)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013101{
Martin v. Löwis18e16552006-02-15 17:27:45 +000013102 Py_ssize_t argidx = *p_argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013103 if (argidx < arglen) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013104 (*p_argidx)++;
13105 if (arglen < 0)
13106 return args;
13107 else
13108 return PyTuple_GetItem(args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013109 }
13110 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013111 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013112 return NULL;
13113}
13114
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013115/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013116
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013117static PyObject *
13118formatfloat(PyObject *v, int flags, int prec, int type)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013119{
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013120 char *p;
13121 PyObject *result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013122 double x;
Tim Petersced69f82003-09-16 20:30:58 +000013123
Guido van Rossumd57fd912000-03-10 22:53:23 +000013124 x = PyFloat_AsDouble(v);
13125 if (x == -1.0 && PyErr_Occurred())
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013126 return NULL;
13127
Guido van Rossumd57fd912000-03-10 22:53:23 +000013128 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000013129 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +000013130
Eric Smith0923d1d2009-04-16 20:16:10 +000013131 p = PyOS_double_to_string(x, type, prec,
13132 (flags & F_ALT) ? Py_DTSF_ALT : 0, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013133 if (p == NULL)
13134 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013135 result = PyUnicode_DecodeASCII(p, strlen(p), NULL);
Eric Smith0923d1d2009-04-16 20:16:10 +000013136 PyMem_Free(p);
13137 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013138}
13139
Tim Peters38fd5b62000-09-21 05:43:11 +000013140static PyObject*
13141formatlong(PyObject *val, int flags, int prec, int type)
13142{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013143 char *buf;
13144 int len;
13145 PyObject *str; /* temporary string object. */
13146 PyObject *result;
Tim Peters38fd5b62000-09-21 05:43:11 +000013147
Benjamin Peterson14339b62009-01-31 16:36:08 +000013148 str = _PyBytes_FormatLong(val, flags, prec, type, &buf, &len);
13149 if (!str)
13150 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013151 result = PyUnicode_DecodeASCII(buf, len, NULL);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013152 Py_DECREF(str);
13153 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +000013154}
13155
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013156static Py_UCS4
13157formatchar(PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013158{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000013159 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000013160 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013161 if (PyUnicode_GET_LENGTH(v) == 1) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013162 return PyUnicode_READ_CHAR(v, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +000013163 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013164 goto onError;
13165 }
13166 else {
13167 /* Integer input truncated to a character */
13168 long x;
13169 x = PyLong_AsLong(v);
13170 if (x == -1 && PyErr_Occurred())
13171 goto onError;
13172
Victor Stinner8faf8212011-12-08 22:14:11 +010013173 if (x < 0 || x > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013174 PyErr_SetString(PyExc_OverflowError,
13175 "%c arg not in range(0x110000)");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013176 return (Py_UCS4) -1;
Benjamin Peterson29060642009-01-31 22:14:21 +000013177 }
13178
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013179 return (Py_UCS4) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013180 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000013181
Benjamin Peterson29060642009-01-31 22:14:21 +000013182 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000013183 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013184 "%c requires int or char");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013185 return (Py_UCS4) -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013186}
13187
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013188static int
13189repeat_accumulate(_PyAccu *acc, PyObject *obj, Py_ssize_t count)
13190{
13191 int r;
13192 assert(count > 0);
13193 assert(PyUnicode_Check(obj));
13194 if (count > 5) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013195 PyObject *repeated = unicode_repeat(obj, count);
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013196 if (repeated == NULL)
13197 return -1;
13198 r = _PyAccu_Accumulate(acc, repeated);
13199 Py_DECREF(repeated);
13200 return r;
13201 }
13202 else {
13203 do {
13204 if (_PyAccu_Accumulate(acc, obj))
13205 return -1;
13206 } while (--count);
13207 return 0;
13208 }
13209}
13210
Alexander Belopolsky40018472011-02-26 01:02:56 +000013211PyObject *
13212PyUnicode_Format(PyObject *format, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013213{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013214 void *fmt;
13215 int fmtkind;
13216 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013217 int kind;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013218 int r;
13219 Py_ssize_t fmtcnt, fmtpos, arglen, argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013220 int args_owned = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013221 PyObject *dict = NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013222 PyObject *temp = NULL;
13223 PyObject *second = NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013224 PyObject *uformat;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013225 _PyAccu acc;
13226 static PyObject *plus, *minus, *blank, *zero, *percent;
13227
13228 if (!plus && !(plus = get_latin1_char('+')))
13229 return NULL;
13230 if (!minus && !(minus = get_latin1_char('-')))
13231 return NULL;
13232 if (!blank && !(blank = get_latin1_char(' ')))
13233 return NULL;
13234 if (!zero && !(zero = get_latin1_char('0')))
13235 return NULL;
13236 if (!percent && !(percent = get_latin1_char('%')))
13237 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000013238
Guido van Rossumd57fd912000-03-10 22:53:23 +000013239 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013240 PyErr_BadInternalCall();
13241 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013242 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013243 uformat = PyUnicode_FromObject(format);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013244 if (uformat == NULL || PyUnicode_READY(uformat) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000013245 return NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013246 if (_PyAccu_Init(&acc))
13247 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013248 fmt = PyUnicode_DATA(uformat);
13249 fmtkind = PyUnicode_KIND(uformat);
13250 fmtcnt = PyUnicode_GET_LENGTH(uformat);
13251 fmtpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013252
Guido van Rossumd57fd912000-03-10 22:53:23 +000013253 if (PyTuple_Check(args)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013254 arglen = PyTuple_Size(args);
13255 argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013256 }
13257 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013258 arglen = -1;
13259 argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013260 }
Christian Heimes90aa7642007-12-19 02:45:37 +000013261 if (Py_TYPE(args)->tp_as_mapping && !PyTuple_Check(args) &&
Christian Heimesf3863112007-11-22 07:46:41 +000013262 !PyUnicode_Check(args))
Benjamin Peterson29060642009-01-31 22:14:21 +000013263 dict = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013264
13265 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013266 if (PyUnicode_READ(fmtkind, fmt, fmtpos) != '%') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013267 PyObject *nonfmt;
13268 Py_ssize_t nonfmtpos;
13269 nonfmtpos = fmtpos++;
13270 while (fmtcnt >= 0 &&
13271 PyUnicode_READ(fmtkind, fmt, fmtpos) != '%') {
13272 fmtpos++;
13273 fmtcnt--;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013274 }
Victor Stinner7931d9a2011-11-04 00:22:48 +010013275 nonfmt = PyUnicode_Substring(uformat, nonfmtpos, fmtpos);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013276 if (nonfmt == NULL)
13277 goto onError;
13278 r = _PyAccu_Accumulate(&acc, nonfmt);
13279 Py_DECREF(nonfmt);
13280 if (r)
13281 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013282 }
13283 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013284 /* Got a format specifier */
13285 int flags = 0;
13286 Py_ssize_t width = -1;
13287 int prec = -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013288 Py_UCS4 c = '\0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013289 Py_UCS4 fill, sign;
Benjamin Peterson29060642009-01-31 22:14:21 +000013290 int isnumok;
13291 PyObject *v = NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013292 void *pbuf = NULL;
13293 Py_ssize_t pindex, len;
13294 PyObject *signobj = NULL, *fillobj = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013295
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013296 fmtpos++;
13297 if (PyUnicode_READ(fmtkind, fmt, fmtpos) == '(') {
13298 Py_ssize_t keystart;
Benjamin Peterson29060642009-01-31 22:14:21 +000013299 Py_ssize_t keylen;
13300 PyObject *key;
13301 int pcount = 1;
Christian Heimesa612dc02008-02-24 13:08:18 +000013302
Benjamin Peterson29060642009-01-31 22:14:21 +000013303 if (dict == NULL) {
13304 PyErr_SetString(PyExc_TypeError,
13305 "format requires a mapping");
13306 goto onError;
13307 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013308 ++fmtpos;
Benjamin Peterson29060642009-01-31 22:14:21 +000013309 --fmtcnt;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013310 keystart = fmtpos;
Benjamin Peterson29060642009-01-31 22:14:21 +000013311 /* Skip over balanced parentheses */
13312 while (pcount > 0 && --fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013313 if (PyUnicode_READ(fmtkind, fmt, fmtpos) == ')')
Benjamin Peterson29060642009-01-31 22:14:21 +000013314 --pcount;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013315 else if (PyUnicode_READ(fmtkind, fmt, fmtpos) == '(')
Benjamin Peterson29060642009-01-31 22:14:21 +000013316 ++pcount;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013317 fmtpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +000013318 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013319 keylen = fmtpos - keystart - 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000013320 if (fmtcnt < 0 || pcount > 0) {
13321 PyErr_SetString(PyExc_ValueError,
13322 "incomplete format key");
13323 goto onError;
13324 }
Victor Stinner7931d9a2011-11-04 00:22:48 +010013325 key = PyUnicode_Substring(uformat,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013326 keystart, keystart + keylen);
Benjamin Peterson29060642009-01-31 22:14:21 +000013327 if (key == NULL)
13328 goto onError;
13329 if (args_owned) {
13330 Py_DECREF(args);
13331 args_owned = 0;
13332 }
13333 args = PyObject_GetItem(dict, key);
13334 Py_DECREF(key);
13335 if (args == NULL) {
13336 goto onError;
13337 }
13338 args_owned = 1;
13339 arglen = -1;
13340 argidx = -2;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013341 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013342 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013343 switch (c = PyUnicode_READ(fmtkind, fmt, fmtpos++)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013344 case '-': flags |= F_LJUST; continue;
13345 case '+': flags |= F_SIGN; continue;
13346 case ' ': flags |= F_BLANK; continue;
13347 case '#': flags |= F_ALT; continue;
13348 case '0': flags |= F_ZERO; continue;
13349 }
13350 break;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013351 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013352 if (c == '*') {
13353 v = getnextarg(args, arglen, &argidx);
13354 if (v == NULL)
13355 goto onError;
13356 if (!PyLong_Check(v)) {
13357 PyErr_SetString(PyExc_TypeError,
13358 "* wants int");
13359 goto onError;
13360 }
13361 width = PyLong_AsLong(v);
13362 if (width == -1 && PyErr_Occurred())
13363 goto onError;
13364 if (width < 0) {
13365 flags |= F_LJUST;
13366 width = -width;
13367 }
13368 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013369 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013370 }
13371 else if (c >= '0' && c <= '9') {
13372 width = c - '0';
13373 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013374 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013375 if (c < '0' || c > '9')
13376 break;
13377 if ((width*10) / 10 != width) {
13378 PyErr_SetString(PyExc_ValueError,
13379 "width too big");
Benjamin Peterson14339b62009-01-31 16:36:08 +000013380 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +000013381 }
13382 width = width*10 + (c - '0');
13383 }
13384 }
13385 if (c == '.') {
13386 prec = 0;
13387 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013388 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013389 if (c == '*') {
13390 v = getnextarg(args, arglen, &argidx);
13391 if (v == NULL)
13392 goto onError;
13393 if (!PyLong_Check(v)) {
13394 PyErr_SetString(PyExc_TypeError,
13395 "* wants int");
13396 goto onError;
13397 }
13398 prec = PyLong_AsLong(v);
13399 if (prec == -1 && PyErr_Occurred())
13400 goto onError;
13401 if (prec < 0)
13402 prec = 0;
13403 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013404 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013405 }
13406 else if (c >= '0' && c <= '9') {
13407 prec = c - '0';
13408 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013409 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013410 if (c < '0' || c > '9')
13411 break;
13412 if ((prec*10) / 10 != prec) {
13413 PyErr_SetString(PyExc_ValueError,
13414 "prec too big");
13415 goto onError;
13416 }
13417 prec = prec*10 + (c - '0');
13418 }
13419 }
13420 } /* prec */
13421 if (fmtcnt >= 0) {
13422 if (c == 'h' || c == 'l' || c == 'L') {
13423 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013424 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013425 }
13426 }
13427 if (fmtcnt < 0) {
13428 PyErr_SetString(PyExc_ValueError,
13429 "incomplete format");
13430 goto onError;
13431 }
13432 if (c != '%') {
13433 v = getnextarg(args, arglen, &argidx);
13434 if (v == NULL)
13435 goto onError;
13436 }
13437 sign = 0;
13438 fill = ' ';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013439 fillobj = blank;
Benjamin Peterson29060642009-01-31 22:14:21 +000013440 switch (c) {
13441
13442 case '%':
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013443 _PyAccu_Accumulate(&acc, percent);
13444 continue;
Benjamin Peterson29060642009-01-31 22:14:21 +000013445
13446 case 's':
13447 case 'r':
13448 case 'a':
Victor Stinner808fc0a2010-03-22 12:50:40 +000013449 if (PyUnicode_CheckExact(v) && c == 's') {
Benjamin Peterson29060642009-01-31 22:14:21 +000013450 temp = v;
13451 Py_INCREF(temp);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013452 }
13453 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013454 if (c == 's')
13455 temp = PyObject_Str(v);
13456 else if (c == 'r')
13457 temp = PyObject_Repr(v);
13458 else
13459 temp = PyObject_ASCII(v);
13460 if (temp == NULL)
13461 goto onError;
13462 if (PyUnicode_Check(temp))
13463 /* nothing to do */;
13464 else {
13465 Py_DECREF(temp);
13466 PyErr_SetString(PyExc_TypeError,
13467 "%s argument has non-string str()");
13468 goto onError;
13469 }
13470 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013471 if (PyUnicode_READY(temp) == -1) {
13472 Py_CLEAR(temp);
13473 goto onError;
13474 }
13475 pbuf = PyUnicode_DATA(temp);
13476 kind = PyUnicode_KIND(temp);
13477 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013478 if (prec >= 0 && len > prec)
13479 len = prec;
13480 break;
13481
13482 case 'i':
13483 case 'd':
13484 case 'u':
13485 case 'o':
13486 case 'x':
13487 case 'X':
Benjamin Peterson29060642009-01-31 22:14:21 +000013488 isnumok = 0;
13489 if (PyNumber_Check(v)) {
13490 PyObject *iobj=NULL;
13491
13492 if (PyLong_Check(v)) {
13493 iobj = v;
13494 Py_INCREF(iobj);
13495 }
13496 else {
13497 iobj = PyNumber_Long(v);
13498 }
13499 if (iobj!=NULL) {
13500 if (PyLong_Check(iobj)) {
13501 isnumok = 1;
Senthil Kumaran9ebe08d2011-07-03 21:03:16 -070013502 temp = formatlong(iobj, flags, prec, (c == 'i'? 'd': c));
Benjamin Peterson29060642009-01-31 22:14:21 +000013503 Py_DECREF(iobj);
13504 if (!temp)
13505 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013506 if (PyUnicode_READY(temp) == -1) {
13507 Py_CLEAR(temp);
13508 goto onError;
13509 }
13510 pbuf = PyUnicode_DATA(temp);
13511 kind = PyUnicode_KIND(temp);
13512 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013513 sign = 1;
13514 }
13515 else {
13516 Py_DECREF(iobj);
13517 }
13518 }
13519 }
13520 if (!isnumok) {
13521 PyErr_Format(PyExc_TypeError,
13522 "%%%c format: a number is required, "
13523 "not %.200s", (char)c, Py_TYPE(v)->tp_name);
13524 goto onError;
13525 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013526 if (flags & F_ZERO) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013527 fill = '0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013528 fillobj = zero;
13529 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013530 break;
13531
13532 case 'e':
13533 case 'E':
13534 case 'f':
13535 case 'F':
13536 case 'g':
13537 case 'G':
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013538 temp = formatfloat(v, flags, prec, c);
13539 if (!temp)
Benjamin Peterson29060642009-01-31 22:14:21 +000013540 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013541 if (PyUnicode_READY(temp) == -1) {
13542 Py_CLEAR(temp);
13543 goto onError;
13544 }
13545 pbuf = PyUnicode_DATA(temp);
13546 kind = PyUnicode_KIND(temp);
13547 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013548 sign = 1;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013549 if (flags & F_ZERO) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013550 fill = '0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013551 fillobj = zero;
13552 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013553 break;
13554
13555 case 'c':
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013556 {
13557 Py_UCS4 ch = formatchar(v);
13558 if (ch == (Py_UCS4) -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000013559 goto onError;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013560 temp = _PyUnicode_FromUCS4(&ch, 1);
13561 if (temp == NULL)
13562 goto onError;
13563 pbuf = PyUnicode_DATA(temp);
13564 kind = PyUnicode_KIND(temp);
13565 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013566 break;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013567 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013568
13569 default:
13570 PyErr_Format(PyExc_ValueError,
13571 "unsupported format character '%c' (0x%x) "
13572 "at index %zd",
13573 (31<=c && c<=126) ? (char)c : '?',
13574 (int)c,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013575 fmtpos - 1);
Benjamin Peterson29060642009-01-31 22:14:21 +000013576 goto onError;
13577 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013578 /* pbuf is initialized here. */
13579 pindex = 0;
Benjamin Peterson29060642009-01-31 22:14:21 +000013580 if (sign) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013581 if (PyUnicode_READ(kind, pbuf, pindex) == '-') {
13582 signobj = minus;
Benjamin Peterson29060642009-01-31 22:14:21 +000013583 len--;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013584 pindex++;
13585 }
13586 else if (PyUnicode_READ(kind, pbuf, pindex) == '+') {
13587 signobj = plus;
13588 len--;
13589 pindex++;
Benjamin Peterson29060642009-01-31 22:14:21 +000013590 }
13591 else if (flags & F_SIGN)
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013592 signobj = plus;
Benjamin Peterson29060642009-01-31 22:14:21 +000013593 else if (flags & F_BLANK)
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013594 signobj = blank;
Benjamin Peterson29060642009-01-31 22:14:21 +000013595 else
13596 sign = 0;
13597 }
13598 if (width < len)
13599 width = len;
Benjamin Peterson29060642009-01-31 22:14:21 +000013600 if (sign) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013601 if (fill != ' ') {
13602 assert(signobj != NULL);
13603 if (_PyAccu_Accumulate(&acc, signobj))
13604 goto onError;
13605 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013606 if (width > len)
13607 width--;
13608 }
13609 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013610 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013611 assert(PyUnicode_READ(kind, pbuf, pindex + 1) == c);
Benjamin Peterson29060642009-01-31 22:14:21 +000013612 if (fill != ' ') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013613 second = get_latin1_char(
13614 PyUnicode_READ(kind, pbuf, pindex + 1));
13615 pindex += 2;
13616 if (second == NULL ||
13617 _PyAccu_Accumulate(&acc, zero) ||
13618 _PyAccu_Accumulate(&acc, second))
13619 goto onError;
13620 Py_CLEAR(second);
Benjamin Peterson29060642009-01-31 22:14:21 +000013621 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013622 width -= 2;
13623 if (width < 0)
13624 width = 0;
13625 len -= 2;
13626 }
13627 if (width > len && !(flags & F_LJUST)) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013628 assert(fillobj != NULL);
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013629 if (repeat_accumulate(&acc, fillobj, width - len))
13630 goto onError;
13631 width = len;
Benjamin Peterson29060642009-01-31 22:14:21 +000013632 }
13633 if (fill == ' ') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013634 if (sign) {
13635 assert(signobj != NULL);
13636 if (_PyAccu_Accumulate(&acc, signobj))
13637 goto onError;
13638 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013639 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013640 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
13641 assert(PyUnicode_READ(kind, pbuf, pindex+1) == c);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013642 second = get_latin1_char(
13643 PyUnicode_READ(kind, pbuf, pindex + 1));
13644 pindex += 2;
13645 if (second == NULL ||
13646 _PyAccu_Accumulate(&acc, zero) ||
13647 _PyAccu_Accumulate(&acc, second))
13648 goto onError;
13649 Py_CLEAR(second);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013650 }
13651 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013652 /* Copy all characters, preserving len */
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013653 if (temp != NULL) {
13654 assert(pbuf == PyUnicode_DATA(temp));
13655 v = PyUnicode_Substring(temp, pindex, pindex + len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013656 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013657 else {
13658 const char *p = (const char *) pbuf;
13659 assert(pbuf != NULL);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013660 p += kind * pindex;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013661 v = PyUnicode_FromKindAndData(kind, p, len);
13662 }
13663 if (v == NULL)
13664 goto onError;
13665 r = _PyAccu_Accumulate(&acc, v);
13666 Py_DECREF(v);
13667 if (r)
13668 goto onError;
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013669 if (width > len && repeat_accumulate(&acc, blank, width - len))
13670 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +000013671 if (dict && (argidx < arglen) && c != '%') {
13672 PyErr_SetString(PyExc_TypeError,
13673 "not all arguments converted during string formatting");
Benjamin Peterson29060642009-01-31 22:14:21 +000013674 goto onError;
13675 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013676 Py_CLEAR(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013677 } /* '%' */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013678 } /* until end */
13679 if (argidx < arglen && !dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013680 PyErr_SetString(PyExc_TypeError,
13681 "not all arguments converted during string formatting");
13682 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013683 }
13684
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013685 result = _PyAccu_Finish(&acc);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013686 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013687 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013688 }
13689 Py_DECREF(uformat);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013690 Py_XDECREF(temp);
13691 Py_XDECREF(second);
Victor Stinner7931d9a2011-11-04 00:22:48 +010013692 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013693
Benjamin Peterson29060642009-01-31 22:14:21 +000013694 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000013695 Py_DECREF(uformat);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013696 Py_XDECREF(temp);
13697 Py_XDECREF(second);
13698 _PyAccu_Destroy(&acc);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013699 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013700 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013701 }
13702 return NULL;
13703}
13704
Jeremy Hylton938ace62002-07-17 16:30:39 +000013705static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +000013706unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
13707
Tim Peters6d6c1a32001-08-02 04:15:00 +000013708static PyObject *
13709unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
13710{
Benjamin Peterson29060642009-01-31 22:14:21 +000013711 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013712 static char *kwlist[] = {"object", "encoding", "errors", 0};
13713 char *encoding = NULL;
13714 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000013715
Benjamin Peterson14339b62009-01-31 16:36:08 +000013716 if (type != &PyUnicode_Type)
13717 return unicode_subtype_new(type, args, kwds);
13718 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +000013719 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +000013720 return NULL;
Victor Stinner382955f2011-12-11 21:44:00 +010013721 if (x == NULL) {
13722 Py_INCREF(unicode_empty);
13723 return unicode_empty;
13724 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000013725 if (encoding == NULL && errors == NULL)
13726 return PyObject_Str(x);
13727 else
Benjamin Peterson29060642009-01-31 22:14:21 +000013728 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +000013729}
13730
Guido van Rossume023fe02001-08-30 03:12:59 +000013731static PyObject *
13732unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
13733{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013734 PyObject *unicode, *self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013735 Py_ssize_t length, char_size;
13736 int share_wstr, share_utf8;
13737 unsigned int kind;
13738 void *data;
Guido van Rossume023fe02001-08-30 03:12:59 +000013739
Benjamin Peterson14339b62009-01-31 16:36:08 +000013740 assert(PyType_IsSubtype(type, &PyUnicode_Type));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013741
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013742 unicode = unicode_new(&PyUnicode_Type, args, kwds);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013743 if (unicode == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000013744 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020013745 assert(_PyUnicode_CHECK(unicode));
Victor Stinnere06e1452011-10-04 20:52:31 +020013746 if (PyUnicode_READY(unicode))
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013747 return NULL;
13748
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013749 self = type->tp_alloc(type, 0);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013750 if (self == NULL) {
13751 Py_DECREF(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013752 return NULL;
13753 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013754 kind = PyUnicode_KIND(unicode);
13755 length = PyUnicode_GET_LENGTH(unicode);
13756
13757 _PyUnicode_LENGTH(self) = length;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020013758#ifdef Py_DEBUG
13759 _PyUnicode_HASH(self) = -1;
13760#else
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013761 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020013762#endif
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013763 _PyUnicode_STATE(self).interned = 0;
13764 _PyUnicode_STATE(self).kind = kind;
13765 _PyUnicode_STATE(self).compact = 0;
Victor Stinner3cf46372011-10-03 14:42:15 +020013766 _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013767 _PyUnicode_STATE(self).ready = 1;
13768 _PyUnicode_WSTR(self) = NULL;
13769 _PyUnicode_UTF8_LENGTH(self) = 0;
13770 _PyUnicode_UTF8(self) = NULL;
13771 _PyUnicode_WSTR_LENGTH(self) = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +020013772 _PyUnicode_DATA_ANY(self) = NULL;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013773
13774 share_utf8 = 0;
13775 share_wstr = 0;
13776 if (kind == PyUnicode_1BYTE_KIND) {
13777 char_size = 1;
13778 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
13779 share_utf8 = 1;
13780 }
13781 else if (kind == PyUnicode_2BYTE_KIND) {
13782 char_size = 2;
13783 if (sizeof(wchar_t) == 2)
13784 share_wstr = 1;
13785 }
13786 else {
13787 assert(kind == PyUnicode_4BYTE_KIND);
13788 char_size = 4;
13789 if (sizeof(wchar_t) == 4)
13790 share_wstr = 1;
13791 }
13792
13793 /* Ensure we won't overflow the length. */
13794 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
13795 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013796 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013797 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013798 data = PyObject_MALLOC((length + 1) * char_size);
13799 if (data == NULL) {
13800 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013801 goto onError;
13802 }
13803
Victor Stinnerc3c74152011-10-02 20:39:55 +020013804 _PyUnicode_DATA_ANY(self) = data;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013805 if (share_utf8) {
13806 _PyUnicode_UTF8_LENGTH(self) = length;
13807 _PyUnicode_UTF8(self) = data;
13808 }
13809 if (share_wstr) {
13810 _PyUnicode_WSTR_LENGTH(self) = length;
13811 _PyUnicode_WSTR(self) = (wchar_t *)data;
13812 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013813
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013814 Py_MEMCPY(data, PyUnicode_DATA(unicode),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013815 kind * (length + 1));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013816 assert(_PyUnicode_CheckConsistency(self, 1));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020013817#ifdef Py_DEBUG
13818 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
13819#endif
Victor Stinnerdd18d3a2011-10-22 11:08:10 +020013820 Py_DECREF(unicode);
Victor Stinner7931d9a2011-11-04 00:22:48 +010013821 return self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013822
13823onError:
13824 Py_DECREF(unicode);
13825 Py_DECREF(self);
13826 return NULL;
Guido van Rossume023fe02001-08-30 03:12:59 +000013827}
13828
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013829PyDoc_STRVAR(unicode_doc,
Benjamin Peterson29060642009-01-31 22:14:21 +000013830 "str(string[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +000013831\n\
Collin Winterd474ce82007-08-07 19:42:11 +000013832Create a new string object from the given encoded string.\n\
Skip Montanaro35b37a52002-07-26 16:22:46 +000013833encoding defaults to the current default string encoding.\n\
13834errors can be 'strict', 'replace' or 'ignore' and defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +000013835
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013836static PyObject *unicode_iter(PyObject *seq);
13837
Guido van Rossumd57fd912000-03-10 22:53:23 +000013838PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000013839 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Benjamin Peterson14339b62009-01-31 16:36:08 +000013840 "str", /* tp_name */
13841 sizeof(PyUnicodeObject), /* tp_size */
13842 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013843 /* Slots */
Benjamin Peterson14339b62009-01-31 16:36:08 +000013844 (destructor)unicode_dealloc, /* tp_dealloc */
13845 0, /* tp_print */
13846 0, /* tp_getattr */
13847 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000013848 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000013849 unicode_repr, /* tp_repr */
13850 &unicode_as_number, /* tp_as_number */
13851 &unicode_as_sequence, /* tp_as_sequence */
13852 &unicode_as_mapping, /* tp_as_mapping */
13853 (hashfunc) unicode_hash, /* tp_hash*/
13854 0, /* tp_call*/
13855 (reprfunc) unicode_str, /* tp_str */
13856 PyObject_GenericGetAttr, /* tp_getattro */
13857 0, /* tp_setattro */
13858 0, /* tp_as_buffer */
13859 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Benjamin Peterson29060642009-01-31 22:14:21 +000013860 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
Benjamin Peterson14339b62009-01-31 16:36:08 +000013861 unicode_doc, /* tp_doc */
13862 0, /* tp_traverse */
13863 0, /* tp_clear */
13864 PyUnicode_RichCompare, /* tp_richcompare */
13865 0, /* tp_weaklistoffset */
13866 unicode_iter, /* tp_iter */
13867 0, /* tp_iternext */
13868 unicode_methods, /* tp_methods */
13869 0, /* tp_members */
13870 0, /* tp_getset */
13871 &PyBaseObject_Type, /* tp_base */
13872 0, /* tp_dict */
13873 0, /* tp_descr_get */
13874 0, /* tp_descr_set */
13875 0, /* tp_dictoffset */
13876 0, /* tp_init */
13877 0, /* tp_alloc */
13878 unicode_new, /* tp_new */
13879 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013880};
13881
13882/* Initialize the Unicode implementation */
13883
Victor Stinner3a50e702011-10-18 21:21:00 +020013884int _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013885{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013886 int i;
13887
Thomas Wouters477c8d52006-05-27 19:21:47 +000013888 /* XXX - move this array to unicodectype.c ? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013889 Py_UCS2 linebreak[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +000013890 0x000A, /* LINE FEED */
13891 0x000D, /* CARRIAGE RETURN */
13892 0x001C, /* FILE SEPARATOR */
13893 0x001D, /* GROUP SEPARATOR */
13894 0x001E, /* RECORD SEPARATOR */
13895 0x0085, /* NEXT LINE */
13896 0x2028, /* LINE SEPARATOR */
13897 0x2029, /* PARAGRAPH SEPARATOR */
13898 };
13899
Fred Drakee4315f52000-05-09 19:53:39 +000013900 /* Init the implementation */
Victor Stinnera464fc12011-10-02 20:39:30 +020013901 unicode_empty = PyUnicode_New(0, 0);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013902 if (!unicode_empty)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013903 Py_FatalError("Can't create empty string");
Victor Stinnerd3df8ab2011-11-22 01:22:34 +010013904 assert(_PyUnicode_CheckConsistency(unicode_empty, 1));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013905
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013906 for (i = 0; i < 256; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +000013907 unicode_latin1[i] = NULL;
Guido van Rossumcacfc072002-05-24 19:01:59 +000013908 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000013909 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +000013910
13911 /* initialize the linebreak bloom filter */
13912 bloom_linebreak = make_bloom_mask(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013913 PyUnicode_2BYTE_KIND, linebreak,
Victor Stinner63941882011-09-29 00:42:28 +020013914 Py_ARRAY_LENGTH(linebreak));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013915
13916 PyType_Ready(&EncodingMapType);
Victor Stinner3a50e702011-10-18 21:21:00 +020013917
13918#ifdef HAVE_MBCS
13919 winver.dwOSVersionInfoSize = sizeof(winver);
13920 if (!GetVersionEx((OSVERSIONINFO*)&winver)) {
13921 PyErr_SetFromWindowsErr(0);
13922 return -1;
13923 }
13924#endif
13925 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013926}
13927
13928/* Finalize the Unicode implementation */
13929
Christian Heimesa156e092008-02-16 07:38:31 +000013930int
13931PyUnicode_ClearFreeList(void)
13932{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013933 return 0;
Christian Heimesa156e092008-02-16 07:38:31 +000013934}
13935
Guido van Rossumd57fd912000-03-10 22:53:23 +000013936void
Thomas Wouters78890102000-07-22 19:25:51 +000013937_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013938{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013939 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013940
Guido van Rossum4ae8ef82000-10-03 18:09:04 +000013941 Py_XDECREF(unicode_empty);
13942 unicode_empty = NULL;
Barry Warsaw5b4c2282000-10-03 20:45:26 +000013943
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013944 for (i = 0; i < 256; i++) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013945 if (unicode_latin1[i]) {
13946 Py_DECREF(unicode_latin1[i]);
13947 unicode_latin1[i] = NULL;
13948 }
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013949 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020013950 _PyUnicode_ClearStaticStrings();
Christian Heimesa156e092008-02-16 07:38:31 +000013951 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +000013952}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000013953
Walter Dörwald16807132007-05-25 13:52:07 +000013954void
13955PyUnicode_InternInPlace(PyObject **p)
13956{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013957 register PyObject *s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013958 PyObject *t;
Victor Stinner4fae54c2011-10-03 02:01:52 +020013959#ifdef Py_DEBUG
13960 assert(s != NULL);
13961 assert(_PyUnicode_CHECK(s));
13962#else
Benjamin Peterson14339b62009-01-31 16:36:08 +000013963 if (s == NULL || !PyUnicode_Check(s))
Victor Stinner4fae54c2011-10-03 02:01:52 +020013964 return;
13965#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000013966 /* If it's a subclass, we don't really know what putting
13967 it in the interned dict might do. */
13968 if (!PyUnicode_CheckExact(s))
13969 return;
13970 if (PyUnicode_CHECK_INTERNED(s))
13971 return;
13972 if (interned == NULL) {
13973 interned = PyDict_New();
13974 if (interned == NULL) {
13975 PyErr_Clear(); /* Don't leave an exception */
13976 return;
13977 }
13978 }
13979 /* It might be that the GetItem call fails even
13980 though the key is present in the dictionary,
13981 namely when this happens during a stack overflow. */
13982 Py_ALLOW_RECURSION
Victor Stinner7931d9a2011-11-04 00:22:48 +010013983 t = PyDict_GetItem(interned, s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013984 Py_END_ALLOW_RECURSION
Martin v. Löwis5b222132007-06-10 09:51:05 +000013985
Benjamin Peterson29060642009-01-31 22:14:21 +000013986 if (t) {
13987 Py_INCREF(t);
13988 Py_DECREF(*p);
13989 *p = t;
13990 return;
13991 }
Walter Dörwald16807132007-05-25 13:52:07 +000013992
Benjamin Peterson14339b62009-01-31 16:36:08 +000013993 PyThreadState_GET()->recursion_critical = 1;
Victor Stinner7931d9a2011-11-04 00:22:48 +010013994 if (PyDict_SetItem(interned, s, s) < 0) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013995 PyErr_Clear();
13996 PyThreadState_GET()->recursion_critical = 0;
13997 return;
13998 }
13999 PyThreadState_GET()->recursion_critical = 0;
14000 /* The two references in interned are not counted by refcnt.
14001 The deallocator will take care of this */
14002 Py_REFCNT(s) -= 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014003 _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000014004}
14005
14006void
14007PyUnicode_InternImmortal(PyObject **p)
14008{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014009 PyUnicode_InternInPlace(p);
14010 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
Victor Stinneraf9e4b82011-10-23 20:07:00 +020014011 _PyUnicode_STATE(*p).interned = SSTATE_INTERNED_IMMORTAL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014012 Py_INCREF(*p);
14013 }
Walter Dörwald16807132007-05-25 13:52:07 +000014014}
14015
14016PyObject *
14017PyUnicode_InternFromString(const char *cp)
14018{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014019 PyObject *s = PyUnicode_FromString(cp);
14020 if (s == NULL)
14021 return NULL;
14022 PyUnicode_InternInPlace(&s);
14023 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000014024}
14025
Alexander Belopolsky40018472011-02-26 01:02:56 +000014026void
14027_Py_ReleaseInternedUnicodeStrings(void)
Walter Dörwald16807132007-05-25 13:52:07 +000014028{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014029 PyObject *keys;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014030 PyObject *s;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014031 Py_ssize_t i, n;
14032 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000014033
Benjamin Peterson14339b62009-01-31 16:36:08 +000014034 if (interned == NULL || !PyDict_Check(interned))
14035 return;
14036 keys = PyDict_Keys(interned);
14037 if (keys == NULL || !PyList_Check(keys)) {
14038 PyErr_Clear();
14039 return;
14040 }
Walter Dörwald16807132007-05-25 13:52:07 +000014041
Benjamin Peterson14339b62009-01-31 16:36:08 +000014042 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
14043 detector, interned unicode strings are not forcibly deallocated;
14044 rather, we give them their stolen references back, and then clear
14045 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000014046
Benjamin Peterson14339b62009-01-31 16:36:08 +000014047 n = PyList_GET_SIZE(keys);
14048 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000014049 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014050 for (i = 0; i < n; i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014051 s = PyList_GET_ITEM(keys, i);
Victor Stinner6b56a7f2011-10-04 20:04:52 +020014052 if (PyUnicode_READY(s) == -1) {
14053 assert(0 && "could not ready string");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014054 fprintf(stderr, "could not ready string\n");
Victor Stinner6b56a7f2011-10-04 20:04:52 +020014055 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014056 switch (PyUnicode_CHECK_INTERNED(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014057 case SSTATE_NOT_INTERNED:
14058 /* XXX Shouldn't happen */
14059 break;
14060 case SSTATE_INTERNED_IMMORTAL:
14061 Py_REFCNT(s) += 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014062 immortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014063 break;
14064 case SSTATE_INTERNED_MORTAL:
14065 Py_REFCNT(s) += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014066 mortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014067 break;
14068 default:
14069 Py_FatalError("Inconsistent interned string state.");
14070 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014071 _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014072 }
14073 fprintf(stderr, "total size of all interned strings: "
14074 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
14075 "mortal/immortal\n", mortal_size, immortal_size);
14076 Py_DECREF(keys);
14077 PyDict_Clear(interned);
14078 Py_DECREF(interned);
14079 interned = NULL;
Walter Dörwald16807132007-05-25 13:52:07 +000014080}
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014081
14082
14083/********************* Unicode Iterator **************************/
14084
14085typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014086 PyObject_HEAD
14087 Py_ssize_t it_index;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014088 PyObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014089} unicodeiterobject;
14090
14091static void
14092unicodeiter_dealloc(unicodeiterobject *it)
14093{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014094 _PyObject_GC_UNTRACK(it);
14095 Py_XDECREF(it->it_seq);
14096 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014097}
14098
14099static int
14100unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
14101{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014102 Py_VISIT(it->it_seq);
14103 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014104}
14105
14106static PyObject *
14107unicodeiter_next(unicodeiterobject *it)
14108{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014109 PyObject *seq, *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014110
Benjamin Peterson14339b62009-01-31 16:36:08 +000014111 assert(it != NULL);
14112 seq = it->it_seq;
14113 if (seq == NULL)
14114 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020014115 assert(_PyUnicode_CHECK(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014116
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014117 if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
14118 int kind = PyUnicode_KIND(seq);
14119 void *data = PyUnicode_DATA(seq);
14120 Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
14121 item = PyUnicode_FromOrdinal(chr);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014122 if (item != NULL)
14123 ++it->it_index;
14124 return item;
14125 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014126
Benjamin Peterson14339b62009-01-31 16:36:08 +000014127 Py_DECREF(seq);
14128 it->it_seq = NULL;
14129 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014130}
14131
14132static PyObject *
14133unicodeiter_len(unicodeiterobject *it)
14134{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014135 Py_ssize_t len = 0;
14136 if (it->it_seq)
Victor Stinnerc4f281e2011-10-11 22:11:42 +020014137 len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014138 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014139}
14140
14141PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
14142
14143static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014144 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000014145 length_hint_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000014146 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014147};
14148
14149PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014150 PyVarObject_HEAD_INIT(&PyType_Type, 0)
14151 "str_iterator", /* tp_name */
14152 sizeof(unicodeiterobject), /* tp_basicsize */
14153 0, /* tp_itemsize */
14154 /* methods */
14155 (destructor)unicodeiter_dealloc, /* tp_dealloc */
14156 0, /* tp_print */
14157 0, /* tp_getattr */
14158 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000014159 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014160 0, /* tp_repr */
14161 0, /* tp_as_number */
14162 0, /* tp_as_sequence */
14163 0, /* tp_as_mapping */
14164 0, /* tp_hash */
14165 0, /* tp_call */
14166 0, /* tp_str */
14167 PyObject_GenericGetAttr, /* tp_getattro */
14168 0, /* tp_setattro */
14169 0, /* tp_as_buffer */
14170 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
14171 0, /* tp_doc */
14172 (traverseproc)unicodeiter_traverse, /* tp_traverse */
14173 0, /* tp_clear */
14174 0, /* tp_richcompare */
14175 0, /* tp_weaklistoffset */
14176 PyObject_SelfIter, /* tp_iter */
14177 (iternextfunc)unicodeiter_next, /* tp_iternext */
14178 unicodeiter_methods, /* tp_methods */
14179 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014180};
14181
14182static PyObject *
14183unicode_iter(PyObject *seq)
14184{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014185 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014186
Benjamin Peterson14339b62009-01-31 16:36:08 +000014187 if (!PyUnicode_Check(seq)) {
14188 PyErr_BadInternalCall();
14189 return NULL;
14190 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014191 if (PyUnicode_READY(seq) == -1)
14192 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014193 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
14194 if (it == NULL)
14195 return NULL;
14196 it->it_index = 0;
14197 Py_INCREF(seq);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014198 it->it_seq = seq;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014199 _PyObject_GC_TRACK(it);
14200 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014201}
14202
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010014203
14204size_t
14205Py_UNICODE_strlen(const Py_UNICODE *u)
14206{
14207 int res = 0;
14208 while(*u++)
14209 res++;
14210 return res;
14211}
14212
14213Py_UNICODE*
14214Py_UNICODE_strcpy(Py_UNICODE *s1, const Py_UNICODE *s2)
14215{
14216 Py_UNICODE *u = s1;
14217 while ((*u++ = *s2++));
14218 return s1;
14219}
14220
14221Py_UNICODE*
14222Py_UNICODE_strncpy(Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
14223{
14224 Py_UNICODE *u = s1;
14225 while ((*u++ = *s2++))
14226 if (n-- == 0)
14227 break;
14228 return s1;
14229}
14230
14231Py_UNICODE*
14232Py_UNICODE_strcat(Py_UNICODE *s1, const Py_UNICODE *s2)
14233{
14234 Py_UNICODE *u1 = s1;
14235 u1 += Py_UNICODE_strlen(u1);
14236 Py_UNICODE_strcpy(u1, s2);
14237 return s1;
14238}
14239
14240int
14241Py_UNICODE_strcmp(const Py_UNICODE *s1, const Py_UNICODE *s2)
14242{
14243 while (*s1 && *s2 && *s1 == *s2)
14244 s1++, s2++;
14245 if (*s1 && *s2)
14246 return (*s1 < *s2) ? -1 : +1;
14247 if (*s1)
14248 return 1;
14249 if (*s2)
14250 return -1;
14251 return 0;
14252}
14253
14254int
14255Py_UNICODE_strncmp(const Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
14256{
14257 register Py_UNICODE u1, u2;
14258 for (; n != 0; n--) {
14259 u1 = *s1;
14260 u2 = *s2;
14261 if (u1 != u2)
14262 return (u1 < u2) ? -1 : +1;
14263 if (u1 == '\0')
14264 return 0;
14265 s1++;
14266 s2++;
14267 }
14268 return 0;
14269}
14270
14271Py_UNICODE*
14272Py_UNICODE_strchr(const Py_UNICODE *s, Py_UNICODE c)
14273{
14274 const Py_UNICODE *p;
14275 for (p = s; *p; p++)
14276 if (*p == c)
14277 return (Py_UNICODE*)p;
14278 return NULL;
14279}
14280
14281Py_UNICODE*
14282Py_UNICODE_strrchr(const Py_UNICODE *s, Py_UNICODE c)
14283{
14284 const Py_UNICODE *p;
14285 p = s + Py_UNICODE_strlen(s);
14286 while (p != s) {
14287 p--;
14288 if (*p == c)
14289 return (Py_UNICODE*)p;
14290 }
14291 return NULL;
14292}
Victor Stinner331ea922010-08-10 16:37:20 +000014293
Victor Stinner71133ff2010-09-01 23:43:53 +000014294Py_UNICODE*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014295PyUnicode_AsUnicodeCopy(PyObject *unicode)
Victor Stinner71133ff2010-09-01 23:43:53 +000014296{
Victor Stinner577db2c2011-10-11 22:12:48 +020014297 Py_UNICODE *u, *copy;
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014298 Py_ssize_t len, size;
Victor Stinner71133ff2010-09-01 23:43:53 +000014299
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014300 if (!PyUnicode_Check(unicode)) {
14301 PyErr_BadArgument();
14302 return NULL;
14303 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014304 u = PyUnicode_AsUnicodeAndSize(unicode, &len);
Victor Stinner577db2c2011-10-11 22:12:48 +020014305 if (u == NULL)
14306 return NULL;
Victor Stinner71133ff2010-09-01 23:43:53 +000014307 /* Ensure we won't overflow the size. */
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014308 if (len > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
Victor Stinner71133ff2010-09-01 23:43:53 +000014309 PyErr_NoMemory();
14310 return NULL;
14311 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014312 size = len + 1; /* copy the null character */
Victor Stinner71133ff2010-09-01 23:43:53 +000014313 size *= sizeof(Py_UNICODE);
14314 copy = PyMem_Malloc(size);
14315 if (copy == NULL) {
14316 PyErr_NoMemory();
14317 return NULL;
14318 }
Victor Stinner577db2c2011-10-11 22:12:48 +020014319 memcpy(copy, u, size);
Victor Stinner71133ff2010-09-01 23:43:53 +000014320 return copy;
14321}
Martin v. Löwis5b222132007-06-10 09:51:05 +000014322
Georg Brandl66c221e2010-10-14 07:04:07 +000014323/* A _string module, to export formatter_parser and formatter_field_name_split
14324 to the string.Formatter class implemented in Python. */
14325
14326static PyMethodDef _string_methods[] = {
14327 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
14328 METH_O, PyDoc_STR("split the argument as a field name")},
14329 {"formatter_parser", (PyCFunction) formatter_parser,
14330 METH_O, PyDoc_STR("parse the argument as a format string")},
14331 {NULL, NULL}
14332};
14333
14334static struct PyModuleDef _string_module = {
14335 PyModuleDef_HEAD_INIT,
14336 "_string",
14337 PyDoc_STR("string helper module"),
14338 0,
14339 _string_methods,
14340 NULL,
14341 NULL,
14342 NULL,
14343 NULL
14344};
14345
14346PyMODINIT_FUNC
14347PyInit__string(void)
14348{
14349 return PyModule_Create(&_string_module);
14350}
14351
14352
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000014353#ifdef __cplusplus
14354}
14355#endif