blob: 2fea30b37f8e4d073e79ba4451e3b71abbe0c725 [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 Stinner76a31a62011-11-04 00:05:13 +01007045 *v = (PyObject*)_PyUnicode_New(outsize);
Benjamin Peterson29060642009-01-31 22:14:21 +00007046 if (*v == NULL)
7047 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007048 out = PyUnicode_AS_UNICODE(*v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007049 }
7050 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007051 /* Extend unicode object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007052 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
Victor Stinner16e6a802011-12-12 13:24:15 +01007053 if (unicode_resize(v, n + outsize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007054 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007055 out = PyUnicode_AS_UNICODE(*v) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007056 }
7057
7058 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007059 outsize = MultiByteToWideChar(code_page, flags, in, insize, out, outsize);
7060 if (outsize <= 0)
7061 goto error;
7062 return insize;
Victor Stinner554f3f02010-06-16 23:33:54 +00007063
Victor Stinner3a50e702011-10-18 21:21:00 +02007064error:
7065 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7066 return -2;
7067 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007068 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007069}
7070
Victor Stinner3a50e702011-10-18 21:21:00 +02007071/*
7072 * Decode a byte string from a code page into unicode object with an error
7073 * handler.
7074 *
7075 * Returns consumed size if succeed, or raise a WindowsError or
7076 * UnicodeDecodeError exception and returns -1 on error.
7077 */
7078static int
7079decode_code_page_errors(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007080 PyObject **v,
7081 const char *in, const int size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007082 const char *errors)
7083{
7084 const char *startin = in;
7085 const char *endin = in + size;
7086 const DWORD flags = decode_code_page_flags(code_page);
7087 /* Ideally, we should get reason from FormatMessage. This is the Windows
7088 2000 English version of the message. */
7089 const char *reason = "No mapping for the Unicode character exists "
7090 "in the target code page.";
7091 /* each step cannot decode more than 1 character, but a character can be
7092 represented as a surrogate pair */
7093 wchar_t buffer[2], *startout, *out;
7094 int insize, outsize;
7095 PyObject *errorHandler = NULL;
7096 PyObject *exc = NULL;
7097 PyObject *encoding_obj = NULL;
7098 char *encoding;
7099 DWORD err;
7100 int ret = -1;
7101
7102 assert(size > 0);
7103
7104 encoding = code_page_name(code_page, &encoding_obj);
7105 if (encoding == NULL)
7106 return -1;
7107
7108 if (errors == NULL || strcmp(errors, "strict") == 0) {
7109 /* The last error was ERROR_NO_UNICODE_TRANSLATION, then we raise a
7110 UnicodeDecodeError. */
7111 make_decode_exception(&exc, encoding, in, size, 0, 0, reason);
7112 if (exc != NULL) {
7113 PyCodec_StrictErrors(exc);
7114 Py_CLEAR(exc);
7115 }
7116 goto error;
7117 }
7118
7119 if (*v == NULL) {
7120 /* Create unicode object */
7121 if (size > PY_SSIZE_T_MAX / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
7122 PyErr_NoMemory();
7123 goto error;
7124 }
Victor Stinner76a31a62011-11-04 00:05:13 +01007125 *v = (PyObject*)_PyUnicode_New(size * Py_ARRAY_LENGTH(buffer));
Victor Stinner3a50e702011-10-18 21:21:00 +02007126 if (*v == NULL)
7127 goto error;
7128 startout = PyUnicode_AS_UNICODE(*v);
7129 }
7130 else {
7131 /* Extend unicode object */
7132 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
7133 if (size > (PY_SSIZE_T_MAX - n) / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
7134 PyErr_NoMemory();
7135 goto error;
7136 }
Victor Stinner16e6a802011-12-12 13:24:15 +01007137 if (unicode_resize(v, n + size * Py_ARRAY_LENGTH(buffer)) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007138 goto error;
7139 startout = PyUnicode_AS_UNICODE(*v) + n;
7140 }
7141
7142 /* Decode the byte string character per character */
7143 out = startout;
7144 while (in < endin)
7145 {
7146 /* Decode a character */
7147 insize = 1;
7148 do
7149 {
7150 outsize = MultiByteToWideChar(code_page, flags,
7151 in, insize,
7152 buffer, Py_ARRAY_LENGTH(buffer));
7153 if (outsize > 0)
7154 break;
7155 err = GetLastError();
7156 if (err != ERROR_NO_UNICODE_TRANSLATION
7157 && err != ERROR_INSUFFICIENT_BUFFER)
7158 {
7159 PyErr_SetFromWindowsErr(0);
7160 goto error;
7161 }
7162 insize++;
7163 }
7164 /* 4=maximum length of a UTF-8 sequence */
7165 while (insize <= 4 && (in + insize) <= endin);
7166
7167 if (outsize <= 0) {
7168 Py_ssize_t startinpos, endinpos, outpos;
7169
7170 startinpos = in - startin;
7171 endinpos = startinpos + 1;
7172 outpos = out - PyUnicode_AS_UNICODE(*v);
7173 if (unicode_decode_call_errorhandler(
7174 errors, &errorHandler,
7175 encoding, reason,
7176 &startin, &endin, &startinpos, &endinpos, &exc, &in,
Victor Stinner596a6c42011-11-09 00:02:18 +01007177 v, &outpos))
Victor Stinner3a50e702011-10-18 21:21:00 +02007178 {
7179 goto error;
7180 }
Victor Stinner596a6c42011-11-09 00:02:18 +01007181 out = PyUnicode_AS_UNICODE(*v) + outpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007182 }
7183 else {
7184 in += insize;
7185 memcpy(out, buffer, outsize * sizeof(wchar_t));
7186 out += outsize;
7187 }
7188 }
7189
7190 /* write a NUL character at the end */
7191 *out = 0;
7192
7193 /* Extend unicode object */
7194 outsize = out - startout;
7195 assert(outsize <= PyUnicode_WSTR_LENGTH(*v));
Victor Stinner16e6a802011-12-12 13:24:15 +01007196 if (unicode_resize(v, outsize) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007197 goto error;
Victor Stinner76a31a62011-11-04 00:05:13 +01007198 ret = size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007199
7200error:
7201 Py_XDECREF(encoding_obj);
7202 Py_XDECREF(errorHandler);
7203 Py_XDECREF(exc);
7204 return ret;
7205}
7206
Victor Stinner3a50e702011-10-18 21:21:00 +02007207static PyObject *
7208decode_code_page_stateful(int code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007209 const char *s, Py_ssize_t size,
7210 const char *errors, Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007211{
Victor Stinner76a31a62011-11-04 00:05:13 +01007212 PyObject *v = NULL;
7213 int chunk_size, final, converted, done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007214
Victor Stinner3a50e702011-10-18 21:21:00 +02007215 if (code_page < 0) {
7216 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7217 return NULL;
7218 }
7219
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007220 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00007221 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007222
Victor Stinner76a31a62011-11-04 00:05:13 +01007223 do
7224 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007225#ifdef NEED_RETRY
Victor Stinner76a31a62011-11-04 00:05:13 +01007226 if (size > INT_MAX) {
7227 chunk_size = INT_MAX;
7228 final = 0;
7229 done = 0;
7230 }
7231 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007232#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007233 {
7234 chunk_size = (int)size;
7235 final = (consumed == NULL);
7236 done = 1;
7237 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007238
Victor Stinner76a31a62011-11-04 00:05:13 +01007239 /* Skip trailing lead-byte unless 'final' is set */
7240 if (!final && is_dbcs_lead_byte(code_page, s, chunk_size - 1))
7241 --chunk_size;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007242
Victor Stinner76a31a62011-11-04 00:05:13 +01007243 if (chunk_size == 0 && done) {
7244 if (v != NULL)
7245 break;
7246 Py_INCREF(unicode_empty);
7247 return unicode_empty;
7248 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007249
Victor Stinner76a31a62011-11-04 00:05:13 +01007250
7251 converted = decode_code_page_strict(code_page, &v,
7252 s, chunk_size);
7253 if (converted == -2)
7254 converted = decode_code_page_errors(code_page, &v,
7255 s, chunk_size,
7256 errors);
7257 assert(converted != 0);
7258
7259 if (converted < 0) {
7260 Py_XDECREF(v);
7261 return NULL;
7262 }
7263
7264 if (consumed)
7265 *consumed += converted;
7266
7267 s += converted;
7268 size -= converted;
7269 } while (!done);
Victor Stinner3a50e702011-10-18 21:21:00 +02007270
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01007271 return unicode_result(v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007272}
7273
Alexander Belopolsky40018472011-02-26 01:02:56 +00007274PyObject *
Victor Stinner3a50e702011-10-18 21:21:00 +02007275PyUnicode_DecodeCodePageStateful(int code_page,
7276 const char *s,
7277 Py_ssize_t size,
7278 const char *errors,
7279 Py_ssize_t *consumed)
7280{
7281 return decode_code_page_stateful(code_page, s, size, errors, consumed);
7282}
7283
7284PyObject *
7285PyUnicode_DecodeMBCSStateful(const char *s,
7286 Py_ssize_t size,
7287 const char *errors,
7288 Py_ssize_t *consumed)
7289{
7290 return decode_code_page_stateful(CP_ACP, s, size, errors, consumed);
7291}
7292
7293PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00007294PyUnicode_DecodeMBCS(const char *s,
7295 Py_ssize_t size,
7296 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007297{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007298 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
7299}
7300
Victor Stinner3a50e702011-10-18 21:21:00 +02007301static DWORD
7302encode_code_page_flags(UINT code_page, const char *errors)
7303{
7304 if (code_page == CP_UTF8) {
7305 if (winver.dwMajorVersion >= 6)
7306 /* CP_UTF8 supports WC_ERR_INVALID_CHARS on Windows Vista
7307 and later */
7308 return WC_ERR_INVALID_CHARS;
7309 else
7310 /* CP_UTF8 only supports flags=0 on Windows older than Vista */
7311 return 0;
7312 }
7313 else if (code_page == CP_UTF7) {
7314 /* CP_UTF7 only supports flags=0 */
7315 return 0;
7316 }
7317 else {
7318 if (errors != NULL && strcmp(errors, "replace") == 0)
7319 return 0;
7320 else
7321 return WC_NO_BEST_FIT_CHARS;
7322 }
7323}
7324
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007325/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007326 * Encode a Unicode string to a Windows code page into a byte string in strict
7327 * mode.
7328 *
7329 * Returns consumed characters if succeed, returns -2 on encode error, or raise
7330 * a WindowsError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007331 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007332static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007333encode_code_page_strict(UINT code_page, PyObject **outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007334 PyObject *unicode, Py_ssize_t offset, int len,
Victor Stinner3a50e702011-10-18 21:21:00 +02007335 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007336{
Victor Stinner554f3f02010-06-16 23:33:54 +00007337 BOOL usedDefaultChar = FALSE;
Victor Stinner3a50e702011-10-18 21:21:00 +02007338 BOOL *pusedDefaultChar = &usedDefaultChar;
7339 int outsize;
Victor Stinner554f3f02010-06-16 23:33:54 +00007340 PyObject *exc = NULL;
Victor Stinner24729f32011-11-10 20:31:37 +01007341 wchar_t *p;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007342 Py_ssize_t size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007343 const DWORD flags = encode_code_page_flags(code_page, NULL);
7344 char *out;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007345 /* Create a substring so that we can get the UTF-16 representation
7346 of just the slice under consideration. */
7347 PyObject *substring;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007348
Martin v. Löwis3d325192011-11-04 18:23:06 +01007349 assert(len > 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007350
Victor Stinner3a50e702011-10-18 21:21:00 +02007351 if (code_page != CP_UTF8 && code_page != CP_UTF7)
Victor Stinner554f3f02010-06-16 23:33:54 +00007352 pusedDefaultChar = &usedDefaultChar;
Victor Stinner3a50e702011-10-18 21:21:00 +02007353 else
Victor Stinner554f3f02010-06-16 23:33:54 +00007354 pusedDefaultChar = NULL;
Victor Stinner554f3f02010-06-16 23:33:54 +00007355
Victor Stinner2fc507f2011-11-04 20:06:39 +01007356 substring = PyUnicode_Substring(unicode, offset, offset+len);
7357 if (substring == NULL)
7358 return -1;
7359 p = PyUnicode_AsUnicodeAndSize(substring, &size);
7360 if (p == NULL) {
7361 Py_DECREF(substring);
7362 return -1;
7363 }
Martin v. Löwis3d325192011-11-04 18:23:06 +01007364
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007365 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007366 outsize = WideCharToMultiByte(code_page, flags,
7367 p, size,
7368 NULL, 0,
7369 NULL, pusedDefaultChar);
7370 if (outsize <= 0)
7371 goto error;
7372 /* If we used a default char, then we failed! */
Victor Stinner2fc507f2011-11-04 20:06:39 +01007373 if (pusedDefaultChar && *pusedDefaultChar) {
7374 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007375 return -2;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007376 }
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007377
Victor Stinner3a50e702011-10-18 21:21:00 +02007378 if (*outbytes == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007379 /* Create string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007380 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007381 if (*outbytes == NULL) {
7382 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007383 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007384 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007385 out = PyBytes_AS_STRING(*outbytes);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007386 }
7387 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007388 /* Extend string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007389 const Py_ssize_t n = PyBytes_Size(*outbytes);
7390 if (outsize > PY_SSIZE_T_MAX - n) {
7391 PyErr_NoMemory();
Victor Stinner2fc507f2011-11-04 20:06:39 +01007392 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007393 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007394 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007395 if (_PyBytes_Resize(outbytes, n + outsize) < 0) {
7396 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007397 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007398 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007399 out = PyBytes_AS_STRING(*outbytes) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007400 }
7401
7402 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007403 outsize = WideCharToMultiByte(code_page, flags,
7404 p, size,
7405 out, outsize,
7406 NULL, pusedDefaultChar);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007407 Py_CLEAR(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007408 if (outsize <= 0)
7409 goto error;
7410 if (pusedDefaultChar && *pusedDefaultChar)
7411 return -2;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007412 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00007413
Victor Stinner3a50e702011-10-18 21:21:00 +02007414error:
Victor Stinner2fc507f2011-11-04 20:06:39 +01007415 Py_XDECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007416 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7417 return -2;
7418 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007419 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007420}
7421
Victor Stinner3a50e702011-10-18 21:21:00 +02007422/*
7423 * Encode a Unicode string to a Windows code page into a byte string using a
7424 * error handler.
7425 *
7426 * Returns consumed characters if succeed, or raise a WindowsError and returns
7427 * -1 on other error.
7428 */
7429static int
7430encode_code_page_errors(UINT code_page, PyObject **outbytes,
Victor Stinner7581cef2011-11-03 22:32:33 +01007431 PyObject *unicode, Py_ssize_t unicode_offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007432 Py_ssize_t insize, const char* errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007433{
Victor Stinner3a50e702011-10-18 21:21:00 +02007434 const DWORD flags = encode_code_page_flags(code_page, errors);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007435 Py_ssize_t pos = unicode_offset;
7436 Py_ssize_t endin = unicode_offset + insize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007437 /* Ideally, we should get reason from FormatMessage. This is the Windows
7438 2000 English version of the message. */
7439 const char *reason = "invalid character";
7440 /* 4=maximum length of a UTF-8 sequence */
7441 char buffer[4];
7442 BOOL usedDefaultChar = FALSE, *pusedDefaultChar;
7443 Py_ssize_t outsize;
7444 char *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007445 PyObject *errorHandler = NULL;
7446 PyObject *exc = NULL;
7447 PyObject *encoding_obj = NULL;
7448 char *encoding;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007449 Py_ssize_t newpos, newoutsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007450 PyObject *rep;
7451 int ret = -1;
7452
7453 assert(insize > 0);
7454
7455 encoding = code_page_name(code_page, &encoding_obj);
7456 if (encoding == NULL)
7457 return -1;
7458
7459 if (errors == NULL || strcmp(errors, "strict") == 0) {
7460 /* The last error was ERROR_NO_UNICODE_TRANSLATION,
7461 then we raise a UnicodeEncodeError. */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007462 make_encode_exception(&exc, encoding, unicode, 0, 0, reason);
Victor Stinner3a50e702011-10-18 21:21:00 +02007463 if (exc != NULL) {
7464 PyCodec_StrictErrors(exc);
7465 Py_DECREF(exc);
7466 }
7467 Py_XDECREF(encoding_obj);
7468 return -1;
7469 }
7470
7471 if (code_page != CP_UTF8 && code_page != CP_UTF7)
7472 pusedDefaultChar = &usedDefaultChar;
7473 else
7474 pusedDefaultChar = NULL;
7475
7476 if (Py_ARRAY_LENGTH(buffer) > PY_SSIZE_T_MAX / insize) {
7477 PyErr_NoMemory();
7478 goto error;
7479 }
7480 outsize = insize * Py_ARRAY_LENGTH(buffer);
7481
7482 if (*outbytes == NULL) {
7483 /* Create string object */
7484 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
7485 if (*outbytes == NULL)
7486 goto error;
7487 out = PyBytes_AS_STRING(*outbytes);
7488 }
7489 else {
7490 /* Extend string object */
7491 Py_ssize_t n = PyBytes_Size(*outbytes);
7492 if (n > PY_SSIZE_T_MAX - outsize) {
7493 PyErr_NoMemory();
7494 goto error;
7495 }
7496 if (_PyBytes_Resize(outbytes, n + outsize) < 0)
7497 goto error;
7498 out = PyBytes_AS_STRING(*outbytes) + n;
7499 }
7500
7501 /* Encode the string character per character */
Martin v. Löwis3d325192011-11-04 18:23:06 +01007502 while (pos < endin)
Victor Stinner3a50e702011-10-18 21:21:00 +02007503 {
Victor Stinner2fc507f2011-11-04 20:06:39 +01007504 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, pos);
7505 wchar_t chars[2];
7506 int charsize;
7507 if (ch < 0x10000) {
7508 chars[0] = (wchar_t)ch;
7509 charsize = 1;
7510 }
7511 else {
7512 ch -= 0x10000;
7513 chars[0] = 0xd800 + (ch >> 10);
7514 chars[1] = 0xdc00 + (ch & 0x3ff);
7515 charsize = 2;
7516 }
7517
Victor Stinner3a50e702011-10-18 21:21:00 +02007518 outsize = WideCharToMultiByte(code_page, flags,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007519 chars, charsize,
Victor Stinner3a50e702011-10-18 21:21:00 +02007520 buffer, Py_ARRAY_LENGTH(buffer),
7521 NULL, pusedDefaultChar);
7522 if (outsize > 0) {
7523 if (pusedDefaultChar == NULL || !(*pusedDefaultChar))
7524 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007525 pos++;
Victor Stinner3a50e702011-10-18 21:21:00 +02007526 memcpy(out, buffer, outsize);
7527 out += outsize;
7528 continue;
7529 }
7530 }
7531 else if (GetLastError() != ERROR_NO_UNICODE_TRANSLATION) {
7532 PyErr_SetFromWindowsErr(0);
7533 goto error;
7534 }
7535
Victor Stinner3a50e702011-10-18 21:21:00 +02007536 rep = unicode_encode_call_errorhandler(
7537 errors, &errorHandler, encoding, reason,
Victor Stinner7581cef2011-11-03 22:32:33 +01007538 unicode, &exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007539 pos, pos + 1, &newpos);
Victor Stinner3a50e702011-10-18 21:21:00 +02007540 if (rep == NULL)
7541 goto error;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007542 pos = newpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007543
7544 if (PyBytes_Check(rep)) {
7545 outsize = PyBytes_GET_SIZE(rep);
7546 if (outsize != 1) {
7547 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7548 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7549 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7550 Py_DECREF(rep);
7551 goto error;
7552 }
7553 out = PyBytes_AS_STRING(*outbytes) + offset;
7554 }
7555 memcpy(out, PyBytes_AS_STRING(rep), outsize);
7556 out += outsize;
7557 }
7558 else {
7559 Py_ssize_t i;
7560 enum PyUnicode_Kind kind;
7561 void *data;
7562
7563 if (PyUnicode_READY(rep) < 0) {
7564 Py_DECREF(rep);
7565 goto error;
7566 }
7567
7568 outsize = PyUnicode_GET_LENGTH(rep);
7569 if (outsize != 1) {
7570 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7571 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7572 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7573 Py_DECREF(rep);
7574 goto error;
7575 }
7576 out = PyBytes_AS_STRING(*outbytes) + offset;
7577 }
7578 kind = PyUnicode_KIND(rep);
7579 data = PyUnicode_DATA(rep);
7580 for (i=0; i < outsize; i++) {
7581 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7582 if (ch > 127) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007583 raise_encode_exception(&exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007584 encoding, unicode,
7585 pos, pos + 1,
Victor Stinner3a50e702011-10-18 21:21:00 +02007586 "unable to encode error handler result to ASCII");
7587 Py_DECREF(rep);
7588 goto error;
7589 }
7590 *out = (unsigned char)ch;
7591 out++;
7592 }
7593 }
7594 Py_DECREF(rep);
7595 }
7596 /* write a NUL byte */
7597 *out = 0;
7598 outsize = out - PyBytes_AS_STRING(*outbytes);
7599 assert(outsize <= PyBytes_GET_SIZE(*outbytes));
7600 if (_PyBytes_Resize(outbytes, outsize) < 0)
7601 goto error;
7602 ret = 0;
7603
7604error:
7605 Py_XDECREF(encoding_obj);
7606 Py_XDECREF(errorHandler);
7607 Py_XDECREF(exc);
7608 return ret;
7609}
7610
Victor Stinner3a50e702011-10-18 21:21:00 +02007611static PyObject *
7612encode_code_page(int code_page,
Victor Stinner7581cef2011-11-03 22:32:33 +01007613 PyObject *unicode,
Victor Stinner3a50e702011-10-18 21:21:00 +02007614 const char *errors)
7615{
Martin v. Löwis3d325192011-11-04 18:23:06 +01007616 Py_ssize_t len;
Victor Stinner3a50e702011-10-18 21:21:00 +02007617 PyObject *outbytes = NULL;
Victor Stinner7581cef2011-11-03 22:32:33 +01007618 Py_ssize_t offset;
Victor Stinner76a31a62011-11-04 00:05:13 +01007619 int chunk_len, ret, done;
Victor Stinner7581cef2011-11-03 22:32:33 +01007620
Victor Stinner2fc507f2011-11-04 20:06:39 +01007621 if (PyUnicode_READY(unicode) < 0)
7622 return NULL;
7623 len = PyUnicode_GET_LENGTH(unicode);
Guido van Rossum03e29f12000-05-04 15:52:20 +00007624
Victor Stinner3a50e702011-10-18 21:21:00 +02007625 if (code_page < 0) {
7626 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7627 return NULL;
7628 }
7629
Martin v. Löwis3d325192011-11-04 18:23:06 +01007630 if (len == 0)
Victor Stinner76a31a62011-11-04 00:05:13 +01007631 return PyBytes_FromStringAndSize(NULL, 0);
7632
Victor Stinner7581cef2011-11-03 22:32:33 +01007633 offset = 0;
7634 do
7635 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007636#ifdef NEED_RETRY
Victor Stinner2fc507f2011-11-04 20:06:39 +01007637 /* UTF-16 encoding may double the size, so use only INT_MAX/2
Martin v. Löwis3d325192011-11-04 18:23:06 +01007638 chunks. */
7639 if (len > INT_MAX/2) {
7640 chunk_len = INT_MAX/2;
Victor Stinner76a31a62011-11-04 00:05:13 +01007641 done = 0;
7642 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007643 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007644#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007645 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007646 chunk_len = (int)len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007647 done = 1;
7648 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007649
Victor Stinner76a31a62011-11-04 00:05:13 +01007650 ret = encode_code_page_strict(code_page, &outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007651 unicode, offset, chunk_len,
Victor Stinner76a31a62011-11-04 00:05:13 +01007652 errors);
7653 if (ret == -2)
7654 ret = encode_code_page_errors(code_page, &outbytes,
7655 unicode, offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007656 chunk_len, errors);
Victor Stinner7581cef2011-11-03 22:32:33 +01007657 if (ret < 0) {
7658 Py_XDECREF(outbytes);
7659 return NULL;
7660 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007661
Victor Stinner7581cef2011-11-03 22:32:33 +01007662 offset += chunk_len;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007663 len -= chunk_len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007664 } while (!done);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007665
Victor Stinner3a50e702011-10-18 21:21:00 +02007666 return outbytes;
7667}
7668
7669PyObject *
7670PyUnicode_EncodeMBCS(const Py_UNICODE *p,
7671 Py_ssize_t size,
7672 const char *errors)
7673{
Victor Stinner7581cef2011-11-03 22:32:33 +01007674 PyObject *unicode, *res;
7675 unicode = PyUnicode_FromUnicode(p, size);
7676 if (unicode == NULL)
7677 return NULL;
7678 res = encode_code_page(CP_ACP, unicode, errors);
7679 Py_DECREF(unicode);
7680 return res;
Victor Stinner3a50e702011-10-18 21:21:00 +02007681}
7682
7683PyObject *
7684PyUnicode_EncodeCodePage(int code_page,
7685 PyObject *unicode,
7686 const char *errors)
7687{
Victor Stinner7581cef2011-11-03 22:32:33 +01007688 return encode_code_page(code_page, unicode, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007689}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007690
Alexander Belopolsky40018472011-02-26 01:02:56 +00007691PyObject *
7692PyUnicode_AsMBCSString(PyObject *unicode)
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007693{
7694 if (!PyUnicode_Check(unicode)) {
7695 PyErr_BadArgument();
7696 return NULL;
7697 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007698 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007699}
7700
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007701#undef NEED_RETRY
7702
Victor Stinner99b95382011-07-04 14:23:54 +02007703#endif /* HAVE_MBCS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007704
Guido van Rossumd57fd912000-03-10 22:53:23 +00007705/* --- Character Mapping Codec -------------------------------------------- */
7706
Alexander Belopolsky40018472011-02-26 01:02:56 +00007707PyObject *
7708PyUnicode_DecodeCharmap(const char *s,
7709 Py_ssize_t size,
7710 PyObject *mapping,
7711 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007712{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007713 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007714 Py_ssize_t startinpos;
7715 Py_ssize_t endinpos;
7716 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007717 const char *e;
Victor Stinner7931d9a2011-11-04 00:22:48 +01007718 PyObject *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007719 Py_ssize_t extrachars = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007720 PyObject *errorHandler = NULL;
7721 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00007722
Guido van Rossumd57fd912000-03-10 22:53:23 +00007723 /* Default to Latin-1 */
7724 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007725 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007726
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007727 v = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007728 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007729 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007730 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01007731 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007732 outpos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007733 e = s + size;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007734 if (PyUnicode_CheckExact(mapping)) {
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007735 Py_ssize_t maplen;
7736 enum PyUnicode_Kind kind;
7737 void *data;
7738 Py_UCS4 x;
7739
7740 if (PyUnicode_READY(mapping) < 0)
7741 return NULL;
7742
7743 maplen = PyUnicode_GET_LENGTH(mapping);
7744 data = PyUnicode_DATA(mapping);
7745 kind = PyUnicode_KIND(mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00007746 while (s < e) {
7747 unsigned char ch = *s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007748
Benjamin Peterson29060642009-01-31 22:14:21 +00007749 if (ch < maplen)
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007750 x = PyUnicode_READ(kind, data, ch);
7751 else
7752 x = 0xfffe; /* invalid value */
Guido van Rossumd57fd912000-03-10 22:53:23 +00007753
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007754 if (x == 0xfffe)
7755 {
Benjamin Peterson29060642009-01-31 22:14:21 +00007756 /* undefined mapping */
Benjamin Peterson29060642009-01-31 22:14:21 +00007757 startinpos = s-starts;
7758 endinpos = startinpos+1;
7759 if (unicode_decode_call_errorhandler(
7760 errors, &errorHandler,
7761 "charmap", "character maps to <undefined>",
7762 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007763 &v, &outpos)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007764 goto onError;
7765 }
7766 continue;
7767 }
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007768
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007769 if (unicode_putchar(&v, &outpos, x) < 0)
7770 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00007771 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007772 }
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007773 }
7774 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007775 while (s < e) {
7776 unsigned char ch = *s;
7777 PyObject *w, *x;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007778
Benjamin Peterson29060642009-01-31 22:14:21 +00007779 /* Get mapping (char ordinal -> integer, Unicode char or None) */
7780 w = PyLong_FromLong((long)ch);
7781 if (w == NULL)
7782 goto onError;
7783 x = PyObject_GetItem(mapping, w);
7784 Py_DECREF(w);
7785 if (x == NULL) {
7786 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7787 /* No mapping found means: mapping is undefined. */
7788 PyErr_Clear();
7789 x = Py_None;
7790 Py_INCREF(x);
7791 } else
7792 goto onError;
7793 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007794
Benjamin Peterson29060642009-01-31 22:14:21 +00007795 /* Apply mapping */
7796 if (PyLong_Check(x)) {
7797 long value = PyLong_AS_LONG(x);
7798 if (value < 0 || value > 65535) {
7799 PyErr_SetString(PyExc_TypeError,
7800 "character mapping must be in range(65536)");
7801 Py_DECREF(x);
7802 goto onError;
7803 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007804 if (unicode_putchar(&v, &outpos, value) < 0)
7805 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00007806 }
7807 else if (x == Py_None) {
7808 /* undefined mapping */
Benjamin Peterson29060642009-01-31 22:14:21 +00007809 startinpos = s-starts;
7810 endinpos = startinpos+1;
7811 if (unicode_decode_call_errorhandler(
7812 errors, &errorHandler,
7813 "charmap", "character maps to <undefined>",
7814 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007815 &v, &outpos)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007816 Py_DECREF(x);
7817 goto onError;
7818 }
7819 Py_DECREF(x);
7820 continue;
7821 }
7822 else if (PyUnicode_Check(x)) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007823 Py_ssize_t targetsize;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007824
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007825 if (PyUnicode_READY(x) < 0)
7826 goto onError;
7827 targetsize = PyUnicode_GET_LENGTH(x);
7828
7829 if (targetsize == 1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007830 /* 1-1 mapping */
Victor Stinner62aa4d02011-11-09 00:03:45 +01007831 if (unicode_putchar(&v, &outpos,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007832 PyUnicode_READ_CHAR(x, 0)) < 0)
7833 goto onError;
7834 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007835 else if (targetsize > 1) {
7836 /* 1-n mapping */
7837 if (targetsize > extrachars) {
7838 /* resize first */
Benjamin Peterson29060642009-01-31 22:14:21 +00007839 Py_ssize_t needed = (targetsize - extrachars) + \
7840 (targetsize << 2);
7841 extrachars += needed;
7842 /* XXX overflow detection missing */
Victor Stinner16e6a802011-12-12 13:24:15 +01007843 if (unicode_resize(&v,
7844 PyUnicode_GET_LENGTH(v) + needed) < 0)
7845 {
Benjamin Peterson29060642009-01-31 22:14:21 +00007846 Py_DECREF(x);
7847 goto onError;
7848 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007849 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007850 if (unicode_widen(&v, PyUnicode_MAX_CHAR_VALUE(x)) < 0)
7851 goto onError;
7852 PyUnicode_CopyCharacters(v, outpos, x, 0, targetsize);
7853 outpos += targetsize;
Benjamin Peterson29060642009-01-31 22:14:21 +00007854 extrachars -= targetsize;
7855 }
7856 /* 1-0 mapping: skip the character */
7857 }
7858 else {
7859 /* wrong return value */
7860 PyErr_SetString(PyExc_TypeError,
7861 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00007862 Py_DECREF(x);
7863 goto onError;
7864 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007865 Py_DECREF(x);
7866 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007867 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00007868 }
Victor Stinner16e6a802011-12-12 13:24:15 +01007869 if (unicode_resize(&v, outpos) < 0)
Antoine Pitroua8f63c02011-11-08 18:37:16 +01007870 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007871 Py_XDECREF(errorHandler);
7872 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01007873 return unicode_result(v);
Tim Petersced69f82003-09-16 20:30:58 +00007874
Benjamin Peterson29060642009-01-31 22:14:21 +00007875 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007876 Py_XDECREF(errorHandler);
7877 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007878 Py_XDECREF(v);
7879 return NULL;
7880}
7881
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007882/* Charmap encoding: the lookup table */
7883
Alexander Belopolsky40018472011-02-26 01:02:56 +00007884struct encoding_map {
Benjamin Peterson29060642009-01-31 22:14:21 +00007885 PyObject_HEAD
7886 unsigned char level1[32];
7887 int count2, count3;
7888 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007889};
7890
7891static PyObject*
7892encoding_map_size(PyObject *obj, PyObject* args)
7893{
7894 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007895 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00007896 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007897}
7898
7899static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007900 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00007901 PyDoc_STR("Return the size (in bytes) of this object") },
7902 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007903};
7904
7905static void
7906encoding_map_dealloc(PyObject* o)
7907{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007908 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007909}
7910
7911static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007912 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007913 "EncodingMap", /*tp_name*/
7914 sizeof(struct encoding_map), /*tp_basicsize*/
7915 0, /*tp_itemsize*/
7916 /* methods */
7917 encoding_map_dealloc, /*tp_dealloc*/
7918 0, /*tp_print*/
7919 0, /*tp_getattr*/
7920 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00007921 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00007922 0, /*tp_repr*/
7923 0, /*tp_as_number*/
7924 0, /*tp_as_sequence*/
7925 0, /*tp_as_mapping*/
7926 0, /*tp_hash*/
7927 0, /*tp_call*/
7928 0, /*tp_str*/
7929 0, /*tp_getattro*/
7930 0, /*tp_setattro*/
7931 0, /*tp_as_buffer*/
7932 Py_TPFLAGS_DEFAULT, /*tp_flags*/
7933 0, /*tp_doc*/
7934 0, /*tp_traverse*/
7935 0, /*tp_clear*/
7936 0, /*tp_richcompare*/
7937 0, /*tp_weaklistoffset*/
7938 0, /*tp_iter*/
7939 0, /*tp_iternext*/
7940 encoding_map_methods, /*tp_methods*/
7941 0, /*tp_members*/
7942 0, /*tp_getset*/
7943 0, /*tp_base*/
7944 0, /*tp_dict*/
7945 0, /*tp_descr_get*/
7946 0, /*tp_descr_set*/
7947 0, /*tp_dictoffset*/
7948 0, /*tp_init*/
7949 0, /*tp_alloc*/
7950 0, /*tp_new*/
7951 0, /*tp_free*/
7952 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007953};
7954
7955PyObject*
7956PyUnicode_BuildEncodingMap(PyObject* string)
7957{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007958 PyObject *result;
7959 struct encoding_map *mresult;
7960 int i;
7961 int need_dict = 0;
7962 unsigned char level1[32];
7963 unsigned char level2[512];
7964 unsigned char *mlevel1, *mlevel2, *mlevel3;
7965 int count2 = 0, count3 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007966 int kind;
7967 void *data;
7968 Py_UCS4 ch;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007969
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007970 if (!PyUnicode_Check(string) || PyUnicode_GET_LENGTH(string) != 256) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007971 PyErr_BadArgument();
7972 return NULL;
7973 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007974 kind = PyUnicode_KIND(string);
7975 data = PyUnicode_DATA(string);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007976 memset(level1, 0xFF, sizeof level1);
7977 memset(level2, 0xFF, sizeof level2);
7978
7979 /* If there isn't a one-to-one mapping of NULL to \0,
7980 or if there are non-BMP characters, we need to use
7981 a mapping dictionary. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007982 if (PyUnicode_READ(kind, data, 0) != 0)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007983 need_dict = 1;
7984 for (i = 1; i < 256; i++) {
7985 int l1, l2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007986 ch = PyUnicode_READ(kind, data, i);
7987 if (ch == 0 || ch > 0xFFFF) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007988 need_dict = 1;
7989 break;
7990 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007991 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007992 /* unmapped character */
7993 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007994 l1 = ch >> 11;
7995 l2 = ch >> 7;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007996 if (level1[l1] == 0xFF)
7997 level1[l1] = count2++;
7998 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00007999 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008000 }
8001
8002 if (count2 >= 0xFF || count3 >= 0xFF)
8003 need_dict = 1;
8004
8005 if (need_dict) {
8006 PyObject *result = PyDict_New();
8007 PyObject *key, *value;
8008 if (!result)
8009 return NULL;
8010 for (i = 0; i < 256; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008011 key = PyLong_FromLong(PyUnicode_READ(kind, data, i));
Christian Heimes217cfd12007-12-02 14:31:20 +00008012 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008013 if (!key || !value)
8014 goto failed1;
8015 if (PyDict_SetItem(result, key, value) == -1)
8016 goto failed1;
8017 Py_DECREF(key);
8018 Py_DECREF(value);
8019 }
8020 return result;
8021 failed1:
8022 Py_XDECREF(key);
8023 Py_XDECREF(value);
8024 Py_DECREF(result);
8025 return NULL;
8026 }
8027
8028 /* Create a three-level trie */
8029 result = PyObject_MALLOC(sizeof(struct encoding_map) +
8030 16*count2 + 128*count3 - 1);
8031 if (!result)
8032 return PyErr_NoMemory();
8033 PyObject_Init(result, &EncodingMapType);
8034 mresult = (struct encoding_map*)result;
8035 mresult->count2 = count2;
8036 mresult->count3 = count3;
8037 mlevel1 = mresult->level1;
8038 mlevel2 = mresult->level23;
8039 mlevel3 = mresult->level23 + 16*count2;
8040 memcpy(mlevel1, level1, 32);
8041 memset(mlevel2, 0xFF, 16*count2);
8042 memset(mlevel3, 0, 128*count3);
8043 count3 = 0;
8044 for (i = 1; i < 256; i++) {
8045 int o1, o2, o3, i2, i3;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008046 if (PyUnicode_READ(kind, data, i) == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008047 /* unmapped character */
8048 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008049 o1 = PyUnicode_READ(kind, data, i)>>11;
8050 o2 = (PyUnicode_READ(kind, data, i)>>7) & 0xF;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008051 i2 = 16*mlevel1[o1] + o2;
8052 if (mlevel2[i2] == 0xFF)
8053 mlevel2[i2] = count3++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008054 o3 = PyUnicode_READ(kind, data, i) & 0x7F;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008055 i3 = 128*mlevel2[i2] + o3;
8056 mlevel3[i3] = i;
8057 }
8058 return result;
8059}
8060
8061static int
Victor Stinner22168992011-11-20 17:09:18 +01008062encoding_map_lookup(Py_UCS4 c, PyObject *mapping)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008063{
8064 struct encoding_map *map = (struct encoding_map*)mapping;
8065 int l1 = c>>11;
8066 int l2 = (c>>7) & 0xF;
8067 int l3 = c & 0x7F;
8068 int i;
8069
Victor Stinner22168992011-11-20 17:09:18 +01008070 if (c > 0xFFFF)
Benjamin Peterson29060642009-01-31 22:14:21 +00008071 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008072 if (c == 0)
8073 return 0;
8074 /* level 1*/
8075 i = map->level1[l1];
8076 if (i == 0xFF) {
8077 return -1;
8078 }
8079 /* level 2*/
8080 i = map->level23[16*i+l2];
8081 if (i == 0xFF) {
8082 return -1;
8083 }
8084 /* level 3 */
8085 i = map->level23[16*map->count2 + 128*i + l3];
8086 if (i == 0) {
8087 return -1;
8088 }
8089 return i;
8090}
8091
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008092/* Lookup the character ch in the mapping. If the character
8093 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00008094 error occurred). */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008095static PyObject *
Victor Stinner22168992011-11-20 17:09:18 +01008096charmapencode_lookup(Py_UCS4 c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008097{
Christian Heimes217cfd12007-12-02 14:31:20 +00008098 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008099 PyObject *x;
8100
8101 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008102 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008103 x = PyObject_GetItem(mapping, w);
8104 Py_DECREF(w);
8105 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008106 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8107 /* No mapping found means: mapping is undefined. */
8108 PyErr_Clear();
8109 x = Py_None;
8110 Py_INCREF(x);
8111 return x;
8112 } else
8113 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008114 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00008115 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008116 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00008117 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008118 long value = PyLong_AS_LONG(x);
8119 if (value < 0 || value > 255) {
8120 PyErr_SetString(PyExc_TypeError,
8121 "character mapping must be in range(256)");
8122 Py_DECREF(x);
8123 return NULL;
8124 }
8125 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008126 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008127 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008128 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008129 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008130 /* wrong return value */
8131 PyErr_Format(PyExc_TypeError,
8132 "character mapping must return integer, bytes or None, not %.400s",
8133 x->ob_type->tp_name);
8134 Py_DECREF(x);
8135 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008136 }
8137}
8138
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008139static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00008140charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008141{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008142 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
8143 /* exponentially overallocate to minimize reallocations */
8144 if (requiredsize < 2*outsize)
8145 requiredsize = 2*outsize;
8146 if (_PyBytes_Resize(outobj, requiredsize))
8147 return -1;
8148 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008149}
8150
Benjamin Peterson14339b62009-01-31 16:36:08 +00008151typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00008152 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Alexander Belopolsky40018472011-02-26 01:02:56 +00008153} charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008154/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00008155 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008156 space is available. Return a new reference to the object that
8157 was put in the output buffer, or Py_None, if the mapping was undefined
8158 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00008159 reallocation error occurred. The caller must decref the result */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008160static charmapencode_result
Victor Stinner22168992011-11-20 17:09:18 +01008161charmapencode_output(Py_UCS4 c, PyObject *mapping,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008162 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008163{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008164 PyObject *rep;
8165 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00008166 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008167
Christian Heimes90aa7642007-12-19 02:45:37 +00008168 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008169 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008170 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008171 if (res == -1)
8172 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00008173 if (outsize<requiredsize)
8174 if (charmapencode_resize(outobj, outpos, requiredsize))
8175 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00008176 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008177 outstart[(*outpos)++] = (char)res;
8178 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008179 }
8180
8181 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008182 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008183 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008184 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008185 Py_DECREF(rep);
8186 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008187 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008188 if (PyLong_Check(rep)) {
8189 Py_ssize_t requiredsize = *outpos+1;
8190 if (outsize<requiredsize)
8191 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8192 Py_DECREF(rep);
8193 return enc_EXCEPTION;
8194 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008195 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008196 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008197 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008198 else {
8199 const char *repchars = PyBytes_AS_STRING(rep);
8200 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
8201 Py_ssize_t requiredsize = *outpos+repsize;
8202 if (outsize<requiredsize)
8203 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8204 Py_DECREF(rep);
8205 return enc_EXCEPTION;
8206 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008207 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008208 memcpy(outstart + *outpos, repchars, repsize);
8209 *outpos += repsize;
8210 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008211 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008212 Py_DECREF(rep);
8213 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008214}
8215
8216/* handle an error in PyUnicode_EncodeCharmap
8217 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008218static int
8219charmap_encoding_error(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008220 PyObject *unicode, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008221 PyObject **exceptionObject,
Walter Dörwalde5402fb2003-08-14 20:25:29 +00008222 int *known_errorHandler, PyObject **errorHandler, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00008223 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008224{
8225 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008226 Py_ssize_t size, repsize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008227 Py_ssize_t newpos;
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008228 enum PyUnicode_Kind kind;
8229 void *data;
8230 Py_ssize_t index;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008231 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008232 Py_ssize_t collstartpos = *inpos;
8233 Py_ssize_t collendpos = *inpos+1;
8234 Py_ssize_t collpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008235 char *encoding = "charmap";
8236 char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008237 charmapencode_result x;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008238 Py_UCS4 ch;
Brian Curtin2787ea42011-11-02 15:09:37 -05008239 int val;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008240
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008241 if (PyUnicode_READY(unicode) < 0)
8242 return -1;
8243 size = PyUnicode_GET_LENGTH(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008244 /* find all unencodable characters */
8245 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008246 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00008247 if (Py_TYPE(mapping) == &EncodingMapType) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008248 ch = PyUnicode_READ_CHAR(unicode, collendpos);
Brian Curtin2787ea42011-11-02 15:09:37 -05008249 val = encoding_map_lookup(ch, mapping);
8250 if (val != -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008251 break;
8252 ++collendpos;
8253 continue;
8254 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008255
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008256 ch = PyUnicode_READ_CHAR(unicode, collendpos);
8257 rep = charmapencode_lookup(ch, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008258 if (rep==NULL)
8259 return -1;
8260 else if (rep!=Py_None) {
8261 Py_DECREF(rep);
8262 break;
8263 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008264 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00008265 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008266 }
8267 /* cache callback name lookup
8268 * (if not done yet, i.e. it's the first error) */
8269 if (*known_errorHandler==-1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008270 if ((errors==NULL) || (!strcmp(errors, "strict")))
8271 *known_errorHandler = 1;
8272 else if (!strcmp(errors, "replace"))
8273 *known_errorHandler = 2;
8274 else if (!strcmp(errors, "ignore"))
8275 *known_errorHandler = 3;
8276 else if (!strcmp(errors, "xmlcharrefreplace"))
8277 *known_errorHandler = 4;
8278 else
8279 *known_errorHandler = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008280 }
8281 switch (*known_errorHandler) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008282 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008283 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008284 return -1;
8285 case 2: /* replace */
8286 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008287 x = charmapencode_output('?', mapping, res, respos);
8288 if (x==enc_EXCEPTION) {
8289 return -1;
8290 }
8291 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008292 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008293 return -1;
8294 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008295 }
8296 /* fall through */
8297 case 3: /* ignore */
8298 *inpos = collendpos;
8299 break;
8300 case 4: /* xmlcharrefreplace */
8301 /* generate replacement (temporarily (mis)uses p) */
8302 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008303 char buffer[2+29+1+1];
8304 char *cp;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008305 sprintf(buffer, "&#%d;", (int)PyUnicode_READ_CHAR(unicode, collpos));
Benjamin Peterson29060642009-01-31 22:14:21 +00008306 for (cp = buffer; *cp; ++cp) {
8307 x = charmapencode_output(*cp, mapping, res, respos);
8308 if (x==enc_EXCEPTION)
8309 return -1;
8310 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008311 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008312 return -1;
8313 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008314 }
8315 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008316 *inpos = collendpos;
8317 break;
8318 default:
8319 repunicode = unicode_encode_call_errorhandler(errors, errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008320 encoding, reason, unicode, exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00008321 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008322 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008323 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00008324 if (PyBytes_Check(repunicode)) {
8325 /* Directly copy bytes result to output. */
8326 Py_ssize_t outsize = PyBytes_Size(*res);
8327 Py_ssize_t requiredsize;
8328 repsize = PyBytes_Size(repunicode);
8329 requiredsize = *respos + repsize;
8330 if (requiredsize > outsize)
8331 /* Make room for all additional bytes. */
8332 if (charmapencode_resize(res, respos, requiredsize)) {
8333 Py_DECREF(repunicode);
8334 return -1;
8335 }
8336 memcpy(PyBytes_AsString(*res) + *respos,
8337 PyBytes_AsString(repunicode), repsize);
8338 *respos += repsize;
8339 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008340 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00008341 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008342 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008343 /* generate replacement */
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008344 if (PyUnicode_READY(repunicode) < 0) {
8345 Py_DECREF(repunicode);
8346 return -1;
8347 }
Victor Stinner9e30aa52011-11-21 02:49:52 +01008348 repsize = PyUnicode_GET_LENGTH(repunicode);
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008349 data = PyUnicode_DATA(repunicode);
8350 kind = PyUnicode_KIND(repunicode);
8351 for (index = 0; index < repsize; index++) {
8352 Py_UCS4 repch = PyUnicode_READ(kind, data, index);
8353 x = charmapencode_output(repch, mapping, res, respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008354 if (x==enc_EXCEPTION) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008355 Py_DECREF(repunicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00008356 return -1;
8357 }
8358 else if (x==enc_FAILED) {
8359 Py_DECREF(repunicode);
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008360 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008361 return -1;
8362 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008363 }
8364 *inpos = newpos;
8365 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008366 }
8367 return 0;
8368}
8369
Alexander Belopolsky40018472011-02-26 01:02:56 +00008370PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008371_PyUnicode_EncodeCharmap(PyObject *unicode,
8372 PyObject *mapping,
8373 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008374{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008375 /* output object */
8376 PyObject *res = NULL;
8377 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008378 Py_ssize_t inpos = 0;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008379 Py_ssize_t size;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008380 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008381 Py_ssize_t respos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008382 PyObject *errorHandler = NULL;
8383 PyObject *exc = NULL;
8384 /* the following variable is used for caching string comparisons
8385 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8386 * 3=ignore, 4=xmlcharrefreplace */
8387 int known_errorHandler = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008388
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008389 if (PyUnicode_READY(unicode) < 0)
8390 return NULL;
8391 size = PyUnicode_GET_LENGTH(unicode);
8392
Guido van Rossumd57fd912000-03-10 22:53:23 +00008393 /* Default to Latin-1 */
8394 if (mapping == NULL)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008395 return unicode_encode_ucs1(unicode, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008396
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008397 /* allocate enough for a simple encoding without
8398 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00008399 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008400 if (res == NULL)
8401 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00008402 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008403 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008404
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008405 while (inpos<size) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008406 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, inpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008407 /* try to encode it */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008408 charmapencode_result x = charmapencode_output(ch, mapping, &res, &respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008409 if (x==enc_EXCEPTION) /* error */
8410 goto onError;
8411 if (x==enc_FAILED) { /* unencodable character */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008412 if (charmap_encoding_error(unicode, &inpos, mapping,
Benjamin Peterson29060642009-01-31 22:14:21 +00008413 &exc,
8414 &known_errorHandler, &errorHandler, errors,
8415 &res, &respos)) {
8416 goto onError;
8417 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008418 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008419 else
8420 /* done with this character => adjust input position */
8421 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008422 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008423
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008424 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00008425 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00008426 if (_PyBytes_Resize(&res, respos) < 0)
8427 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00008428
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008429 Py_XDECREF(exc);
8430 Py_XDECREF(errorHandler);
8431 return res;
8432
Benjamin Peterson29060642009-01-31 22:14:21 +00008433 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008434 Py_XDECREF(res);
8435 Py_XDECREF(exc);
8436 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008437 return NULL;
8438}
8439
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008440/* Deprecated */
8441PyObject *
8442PyUnicode_EncodeCharmap(const Py_UNICODE *p,
8443 Py_ssize_t size,
8444 PyObject *mapping,
8445 const char *errors)
8446{
8447 PyObject *result;
8448 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8449 if (unicode == NULL)
8450 return NULL;
8451 result = _PyUnicode_EncodeCharmap(unicode, mapping, errors);
8452 Py_DECREF(unicode);
Victor Stinnerfc026c92011-11-04 00:24:51 +01008453 return result;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008454}
8455
Alexander Belopolsky40018472011-02-26 01:02:56 +00008456PyObject *
8457PyUnicode_AsCharmapString(PyObject *unicode,
8458 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008459{
8460 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008461 PyErr_BadArgument();
8462 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008463 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008464 return _PyUnicode_EncodeCharmap(unicode, mapping, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008465}
8466
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008467/* create or adjust a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008468static void
8469make_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008470 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008471 Py_ssize_t startpos, Py_ssize_t endpos,
8472 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008473{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008474 if (*exceptionObject == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008475 *exceptionObject = _PyUnicodeTranslateError_Create(
8476 unicode, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008477 }
8478 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008479 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
8480 goto onError;
8481 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
8482 goto onError;
8483 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
8484 goto onError;
8485 return;
8486 onError:
8487 Py_DECREF(*exceptionObject);
8488 *exceptionObject = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008489 }
8490}
8491
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008492/* raises a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008493static void
8494raise_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008495 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008496 Py_ssize_t startpos, Py_ssize_t endpos,
8497 const char *reason)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008498{
8499 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008500 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008501 if (*exceptionObject != NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008502 PyCodec_StrictErrors(*exceptionObject);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008503}
8504
8505/* error handling callback helper:
8506 build arguments, call the callback and check the arguments,
8507 put the result into newpos and return the replacement string, which
8508 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008509static PyObject *
8510unicode_translate_call_errorhandler(const char *errors,
8511 PyObject **errorHandler,
8512 const char *reason,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008513 PyObject *unicode, PyObject **exceptionObject,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008514 Py_ssize_t startpos, Py_ssize_t endpos,
8515 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008516{
Benjamin Peterson142957c2008-07-04 19:55:29 +00008517 static char *argparse = "O!n;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008518
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008519 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008520 PyObject *restuple;
8521 PyObject *resunicode;
8522
8523 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008524 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008525 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008526 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008527 }
8528
8529 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008530 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008531 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008532 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008533
8534 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00008535 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008536 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008537 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008538 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00008539 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00008540 Py_DECREF(restuple);
8541 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008542 }
8543 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type,
Benjamin Peterson29060642009-01-31 22:14:21 +00008544 &resunicode, &i_newpos)) {
8545 Py_DECREF(restuple);
8546 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008547 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00008548 if (i_newpos<0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008549 *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008550 else
8551 *newpos = i_newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008552 if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008553 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
8554 Py_DECREF(restuple);
8555 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00008556 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008557 Py_INCREF(resunicode);
8558 Py_DECREF(restuple);
8559 return resunicode;
8560}
8561
8562/* Lookup the character ch in the mapping and put the result in result,
8563 which must be decrefed by the caller.
8564 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008565static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008566charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008567{
Christian Heimes217cfd12007-12-02 14:31:20 +00008568 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008569 PyObject *x;
8570
8571 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008572 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008573 x = PyObject_GetItem(mapping, w);
8574 Py_DECREF(w);
8575 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008576 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8577 /* No mapping found means: use 1:1 mapping. */
8578 PyErr_Clear();
8579 *result = NULL;
8580 return 0;
8581 } else
8582 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008583 }
8584 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008585 *result = x;
8586 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008587 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008588 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008589 long value = PyLong_AS_LONG(x);
8590 long max = PyUnicode_GetMax();
8591 if (value < 0 || value > max) {
8592 PyErr_Format(PyExc_TypeError,
Guido van Rossum5a2f7e602007-10-24 21:13:09 +00008593 "character mapping must be in range(0x%x)", max+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00008594 Py_DECREF(x);
8595 return -1;
8596 }
8597 *result = x;
8598 return 0;
8599 }
8600 else if (PyUnicode_Check(x)) {
8601 *result = x;
8602 return 0;
8603 }
8604 else {
8605 /* wrong return value */
8606 PyErr_SetString(PyExc_TypeError,
8607 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00008608 Py_DECREF(x);
8609 return -1;
8610 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008611}
8612/* ensure that *outobj is at least requiredsize characters long,
Benjamin Peterson29060642009-01-31 22:14:21 +00008613 if not reallocate and adjust various state variables.
8614 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008615static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008616charmaptranslate_makespace(Py_UCS4 **outobj, Py_ssize_t *psize,
Benjamin Peterson29060642009-01-31 22:14:21 +00008617 Py_ssize_t requiredsize)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008618{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008619 Py_ssize_t oldsize = *psize;
Walter Dörwald4894c302003-10-24 14:25:28 +00008620 if (requiredsize > oldsize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008621 /* exponentially overallocate to minimize reallocations */
8622 if (requiredsize < 2 * oldsize)
8623 requiredsize = 2 * oldsize;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008624 *outobj = PyMem_Realloc(*outobj, requiredsize * sizeof(Py_UCS4));
8625 if (*outobj == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008626 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008627 *psize = requiredsize;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008628 }
8629 return 0;
8630}
8631/* lookup the character, put the result in the output string and adjust
8632 various state variables. Return a new reference to the object that
8633 was put in the output buffer in *result, or Py_None, if the mapping was
8634 undefined (in which case no character was written).
8635 The called must decref result.
8636 Return 0 on success, -1 on error. */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008637static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008638charmaptranslate_output(PyObject *input, Py_ssize_t ipos,
8639 PyObject *mapping, Py_UCS4 **output,
8640 Py_ssize_t *osize, Py_ssize_t *opos,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008641 PyObject **res)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008642{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008643 Py_UCS4 curinp = PyUnicode_READ_CHAR(input, ipos);
8644 if (charmaptranslate_lookup(curinp, mapping, res))
Benjamin Peterson29060642009-01-31 22:14:21 +00008645 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008646 if (*res==NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008647 /* not found => default to 1:1 mapping */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008648 (*output)[(*opos)++] = curinp;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008649 }
8650 else if (*res==Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008651 ;
Christian Heimes217cfd12007-12-02 14:31:20 +00008652 else if (PyLong_Check(*res)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008653 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008654 (*output)[(*opos)++] = (Py_UCS4)PyLong_AS_LONG(*res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008655 }
8656 else if (PyUnicode_Check(*res)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008657 Py_ssize_t repsize;
8658 if (PyUnicode_READY(*res) == -1)
8659 return -1;
8660 repsize = PyUnicode_GET_LENGTH(*res);
Benjamin Peterson29060642009-01-31 22:14:21 +00008661 if (repsize==1) {
8662 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008663 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +00008664 }
8665 else if (repsize!=0) {
8666 /* more than one character */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008667 Py_ssize_t requiredsize = *opos +
8668 (PyUnicode_GET_LENGTH(input) - ipos) +
Benjamin Peterson29060642009-01-31 22:14:21 +00008669 repsize - 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008670 Py_ssize_t i;
8671 if (charmaptranslate_makespace(output, osize, requiredsize))
Benjamin Peterson29060642009-01-31 22:14:21 +00008672 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008673 for(i = 0; i < repsize; i++)
8674 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00008675 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008676 }
8677 else
Benjamin Peterson29060642009-01-31 22:14:21 +00008678 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008679 return 0;
8680}
8681
Alexander Belopolsky40018472011-02-26 01:02:56 +00008682PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008683_PyUnicode_TranslateCharmap(PyObject *input,
8684 PyObject *mapping,
8685 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008686{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008687 /* input object */
8688 char *idata;
8689 Py_ssize_t size, i;
8690 int kind;
8691 /* output buffer */
8692 Py_UCS4 *output = NULL;
8693 Py_ssize_t osize;
8694 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008695 /* current output position */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008696 Py_ssize_t opos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008697 char *reason = "character maps to <undefined>";
8698 PyObject *errorHandler = NULL;
8699 PyObject *exc = NULL;
8700 /* the following variable is used for caching string comparisons
8701 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8702 * 3=ignore, 4=xmlcharrefreplace */
8703 int known_errorHandler = -1;
8704
Guido van Rossumd57fd912000-03-10 22:53:23 +00008705 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008706 PyErr_BadArgument();
8707 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008708 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008709
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008710 if (PyUnicode_READY(input) == -1)
8711 return NULL;
8712 idata = (char*)PyUnicode_DATA(input);
8713 kind = PyUnicode_KIND(input);
8714 size = PyUnicode_GET_LENGTH(input);
8715 i = 0;
8716
8717 if (size == 0) {
8718 Py_INCREF(input);
8719 return input;
8720 }
8721
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008722 /* allocate enough for a simple 1:1 translation without
8723 replacements, if we need more, we'll resize */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008724 osize = size;
8725 output = PyMem_Malloc(osize * sizeof(Py_UCS4));
8726 opos = 0;
8727 if (output == NULL) {
8728 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00008729 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008730 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008731
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008732 while (i<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008733 /* try to encode it */
8734 PyObject *x = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008735 if (charmaptranslate_output(input, i, mapping,
8736 &output, &osize, &opos, &x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008737 Py_XDECREF(x);
8738 goto onError;
8739 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008740 Py_XDECREF(x);
Benjamin Peterson29060642009-01-31 22:14:21 +00008741 if (x!=Py_None) /* it worked => adjust input pointer */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008742 ++i;
Benjamin Peterson29060642009-01-31 22:14:21 +00008743 else { /* untranslatable character */
8744 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
8745 Py_ssize_t repsize;
8746 Py_ssize_t newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008747 Py_ssize_t uni2;
Benjamin Peterson29060642009-01-31 22:14:21 +00008748 /* startpos for collecting untranslatable chars */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008749 Py_ssize_t collstart = i;
8750 Py_ssize_t collend = i+1;
8751 Py_ssize_t coll;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008752
Benjamin Peterson29060642009-01-31 22:14:21 +00008753 /* find all untranslatable characters */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008754 while (collend < size) {
8755 if (charmaptranslate_lookup(PyUnicode_READ(kind,idata, collend), mapping, &x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008756 goto onError;
8757 Py_XDECREF(x);
8758 if (x!=Py_None)
8759 break;
8760 ++collend;
8761 }
8762 /* cache callback name lookup
8763 * (if not done yet, i.e. it's the first error) */
8764 if (known_errorHandler==-1) {
8765 if ((errors==NULL) || (!strcmp(errors, "strict")))
8766 known_errorHandler = 1;
8767 else if (!strcmp(errors, "replace"))
8768 known_errorHandler = 2;
8769 else if (!strcmp(errors, "ignore"))
8770 known_errorHandler = 3;
8771 else if (!strcmp(errors, "xmlcharrefreplace"))
8772 known_errorHandler = 4;
8773 else
8774 known_errorHandler = 0;
8775 }
8776 switch (known_errorHandler) {
8777 case 1: /* strict */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008778 raise_translate_exception(&exc, input, collstart,
8779 collend, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008780 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00008781 case 2: /* replace */
8782 /* No need to check for space, this is a 1:1 replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008783 for (coll = collstart; coll<collend; coll++)
8784 output[opos++] = '?';
Benjamin Peterson29060642009-01-31 22:14:21 +00008785 /* fall through */
8786 case 3: /* ignore */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008787 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008788 break;
8789 case 4: /* xmlcharrefreplace */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008790 /* generate replacement (temporarily (mis)uses i) */
8791 for (i = collstart; i < collend; ++i) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008792 char buffer[2+29+1+1];
8793 char *cp;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008794 sprintf(buffer, "&#%d;", PyUnicode_READ(kind, idata, i));
8795 if (charmaptranslate_makespace(&output, &osize,
8796 opos+strlen(buffer)+(size-collend)))
Benjamin Peterson29060642009-01-31 22:14:21 +00008797 goto onError;
8798 for (cp = buffer; *cp; ++cp)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008799 output[opos++] = *cp;
Benjamin Peterson29060642009-01-31 22:14:21 +00008800 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008801 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008802 break;
8803 default:
8804 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008805 reason, input, &exc,
8806 collstart, collend, &newpos);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008807 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008808 goto onError;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008809 if (PyUnicode_READY(repunicode) < 0) {
8810 Py_DECREF(repunicode);
8811 goto onError;
8812 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008813 /* generate replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008814 repsize = PyUnicode_GET_LENGTH(repunicode);
8815 if (charmaptranslate_makespace(&output, &osize,
8816 opos+repsize+(size-collend))) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008817 Py_DECREF(repunicode);
8818 goto onError;
8819 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008820 for (uni2 = 0; repsize-->0; ++uni2)
8821 output[opos++] = PyUnicode_READ_CHAR(repunicode, uni2);
8822 i = newpos;
Benjamin Peterson29060642009-01-31 22:14:21 +00008823 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008824 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008825 }
8826 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008827 res = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND, output, opos);
8828 if (!res)
8829 goto onError;
8830 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008831 Py_XDECREF(exc);
8832 Py_XDECREF(errorHandler);
8833 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008834
Benjamin Peterson29060642009-01-31 22:14:21 +00008835 onError:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008836 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008837 Py_XDECREF(exc);
8838 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008839 return NULL;
8840}
8841
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008842/* Deprecated. Use PyUnicode_Translate instead. */
8843PyObject *
8844PyUnicode_TranslateCharmap(const Py_UNICODE *p,
8845 Py_ssize_t size,
8846 PyObject *mapping,
8847 const char *errors)
8848{
8849 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8850 if (!unicode)
8851 return NULL;
8852 return _PyUnicode_TranslateCharmap(unicode, mapping, errors);
8853}
8854
Alexander Belopolsky40018472011-02-26 01:02:56 +00008855PyObject *
8856PyUnicode_Translate(PyObject *str,
8857 PyObject *mapping,
8858 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008859{
8860 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +00008861
Guido van Rossumd57fd912000-03-10 22:53:23 +00008862 str = PyUnicode_FromObject(str);
8863 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008864 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008865 result = _PyUnicode_TranslateCharmap(str, mapping, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008866 Py_DECREF(str);
8867 return result;
Tim Petersced69f82003-09-16 20:30:58 +00008868
Benjamin Peterson29060642009-01-31 22:14:21 +00008869 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00008870 Py_XDECREF(str);
8871 return NULL;
8872}
Tim Petersced69f82003-09-16 20:30:58 +00008873
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008874static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02008875fix_decimal_and_space_to_ascii(PyObject *self)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008876{
8877 /* No need to call PyUnicode_READY(self) because this function is only
8878 called as a callback from fixup() which does it already. */
8879 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
8880 const int kind = PyUnicode_KIND(self);
8881 void *data = PyUnicode_DATA(self);
8882 Py_UCS4 maxchar = 0, ch, fixed;
8883 Py_ssize_t i;
8884
8885 for (i = 0; i < len; ++i) {
8886 ch = PyUnicode_READ(kind, data, i);
8887 fixed = 0;
8888 if (ch > 127) {
8889 if (Py_UNICODE_ISSPACE(ch))
8890 fixed = ' ';
8891 else {
8892 const int decimal = Py_UNICODE_TODECIMAL(ch);
8893 if (decimal >= 0)
8894 fixed = '0' + decimal;
8895 }
8896 if (fixed != 0) {
8897 if (fixed > maxchar)
8898 maxchar = fixed;
8899 PyUnicode_WRITE(kind, data, i, fixed);
8900 }
8901 else if (ch > maxchar)
8902 maxchar = ch;
8903 }
8904 else if (ch > maxchar)
8905 maxchar = ch;
8906 }
8907
8908 return maxchar;
8909}
8910
8911PyObject *
8912_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
8913{
8914 if (!PyUnicode_Check(unicode)) {
8915 PyErr_BadInternalCall();
8916 return NULL;
8917 }
8918 if (PyUnicode_READY(unicode) == -1)
8919 return NULL;
8920 if (PyUnicode_MAX_CHAR_VALUE(unicode) <= 127) {
8921 /* If the string is already ASCII, just return the same string */
8922 Py_INCREF(unicode);
8923 return unicode;
8924 }
Victor Stinner9310abb2011-10-05 00:59:23 +02008925 return fixup(unicode, fix_decimal_and_space_to_ascii);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008926}
8927
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008928PyObject *
8929PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
8930 Py_ssize_t length)
8931{
Victor Stinnerf0124502011-11-21 23:12:56 +01008932 PyObject *decimal;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008933 Py_ssize_t i;
Victor Stinnerf0124502011-11-21 23:12:56 +01008934 Py_UCS4 maxchar;
8935 enum PyUnicode_Kind kind;
8936 void *data;
8937
8938 maxchar = 0;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008939 for (i = 0; i < length; i++) {
Victor Stinnerf0124502011-11-21 23:12:56 +01008940 Py_UNICODE ch = s[i];
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008941 if (ch > 127) {
8942 int decimal = Py_UNICODE_TODECIMAL(ch);
8943 if (decimal >= 0)
Victor Stinnerf0124502011-11-21 23:12:56 +01008944 ch = '0' + decimal;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008945 }
Victor Stinnerf0124502011-11-21 23:12:56 +01008946 maxchar = Py_MAX(maxchar, ch);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008947 }
Victor Stinnerf0124502011-11-21 23:12:56 +01008948
8949 /* Copy to a new string */
8950 decimal = PyUnicode_New(length, maxchar);
8951 if (decimal == NULL)
8952 return decimal;
8953 kind = PyUnicode_KIND(decimal);
8954 data = PyUnicode_DATA(decimal);
8955 /* Iterate over code points */
8956 for (i = 0; i < length; i++) {
8957 Py_UNICODE ch = s[i];
8958 if (ch > 127) {
8959 int decimal = Py_UNICODE_TODECIMAL(ch);
8960 if (decimal >= 0)
8961 ch = '0' + decimal;
8962 }
8963 PyUnicode_WRITE(kind, data, i, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008964 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008965 return unicode_result(decimal);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008966}
Guido van Rossum9e896b32000-04-05 20:11:21 +00008967/* --- Decimal Encoder ---------------------------------------------------- */
8968
Alexander Belopolsky40018472011-02-26 01:02:56 +00008969int
8970PyUnicode_EncodeDecimal(Py_UNICODE *s,
8971 Py_ssize_t length,
8972 char *output,
8973 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00008974{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008975 PyObject *unicode;
Victor Stinner6345be92011-11-25 20:09:01 +01008976 Py_ssize_t i;
Victor Stinner42bf7752011-11-21 22:52:58 +01008977 enum PyUnicode_Kind kind;
8978 void *data;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008979
8980 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008981 PyErr_BadArgument();
8982 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008983 }
8984
Victor Stinner42bf7752011-11-21 22:52:58 +01008985 unicode = PyUnicode_FromUnicode(s, length);
8986 if (unicode == NULL)
8987 return -1;
8988
Victor Stinner6345be92011-11-25 20:09:01 +01008989 if (PyUnicode_READY(unicode) < 0) {
8990 Py_DECREF(unicode);
8991 return -1;
8992 }
Victor Stinner42bf7752011-11-21 22:52:58 +01008993 kind = PyUnicode_KIND(unicode);
8994 data = PyUnicode_DATA(unicode);
8995
Victor Stinnerb84d7232011-11-22 01:50:07 +01008996 for (i=0; i < length; ) {
Victor Stinner6345be92011-11-25 20:09:01 +01008997 PyObject *exc;
8998 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00008999 int decimal;
Victor Stinner6345be92011-11-25 20:09:01 +01009000 Py_ssize_t startpos;
9001
9002 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +00009003
Benjamin Peterson29060642009-01-31 22:14:21 +00009004 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009005 *output++ = ' ';
Victor Stinnerb84d7232011-11-22 01:50:07 +01009006 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009007 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009008 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009009 decimal = Py_UNICODE_TODECIMAL(ch);
9010 if (decimal >= 0) {
9011 *output++ = '0' + decimal;
Victor Stinnerb84d7232011-11-22 01:50:07 +01009012 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009013 continue;
9014 }
9015 if (0 < ch && ch < 256) {
9016 *output++ = (char)ch;
Victor Stinnerb84d7232011-11-22 01:50:07 +01009017 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009018 continue;
9019 }
Victor Stinner6345be92011-11-25 20:09:01 +01009020
Victor Stinner42bf7752011-11-21 22:52:58 +01009021 startpos = i;
Victor Stinner6345be92011-11-25 20:09:01 +01009022 exc = NULL;
9023 raise_encode_exception(&exc, "decimal", unicode,
9024 startpos, startpos+1,
9025 "invalid decimal Unicode string");
9026 Py_XDECREF(exc);
9027 Py_DECREF(unicode);
9028 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009029 }
9030 /* 0-terminate the output string */
9031 *output++ = '\0';
Victor Stinner42bf7752011-11-21 22:52:58 +01009032 Py_DECREF(unicode);
Guido van Rossum9e896b32000-04-05 20:11:21 +00009033 return 0;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009034}
9035
Guido van Rossumd57fd912000-03-10 22:53:23 +00009036/* --- Helpers ------------------------------------------------------------ */
9037
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009038static Py_ssize_t
Victor Stinner794d5672011-10-10 03:21:36 +02009039any_find_slice(int direction, PyObject* s1, PyObject* s2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009040 Py_ssize_t start,
9041 Py_ssize_t end)
9042{
9043 int kind1, kind2, kind;
9044 void *buf1, *buf2;
9045 Py_ssize_t len1, len2, result;
9046
9047 kind1 = PyUnicode_KIND(s1);
9048 kind2 = PyUnicode_KIND(s2);
9049 kind = kind1 > kind2 ? kind1 : kind2;
9050 buf1 = PyUnicode_DATA(s1);
9051 buf2 = PyUnicode_DATA(s2);
9052 if (kind1 != kind)
9053 buf1 = _PyUnicode_AsKind(s1, kind);
9054 if (!buf1)
9055 return -2;
9056 if (kind2 != kind)
9057 buf2 = _PyUnicode_AsKind(s2, kind);
9058 if (!buf2) {
9059 if (kind1 != kind) PyMem_Free(buf1);
9060 return -2;
9061 }
9062 len1 = PyUnicode_GET_LENGTH(s1);
9063 len2 = PyUnicode_GET_LENGTH(s2);
9064
Victor Stinner794d5672011-10-10 03:21:36 +02009065 if (direction > 0) {
9066 switch(kind) {
9067 case PyUnicode_1BYTE_KIND:
9068 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9069 result = asciilib_find_slice(buf1, len1, buf2, len2, start, end);
9070 else
9071 result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end);
9072 break;
9073 case PyUnicode_2BYTE_KIND:
9074 result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end);
9075 break;
9076 case PyUnicode_4BYTE_KIND:
9077 result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end);
9078 break;
9079 default:
9080 assert(0); result = -2;
9081 }
9082 }
9083 else {
9084 switch(kind) {
9085 case PyUnicode_1BYTE_KIND:
9086 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9087 result = asciilib_rfind_slice(buf1, len1, buf2, len2, start, end);
9088 else
9089 result = ucs1lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9090 break;
9091 case PyUnicode_2BYTE_KIND:
9092 result = ucs2lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9093 break;
9094 case PyUnicode_4BYTE_KIND:
9095 result = ucs4lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9096 break;
9097 default:
9098 assert(0); result = -2;
9099 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009100 }
9101
9102 if (kind1 != kind)
9103 PyMem_Free(buf1);
9104 if (kind2 != kind)
9105 PyMem_Free(buf2);
9106
9107 return result;
9108}
9109
9110Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +02009111_PyUnicode_InsertThousandsGrouping(PyObject *unicode, int kind, void *data,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009112 Py_ssize_t n_buffer,
9113 void *digits, Py_ssize_t n_digits,
9114 Py_ssize_t min_width,
9115 const char *grouping,
9116 const char *thousands_sep)
9117{
9118 switch(kind) {
9119 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009120 if (unicode != NULL && PyUnicode_IS_ASCII(unicode))
9121 return _PyUnicode_ascii_InsertThousandsGrouping(
9122 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
9123 min_width, grouping, thousands_sep);
9124 else
9125 return _PyUnicode_ucs1_InsertThousandsGrouping(
9126 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
9127 min_width, grouping, thousands_sep);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009128 case PyUnicode_2BYTE_KIND:
9129 return _PyUnicode_ucs2_InsertThousandsGrouping(
9130 (Py_UCS2*)data, n_buffer, (Py_UCS2*)digits, n_digits,
9131 min_width, grouping, thousands_sep);
9132 case PyUnicode_4BYTE_KIND:
9133 return _PyUnicode_ucs4_InsertThousandsGrouping(
9134 (Py_UCS4*)data, n_buffer, (Py_UCS4*)digits, n_digits,
9135 min_width, grouping, thousands_sep);
9136 }
9137 assert(0);
9138 return -1;
9139}
9140
9141
Thomas Wouters477c8d52006-05-27 19:21:47 +00009142/* helper macro to fixup start/end slice values */
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009143#define ADJUST_INDICES(start, end, len) \
9144 if (end > len) \
9145 end = len; \
9146 else if (end < 0) { \
9147 end += len; \
9148 if (end < 0) \
9149 end = 0; \
9150 } \
9151 if (start < 0) { \
9152 start += len; \
9153 if (start < 0) \
9154 start = 0; \
9155 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009156
Alexander Belopolsky40018472011-02-26 01:02:56 +00009157Py_ssize_t
9158PyUnicode_Count(PyObject *str,
9159 PyObject *substr,
9160 Py_ssize_t start,
9161 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009162{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009163 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009164 PyObject* str_obj;
9165 PyObject* sub_obj;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009166 int kind1, kind2, kind;
9167 void *buf1 = NULL, *buf2 = NULL;
9168 Py_ssize_t len1, len2;
Tim Petersced69f82003-09-16 20:30:58 +00009169
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009170 str_obj = PyUnicode_FromObject(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009171 if (!str_obj || PyUnicode_READY(str_obj) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00009172 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009173 sub_obj = PyUnicode_FromObject(substr);
Victor Stinnere9a29352011-10-01 02:14:59 +02009174 if (!sub_obj || PyUnicode_READY(sub_obj) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009175 Py_DECREF(str_obj);
9176 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009177 }
Tim Petersced69f82003-09-16 20:30:58 +00009178
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009179 kind1 = PyUnicode_KIND(str_obj);
9180 kind2 = PyUnicode_KIND(sub_obj);
9181 kind = kind1 > kind2 ? kind1 : kind2;
9182 buf1 = PyUnicode_DATA(str_obj);
9183 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009184 buf1 = _PyUnicode_AsKind(str_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009185 if (!buf1)
9186 goto onError;
9187 buf2 = PyUnicode_DATA(sub_obj);
9188 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009189 buf2 = _PyUnicode_AsKind(sub_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009190 if (!buf2)
9191 goto onError;
9192 len1 = PyUnicode_GET_LENGTH(str_obj);
9193 len2 = PyUnicode_GET_LENGTH(sub_obj);
9194
9195 ADJUST_INDICES(start, end, len1);
9196 switch(kind) {
9197 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009198 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sub_obj))
9199 result = asciilib_count(
9200 ((Py_UCS1*)buf1) + start, end - start,
9201 buf2, len2, PY_SSIZE_T_MAX
9202 );
9203 else
9204 result = ucs1lib_count(
9205 ((Py_UCS1*)buf1) + start, end - start,
9206 buf2, len2, PY_SSIZE_T_MAX
9207 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009208 break;
9209 case PyUnicode_2BYTE_KIND:
9210 result = ucs2lib_count(
9211 ((Py_UCS2*)buf1) + start, end - start,
9212 buf2, len2, PY_SSIZE_T_MAX
9213 );
9214 break;
9215 case PyUnicode_4BYTE_KIND:
9216 result = ucs4lib_count(
9217 ((Py_UCS4*)buf1) + start, end - start,
9218 buf2, len2, PY_SSIZE_T_MAX
9219 );
9220 break;
9221 default:
9222 assert(0); result = 0;
9223 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009224
9225 Py_DECREF(sub_obj);
9226 Py_DECREF(str_obj);
9227
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009228 if (kind1 != kind)
9229 PyMem_Free(buf1);
9230 if (kind2 != kind)
9231 PyMem_Free(buf2);
9232
Guido van Rossumd57fd912000-03-10 22:53:23 +00009233 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009234 onError:
9235 Py_DECREF(sub_obj);
9236 Py_DECREF(str_obj);
9237 if (kind1 != kind && buf1)
9238 PyMem_Free(buf1);
9239 if (kind2 != kind && buf2)
9240 PyMem_Free(buf2);
9241 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009242}
9243
Alexander Belopolsky40018472011-02-26 01:02:56 +00009244Py_ssize_t
9245PyUnicode_Find(PyObject *str,
9246 PyObject *sub,
9247 Py_ssize_t start,
9248 Py_ssize_t end,
9249 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009250{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009251 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009252
Guido van Rossumd57fd912000-03-10 22:53:23 +00009253 str = PyUnicode_FromObject(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009254 if (!str || PyUnicode_READY(str) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00009255 return -2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009256 sub = PyUnicode_FromObject(sub);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009257 if (!sub || PyUnicode_READY(sub) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009258 Py_DECREF(str);
9259 return -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009260 }
Tim Petersced69f82003-09-16 20:30:58 +00009261
Victor Stinner794d5672011-10-10 03:21:36 +02009262 result = any_find_slice(direction,
9263 str, sub, start, end
9264 );
Thomas Wouters477c8d52006-05-27 19:21:47 +00009265
Guido van Rossumd57fd912000-03-10 22:53:23 +00009266 Py_DECREF(str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009267 Py_DECREF(sub);
9268
Guido van Rossumd57fd912000-03-10 22:53:23 +00009269 return result;
9270}
9271
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009272Py_ssize_t
9273PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
9274 Py_ssize_t start, Py_ssize_t end,
9275 int direction)
9276{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009277 int kind;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009278 Py_ssize_t result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009279 if (PyUnicode_READY(str) == -1)
9280 return -2;
Victor Stinner267aa242011-10-02 01:08:37 +02009281 if (start < 0 || end < 0) {
9282 PyErr_SetString(PyExc_IndexError, "string index out of range");
9283 return -2;
9284 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009285 if (end > PyUnicode_GET_LENGTH(str))
9286 end = PyUnicode_GET_LENGTH(str);
9287 kind = PyUnicode_KIND(str);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009288 result = findchar(PyUnicode_1BYTE_DATA(str) + kind*start,
9289 kind, end-start, ch, direction);
9290 if (result == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009291 return -1;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009292 else
9293 return start + result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009294}
9295
Alexander Belopolsky40018472011-02-26 01:02:56 +00009296static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009297tailmatch(PyObject *self,
9298 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009299 Py_ssize_t start,
9300 Py_ssize_t end,
9301 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009302{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009303 int kind_self;
9304 int kind_sub;
9305 void *data_self;
9306 void *data_sub;
9307 Py_ssize_t offset;
9308 Py_ssize_t i;
9309 Py_ssize_t end_sub;
9310
9311 if (PyUnicode_READY(self) == -1 ||
9312 PyUnicode_READY(substring) == -1)
9313 return 0;
9314
9315 if (PyUnicode_GET_LENGTH(substring) == 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009316 return 1;
9317
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009318 ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
9319 end -= PyUnicode_GET_LENGTH(substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009320 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00009321 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009322
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009323 kind_self = PyUnicode_KIND(self);
9324 data_self = PyUnicode_DATA(self);
9325 kind_sub = PyUnicode_KIND(substring);
9326 data_sub = PyUnicode_DATA(substring);
9327 end_sub = PyUnicode_GET_LENGTH(substring) - 1;
9328
9329 if (direction > 0)
9330 offset = end;
9331 else
9332 offset = start;
9333
9334 if (PyUnicode_READ(kind_self, data_self, offset) ==
9335 PyUnicode_READ(kind_sub, data_sub, 0) &&
9336 PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
9337 PyUnicode_READ(kind_sub, data_sub, end_sub)) {
9338 /* If both are of the same kind, memcmp is sufficient */
9339 if (kind_self == kind_sub) {
9340 return ! memcmp((char *)data_self +
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009341 (offset * PyUnicode_KIND(substring)),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009342 data_sub,
9343 PyUnicode_GET_LENGTH(substring) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009344 PyUnicode_KIND(substring));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009345 }
9346 /* otherwise we have to compare each character by first accesing it */
9347 else {
9348 /* We do not need to compare 0 and len(substring)-1 because
9349 the if statement above ensured already that they are equal
9350 when we end up here. */
9351 // TODO: honor direction and do a forward or backwards search
9352 for (i = 1; i < end_sub; ++i) {
9353 if (PyUnicode_READ(kind_self, data_self, offset + i) !=
9354 PyUnicode_READ(kind_sub, data_sub, i))
9355 return 0;
9356 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009357 return 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009358 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009359 }
9360
9361 return 0;
9362}
9363
Alexander Belopolsky40018472011-02-26 01:02:56 +00009364Py_ssize_t
9365PyUnicode_Tailmatch(PyObject *str,
9366 PyObject *substr,
9367 Py_ssize_t start,
9368 Py_ssize_t end,
9369 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009370{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009371 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009372
Guido van Rossumd57fd912000-03-10 22:53:23 +00009373 str = PyUnicode_FromObject(str);
9374 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009375 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009376 substr = PyUnicode_FromObject(substr);
9377 if (substr == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009378 Py_DECREF(str);
9379 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009380 }
Tim Petersced69f82003-09-16 20:30:58 +00009381
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009382 result = tailmatch(str, substr,
Benjamin Peterson29060642009-01-31 22:14:21 +00009383 start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009384 Py_DECREF(str);
9385 Py_DECREF(substr);
9386 return result;
9387}
9388
Guido van Rossumd57fd912000-03-10 22:53:23 +00009389/* Apply fixfct filter to the Unicode object self and return a
9390 reference to the modified object */
9391
Alexander Belopolsky40018472011-02-26 01:02:56 +00009392static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009393fixup(PyObject *self,
9394 Py_UCS4 (*fixfct)(PyObject *s))
Guido van Rossumd57fd912000-03-10 22:53:23 +00009395{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009396 PyObject *u;
9397 Py_UCS4 maxchar_old, maxchar_new = 0;
Victor Stinnereaab6042011-12-11 22:22:39 +01009398 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009399
Victor Stinnerbf6e5602011-12-12 01:53:47 +01009400 u = _PyUnicode_Copy(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009401 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009402 return NULL;
Victor Stinner87af4f22011-11-21 23:03:47 +01009403 maxchar_old = PyUnicode_MAX_CHAR_VALUE(u);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009404
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009405 /* fix functions return the new maximum character in a string,
9406 if the kind of the resulting unicode object does not change,
9407 everything is fine. Otherwise we need to change the string kind
9408 and re-run the fix function. */
Victor Stinner9310abb2011-10-05 00:59:23 +02009409 maxchar_new = fixfct(u);
Victor Stinnereaab6042011-12-11 22:22:39 +01009410
9411 if (maxchar_new == 0) {
9412 /* no changes */;
9413 if (PyUnicode_CheckExact(self)) {
9414 Py_DECREF(u);
9415 Py_INCREF(self);
9416 return self;
9417 }
9418 else
9419 return u;
9420 }
9421
9422 if (maxchar_new <= 127)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009423 maxchar_new = 127;
9424 else if (maxchar_new <= 255)
9425 maxchar_new = 255;
9426 else if (maxchar_new <= 65535)
9427 maxchar_new = 65535;
9428 else
Victor Stinner8faf8212011-12-08 22:14:11 +01009429 maxchar_new = MAX_UNICODE;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009430
Victor Stinnereaab6042011-12-11 22:22:39 +01009431 if (maxchar_new == maxchar_old)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009432 return u;
Victor Stinnereaab6042011-12-11 22:22:39 +01009433
9434 /* In case the maximum character changed, we need to
9435 convert the string to the new category. */
9436 v = PyUnicode_New(PyUnicode_GET_LENGTH(self), maxchar_new);
9437 if (v == NULL) {
9438 Py_DECREF(u);
9439 return NULL;
9440 }
9441 if (maxchar_new > maxchar_old) {
9442 /* If the maxchar increased so that the kind changed, not all
9443 characters are representable anymore and we need to fix the
9444 string again. This only happens in very few cases. */
9445 copy_characters(v, 0, self, 0, PyUnicode_GET_LENGTH(self));
9446 maxchar_old = fixfct(v);
9447 assert(maxchar_old > 0 && maxchar_old <= maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009448 }
9449 else {
Victor Stinnereaab6042011-12-11 22:22:39 +01009450 copy_characters(v, 0, u, 0, PyUnicode_GET_LENGTH(self));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009451 }
Victor Stinnereaab6042011-12-11 22:22:39 +01009452 Py_DECREF(u);
9453 assert(_PyUnicode_CheckConsistency(v, 1));
9454 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009455}
9456
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009457static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009458fixupper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009459{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009460 /* No need to call PyUnicode_READY(self) because this function is only
9461 called as a callback from fixup() which does it already. */
9462 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9463 const int kind = PyUnicode_KIND(self);
9464 void *data = PyUnicode_DATA(self);
9465 int touched = 0;
9466 Py_UCS4 maxchar = 0;
9467 Py_ssize_t i;
Tim Petersced69f82003-09-16 20:30:58 +00009468
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009469 for (i = 0; i < len; ++i) {
9470 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9471 const Py_UCS4 up = Py_UNICODE_TOUPPER(ch);
9472 if (up != ch) {
9473 if (up > maxchar)
9474 maxchar = up;
9475 PyUnicode_WRITE(kind, data, i, up);
9476 touched = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00009477 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009478 else if (ch > maxchar)
9479 maxchar = ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009480 }
9481
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009482 if (touched)
9483 return maxchar;
9484 else
9485 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009486}
9487
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009488static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009489fixlower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009490{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009491 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
9492 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9493 const int kind = PyUnicode_KIND(self);
9494 void *data = PyUnicode_DATA(self);
9495 int touched = 0;
9496 Py_UCS4 maxchar = 0;
9497 Py_ssize_t i;
Tim Petersced69f82003-09-16 20:30:58 +00009498
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009499 for(i = 0; i < len; ++i) {
9500 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9501 const Py_UCS4 lo = Py_UNICODE_TOLOWER(ch);
9502 if (lo != ch) {
9503 if (lo > maxchar)
9504 maxchar = lo;
9505 PyUnicode_WRITE(kind, data, i, lo);
9506 touched = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00009507 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009508 else if (ch > maxchar)
9509 maxchar = ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009510 }
9511
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009512 if (touched)
9513 return maxchar;
9514 else
9515 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009516}
9517
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009518static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009519fixswapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009520{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009521 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
9522 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9523 const int kind = PyUnicode_KIND(self);
9524 void *data = PyUnicode_DATA(self);
9525 int touched = 0;
9526 Py_UCS4 maxchar = 0;
9527 Py_ssize_t i;
Tim Petersced69f82003-09-16 20:30:58 +00009528
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009529 for(i = 0; i < len; ++i) {
9530 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9531 Py_UCS4 nu = 0;
9532
9533 if (Py_UNICODE_ISUPPER(ch))
9534 nu = Py_UNICODE_TOLOWER(ch);
9535 else if (Py_UNICODE_ISLOWER(ch))
9536 nu = Py_UNICODE_TOUPPER(ch);
9537
9538 if (nu != 0) {
9539 if (nu > maxchar)
9540 maxchar = nu;
9541 PyUnicode_WRITE(kind, data, i, nu);
9542 touched = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009543 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009544 else if (ch > maxchar)
9545 maxchar = ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009546 }
9547
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009548 if (touched)
9549 return maxchar;
9550 else
9551 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009552}
9553
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009554static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009555fixcapitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009556{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009557 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
9558 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9559 const int kind = PyUnicode_KIND(self);
9560 void *data = PyUnicode_DATA(self);
9561 int touched = 0;
9562 Py_UCS4 maxchar = 0;
9563 Py_ssize_t i = 0;
9564 Py_UCS4 ch;
Tim Petersced69f82003-09-16 20:30:58 +00009565
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009566 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009567 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009568
9569 ch = PyUnicode_READ(kind, data, i);
9570 if (!Py_UNICODE_ISUPPER(ch)) {
9571 maxchar = Py_UNICODE_TOUPPER(ch);
9572 PyUnicode_WRITE(kind, data, i, maxchar);
9573 touched = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009574 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009575 ++i;
9576 for(; i < len; ++i) {
9577 ch = PyUnicode_READ(kind, data, i);
9578 if (!Py_UNICODE_ISLOWER(ch)) {
9579 const Py_UCS4 lo = Py_UNICODE_TOLOWER(ch);
9580 if (lo > maxchar)
9581 maxchar = lo;
9582 PyUnicode_WRITE(kind, data, i, lo);
9583 touched = 1;
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009584 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009585 else if (ch > maxchar)
9586 maxchar = ch;
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009587 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009588
9589 if (touched)
9590 return maxchar;
9591 else
9592 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009593}
9594
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009595static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009596fixtitle(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009597{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009598 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
9599 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9600 const int kind = PyUnicode_KIND(self);
9601 void *data = PyUnicode_DATA(self);
9602 Py_UCS4 maxchar = 0;
9603 Py_ssize_t i = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009604 int previous_is_cased;
9605
9606 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009607 if (len == 1) {
9608 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9609 const Py_UCS4 ti = Py_UNICODE_TOTITLE(ch);
9610 if (ti != ch) {
9611 PyUnicode_WRITE(kind, data, i, ti);
9612 return ti;
Benjamin Peterson29060642009-01-31 22:14:21 +00009613 }
9614 else
9615 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009616 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009617 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009618 for(; i < len; ++i) {
9619 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9620 Py_UCS4 nu;
Tim Petersced69f82003-09-16 20:30:58 +00009621
Benjamin Peterson29060642009-01-31 22:14:21 +00009622 if (previous_is_cased)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009623 nu = Py_UNICODE_TOLOWER(ch);
Benjamin Peterson29060642009-01-31 22:14:21 +00009624 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009625 nu = Py_UNICODE_TOTITLE(ch);
9626
9627 if (nu > maxchar)
9628 maxchar = nu;
9629 PyUnicode_WRITE(kind, data, i, nu);
Tim Petersced69f82003-09-16 20:30:58 +00009630
Benjamin Peterson29060642009-01-31 22:14:21 +00009631 if (Py_UNICODE_ISLOWER(ch) ||
9632 Py_UNICODE_ISUPPER(ch) ||
9633 Py_UNICODE_ISTITLE(ch))
9634 previous_is_cased = 1;
9635 else
9636 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009637 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009638 return maxchar;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009639}
9640
Tim Peters8ce9f162004-08-27 01:49:32 +00009641PyObject *
9642PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009643{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009644 PyObject *sep = NULL;
Victor Stinnerdd077322011-10-07 17:02:31 +02009645 Py_ssize_t seplen;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009646 PyObject *res = NULL; /* the result */
Tim Peters05eba1f2004-08-27 21:32:02 +00009647 PyObject *fseq; /* PySequence_Fast(seq) */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009648 Py_ssize_t seqlen; /* len(fseq) -- number of items in sequence */
9649 PyObject **items;
Tim Peters8ce9f162004-08-27 01:49:32 +00009650 PyObject *item;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009651 Py_ssize_t sz, i, res_offset;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009652 Py_UCS4 maxchar;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009653 Py_UCS4 item_maxchar;
Victor Stinnerdd077322011-10-07 17:02:31 +02009654 int use_memcpy;
9655 unsigned char *res_data = NULL, *sep_data = NULL;
9656 PyObject *last_obj;
9657 unsigned int kind = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009658
Tim Peters05eba1f2004-08-27 21:32:02 +00009659 fseq = PySequence_Fast(seq, "");
9660 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009661 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00009662 }
9663
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009664 /* NOTE: the following code can't call back into Python code,
9665 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00009666 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009667
Tim Peters05eba1f2004-08-27 21:32:02 +00009668 seqlen = PySequence_Fast_GET_SIZE(fseq);
9669 /* If empty sequence, return u"". */
9670 if (seqlen == 0) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009671 Py_DECREF(fseq);
9672 Py_INCREF(unicode_empty);
9673 res = unicode_empty;
9674 return res;
Tim Peters05eba1f2004-08-27 21:32:02 +00009675 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009676
Tim Peters05eba1f2004-08-27 21:32:02 +00009677 /* If singleton sequence with an exact Unicode, return that. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009678 last_obj = NULL;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009679 items = PySequence_Fast_ITEMS(fseq);
Victor Stinneracf47b82011-10-06 12:32:37 +02009680 if (seqlen == 1) {
9681 if (PyUnicode_CheckExact(items[0])) {
9682 res = items[0];
9683 Py_INCREF(res);
9684 Py_DECREF(fseq);
9685 return res;
9686 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009687 seplen = 0;
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009688 maxchar = 0;
Tim Peters8ce9f162004-08-27 01:49:32 +00009689 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009690 else {
Victor Stinneracf47b82011-10-06 12:32:37 +02009691 /* Set up sep and seplen */
9692 if (separator == NULL) {
9693 /* fall back to a blank space separator */
9694 sep = PyUnicode_FromOrdinal(' ');
9695 if (!sep)
9696 goto onError;
Victor Stinnerdd077322011-10-07 17:02:31 +02009697 seplen = 1;
Victor Stinneracf47b82011-10-06 12:32:37 +02009698 maxchar = 32;
Tim Peters05eba1f2004-08-27 21:32:02 +00009699 }
Victor Stinneracf47b82011-10-06 12:32:37 +02009700 else {
9701 if (!PyUnicode_Check(separator)) {
9702 PyErr_Format(PyExc_TypeError,
9703 "separator: expected str instance,"
9704 " %.80s found",
9705 Py_TYPE(separator)->tp_name);
9706 goto onError;
9707 }
9708 if (PyUnicode_READY(separator))
9709 goto onError;
9710 sep = separator;
9711 seplen = PyUnicode_GET_LENGTH(separator);
9712 maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
9713 /* inc refcount to keep this code path symmetric with the
9714 above case of a blank separator */
9715 Py_INCREF(sep);
9716 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009717 last_obj = sep;
Tim Peters05eba1f2004-08-27 21:32:02 +00009718 }
9719
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009720 /* There are at least two things to join, or else we have a subclass
9721 * of str in the sequence.
9722 * Do a pre-pass to figure out the total amount of space we'll
9723 * need (sz), and see whether all argument are strings.
9724 */
9725 sz = 0;
Victor Stinnerdd077322011-10-07 17:02:31 +02009726#ifdef Py_DEBUG
9727 use_memcpy = 0;
9728#else
9729 use_memcpy = 1;
9730#endif
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009731 for (i = 0; i < seqlen; i++) {
9732 const Py_ssize_t old_sz = sz;
9733 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009734 if (!PyUnicode_Check(item)) {
9735 PyErr_Format(PyExc_TypeError,
9736 "sequence item %zd: expected str instance,"
9737 " %.80s found",
9738 i, Py_TYPE(item)->tp_name);
9739 goto onError;
9740 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009741 if (PyUnicode_READY(item) == -1)
9742 goto onError;
9743 sz += PyUnicode_GET_LENGTH(item);
9744 item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009745 maxchar = Py_MAX(maxchar, item_maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009746 if (i != 0)
9747 sz += seplen;
9748 if (sz < old_sz || sz > PY_SSIZE_T_MAX) {
9749 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009750 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009751 goto onError;
9752 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009753 if (use_memcpy && last_obj != NULL) {
9754 if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
9755 use_memcpy = 0;
9756 }
9757 last_obj = item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009758 }
Tim Petersced69f82003-09-16 20:30:58 +00009759
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009760 res = PyUnicode_New(sz, maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009761 if (res == NULL)
9762 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +00009763
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009764 /* Catenate everything. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009765#ifdef Py_DEBUG
9766 use_memcpy = 0;
9767#else
9768 if (use_memcpy) {
9769 res_data = PyUnicode_1BYTE_DATA(res);
9770 kind = PyUnicode_KIND(res);
9771 if (seplen != 0)
9772 sep_data = PyUnicode_1BYTE_DATA(sep);
9773 }
9774#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009775 for (i = 0, res_offset = 0; i < seqlen; ++i) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009776 Py_ssize_t itemlen;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009777 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009778 /* Copy item, and maybe the separator. */
Victor Stinner9ce5a832011-10-03 23:36:02 +02009779 if (i && seplen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009780 if (use_memcpy) {
9781 Py_MEMCPY(res_data,
9782 sep_data,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009783 kind * seplen);
9784 res_data += kind * seplen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009785 }
9786 else {
9787 copy_characters(res, res_offset, sep, 0, seplen);
9788 res_offset += seplen;
9789 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009790 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009791 itemlen = PyUnicode_GET_LENGTH(item);
9792 if (itemlen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009793 if (use_memcpy) {
9794 Py_MEMCPY(res_data,
9795 PyUnicode_DATA(item),
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009796 kind * itemlen);
9797 res_data += kind * itemlen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009798 }
9799 else {
9800 copy_characters(res, res_offset, item, 0, itemlen);
9801 res_offset += itemlen;
9802 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009803 }
Tim Peters05eba1f2004-08-27 21:32:02 +00009804 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009805 if (use_memcpy)
9806 assert(res_data == PyUnicode_1BYTE_DATA(res)
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009807 + kind * PyUnicode_GET_LENGTH(res));
Victor Stinnerdd077322011-10-07 17:02:31 +02009808 else
9809 assert(res_offset == PyUnicode_GET_LENGTH(res));
Tim Peters8ce9f162004-08-27 01:49:32 +00009810
Tim Peters05eba1f2004-08-27 21:32:02 +00009811 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009812 Py_XDECREF(sep);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009813 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009814 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009815
Benjamin Peterson29060642009-01-31 22:14:21 +00009816 onError:
Tim Peters05eba1f2004-08-27 21:32:02 +00009817 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009818 Py_XDECREF(sep);
Tim Peters8ce9f162004-08-27 01:49:32 +00009819 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009820 return NULL;
9821}
9822
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009823#define FILL(kind, data, value, start, length) \
9824 do { \
9825 Py_ssize_t i_ = 0; \
9826 assert(kind != PyUnicode_WCHAR_KIND); \
9827 switch ((kind)) { \
9828 case PyUnicode_1BYTE_KIND: { \
9829 unsigned char * to_ = (unsigned char *)((data)) + (start); \
9830 memset(to_, (unsigned char)value, length); \
9831 break; \
9832 } \
9833 case PyUnicode_2BYTE_KIND: { \
9834 Py_UCS2 * to_ = (Py_UCS2 *)((data)) + (start); \
9835 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9836 break; \
9837 } \
9838 default: { \
9839 Py_UCS4 * to_ = (Py_UCS4 *)((data)) + (start); \
9840 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9841 break; \
9842 } \
9843 } \
9844 } while (0)
9845
Victor Stinner9310abb2011-10-05 00:59:23 +02009846static PyObject *
9847pad(PyObject *self,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009848 Py_ssize_t left,
9849 Py_ssize_t right,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009850 Py_UCS4 fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009851{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009852 PyObject *u;
9853 Py_UCS4 maxchar;
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009854 int kind;
9855 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009856
9857 if (left < 0)
9858 left = 0;
9859 if (right < 0)
9860 right = 0;
9861
Victor Stinnerc4b49542011-12-11 22:44:26 +01009862 if (left == 0 && right == 0)
9863 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009864
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009865 if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
9866 right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +00009867 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
9868 return NULL;
9869 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009870 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
9871 if (fill > maxchar)
9872 maxchar = fill;
9873 u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009874 if (!u)
9875 return NULL;
9876
9877 kind = PyUnicode_KIND(u);
9878 data = PyUnicode_DATA(u);
9879 if (left)
9880 FILL(kind, data, fill, 0, left);
9881 if (right)
9882 FILL(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009883 copy_characters(u, left, self, 0, _PyUnicode_LENGTH(self));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009884 assert(_PyUnicode_CheckConsistency(u, 1));
9885 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009886}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009887#undef FILL
Guido van Rossumd57fd912000-03-10 22:53:23 +00009888
Alexander Belopolsky40018472011-02-26 01:02:56 +00009889PyObject *
9890PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009891{
Guido van Rossumd57fd912000-03-10 22:53:23 +00009892 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009893
9894 string = PyUnicode_FromObject(string);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009895 if (string == NULL || PyUnicode_READY(string) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00009896 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009897
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009898 switch(PyUnicode_KIND(string)) {
9899 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009900 if (PyUnicode_IS_ASCII(string))
9901 list = asciilib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009902 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009903 PyUnicode_GET_LENGTH(string), keepends);
9904 else
9905 list = ucs1lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009906 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009907 PyUnicode_GET_LENGTH(string), keepends);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009908 break;
9909 case PyUnicode_2BYTE_KIND:
9910 list = ucs2lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009911 string, PyUnicode_2BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009912 PyUnicode_GET_LENGTH(string), keepends);
9913 break;
9914 case PyUnicode_4BYTE_KIND:
9915 list = ucs4lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009916 string, PyUnicode_4BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009917 PyUnicode_GET_LENGTH(string), keepends);
9918 break;
9919 default:
9920 assert(0);
9921 list = 0;
9922 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009923 Py_DECREF(string);
9924 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009925}
9926
Alexander Belopolsky40018472011-02-26 01:02:56 +00009927static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009928split(PyObject *self,
9929 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009930 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009931{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009932 int kind1, kind2, kind;
9933 void *buf1, *buf2;
9934 Py_ssize_t len1, len2;
9935 PyObject* out;
9936
Guido van Rossumd57fd912000-03-10 22:53:23 +00009937 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00009938 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009939
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009940 if (PyUnicode_READY(self) == -1)
9941 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009942
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009943 if (substring == NULL)
9944 switch(PyUnicode_KIND(self)) {
9945 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009946 if (PyUnicode_IS_ASCII(self))
9947 return asciilib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009948 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009949 PyUnicode_GET_LENGTH(self), maxcount
9950 );
9951 else
9952 return ucs1lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009953 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009954 PyUnicode_GET_LENGTH(self), maxcount
9955 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009956 case PyUnicode_2BYTE_KIND:
9957 return ucs2lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009958 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009959 PyUnicode_GET_LENGTH(self), maxcount
9960 );
9961 case PyUnicode_4BYTE_KIND:
9962 return ucs4lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009963 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009964 PyUnicode_GET_LENGTH(self), maxcount
9965 );
9966 default:
9967 assert(0);
9968 return NULL;
9969 }
9970
9971 if (PyUnicode_READY(substring) == -1)
9972 return NULL;
9973
9974 kind1 = PyUnicode_KIND(self);
9975 kind2 = PyUnicode_KIND(substring);
9976 kind = kind1 > kind2 ? kind1 : kind2;
9977 buf1 = PyUnicode_DATA(self);
9978 buf2 = PyUnicode_DATA(substring);
9979 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009980 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009981 if (!buf1)
9982 return NULL;
9983 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009984 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009985 if (!buf2) {
9986 if (kind1 != kind) PyMem_Free(buf1);
9987 return NULL;
9988 }
9989 len1 = PyUnicode_GET_LENGTH(self);
9990 len2 = PyUnicode_GET_LENGTH(substring);
9991
9992 switch(kind) {
9993 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009994 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
9995 out = asciilib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009996 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +02009997 else
9998 out = ucs1lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009999 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010000 break;
10001 case PyUnicode_2BYTE_KIND:
10002 out = ucs2lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010003 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010004 break;
10005 case PyUnicode_4BYTE_KIND:
10006 out = ucs4lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010007 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010008 break;
10009 default:
10010 out = NULL;
10011 }
10012 if (kind1 != kind)
10013 PyMem_Free(buf1);
10014 if (kind2 != kind)
10015 PyMem_Free(buf2);
10016 return out;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010017}
10018
Alexander Belopolsky40018472011-02-26 01:02:56 +000010019static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010020rsplit(PyObject *self,
10021 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010022 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010023{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010024 int kind1, kind2, kind;
10025 void *buf1, *buf2;
10026 Py_ssize_t len1, len2;
10027 PyObject* out;
10028
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010029 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010030 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010031
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010032 if (PyUnicode_READY(self) == -1)
10033 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010034
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010035 if (substring == NULL)
10036 switch(PyUnicode_KIND(self)) {
10037 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010038 if (PyUnicode_IS_ASCII(self))
10039 return asciilib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010040 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010041 PyUnicode_GET_LENGTH(self), maxcount
10042 );
10043 else
10044 return ucs1lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010045 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010046 PyUnicode_GET_LENGTH(self), maxcount
10047 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010048 case PyUnicode_2BYTE_KIND:
10049 return ucs2lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010050 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010051 PyUnicode_GET_LENGTH(self), maxcount
10052 );
10053 case PyUnicode_4BYTE_KIND:
10054 return ucs4lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010055 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010056 PyUnicode_GET_LENGTH(self), maxcount
10057 );
10058 default:
10059 assert(0);
10060 return NULL;
10061 }
10062
10063 if (PyUnicode_READY(substring) == -1)
10064 return NULL;
10065
10066 kind1 = PyUnicode_KIND(self);
10067 kind2 = PyUnicode_KIND(substring);
10068 kind = kind1 > kind2 ? kind1 : kind2;
10069 buf1 = PyUnicode_DATA(self);
10070 buf2 = PyUnicode_DATA(substring);
10071 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010072 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010073 if (!buf1)
10074 return NULL;
10075 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010076 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010077 if (!buf2) {
10078 if (kind1 != kind) PyMem_Free(buf1);
10079 return NULL;
10080 }
10081 len1 = PyUnicode_GET_LENGTH(self);
10082 len2 = PyUnicode_GET_LENGTH(substring);
10083
10084 switch(kind) {
10085 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010086 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10087 out = asciilib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010088 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010089 else
10090 out = ucs1lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010091 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010092 break;
10093 case PyUnicode_2BYTE_KIND:
10094 out = ucs2lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010095 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010096 break;
10097 case PyUnicode_4BYTE_KIND:
10098 out = ucs4lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010099 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010100 break;
10101 default:
10102 out = NULL;
10103 }
10104 if (kind1 != kind)
10105 PyMem_Free(buf1);
10106 if (kind2 != kind)
10107 PyMem_Free(buf2);
10108 return out;
10109}
10110
10111static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010112anylib_find(int kind, PyObject *str1, void *buf1, Py_ssize_t len1,
10113 PyObject *str2, void *buf2, Py_ssize_t len2, Py_ssize_t offset)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010114{
10115 switch(kind) {
10116 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010117 if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
10118 return asciilib_find(buf1, len1, buf2, len2, offset);
10119 else
10120 return ucs1lib_find(buf1, len1, buf2, len2, offset);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010121 case PyUnicode_2BYTE_KIND:
10122 return ucs2lib_find(buf1, len1, buf2, len2, offset);
10123 case PyUnicode_4BYTE_KIND:
10124 return ucs4lib_find(buf1, len1, buf2, len2, offset);
10125 }
10126 assert(0);
10127 return -1;
10128}
10129
10130static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010131anylib_count(int kind, PyObject *sstr, void* sbuf, Py_ssize_t slen,
10132 PyObject *str1, void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010133{
10134 switch(kind) {
10135 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010136 if (PyUnicode_IS_ASCII(sstr) && PyUnicode_IS_ASCII(str1))
10137 return asciilib_count(sbuf, slen, buf1, len1, maxcount);
10138 else
10139 return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010140 case PyUnicode_2BYTE_KIND:
10141 return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
10142 case PyUnicode_4BYTE_KIND:
10143 return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
10144 }
10145 assert(0);
10146 return 0;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010147}
10148
Alexander Belopolsky40018472011-02-26 01:02:56 +000010149static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010150replace(PyObject *self, PyObject *str1,
10151 PyObject *str2, Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010152{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010153 PyObject *u;
10154 char *sbuf = PyUnicode_DATA(self);
10155 char *buf1 = PyUnicode_DATA(str1);
10156 char *buf2 = PyUnicode_DATA(str2);
10157 int srelease = 0, release1 = 0, release2 = 0;
10158 int skind = PyUnicode_KIND(self);
10159 int kind1 = PyUnicode_KIND(str1);
10160 int kind2 = PyUnicode_KIND(str2);
10161 Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
10162 Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
10163 Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010164 int mayshrink;
10165 Py_UCS4 maxchar, maxchar_str2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010166
10167 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010168 maxcount = PY_SSIZE_T_MAX;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010169 else if (maxcount == 0 || slen == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010170 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010171
Victor Stinner59de0ee2011-10-07 10:01:28 +020010172 if (str1 == str2)
10173 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010174 if (skind < kind1)
10175 /* substring too wide to be present */
10176 goto nothing;
10177
Victor Stinner49a0a212011-10-12 23:46:10 +020010178 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
10179 maxchar_str2 = PyUnicode_MAX_CHAR_VALUE(str2);
10180 /* Replacing str1 with str2 may cause a maxchar reduction in the
10181 result string. */
10182 mayshrink = (maxchar_str2 < maxchar);
10183 maxchar = Py_MAX(maxchar, maxchar_str2);
10184
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010185 if (len1 == len2) {
Antoine Pitroucbfdee32010-01-13 08:58:08 +000010186 Py_ssize_t i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010187 /* same length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010188 if (len1 == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010189 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010190 if (len1 == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010191 /* replace characters */
Victor Stinner49a0a212011-10-12 23:46:10 +020010192 Py_UCS4 u1, u2;
10193 int rkind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010194 u1 = PyUnicode_READ_CHAR(str1, 0);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +020010195 if (findchar(sbuf, PyUnicode_KIND(self),
10196 slen, u1, 1) < 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010197 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010198 u2 = PyUnicode_READ_CHAR(str2, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010199 u = PyUnicode_New(slen, maxchar);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010200 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010201 goto error;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020010202 copy_characters(u, 0, self, 0, slen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010203 rkind = PyUnicode_KIND(u);
10204 for (i = 0; i < PyUnicode_GET_LENGTH(u); i++)
10205 if (PyUnicode_READ(rkind, PyUnicode_DATA(u), i) == u1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010206 if (--maxcount < 0)
10207 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010208 PyUnicode_WRITE(rkind, PyUnicode_DATA(u), i, u2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010209 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010210 }
10211 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010212 int rkind = skind;
10213 char *res;
Victor Stinner25a4b292011-10-06 12:31:55 +020010214
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010215 if (kind1 < rkind) {
10216 /* widen substring */
10217 buf1 = _PyUnicode_AsKind(str1, rkind);
10218 if (!buf1) goto error;
10219 release1 = 1;
10220 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010221 i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010222 if (i < 0)
10223 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010224 if (rkind > kind2) {
10225 /* widen replacement */
10226 buf2 = _PyUnicode_AsKind(str2, rkind);
10227 if (!buf2) goto error;
10228 release2 = 1;
10229 }
10230 else if (rkind < kind2) {
10231 /* widen self and buf1 */
10232 rkind = kind2;
10233 if (release1) PyMem_Free(buf1);
10234 sbuf = _PyUnicode_AsKind(self, rkind);
10235 if (!sbuf) goto error;
10236 srelease = 1;
10237 buf1 = _PyUnicode_AsKind(str1, rkind);
10238 if (!buf1) goto error;
10239 release1 = 1;
10240 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010241 u = PyUnicode_New(slen, maxchar);
10242 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010243 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010244 assert(PyUnicode_KIND(u) == rkind);
10245 res = PyUnicode_DATA(u);
Victor Stinner25a4b292011-10-06 12:31:55 +020010246
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010247 memcpy(res, sbuf, rkind * slen);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010248 /* change everything in-place, starting with this one */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010249 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010250 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010251 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010252 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010253
10254 while ( --maxcount > 0) {
Victor Stinnerc3cec782011-10-05 21:24:08 +020010255 i = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010256 sbuf+rkind*i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010257 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010258 if (i == -1)
10259 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010260 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010261 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010262 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010263 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010264 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010265 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010266 }
10267 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010268 Py_ssize_t n, i, j, ires;
10269 Py_ssize_t product, new_size;
10270 int rkind = skind;
10271 char *res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010272
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010273 if (kind1 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010274 /* widen substring */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010275 buf1 = _PyUnicode_AsKind(str1, rkind);
10276 if (!buf1) goto error;
10277 release1 = 1;
10278 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010279 n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010280 if (n == 0)
10281 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010282 if (kind2 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010283 /* widen replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010284 buf2 = _PyUnicode_AsKind(str2, rkind);
10285 if (!buf2) goto error;
10286 release2 = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010287 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010288 else if (kind2 > rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010289 /* widen self and buf1 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010290 rkind = kind2;
10291 sbuf = _PyUnicode_AsKind(self, rkind);
10292 if (!sbuf) goto error;
10293 srelease = 1;
10294 if (release1) PyMem_Free(buf1);
10295 buf1 = _PyUnicode_AsKind(str1, rkind);
10296 if (!buf1) goto error;
10297 release1 = 1;
10298 }
10299 /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
10300 PyUnicode_GET_LENGTH(str1))); */
10301 product = n * (len2-len1);
10302 if ((product / (len2-len1)) != n) {
10303 PyErr_SetString(PyExc_OverflowError,
10304 "replace string is too long");
10305 goto error;
10306 }
10307 new_size = slen + product;
Victor Stinner49a0a212011-10-12 23:46:10 +020010308 if (new_size == 0) {
10309 Py_INCREF(unicode_empty);
10310 u = unicode_empty;
10311 goto done;
10312 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010313 if (new_size < 0 || new_size > (PY_SSIZE_T_MAX >> (rkind-1))) {
10314 PyErr_SetString(PyExc_OverflowError,
10315 "replace string is too long");
10316 goto error;
10317 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010318 u = PyUnicode_New(new_size, maxchar);
10319 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010320 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010321 assert(PyUnicode_KIND(u) == rkind);
10322 res = PyUnicode_DATA(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010323 ires = i = 0;
10324 if (len1 > 0) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010325 while (n-- > 0) {
10326 /* look for next match */
Victor Stinnerc3cec782011-10-05 21:24:08 +020010327 j = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010328 sbuf + rkind * i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010329 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010330 if (j == -1)
10331 break;
10332 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010333 /* copy unchanged part [i:j] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010334 memcpy(res + rkind * ires,
10335 sbuf + rkind * i,
10336 rkind * (j-i));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010337 ires += j - i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010338 }
10339 /* copy substitution string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010340 if (len2 > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010341 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010342 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010343 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010344 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010345 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010346 i = j + len1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010347 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010348 if (i < slen)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010349 /* copy tail [i:] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010350 memcpy(res + rkind * ires,
10351 sbuf + rkind * i,
10352 rkind * (slen-i));
Victor Stinner49a0a212011-10-12 23:46:10 +020010353 }
10354 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010355 /* interleave */
10356 while (n > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010357 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010358 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010359 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010360 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010361 if (--n <= 0)
10362 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010363 memcpy(res + rkind * ires,
10364 sbuf + rkind * i,
10365 rkind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010366 ires++;
10367 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010368 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010369 memcpy(res + rkind * ires,
10370 sbuf + rkind * i,
10371 rkind * (slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +000010372 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010373 }
10374
10375 if (mayshrink) {
Victor Stinner25a4b292011-10-06 12:31:55 +020010376 unicode_adjust_maxchar(&u);
10377 if (u == NULL)
10378 goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010379 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010380
10381 done:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010382 if (srelease)
10383 PyMem_FREE(sbuf);
10384 if (release1)
10385 PyMem_FREE(buf1);
10386 if (release2)
10387 PyMem_FREE(buf2);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010388 assert(_PyUnicode_CheckConsistency(u, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010389 return u;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010390
Benjamin Peterson29060642009-01-31 22:14:21 +000010391 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +000010392 /* nothing to replace; return original string (when possible) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010393 if (srelease)
10394 PyMem_FREE(sbuf);
10395 if (release1)
10396 PyMem_FREE(buf1);
10397 if (release2)
10398 PyMem_FREE(buf2);
Victor Stinnerc4b49542011-12-11 22:44:26 +010010399 return unicode_result_unchanged(self);
10400
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010401 error:
10402 if (srelease && sbuf)
10403 PyMem_FREE(sbuf);
10404 if (release1 && buf1)
10405 PyMem_FREE(buf1);
10406 if (release2 && buf2)
10407 PyMem_FREE(buf2);
10408 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010409}
10410
10411/* --- Unicode Object Methods --------------------------------------------- */
10412
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010413PyDoc_STRVAR(title__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010414 "S.title() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010415\n\
10416Return a titlecased version of S, i.e. words start with title case\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010417characters, all remaining cased characters have lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010418
10419static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010420unicode_title(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010421{
Guido van Rossumd57fd912000-03-10 22:53:23 +000010422 return fixup(self, fixtitle);
10423}
10424
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010425PyDoc_STRVAR(capitalize__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010426 "S.capitalize() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010427\n\
10428Return a capitalized version of S, i.e. make the first character\n\
Senthil Kumarane51ee8a2010-07-05 12:00:56 +000010429have upper case and the rest lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010430
10431static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010432unicode_capitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010433{
Guido van Rossumd57fd912000-03-10 22:53:23 +000010434 return fixup(self, fixcapitalize);
10435}
10436
10437#if 0
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010438PyDoc_STRVAR(capwords__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010439 "S.capwords() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010440\n\
10441Apply .capitalize() to all words in S and return the result with\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010442normalized whitespace (all whitespace strings are replaced by ' ').");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010443
10444static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010445unicode_capwords(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010446{
10447 PyObject *list;
10448 PyObject *item;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010449 Py_ssize_t i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010450
Guido van Rossumd57fd912000-03-10 22:53:23 +000010451 /* Split into words */
10452 list = split(self, NULL, -1);
10453 if (!list)
10454 return NULL;
10455
10456 /* Capitalize each word */
10457 for (i = 0; i < PyList_GET_SIZE(list); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010458 item = fixup(PyList_GET_ITEM(list, i),
Benjamin Peterson29060642009-01-31 22:14:21 +000010459 fixcapitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010460 if (item == NULL)
10461 goto onError;
10462 Py_DECREF(PyList_GET_ITEM(list, i));
10463 PyList_SET_ITEM(list, i, item);
10464 }
10465
10466 /* Join the words to form a new string */
10467 item = PyUnicode_Join(NULL, list);
10468
Benjamin Peterson29060642009-01-31 22:14:21 +000010469 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000010470 Py_DECREF(list);
Victor Stinner7931d9a2011-11-04 00:22:48 +010010471 return item;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010472}
10473#endif
10474
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010475/* Argument converter. Coerces to a single unicode character */
10476
10477static int
10478convert_uc(PyObject *obj, void *addr)
10479{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010480 Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010481 PyObject *uniobj;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010482
Benjamin Peterson14339b62009-01-31 16:36:08 +000010483 uniobj = PyUnicode_FromObject(obj);
10484 if (uniobj == NULL) {
10485 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010486 "The fill character cannot be converted to Unicode");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010487 return 0;
10488 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010489 if (PyUnicode_GET_LENGTH(uniobj) != 1) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010490 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010491 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010492 Py_DECREF(uniobj);
10493 return 0;
10494 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010495 *fillcharloc = PyUnicode_READ_CHAR(uniobj, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010496 Py_DECREF(uniobj);
10497 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010498}
10499
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010500PyDoc_STRVAR(center__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010501 "S.center(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010502\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010503Return S centered in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010504done using the specified fill character (default is a space)");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010505
10506static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010507unicode_center(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010508{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010509 Py_ssize_t marg, left;
10510 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010511 Py_UCS4 fillchar = ' ';
10512
Victor Stinnere9a29352011-10-01 02:14:59 +020010513 if (!PyArg_ParseTuple(args, "n|O&:center", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010514 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010515
Victor Stinnerc4b49542011-12-11 22:44:26 +010010516 if (PyUnicode_READY(self) < 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010517 return NULL;
10518
Victor Stinnerc4b49542011-12-11 22:44:26 +010010519 if (PyUnicode_GET_LENGTH(self) >= width)
10520 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010521
Victor Stinnerc4b49542011-12-11 22:44:26 +010010522 marg = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010523 left = marg / 2 + (marg & width & 1);
10524
Victor Stinner9310abb2011-10-05 00:59:23 +020010525 return pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010526}
10527
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010528/* This function assumes that str1 and str2 are readied by the caller. */
10529
Marc-André Lemburge5034372000-08-08 08:04:29 +000010530static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010531unicode_compare(PyObject *str1, PyObject *str2)
Marc-André Lemburge5034372000-08-08 08:04:29 +000010532{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010533 int kind1, kind2;
10534 void *data1, *data2;
10535 Py_ssize_t len1, len2, i;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010536
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010537 kind1 = PyUnicode_KIND(str1);
10538 kind2 = PyUnicode_KIND(str2);
10539 data1 = PyUnicode_DATA(str1);
10540 data2 = PyUnicode_DATA(str2);
10541 len1 = PyUnicode_GET_LENGTH(str1);
10542 len2 = PyUnicode_GET_LENGTH(str2);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010543
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010544 for (i = 0; i < len1 && i < len2; ++i) {
10545 Py_UCS4 c1, c2;
10546 c1 = PyUnicode_READ(kind1, data1, i);
10547 c2 = PyUnicode_READ(kind2, data2, i);
Fredrik Lundh45714e92001-06-26 16:39:36 +000010548
10549 if (c1 != c2)
10550 return (c1 < c2) ? -1 : 1;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010551 }
10552
10553 return (len1 < len2) ? -1 : (len1 != len2);
10554}
10555
Alexander Belopolsky40018472011-02-26 01:02:56 +000010556int
10557PyUnicode_Compare(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010558{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010559 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10560 if (PyUnicode_READY(left) == -1 ||
10561 PyUnicode_READY(right) == -1)
10562 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010563 return unicode_compare(left, right);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010564 }
Guido van Rossum09dc34f2007-05-04 04:17:33 +000010565 PyErr_Format(PyExc_TypeError,
10566 "Can't compare %.100s and %.100s",
10567 left->ob_type->tp_name,
10568 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010569 return -1;
10570}
10571
Martin v. Löwis5b222132007-06-10 09:51:05 +000010572int
10573PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
10574{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010575 Py_ssize_t i;
10576 int kind;
10577 void *data;
10578 Py_UCS4 chr;
10579
Victor Stinner910337b2011-10-03 03:20:16 +020010580 assert(_PyUnicode_CHECK(uni));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010581 if (PyUnicode_READY(uni) == -1)
10582 return -1;
10583 kind = PyUnicode_KIND(uni);
10584 data = PyUnicode_DATA(uni);
Martin v. Löwis5b222132007-06-10 09:51:05 +000010585 /* Compare Unicode string and source character set string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010586 for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
10587 if (chr != str[i])
10588 return (chr < (unsigned char)(str[i])) ? -1 : 1;
Benjamin Peterson8667a9b2010-01-09 21:45:28 +000010589 /* This check keeps Python strings that end in '\0' from comparing equal
10590 to C strings identical up to that point. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010591 if (PyUnicode_GET_LENGTH(uni) != i || chr)
Benjamin Peterson29060642009-01-31 22:14:21 +000010592 return 1; /* uni is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010593 if (str[i])
Benjamin Peterson29060642009-01-31 22:14:21 +000010594 return -1; /* str is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010595 return 0;
10596}
10597
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010598
Benjamin Peterson29060642009-01-31 22:14:21 +000010599#define TEST_COND(cond) \
Benjamin Peterson14339b62009-01-31 16:36:08 +000010600 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010601
Alexander Belopolsky40018472011-02-26 01:02:56 +000010602PyObject *
10603PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010604{
10605 int result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010606
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010607 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10608 PyObject *v;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010609 if (PyUnicode_READY(left) == -1 ||
10610 PyUnicode_READY(right) == -1)
10611 return NULL;
10612 if (PyUnicode_GET_LENGTH(left) != PyUnicode_GET_LENGTH(right) ||
10613 PyUnicode_KIND(left) != PyUnicode_KIND(right)) {
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010614 if (op == Py_EQ) {
10615 Py_INCREF(Py_False);
10616 return Py_False;
10617 }
10618 if (op == Py_NE) {
10619 Py_INCREF(Py_True);
10620 return Py_True;
10621 }
10622 }
10623 if (left == right)
10624 result = 0;
10625 else
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010626 result = unicode_compare(left, right);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010627
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010628 /* Convert the return value to a Boolean */
10629 switch (op) {
10630 case Py_EQ:
10631 v = TEST_COND(result == 0);
10632 break;
10633 case Py_NE:
10634 v = TEST_COND(result != 0);
10635 break;
10636 case Py_LE:
10637 v = TEST_COND(result <= 0);
10638 break;
10639 case Py_GE:
10640 v = TEST_COND(result >= 0);
10641 break;
10642 case Py_LT:
10643 v = TEST_COND(result == -1);
10644 break;
10645 case Py_GT:
10646 v = TEST_COND(result == 1);
10647 break;
10648 default:
10649 PyErr_BadArgument();
10650 return NULL;
10651 }
10652 Py_INCREF(v);
10653 return v;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010654 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000010655
Brian Curtindfc80e32011-08-10 20:28:54 -050010656 Py_RETURN_NOTIMPLEMENTED;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010657}
10658
Alexander Belopolsky40018472011-02-26 01:02:56 +000010659int
10660PyUnicode_Contains(PyObject *container, PyObject *element)
Guido van Rossum403d68b2000-03-13 15:55:09 +000010661{
Thomas Wouters477c8d52006-05-27 19:21:47 +000010662 PyObject *str, *sub;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010663 int kind1, kind2, kind;
10664 void *buf1, *buf2;
10665 Py_ssize_t len1, len2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010666 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010667
10668 /* Coerce the two arguments */
Thomas Wouters477c8d52006-05-27 19:21:47 +000010669 sub = PyUnicode_FromObject(element);
10670 if (!sub) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010671 PyErr_Format(PyExc_TypeError,
10672 "'in <string>' requires string as left operand, not %s",
10673 element->ob_type->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010674 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010675 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010676 if (PyUnicode_READY(sub) == -1)
10677 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010678
Thomas Wouters477c8d52006-05-27 19:21:47 +000010679 str = PyUnicode_FromObject(container);
Victor Stinnere9a29352011-10-01 02:14:59 +020010680 if (!str || PyUnicode_READY(str) == -1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010681 Py_DECREF(sub);
10682 return -1;
10683 }
10684
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010685 kind1 = PyUnicode_KIND(str);
10686 kind2 = PyUnicode_KIND(sub);
10687 kind = kind1 > kind2 ? kind1 : kind2;
10688 buf1 = PyUnicode_DATA(str);
10689 buf2 = PyUnicode_DATA(sub);
10690 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010691 buf1 = _PyUnicode_AsKind(str, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010692 if (!buf1) {
10693 Py_DECREF(sub);
10694 return -1;
10695 }
10696 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010697 buf2 = _PyUnicode_AsKind(sub, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010698 if (!buf2) {
10699 Py_DECREF(sub);
10700 if (kind1 != kind) PyMem_Free(buf1);
10701 return -1;
10702 }
10703 len1 = PyUnicode_GET_LENGTH(str);
10704 len2 = PyUnicode_GET_LENGTH(sub);
10705
10706 switch(kind) {
10707 case PyUnicode_1BYTE_KIND:
10708 result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
10709 break;
10710 case PyUnicode_2BYTE_KIND:
10711 result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
10712 break;
10713 case PyUnicode_4BYTE_KIND:
10714 result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
10715 break;
10716 default:
10717 result = -1;
10718 assert(0);
10719 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000010720
10721 Py_DECREF(str);
10722 Py_DECREF(sub);
10723
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010724 if (kind1 != kind)
10725 PyMem_Free(buf1);
10726 if (kind2 != kind)
10727 PyMem_Free(buf2);
10728
Guido van Rossum403d68b2000-03-13 15:55:09 +000010729 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010730}
10731
Guido van Rossumd57fd912000-03-10 22:53:23 +000010732/* Concat to string or Unicode object giving a new Unicode object. */
10733
Alexander Belopolsky40018472011-02-26 01:02:56 +000010734PyObject *
10735PyUnicode_Concat(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010736{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010737 PyObject *u = NULL, *v = NULL, *w;
Victor Stinner127226b2011-10-13 01:12:34 +020010738 Py_UCS4 maxchar, maxchar2;
Victor Stinner488fa492011-12-12 00:01:39 +010010739 Py_ssize_t u_len, v_len, new_len;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010740
10741 /* Coerce the two arguments */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010742 u = PyUnicode_FromObject(left);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010743 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010744 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010745 v = PyUnicode_FromObject(right);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010746 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010747 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010748
10749 /* Shortcuts */
Victor Stinnera464fc12011-10-02 20:39:30 +020010750 if (v == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010751 Py_DECREF(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010752 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010753 }
Victor Stinnera464fc12011-10-02 20:39:30 +020010754 if (u == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010755 Py_DECREF(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010756 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010757 }
10758
Victor Stinner488fa492011-12-12 00:01:39 +010010759 u_len = PyUnicode_GET_LENGTH(u);
10760 v_len = PyUnicode_GET_LENGTH(v);
10761 if (u_len > PY_SSIZE_T_MAX - v_len) {
10762 PyErr_SetString(PyExc_OverflowError,
10763 "strings are too large to concat");
10764 goto onError;
10765 }
10766 new_len = u_len + v_len;
10767
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010768 maxchar = PyUnicode_MAX_CHAR_VALUE(u);
Victor Stinner127226b2011-10-13 01:12:34 +020010769 maxchar2 = PyUnicode_MAX_CHAR_VALUE(v);
10770 maxchar = Py_MAX(maxchar, maxchar2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010771
Guido van Rossumd57fd912000-03-10 22:53:23 +000010772 /* Concat the two Unicode strings */
Victor Stinner488fa492011-12-12 00:01:39 +010010773 w = PyUnicode_New(new_len, maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010774 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010775 goto onError;
Victor Stinner488fa492011-12-12 00:01:39 +010010776 copy_characters(w, 0, u, 0, u_len);
10777 copy_characters(w, u_len, v, 0, v_len);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010778 Py_DECREF(u);
10779 Py_DECREF(v);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010780 assert(_PyUnicode_CheckConsistency(w, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010781 return w;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010782
Benjamin Peterson29060642009-01-31 22:14:21 +000010783 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000010784 Py_XDECREF(u);
10785 Py_XDECREF(v);
10786 return NULL;
10787}
10788
Walter Dörwald1ab83302007-05-18 17:15:44 +000010789void
Victor Stinner23e56682011-10-03 03:54:37 +020010790PyUnicode_Append(PyObject **p_left, PyObject *right)
Walter Dörwald1ab83302007-05-18 17:15:44 +000010791{
Victor Stinner23e56682011-10-03 03:54:37 +020010792 PyObject *left, *res;
Victor Stinner488fa492011-12-12 00:01:39 +010010793 Py_UCS4 maxchar, maxchar2;
10794 Py_ssize_t left_len, right_len, new_len;
Victor Stinner23e56682011-10-03 03:54:37 +020010795
10796 if (p_left == NULL) {
10797 if (!PyErr_Occurred())
10798 PyErr_BadInternalCall();
Benjamin Peterson14339b62009-01-31 16:36:08 +000010799 return;
10800 }
Victor Stinner23e56682011-10-03 03:54:37 +020010801 left = *p_left;
10802 if (right == NULL || !PyUnicode_Check(left)) {
10803 if (!PyErr_Occurred())
10804 PyErr_BadInternalCall();
10805 goto error;
10806 }
10807
Victor Stinnere1335c72011-10-04 20:53:03 +020010808 if (PyUnicode_READY(left))
10809 goto error;
10810 if (PyUnicode_READY(right))
10811 goto error;
10812
Victor Stinner488fa492011-12-12 00:01:39 +010010813 /* Shortcuts */
10814 if (left == unicode_empty) {
10815 Py_DECREF(left);
10816 Py_INCREF(right);
10817 *p_left = right;
10818 return;
10819 }
10820 if (right == unicode_empty)
10821 return;
10822
10823 left_len = PyUnicode_GET_LENGTH(left);
10824 right_len = PyUnicode_GET_LENGTH(right);
10825 if (left_len > PY_SSIZE_T_MAX - right_len) {
10826 PyErr_SetString(PyExc_OverflowError,
10827 "strings are too large to concat");
10828 goto error;
10829 }
10830 new_len = left_len + right_len;
10831
10832 if (unicode_modifiable(left)
10833 && PyUnicode_CheckExact(right)
10834 && PyUnicode_KIND(right) <= PyUnicode_KIND(left)
Victor Stinnerb0923652011-10-04 01:17:31 +020010835 /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
10836 to change the structure size, but characters are stored just after
Georg Brandl7597add2011-10-05 16:36:47 +020010837 the structure, and so it requires to move all characters which is
Victor Stinnerb0923652011-10-04 01:17:31 +020010838 not so different than duplicating the string. */
Victor Stinner488fa492011-12-12 00:01:39 +010010839 && !(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
10840 {
10841 /* append inplace */
10842 if (unicode_resize(p_left, new_len) != 0) {
10843 /* XXX if _PyUnicode_Resize() fails, 'left' has been
10844 * deallocated so it cannot be put back into
10845 * 'variable'. The MemoryError is raised when there
10846 * is no value in 'variable', which might (very
10847 * remotely) be a cause of incompatibilities.
10848 */
10849 goto error;
Victor Stinner23e56682011-10-03 03:54:37 +020010850 }
Victor Stinner488fa492011-12-12 00:01:39 +010010851 /* copy 'right' into the newly allocated area of 'left' */
10852 copy_characters(*p_left, left_len, right, 0, right_len);
Victor Stinner23e56682011-10-03 03:54:37 +020010853 }
Victor Stinner488fa492011-12-12 00:01:39 +010010854 else {
10855 maxchar = PyUnicode_MAX_CHAR_VALUE(left);
10856 maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
10857 maxchar = Py_MAX(maxchar, maxchar2);
Victor Stinner23e56682011-10-03 03:54:37 +020010858
Victor Stinner488fa492011-12-12 00:01:39 +010010859 /* Concat the two Unicode strings */
10860 res = PyUnicode_New(new_len, maxchar);
10861 if (res == NULL)
10862 goto error;
10863 copy_characters(res, 0, left, 0, left_len);
10864 copy_characters(res, left_len, right, 0, right_len);
10865 Py_DECREF(left);
10866 *p_left = res;
10867 }
10868 assert(_PyUnicode_CheckConsistency(*p_left, 1));
Victor Stinner23e56682011-10-03 03:54:37 +020010869 return;
10870
10871error:
Victor Stinner488fa492011-12-12 00:01:39 +010010872 Py_CLEAR(*p_left);
Walter Dörwald1ab83302007-05-18 17:15:44 +000010873}
10874
10875void
10876PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
10877{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010878 PyUnicode_Append(pleft, right);
10879 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +000010880}
10881
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010882PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010883 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010884\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000010885Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010886string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010887interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010888
10889static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010890unicode_count(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010891{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010892 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010893 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010894 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010895 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010896 int kind1, kind2, kind;
10897 void *buf1, *buf2;
10898 Py_ssize_t len1, len2, iresult;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010899
Jesus Ceaac451502011-04-20 17:09:23 +020010900 if (!stringlib_parse_args_finds_unicode("count", args, &substring,
10901 &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000010902 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000010903
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010904 kind1 = PyUnicode_KIND(self);
10905 kind2 = PyUnicode_KIND(substring);
10906 kind = kind1 > kind2 ? kind1 : kind2;
10907 buf1 = PyUnicode_DATA(self);
10908 buf2 = PyUnicode_DATA(substring);
10909 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010910 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010911 if (!buf1) {
10912 Py_DECREF(substring);
10913 return NULL;
10914 }
10915 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010916 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010917 if (!buf2) {
10918 Py_DECREF(substring);
10919 if (kind1 != kind) PyMem_Free(buf1);
10920 return NULL;
10921 }
10922 len1 = PyUnicode_GET_LENGTH(self);
10923 len2 = PyUnicode_GET_LENGTH(substring);
10924
10925 ADJUST_INDICES(start, end, len1);
10926 switch(kind) {
10927 case PyUnicode_1BYTE_KIND:
10928 iresult = ucs1lib_count(
10929 ((Py_UCS1*)buf1) + start, end - start,
10930 buf2, len2, PY_SSIZE_T_MAX
10931 );
10932 break;
10933 case PyUnicode_2BYTE_KIND:
10934 iresult = ucs2lib_count(
10935 ((Py_UCS2*)buf1) + start, end - start,
10936 buf2, len2, PY_SSIZE_T_MAX
10937 );
10938 break;
10939 case PyUnicode_4BYTE_KIND:
10940 iresult = ucs4lib_count(
10941 ((Py_UCS4*)buf1) + start, end - start,
10942 buf2, len2, PY_SSIZE_T_MAX
10943 );
10944 break;
10945 default:
10946 assert(0); iresult = 0;
10947 }
10948
10949 result = PyLong_FromSsize_t(iresult);
10950
10951 if (kind1 != kind)
10952 PyMem_Free(buf1);
10953 if (kind2 != kind)
10954 PyMem_Free(buf2);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010955
10956 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010957
Guido van Rossumd57fd912000-03-10 22:53:23 +000010958 return result;
10959}
10960
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010961PyDoc_STRVAR(encode__doc__,
Victor Stinnerc911bbf2010-11-07 19:04:46 +000010962 "S.encode(encoding='utf-8', errors='strict') -> bytes\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010963\n\
Victor Stinnere14e2122010-11-07 18:41:46 +000010964Encode S using the codec registered for encoding. Default encoding\n\
10965is 'utf-8'. errors may be given to set a different error\n\
Fred Drakee4315f52000-05-09 19:53:39 +000010966handling scheme. Default is 'strict' meaning that encoding errors raise\n\
Walter Dörwald3aeb6322002-09-02 13:14:32 +000010967a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
10968'xmlcharrefreplace' as well as any other name registered with\n\
10969codecs.register_error that can handle UnicodeEncodeErrors.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010970
10971static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010972unicode_encode(PyObject *self, PyObject *args, PyObject *kwargs)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010973{
Benjamin Peterson308d6372009-09-18 21:42:35 +000010974 static char *kwlist[] = {"encoding", "errors", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000010975 char *encoding = NULL;
10976 char *errors = NULL;
Guido van Rossum35d94282007-08-27 18:20:11 +000010977
Benjamin Peterson308d6372009-09-18 21:42:35 +000010978 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:encode",
10979 kwlist, &encoding, &errors))
Guido van Rossumd57fd912000-03-10 22:53:23 +000010980 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010981 return PyUnicode_AsEncodedString(self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +000010982}
10983
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010984PyDoc_STRVAR(expandtabs__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010985 "S.expandtabs([tabsize]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010986\n\
10987Return a copy of S where all tab characters are expanded using spaces.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010988If tabsize is not given, a tab size of 8 characters is assumed.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010989
10990static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010991unicode_expandtabs(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010992{
Antoine Pitroue71d5742011-10-04 15:55:09 +020010993 Py_ssize_t i, j, line_pos, src_len, incr;
10994 Py_UCS4 ch;
10995 PyObject *u;
10996 void *src_data, *dest_data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010997 int tabsize = 8;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010998 int kind;
Antoine Pitroue19aa382011-10-04 16:04:01 +020010999 int found;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011000
11001 if (!PyArg_ParseTuple(args, "|i:expandtabs", &tabsize))
Benjamin Peterson29060642009-01-31 22:14:21 +000011002 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011003
Antoine Pitrou22425222011-10-04 19:10:51 +020011004 if (PyUnicode_READY(self) == -1)
11005 return NULL;
11006
Thomas Wouters7e474022000-07-16 12:04:32 +000011007 /* First pass: determine size of output string */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011008 src_len = PyUnicode_GET_LENGTH(self);
11009 i = j = line_pos = 0;
11010 kind = PyUnicode_KIND(self);
11011 src_data = PyUnicode_DATA(self);
Antoine Pitroue19aa382011-10-04 16:04:01 +020011012 found = 0;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011013 for (; i < src_len; i++) {
11014 ch = PyUnicode_READ(kind, src_data, i);
11015 if (ch == '\t') {
Antoine Pitroue19aa382011-10-04 16:04:01 +020011016 found = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000011017 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011018 incr = tabsize - (line_pos % tabsize); /* cannot overflow */
Benjamin Peterson29060642009-01-31 22:14:21 +000011019 if (j > PY_SSIZE_T_MAX - incr)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011020 goto overflow;
11021 line_pos += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011022 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011023 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011024 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011025 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000011026 if (j > PY_SSIZE_T_MAX - 1)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011027 goto overflow;
11028 line_pos++;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011029 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011030 if (ch == '\n' || ch == '\r')
11031 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011032 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011033 }
Victor Stinnerc4b49542011-12-11 22:44:26 +010011034 if (!found)
11035 return unicode_result_unchanged(self);
Guido van Rossumcd16bf62007-06-13 18:07:49 +000011036
Guido van Rossumd57fd912000-03-10 22:53:23 +000011037 /* Second pass: create output string and fill it */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011038 u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011039 if (!u)
11040 return NULL;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011041 dest_data = PyUnicode_DATA(u);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011042
Antoine Pitroue71d5742011-10-04 15:55:09 +020011043 i = j = line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011044
Antoine Pitroue71d5742011-10-04 15:55:09 +020011045 for (; i < src_len; i++) {
11046 ch = PyUnicode_READ(kind, src_data, i);
11047 if (ch == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +000011048 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011049 incr = tabsize - (line_pos % tabsize);
11050 line_pos += incr;
11051 while (incr--) {
11052 PyUnicode_WRITE(kind, dest_data, j, ' ');
11053 j++;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011054 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011055 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011056 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011057 else {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011058 line_pos++;
11059 PyUnicode_WRITE(kind, dest_data, j, ch);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011060 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011061 if (ch == '\n' || ch == '\r')
11062 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011063 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011064 }
11065 assert (j == PyUnicode_GET_LENGTH(u));
Victor Stinnerd3df8ab2011-11-22 01:22:34 +010011066 return unicode_result(u);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011067
Antoine Pitroue71d5742011-10-04 15:55:09 +020011068 overflow:
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011069 PyErr_SetString(PyExc_OverflowError, "new string is too long");
11070 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011071}
11072
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011073PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011074 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011075\n\
11076Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080011077such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011078arguments start and end are interpreted as in slice notation.\n\
11079\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011080Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011081
11082static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011083unicode_find(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011084{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011085 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011086 Py_ssize_t start;
11087 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011088 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011089
Jesus Ceaac451502011-04-20 17:09:23 +020011090 if (!stringlib_parse_args_finds_unicode("find", args, &substring,
11091 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011092 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011093
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011094 if (PyUnicode_READY(self) == -1)
11095 return NULL;
11096 if (PyUnicode_READY(substring) == -1)
11097 return NULL;
11098
Victor Stinner7931d9a2011-11-04 00:22:48 +010011099 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011100
11101 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011102
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011103 if (result == -2)
11104 return NULL;
11105
Christian Heimes217cfd12007-12-02 14:31:20 +000011106 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011107}
11108
11109static PyObject *
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011110unicode_getitem(PyObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011111{
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011112 Py_UCS4 ch = PyUnicode_ReadChar(self, index);
11113 if (ch == (Py_UCS4)-1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011114 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011115 return PyUnicode_FromOrdinal(ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011116}
11117
Guido van Rossumc2504932007-09-18 19:42:40 +000011118/* Believe it or not, this produces the same value for ASCII strings
Mark Dickinson57e683e2011-09-24 18:18:40 +010011119 as bytes_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +000011120static Py_hash_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011121unicode_hash(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011122{
Guido van Rossumc2504932007-09-18 19:42:40 +000011123 Py_ssize_t len;
Mark Dickinson57e683e2011-09-24 18:18:40 +010011124 Py_uhash_t x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011125
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011126 if (_PyUnicode_HASH(self) != -1)
11127 return _PyUnicode_HASH(self);
11128 if (PyUnicode_READY(self) == -1)
11129 return -1;
11130 len = PyUnicode_GET_LENGTH(self);
11131
11132 /* The hash function as a macro, gets expanded three times below. */
11133#define HASH(P) \
11134 x = (Py_uhash_t)*P << 7; \
11135 while (--len >= 0) \
11136 x = (1000003*x) ^ (Py_uhash_t)*P++;
11137
11138 switch (PyUnicode_KIND(self)) {
11139 case PyUnicode_1BYTE_KIND: {
11140 const unsigned char *c = PyUnicode_1BYTE_DATA(self);
11141 HASH(c);
11142 break;
11143 }
11144 case PyUnicode_2BYTE_KIND: {
11145 const Py_UCS2 *s = PyUnicode_2BYTE_DATA(self);
11146 HASH(s);
11147 break;
11148 }
11149 default: {
11150 Py_UCS4 *l;
11151 assert(PyUnicode_KIND(self) == PyUnicode_4BYTE_KIND &&
11152 "Impossible switch case in unicode_hash");
11153 l = PyUnicode_4BYTE_DATA(self);
11154 HASH(l);
11155 break;
11156 }
11157 }
11158 x ^= (Py_uhash_t)PyUnicode_GET_LENGTH(self);
11159
Guido van Rossumc2504932007-09-18 19:42:40 +000011160 if (x == -1)
11161 x = -2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011162 _PyUnicode_HASH(self) = x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011163 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011164}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011165#undef HASH
Guido van Rossumd57fd912000-03-10 22:53:23 +000011166
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011167PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011168 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011169\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011170Like S.find() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011171
11172static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011173unicode_index(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011174{
Martin v. Löwis18e16552006-02-15 17:27:45 +000011175 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011176 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011177 Py_ssize_t start;
11178 Py_ssize_t end;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011179
Jesus Ceaac451502011-04-20 17:09:23 +020011180 if (!stringlib_parse_args_finds_unicode("index", args, &substring,
11181 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011182 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011183
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011184 if (PyUnicode_READY(self) == -1)
11185 return NULL;
11186 if (PyUnicode_READY(substring) == -1)
11187 return NULL;
11188
Victor Stinner7931d9a2011-11-04 00:22:48 +010011189 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011190
11191 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011192
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011193 if (result == -2)
11194 return NULL;
11195
Guido van Rossumd57fd912000-03-10 22:53:23 +000011196 if (result < 0) {
11197 PyErr_SetString(PyExc_ValueError, "substring not found");
11198 return NULL;
11199 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011200
Christian Heimes217cfd12007-12-02 14:31:20 +000011201 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011202}
11203
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011204PyDoc_STRVAR(islower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011205 "S.islower() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011206\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011207Return True if all cased characters in S are lowercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011208at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011209
11210static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011211unicode_islower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011212{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011213 Py_ssize_t i, length;
11214 int kind;
11215 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011216 int cased;
11217
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011218 if (PyUnicode_READY(self) == -1)
11219 return NULL;
11220 length = PyUnicode_GET_LENGTH(self);
11221 kind = PyUnicode_KIND(self);
11222 data = PyUnicode_DATA(self);
11223
Guido van Rossumd57fd912000-03-10 22:53:23 +000011224 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011225 if (length == 1)
11226 return PyBool_FromLong(
11227 Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011228
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011229 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011230 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011231 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011232
Guido van Rossumd57fd912000-03-10 22:53:23 +000011233 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011234 for (i = 0; i < length; i++) {
11235 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011236
Benjamin Peterson29060642009-01-31 22:14:21 +000011237 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
11238 return PyBool_FromLong(0);
11239 else if (!cased && Py_UNICODE_ISLOWER(ch))
11240 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011241 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011242 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011243}
11244
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011245PyDoc_STRVAR(isupper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011246 "S.isupper() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011247\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011248Return True if all cased characters in S are uppercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011249at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011250
11251static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011252unicode_isupper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011253{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011254 Py_ssize_t i, length;
11255 int kind;
11256 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011257 int cased;
11258
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011259 if (PyUnicode_READY(self) == -1)
11260 return NULL;
11261 length = PyUnicode_GET_LENGTH(self);
11262 kind = PyUnicode_KIND(self);
11263 data = PyUnicode_DATA(self);
11264
Guido van Rossumd57fd912000-03-10 22:53:23 +000011265 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011266 if (length == 1)
11267 return PyBool_FromLong(
11268 Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011269
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011270 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011271 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011272 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011273
Guido van Rossumd57fd912000-03-10 22:53:23 +000011274 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011275 for (i = 0; i < length; i++) {
11276 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011277
Benjamin Peterson29060642009-01-31 22:14:21 +000011278 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
11279 return PyBool_FromLong(0);
11280 else if (!cased && Py_UNICODE_ISUPPER(ch))
11281 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011282 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011283 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011284}
11285
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011286PyDoc_STRVAR(istitle__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011287 "S.istitle() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011288\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011289Return True if S is a titlecased string and there is at least one\n\
11290character in S, i.e. upper- and titlecase characters may only\n\
11291follow uncased characters and lowercase characters only cased ones.\n\
11292Return False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011293
11294static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011295unicode_istitle(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011296{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011297 Py_ssize_t i, length;
11298 int kind;
11299 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011300 int cased, previous_is_cased;
11301
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011302 if (PyUnicode_READY(self) == -1)
11303 return NULL;
11304 length = PyUnicode_GET_LENGTH(self);
11305 kind = PyUnicode_KIND(self);
11306 data = PyUnicode_DATA(self);
11307
Guido van Rossumd57fd912000-03-10 22:53:23 +000011308 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011309 if (length == 1) {
11310 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11311 return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
11312 (Py_UNICODE_ISUPPER(ch) != 0));
11313 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011314
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011315 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011316 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011317 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011318
Guido van Rossumd57fd912000-03-10 22:53:23 +000011319 cased = 0;
11320 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011321 for (i = 0; i < length; i++) {
11322 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011323
Benjamin Peterson29060642009-01-31 22:14:21 +000011324 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
11325 if (previous_is_cased)
11326 return PyBool_FromLong(0);
11327 previous_is_cased = 1;
11328 cased = 1;
11329 }
11330 else if (Py_UNICODE_ISLOWER(ch)) {
11331 if (!previous_is_cased)
11332 return PyBool_FromLong(0);
11333 previous_is_cased = 1;
11334 cased = 1;
11335 }
11336 else
11337 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011338 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011339 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011340}
11341
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011342PyDoc_STRVAR(isspace__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011343 "S.isspace() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011344\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011345Return True if all characters in S are whitespace\n\
11346and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011347
11348static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011349unicode_isspace(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011350{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011351 Py_ssize_t i, length;
11352 int kind;
11353 void *data;
11354
11355 if (PyUnicode_READY(self) == -1)
11356 return NULL;
11357 length = PyUnicode_GET_LENGTH(self);
11358 kind = PyUnicode_KIND(self);
11359 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011360
Guido van Rossumd57fd912000-03-10 22:53:23 +000011361 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011362 if (length == 1)
11363 return PyBool_FromLong(
11364 Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011365
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011366 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011367 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011368 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011369
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011370 for (i = 0; i < length; i++) {
11371 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011372 if (!Py_UNICODE_ISSPACE(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011373 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011374 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011375 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011376}
11377
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011378PyDoc_STRVAR(isalpha__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011379 "S.isalpha() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011380\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011381Return True if all characters in S are alphabetic\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011382and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011383
11384static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011385unicode_isalpha(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011386{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011387 Py_ssize_t i, length;
11388 int kind;
11389 void *data;
11390
11391 if (PyUnicode_READY(self) == -1)
11392 return NULL;
11393 length = PyUnicode_GET_LENGTH(self);
11394 kind = PyUnicode_KIND(self);
11395 data = PyUnicode_DATA(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011396
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011397 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011398 if (length == 1)
11399 return PyBool_FromLong(
11400 Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011401
11402 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011403 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011404 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011405
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011406 for (i = 0; i < length; i++) {
11407 if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011408 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011409 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011410 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011411}
11412
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011413PyDoc_STRVAR(isalnum__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011414 "S.isalnum() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011415\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011416Return True if all characters in S are alphanumeric\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011417and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011418
11419static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011420unicode_isalnum(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011421{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011422 int kind;
11423 void *data;
11424 Py_ssize_t len, i;
11425
11426 if (PyUnicode_READY(self) == -1)
11427 return NULL;
11428
11429 kind = PyUnicode_KIND(self);
11430 data = PyUnicode_DATA(self);
11431 len = PyUnicode_GET_LENGTH(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011432
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011433 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011434 if (len == 1) {
11435 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11436 return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
11437 }
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011438
11439 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011440 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011441 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011442
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011443 for (i = 0; i < len; i++) {
11444 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011445 if (!Py_UNICODE_ISALNUM(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011446 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011447 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011448 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011449}
11450
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011451PyDoc_STRVAR(isdecimal__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011452 "S.isdecimal() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011453\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011454Return True if there are only decimal characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011455False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011456
11457static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011458unicode_isdecimal(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011459{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011460 Py_ssize_t i, length;
11461 int kind;
11462 void *data;
11463
11464 if (PyUnicode_READY(self) == -1)
11465 return NULL;
11466 length = PyUnicode_GET_LENGTH(self);
11467 kind = PyUnicode_KIND(self);
11468 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011469
Guido van Rossumd57fd912000-03-10 22:53:23 +000011470 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011471 if (length == 1)
11472 return PyBool_FromLong(
11473 Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011474
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011475 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011476 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011477 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011478
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011479 for (i = 0; i < length; i++) {
11480 if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011481 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011482 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011483 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011484}
11485
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011486PyDoc_STRVAR(isdigit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011487 "S.isdigit() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011488\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011489Return True if all characters in S are digits\n\
11490and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011491
11492static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011493unicode_isdigit(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011494{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011495 Py_ssize_t i, length;
11496 int kind;
11497 void *data;
11498
11499 if (PyUnicode_READY(self) == -1)
11500 return NULL;
11501 length = PyUnicode_GET_LENGTH(self);
11502 kind = PyUnicode_KIND(self);
11503 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011504
Guido van Rossumd57fd912000-03-10 22:53:23 +000011505 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011506 if (length == 1) {
11507 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11508 return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
11509 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011510
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011511 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011512 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011513 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011514
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011515 for (i = 0; i < length; i++) {
11516 if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011517 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011518 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011519 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011520}
11521
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011522PyDoc_STRVAR(isnumeric__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011523 "S.isnumeric() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011524\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011525Return True if there are only numeric characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011526False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011527
11528static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011529unicode_isnumeric(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011530{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011531 Py_ssize_t i, length;
11532 int kind;
11533 void *data;
11534
11535 if (PyUnicode_READY(self) == -1)
11536 return NULL;
11537 length = PyUnicode_GET_LENGTH(self);
11538 kind = PyUnicode_KIND(self);
11539 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011540
Guido van Rossumd57fd912000-03-10 22:53:23 +000011541 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011542 if (length == 1)
11543 return PyBool_FromLong(
11544 Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011545
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011546 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011547 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011548 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011549
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011550 for (i = 0; i < length; i++) {
11551 if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011552 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011553 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011554 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011555}
11556
Martin v. Löwis47383402007-08-15 07:32:56 +000011557int
11558PyUnicode_IsIdentifier(PyObject *self)
11559{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011560 int kind;
11561 void *data;
11562 Py_ssize_t i;
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011563 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +000011564
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011565 if (PyUnicode_READY(self) == -1) {
11566 Py_FatalError("identifier not ready");
Benjamin Peterson29060642009-01-31 22:14:21 +000011567 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011568 }
11569
11570 /* Special case for empty strings */
11571 if (PyUnicode_GET_LENGTH(self) == 0)
11572 return 0;
11573 kind = PyUnicode_KIND(self);
11574 data = PyUnicode_DATA(self);
Martin v. Löwis47383402007-08-15 07:32:56 +000011575
11576 /* PEP 3131 says that the first character must be in
11577 XID_Start and subsequent characters in XID_Continue,
11578 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +000011579 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +000011580 letters, digits, underscore). However, given the current
11581 definition of XID_Start and XID_Continue, it is sufficient
11582 to check just for these, except that _ must be allowed
11583 as starting an identifier. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011584 first = PyUnicode_READ(kind, data, 0);
Benjamin Petersonf413b802011-08-12 22:17:18 -050011585 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +000011586 return 0;
11587
Benjamin Peterson9c6e6a02011-09-28 08:09:05 -040011588 for (i = 1; i < PyUnicode_GET_LENGTH(self); i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011589 if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011590 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +000011591 return 1;
11592}
11593
11594PyDoc_STRVAR(isidentifier__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011595 "S.isidentifier() -> bool\n\
Martin v. Löwis47383402007-08-15 07:32:56 +000011596\n\
11597Return True if S is a valid identifier according\n\
11598to the language definition.");
11599
11600static PyObject*
11601unicode_isidentifier(PyObject *self)
11602{
11603 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
11604}
11605
Georg Brandl559e5d72008-06-11 18:37:52 +000011606PyDoc_STRVAR(isprintable__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011607 "S.isprintable() -> bool\n\
Georg Brandl559e5d72008-06-11 18:37:52 +000011608\n\
11609Return True if all characters in S are considered\n\
11610printable in repr() or S is empty, False otherwise.");
11611
11612static PyObject*
11613unicode_isprintable(PyObject *self)
11614{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011615 Py_ssize_t i, length;
11616 int kind;
11617 void *data;
11618
11619 if (PyUnicode_READY(self) == -1)
11620 return NULL;
11621 length = PyUnicode_GET_LENGTH(self);
11622 kind = PyUnicode_KIND(self);
11623 data = PyUnicode_DATA(self);
Georg Brandl559e5d72008-06-11 18:37:52 +000011624
11625 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011626 if (length == 1)
11627 return PyBool_FromLong(
11628 Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
Georg Brandl559e5d72008-06-11 18:37:52 +000011629
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011630 for (i = 0; i < length; i++) {
11631 if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
Georg Brandl559e5d72008-06-11 18:37:52 +000011632 Py_RETURN_FALSE;
11633 }
11634 }
11635 Py_RETURN_TRUE;
11636}
11637
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011638PyDoc_STRVAR(join__doc__,
Georg Brandl495f7b52009-10-27 15:28:25 +000011639 "S.join(iterable) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011640\n\
11641Return a string which is the concatenation of the strings in the\n\
Georg Brandl495f7b52009-10-27 15:28:25 +000011642iterable. The separator between elements is S.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011643
11644static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011645unicode_join(PyObject *self, PyObject *data)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011646{
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011647 return PyUnicode_Join(self, data);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011648}
11649
Martin v. Löwis18e16552006-02-15 17:27:45 +000011650static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011651unicode_length(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011652{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011653 if (PyUnicode_READY(self) == -1)
11654 return -1;
11655 return PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011656}
11657
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011658PyDoc_STRVAR(ljust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011659 "S.ljust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011660\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000011661Return S left-justified in a Unicode string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011662done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011663
11664static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020011665unicode_ljust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011666{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011667 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011668 Py_UCS4 fillchar = ' ';
11669
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011670 if (!PyArg_ParseTuple(args, "n|O&:ljust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011671 return NULL;
11672
Victor Stinnerc4b49542011-12-11 22:44:26 +010011673 if (PyUnicode_READY(self) < 0)
11674 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011675
Victor Stinnerc4b49542011-12-11 22:44:26 +010011676 if (PyUnicode_GET_LENGTH(self) >= width)
11677 return unicode_result_unchanged(self);
11678
11679 return pad(self, 0, width - PyUnicode_GET_LENGTH(self), fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011680}
11681
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011682PyDoc_STRVAR(lower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011683 "S.lower() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011684\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011685Return a copy of the string S converted to lowercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011686
11687static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020011688unicode_lower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011689{
Guido van Rossumd57fd912000-03-10 22:53:23 +000011690 return fixup(self, fixlower);
11691}
11692
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011693#define LEFTSTRIP 0
11694#define RIGHTSTRIP 1
11695#define BOTHSTRIP 2
11696
11697/* Arrays indexed by above */
11698static const char *stripformat[] = {"|O:lstrip", "|O:rstrip", "|O:strip"};
11699
11700#define STRIPNAME(i) (stripformat[i]+3)
11701
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011702/* externally visible for str.strip(unicode) */
11703PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011704_PyUnicode_XStrip(PyObject *self, int striptype, PyObject *sepobj)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011705{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011706 void *data;
11707 int kind;
11708 Py_ssize_t i, j, len;
11709 BLOOM_MASK sepmask;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011710
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011711 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
11712 return NULL;
11713
11714 kind = PyUnicode_KIND(self);
11715 data = PyUnicode_DATA(self);
11716 len = PyUnicode_GET_LENGTH(self);
11717 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
11718 PyUnicode_DATA(sepobj),
11719 PyUnicode_GET_LENGTH(sepobj));
Thomas Wouters477c8d52006-05-27 19:21:47 +000011720
Benjamin Peterson14339b62009-01-31 16:36:08 +000011721 i = 0;
11722 if (striptype != RIGHTSTRIP) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011723 while (i < len &&
11724 BLOOM_MEMBER(sepmask, PyUnicode_READ(kind, data, i), sepobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011725 i++;
11726 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011727 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011728
Benjamin Peterson14339b62009-01-31 16:36:08 +000011729 j = len;
11730 if (striptype != LEFTSTRIP) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011731 do {
11732 j--;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011733 } while (j >= i &&
11734 BLOOM_MEMBER(sepmask, PyUnicode_READ(kind, data, j), sepobj));
Benjamin Peterson29060642009-01-31 22:14:21 +000011735 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011736 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011737
Victor Stinner7931d9a2011-11-04 00:22:48 +010011738 return PyUnicode_Substring(self, i, j);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011739}
11740
11741PyObject*
11742PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
11743{
11744 unsigned char *data;
11745 int kind;
Victor Stinner12bab6d2011-10-01 01:53:49 +020011746 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011747
Victor Stinnerde636f32011-10-01 03:55:54 +020011748 if (PyUnicode_READY(self) == -1)
11749 return NULL;
11750
11751 end = Py_MIN(end, PyUnicode_GET_LENGTH(self));
11752
Victor Stinner12bab6d2011-10-01 01:53:49 +020011753 if (start == 0 && end == PyUnicode_GET_LENGTH(self))
Victor Stinnerc4b49542011-12-11 22:44:26 +010011754 return unicode_result_unchanged(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011755
Victor Stinner12bab6d2011-10-01 01:53:49 +020011756 length = end - start;
11757 if (length == 1)
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011758 return unicode_getitem(self, start);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011759
Victor Stinnerde636f32011-10-01 03:55:54 +020011760 if (start < 0 || end < 0) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020011761 PyErr_SetString(PyExc_IndexError, "string index out of range");
11762 return NULL;
11763 }
11764
Victor Stinnerb9275c12011-10-05 14:01:42 +020011765 if (PyUnicode_IS_ASCII(self)) {
11766 kind = PyUnicode_KIND(self);
11767 data = PyUnicode_1BYTE_DATA(self);
11768 return unicode_fromascii(data + start, length);
11769 }
11770 else {
11771 kind = PyUnicode_KIND(self);
11772 data = PyUnicode_1BYTE_DATA(self);
11773 return PyUnicode_FromKindAndData(kind,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020011774 data + kind * start,
Victor Stinnerb9275c12011-10-05 14:01:42 +020011775 length);
11776 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011777}
Guido van Rossumd57fd912000-03-10 22:53:23 +000011778
11779static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011780do_strip(PyObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011781{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011782 int kind;
11783 void *data;
11784 Py_ssize_t len, i, j;
11785
11786 if (PyUnicode_READY(self) == -1)
11787 return NULL;
11788
11789 kind = PyUnicode_KIND(self);
11790 data = PyUnicode_DATA(self);
11791 len = PyUnicode_GET_LENGTH(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011792
Benjamin Peterson14339b62009-01-31 16:36:08 +000011793 i = 0;
11794 if (striptype != RIGHTSTRIP) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011795 while (i < len && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, i))) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000011796 i++;
11797 }
11798 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011799
Benjamin Peterson14339b62009-01-31 16:36:08 +000011800 j = len;
11801 if (striptype != LEFTSTRIP) {
11802 do {
11803 j--;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011804 } while (j >= i && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, j)));
Benjamin Peterson14339b62009-01-31 16:36:08 +000011805 j++;
11806 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011807
Victor Stinner7931d9a2011-11-04 00:22:48 +010011808 return PyUnicode_Substring(self, i, j);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011809}
11810
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011811
11812static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011813do_argstrip(PyObject *self, int striptype, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011814{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011815 PyObject *sep = NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011816
Benjamin Peterson14339b62009-01-31 16:36:08 +000011817 if (!PyArg_ParseTuple(args, (char *)stripformat[striptype], &sep))
11818 return NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011819
Benjamin Peterson14339b62009-01-31 16:36:08 +000011820 if (sep != NULL && sep != Py_None) {
11821 if (PyUnicode_Check(sep))
11822 return _PyUnicode_XStrip(self, striptype, sep);
11823 else {
11824 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000011825 "%s arg must be None or str",
11826 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +000011827 return NULL;
11828 }
11829 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011830
Benjamin Peterson14339b62009-01-31 16:36:08 +000011831 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011832}
11833
11834
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011835PyDoc_STRVAR(strip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011836 "S.strip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011837\n\
11838Return a copy of the string S with leading and trailing\n\
11839whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011840If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011841
11842static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011843unicode_strip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011844{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011845 if (PyTuple_GET_SIZE(args) == 0)
11846 return do_strip(self, BOTHSTRIP); /* Common case */
11847 else
11848 return do_argstrip(self, BOTHSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011849}
11850
11851
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011852PyDoc_STRVAR(lstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011853 "S.lstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011854\n\
11855Return a copy of the string S with leading whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011856If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011857
11858static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011859unicode_lstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011860{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011861 if (PyTuple_GET_SIZE(args) == 0)
11862 return do_strip(self, LEFTSTRIP); /* Common case */
11863 else
11864 return do_argstrip(self, LEFTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011865}
11866
11867
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011868PyDoc_STRVAR(rstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011869 "S.rstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011870\n\
11871Return a copy of the string S with trailing whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011872If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011873
11874static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011875unicode_rstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011876{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011877 if (PyTuple_GET_SIZE(args) == 0)
11878 return do_strip(self, RIGHTSTRIP); /* Common case */
11879 else
11880 return do_argstrip(self, RIGHTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011881}
11882
11883
Guido van Rossumd57fd912000-03-10 22:53:23 +000011884static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011885unicode_repeat(PyObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011886{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011887 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011888 Py_ssize_t nchars, n;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011889
Georg Brandl222de0f2009-04-12 12:01:50 +000011890 if (len < 1) {
11891 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +020011892 return unicode_empty;
Georg Brandl222de0f2009-04-12 12:01:50 +000011893 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011894
Victor Stinnerc4b49542011-12-11 22:44:26 +010011895 /* no repeat, return original string */
11896 if (len == 1)
11897 return unicode_result_unchanged(str);
Tim Peters8f422462000-09-09 06:13:41 +000011898
Victor Stinnerc4b49542011-12-11 22:44:26 +010011899 if (PyUnicode_READY(str) < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011900 return NULL;
11901
Victor Stinnerc759f3e2011-10-01 03:09:58 +020011902 if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
Victor Stinner67ca64c2011-10-01 02:47:29 +020011903 PyErr_SetString(PyExc_OverflowError,
11904 "repeated string is too long");
11905 return NULL;
11906 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011907 nchars = len * PyUnicode_GET_LENGTH(str);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011908
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011909 u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011910 if (!u)
11911 return NULL;
Victor Stinner67ca64c2011-10-01 02:47:29 +020011912 assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011913
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011914 if (PyUnicode_GET_LENGTH(str) == 1) {
11915 const int kind = PyUnicode_KIND(str);
11916 const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
11917 void *to = PyUnicode_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011918 if (kind == PyUnicode_1BYTE_KIND)
11919 memset(to, (unsigned char)fill_char, len);
11920 else {
11921 for (n = 0; n < len; ++n)
11922 PyUnicode_WRITE(kind, to, n, fill_char);
11923 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011924 }
11925 else {
11926 /* number of characters copied this far */
11927 Py_ssize_t done = PyUnicode_GET_LENGTH(str);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020011928 const Py_ssize_t char_size = PyUnicode_KIND(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011929 char *to = (char *) PyUnicode_DATA(u);
11930 Py_MEMCPY(to, PyUnicode_DATA(str),
11931 PyUnicode_GET_LENGTH(str) * char_size);
Benjamin Peterson29060642009-01-31 22:14:21 +000011932 while (done < nchars) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011933 n = (done <= nchars-done) ? done : nchars-done;
11934 Py_MEMCPY(to + (done * char_size), to, n * char_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011935 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +000011936 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011937 }
11938
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020011939 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011940 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011941}
11942
Alexander Belopolsky40018472011-02-26 01:02:56 +000011943PyObject *
11944PyUnicode_Replace(PyObject *obj,
11945 PyObject *subobj,
11946 PyObject *replobj,
11947 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011948{
11949 PyObject *self;
11950 PyObject *str1;
11951 PyObject *str2;
11952 PyObject *result;
11953
11954 self = PyUnicode_FromObject(obj);
Victor Stinnere9a29352011-10-01 02:14:59 +020011955 if (self == NULL || PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000011956 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011957 str1 = PyUnicode_FromObject(subobj);
Victor Stinnere9a29352011-10-01 02:14:59 +020011958 if (str1 == NULL || PyUnicode_READY(str1) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011959 Py_DECREF(self);
11960 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011961 }
11962 str2 = PyUnicode_FromObject(replobj);
Victor Stinnere9a29352011-10-01 02:14:59 +020011963 if (str2 == NULL || PyUnicode_READY(str2)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011964 Py_DECREF(self);
11965 Py_DECREF(str1);
11966 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011967 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011968 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011969 Py_DECREF(self);
11970 Py_DECREF(str1);
11971 Py_DECREF(str2);
11972 return result;
11973}
11974
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011975PyDoc_STRVAR(replace__doc__,
Ezio Melottic1897e72010-06-26 18:50:39 +000011976 "S.replace(old, new[, count]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011977\n\
11978Return a copy of S with all occurrences of substring\n\
Georg Brandlf08a9dd2008-06-10 16:57:31 +000011979old replaced by new. If the optional argument count is\n\
11980given, only the first count occurrences are replaced.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011981
11982static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011983unicode_replace(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011984{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011985 PyObject *str1;
11986 PyObject *str2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011987 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011988 PyObject *result;
11989
Martin v. Löwis18e16552006-02-15 17:27:45 +000011990 if (!PyArg_ParseTuple(args, "OO|n:replace", &str1, &str2, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011991 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011992 if (!PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000011993 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011994 str1 = PyUnicode_FromObject(str1);
11995 if (str1 == NULL || PyUnicode_READY(str1) == -1)
11996 return NULL;
11997 str2 = PyUnicode_FromObject(str2);
Victor Stinnere9a29352011-10-01 02:14:59 +020011998 if (str2 == NULL || PyUnicode_READY(str2) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011999 Py_DECREF(str1);
12000 return NULL;
Walter Dörwaldf6b56ae2003-02-09 23:42:56 +000012001 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012002
12003 result = replace(self, str1, str2, maxcount);
12004
12005 Py_DECREF(str1);
12006 Py_DECREF(str2);
12007 return result;
12008}
12009
Alexander Belopolsky40018472011-02-26 01:02:56 +000012010static PyObject *
12011unicode_repr(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012012{
Walter Dörwald79e913e2007-05-12 11:08:06 +000012013 PyObject *repr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012014 Py_ssize_t isize;
12015 Py_ssize_t osize, squote, dquote, i, o;
12016 Py_UCS4 max, quote;
12017 int ikind, okind;
12018 void *idata, *odata;
Walter Dörwald79e913e2007-05-12 11:08:06 +000012019
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012020 if (PyUnicode_READY(unicode) == -1)
Walter Dörwald79e913e2007-05-12 11:08:06 +000012021 return NULL;
12022
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012023 isize = PyUnicode_GET_LENGTH(unicode);
12024 idata = PyUnicode_DATA(unicode);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012025
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012026 /* Compute length of output, quote characters, and
12027 maximum character */
12028 osize = 2; /* quotes */
12029 max = 127;
12030 squote = dquote = 0;
12031 ikind = PyUnicode_KIND(unicode);
12032 for (i = 0; i < isize; i++) {
12033 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
12034 switch (ch) {
12035 case '\'': squote++; osize++; break;
12036 case '"': dquote++; osize++; break;
12037 case '\\': case '\t': case '\r': case '\n':
12038 osize += 2; break;
12039 default:
12040 /* Fast-path ASCII */
12041 if (ch < ' ' || ch == 0x7f)
12042 osize += 4; /* \xHH */
12043 else if (ch < 0x7f)
12044 osize++;
12045 else if (Py_UNICODE_ISPRINTABLE(ch)) {
12046 osize++;
12047 max = ch > max ? ch : max;
12048 }
12049 else if (ch < 0x100)
12050 osize += 4; /* \xHH */
12051 else if (ch < 0x10000)
12052 osize += 6; /* \uHHHH */
12053 else
12054 osize += 10; /* \uHHHHHHHH */
12055 }
12056 }
12057
12058 quote = '\'';
12059 if (squote) {
12060 if (dquote)
12061 /* Both squote and dquote present. Use squote,
12062 and escape them */
12063 osize += squote;
12064 else
12065 quote = '"';
12066 }
12067
12068 repr = PyUnicode_New(osize, max);
12069 if (repr == NULL)
12070 return NULL;
12071 okind = PyUnicode_KIND(repr);
12072 odata = PyUnicode_DATA(repr);
12073
12074 PyUnicode_WRITE(okind, odata, 0, quote);
12075 PyUnicode_WRITE(okind, odata, osize-1, quote);
12076
12077 for (i = 0, o = 1; i < isize; i++) {
12078 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012079
12080 /* Escape quotes and backslashes */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012081 if ((ch == quote) || (ch == '\\')) {
12082 PyUnicode_WRITE(okind, odata, o++, '\\');
12083 PyUnicode_WRITE(okind, odata, o++, ch);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012084 continue;
12085 }
12086
Benjamin Peterson29060642009-01-31 22:14:21 +000012087 /* Map special whitespace to '\t', \n', '\r' */
Georg Brandl559e5d72008-06-11 18:37:52 +000012088 if (ch == '\t') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012089 PyUnicode_WRITE(okind, odata, o++, '\\');
12090 PyUnicode_WRITE(okind, odata, o++, 't');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012091 }
12092 else if (ch == '\n') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012093 PyUnicode_WRITE(okind, odata, o++, '\\');
12094 PyUnicode_WRITE(okind, odata, o++, 'n');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012095 }
12096 else if (ch == '\r') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012097 PyUnicode_WRITE(okind, odata, o++, '\\');
12098 PyUnicode_WRITE(okind, odata, o++, 'r');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012099 }
12100
12101 /* Map non-printable US ASCII to '\xhh' */
Georg Brandl559e5d72008-06-11 18:37:52 +000012102 else if (ch < ' ' || ch == 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012103 PyUnicode_WRITE(okind, odata, o++, '\\');
12104 PyUnicode_WRITE(okind, odata, o++, 'x');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012105 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12106 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012107 }
12108
Georg Brandl559e5d72008-06-11 18:37:52 +000012109 /* Copy ASCII characters as-is */
12110 else if (ch < 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012111 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000012112 }
12113
Benjamin Peterson29060642009-01-31 22:14:21 +000012114 /* Non-ASCII characters */
Georg Brandl559e5d72008-06-11 18:37:52 +000012115 else {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012116 /* Map Unicode whitespace and control characters
Georg Brandl559e5d72008-06-11 18:37:52 +000012117 (categories Z* and C* except ASCII space)
12118 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012119 if (!Py_UNICODE_ISPRINTABLE(ch)) {
Georg Brandl559e5d72008-06-11 18:37:52 +000012120 /* Map 8-bit characters to '\xhh' */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012121 if (ch <= 0xff) {
12122 PyUnicode_WRITE(okind, odata, o++, '\\');
12123 PyUnicode_WRITE(okind, odata, o++, 'x');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012124 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12125 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012126 }
12127 /* Map 21-bit characters to '\U00xxxxxx' */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012128 else if (ch >= 0x10000) {
12129 PyUnicode_WRITE(okind, odata, o++, '\\');
12130 PyUnicode_WRITE(okind, odata, o++, 'U');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012131 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 28) & 0xF]);
12132 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 24) & 0xF]);
12133 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 20) & 0xF]);
12134 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 16) & 0xF]);
12135 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12136 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12137 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12138 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012139 }
12140 /* Map 16-bit characters to '\uxxxx' */
12141 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012142 PyUnicode_WRITE(okind, odata, o++, '\\');
12143 PyUnicode_WRITE(okind, odata, o++, 'u');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012144 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12145 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12146 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12147 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012148 }
12149 }
12150 /* Copy characters as-is */
12151 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012152 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000012153 }
12154 }
Walter Dörwald79e913e2007-05-12 11:08:06 +000012155 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012156 /* Closing quote already added at the beginning */
Victor Stinner05d11892011-10-06 01:13:58 +020012157 assert(_PyUnicode_CheckConsistency(repr, 1));
Walter Dörwald79e913e2007-05-12 11:08:06 +000012158 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012159}
12160
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012161PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012162 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012163\n\
12164Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080012165such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012166arguments start and end are interpreted as in slice notation.\n\
12167\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012168Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012169
12170static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012171unicode_rfind(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012172{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012173 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012174 Py_ssize_t start;
12175 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012176 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012177
Jesus Ceaac451502011-04-20 17:09:23 +020012178 if (!stringlib_parse_args_finds_unicode("rfind", args, &substring,
12179 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012180 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012181
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012182 if (PyUnicode_READY(self) == -1)
12183 return NULL;
12184 if (PyUnicode_READY(substring) == -1)
12185 return NULL;
12186
Victor Stinner7931d9a2011-11-04 00:22:48 +010012187 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012188
12189 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012190
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012191 if (result == -2)
12192 return NULL;
12193
Christian Heimes217cfd12007-12-02 14:31:20 +000012194 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012195}
12196
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012197PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012198 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012199\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012200Like S.rfind() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012201
12202static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012203unicode_rindex(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012204{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012205 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012206 Py_ssize_t start;
12207 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012208 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012209
Jesus Ceaac451502011-04-20 17:09:23 +020012210 if (!stringlib_parse_args_finds_unicode("rindex", args, &substring,
12211 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012212 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012213
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012214 if (PyUnicode_READY(self) == -1)
12215 return NULL;
12216 if (PyUnicode_READY(substring) == -1)
12217 return NULL;
12218
Victor Stinner7931d9a2011-11-04 00:22:48 +010012219 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012220
12221 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012222
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012223 if (result == -2)
12224 return NULL;
12225
Guido van Rossumd57fd912000-03-10 22:53:23 +000012226 if (result < 0) {
12227 PyErr_SetString(PyExc_ValueError, "substring not found");
12228 return NULL;
12229 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012230
Christian Heimes217cfd12007-12-02 14:31:20 +000012231 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012232}
12233
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012234PyDoc_STRVAR(rjust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012235 "S.rjust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012236\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012237Return S right-justified in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012238done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012239
12240static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012241unicode_rjust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012242{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012243 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012244 Py_UCS4 fillchar = ' ';
12245
Victor Stinnere9a29352011-10-01 02:14:59 +020012246 if (!PyArg_ParseTuple(args, "n|O&:rjust", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012247 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012248
Victor Stinnerc4b49542011-12-11 22:44:26 +010012249 if (PyUnicode_READY(self) < 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012250 return NULL;
12251
Victor Stinnerc4b49542011-12-11 22:44:26 +010012252 if (PyUnicode_GET_LENGTH(self) >= width)
12253 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012254
Victor Stinnerc4b49542011-12-11 22:44:26 +010012255 return pad(self, width - PyUnicode_GET_LENGTH(self), 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012256}
12257
Alexander Belopolsky40018472011-02-26 01:02:56 +000012258PyObject *
12259PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012260{
12261 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +000012262
Guido van Rossumd57fd912000-03-10 22:53:23 +000012263 s = PyUnicode_FromObject(s);
12264 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012265 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012266 if (sep != NULL) {
12267 sep = PyUnicode_FromObject(sep);
12268 if (sep == NULL) {
12269 Py_DECREF(s);
12270 return NULL;
12271 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012272 }
12273
Victor Stinner9310abb2011-10-05 00:59:23 +020012274 result = split(s, sep, maxsplit);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012275
12276 Py_DECREF(s);
12277 Py_XDECREF(sep);
12278 return result;
12279}
12280
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012281PyDoc_STRVAR(split__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012282 "S.split([sep[, maxsplit]]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012283\n\
12284Return a list of the words in S, using sep as the\n\
12285delimiter string. If maxsplit is given, at most maxsplit\n\
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000012286splits are done. If sep is not specified or is None, any\n\
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +000012287whitespace string is a separator and empty strings are\n\
12288removed from the result.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012289
12290static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012291unicode_split(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012292{
12293 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012294 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012295
Martin v. Löwis18e16552006-02-15 17:27:45 +000012296 if (!PyArg_ParseTuple(args, "|On:split", &substring, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012297 return NULL;
12298
12299 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012300 return split(self, NULL, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012301 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012302 return split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012303 else
Victor Stinner7931d9a2011-11-04 00:22:48 +010012304 return PyUnicode_Split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012305}
12306
Thomas Wouters477c8d52006-05-27 19:21:47 +000012307PyObject *
12308PyUnicode_Partition(PyObject *str_in, PyObject *sep_in)
12309{
12310 PyObject* str_obj;
12311 PyObject* sep_obj;
12312 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012313 int kind1, kind2, kind;
12314 void *buf1 = NULL, *buf2 = NULL;
12315 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012316
12317 str_obj = PyUnicode_FromObject(str_in);
Victor Stinnere9a29352011-10-01 02:14:59 +020012318 if (!str_obj || PyUnicode_READY(str_obj) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000012319 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012320 sep_obj = PyUnicode_FromObject(sep_in);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012321 if (!sep_obj || PyUnicode_READY(sep_obj) == -1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000012322 Py_DECREF(str_obj);
12323 return NULL;
12324 }
12325
Victor Stinner14f8f022011-10-05 20:58:25 +020012326 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012327 kind2 = PyUnicode_KIND(sep_obj);
Victor Stinner14f8f022011-10-05 20:58:25 +020012328 kind = Py_MAX(kind1, kind2);
12329 buf1 = PyUnicode_DATA(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012330 if (kind1 != kind)
Victor Stinner14f8f022011-10-05 20:58:25 +020012331 buf1 = _PyUnicode_AsKind(str_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012332 if (!buf1)
12333 goto onError;
12334 buf2 = PyUnicode_DATA(sep_obj);
12335 if (kind2 != kind)
12336 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12337 if (!buf2)
12338 goto onError;
12339 len1 = PyUnicode_GET_LENGTH(str_obj);
12340 len2 = PyUnicode_GET_LENGTH(sep_obj);
12341
Victor Stinner14f8f022011-10-05 20:58:25 +020012342 switch(PyUnicode_KIND(str_obj)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012343 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012344 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12345 out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12346 else
12347 out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012348 break;
12349 case PyUnicode_2BYTE_KIND:
12350 out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12351 break;
12352 case PyUnicode_4BYTE_KIND:
12353 out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12354 break;
12355 default:
12356 assert(0);
12357 out = 0;
12358 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012359
12360 Py_DECREF(sep_obj);
12361 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012362 if (kind1 != kind)
12363 PyMem_Free(buf1);
12364 if (kind2 != kind)
12365 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012366
12367 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012368 onError:
12369 Py_DECREF(sep_obj);
12370 Py_DECREF(str_obj);
12371 if (kind1 != kind && buf1)
12372 PyMem_Free(buf1);
12373 if (kind2 != kind && buf2)
12374 PyMem_Free(buf2);
12375 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012376}
12377
12378
12379PyObject *
12380PyUnicode_RPartition(PyObject *str_in, PyObject *sep_in)
12381{
12382 PyObject* str_obj;
12383 PyObject* sep_obj;
12384 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012385 int kind1, kind2, kind;
12386 void *buf1 = NULL, *buf2 = NULL;
12387 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012388
12389 str_obj = PyUnicode_FromObject(str_in);
12390 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012391 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012392 sep_obj = PyUnicode_FromObject(sep_in);
12393 if (!sep_obj) {
12394 Py_DECREF(str_obj);
12395 return NULL;
12396 }
12397
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012398 kind1 = PyUnicode_KIND(str_in);
12399 kind2 = PyUnicode_KIND(sep_obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +020012400 kind = Py_MAX(kind1, kind2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012401 buf1 = PyUnicode_DATA(str_in);
12402 if (kind1 != kind)
12403 buf1 = _PyUnicode_AsKind(str_in, kind);
12404 if (!buf1)
12405 goto onError;
12406 buf2 = PyUnicode_DATA(sep_obj);
12407 if (kind2 != kind)
12408 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12409 if (!buf2)
12410 goto onError;
12411 len1 = PyUnicode_GET_LENGTH(str_obj);
12412 len2 = PyUnicode_GET_LENGTH(sep_obj);
12413
12414 switch(PyUnicode_KIND(str_in)) {
12415 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012416 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12417 out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12418 else
12419 out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012420 break;
12421 case PyUnicode_2BYTE_KIND:
12422 out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12423 break;
12424 case PyUnicode_4BYTE_KIND:
12425 out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12426 break;
12427 default:
12428 assert(0);
12429 out = 0;
12430 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012431
12432 Py_DECREF(sep_obj);
12433 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012434 if (kind1 != kind)
12435 PyMem_Free(buf1);
12436 if (kind2 != kind)
12437 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012438
12439 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012440 onError:
12441 Py_DECREF(sep_obj);
12442 Py_DECREF(str_obj);
12443 if (kind1 != kind && buf1)
12444 PyMem_Free(buf1);
12445 if (kind2 != kind && buf2)
12446 PyMem_Free(buf2);
12447 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012448}
12449
12450PyDoc_STRVAR(partition__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012451 "S.partition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012452\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012453Search for the separator sep in S, and return the part before it,\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012454the separator itself, and the part after it. If the separator is not\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012455found, return S and two empty strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012456
12457static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012458unicode_partition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012459{
Victor Stinner9310abb2011-10-05 00:59:23 +020012460 return PyUnicode_Partition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012461}
12462
12463PyDoc_STRVAR(rpartition__doc__,
Ezio Melotti5b2b2422010-01-25 11:58:28 +000012464 "S.rpartition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012465\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012466Search for the separator sep in S, starting at the end of S, and return\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012467the part before it, the separator itself, and the part after it. If the\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012468separator is not found, return two empty strings and S.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012469
12470static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012471unicode_rpartition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012472{
Victor Stinner9310abb2011-10-05 00:59:23 +020012473 return PyUnicode_RPartition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012474}
12475
Alexander Belopolsky40018472011-02-26 01:02:56 +000012476PyObject *
12477PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012478{
12479 PyObject *result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012480
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012481 s = PyUnicode_FromObject(s);
12482 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012483 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012484 if (sep != NULL) {
12485 sep = PyUnicode_FromObject(sep);
12486 if (sep == NULL) {
12487 Py_DECREF(s);
12488 return NULL;
12489 }
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012490 }
12491
Victor Stinner9310abb2011-10-05 00:59:23 +020012492 result = rsplit(s, sep, maxsplit);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012493
12494 Py_DECREF(s);
12495 Py_XDECREF(sep);
12496 return result;
12497}
12498
12499PyDoc_STRVAR(rsplit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012500 "S.rsplit([sep[, maxsplit]]) -> list of strings\n\
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012501\n\
12502Return a list of the words in S, using sep as the\n\
12503delimiter string, starting at the end of the string and\n\
12504working to the front. If maxsplit is given, at most maxsplit\n\
12505splits are done. If sep is not specified, any whitespace string\n\
12506is a separator.");
12507
12508static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012509unicode_rsplit(PyObject *self, PyObject *args)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012510{
12511 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012512 Py_ssize_t maxcount = -1;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012513
Martin v. Löwis18e16552006-02-15 17:27:45 +000012514 if (!PyArg_ParseTuple(args, "|On:rsplit", &substring, &maxcount))
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012515 return NULL;
12516
12517 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012518 return rsplit(self, NULL, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012519 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012520 return rsplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012521 else
Victor Stinner9310abb2011-10-05 00:59:23 +020012522 return PyUnicode_RSplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012523}
12524
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012525PyDoc_STRVAR(splitlines__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012526 "S.splitlines([keepends]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012527\n\
12528Return a list of the lines in S, breaking at line boundaries.\n\
Guido van Rossum86662912000-04-11 15:38:46 +000012529Line breaks are not included in the resulting list unless keepends\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012530is given and true.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012531
12532static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012533unicode_splitlines(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012534{
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012535 static char *kwlist[] = {"keepends", 0};
Guido van Rossum86662912000-04-11 15:38:46 +000012536 int keepends = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012537
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012538 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:splitlines",
12539 kwlist, &keepends))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012540 return NULL;
12541
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012542 return PyUnicode_Splitlines(self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012543}
12544
12545static
Guido van Rossumf15a29f2007-05-04 00:41:39 +000012546PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012547{
Victor Stinnerc4b49542011-12-11 22:44:26 +010012548 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012549}
12550
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012551PyDoc_STRVAR(swapcase__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012552 "S.swapcase() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012553\n\
12554Return a copy of S with uppercase characters converted to lowercase\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012555and vice versa.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012556
12557static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012558unicode_swapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012559{
Guido van Rossumd57fd912000-03-10 22:53:23 +000012560 return fixup(self, fixswapcase);
12561}
12562
Georg Brandlceee0772007-11-27 23:48:05 +000012563PyDoc_STRVAR(maketrans__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012564 "str.maketrans(x[, y[, z]]) -> dict (static method)\n\
Georg Brandlceee0772007-11-27 23:48:05 +000012565\n\
12566Return a translation table usable for str.translate().\n\
12567If there is only one argument, it must be a dictionary mapping Unicode\n\
12568ordinals (integers) or characters to Unicode ordinals, strings or None.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012569Character keys will be then converted to ordinals.\n\
Georg Brandlceee0772007-11-27 23:48:05 +000012570If there are two arguments, they must be strings of equal length, and\n\
12571in the resulting dictionary, each character in x will be mapped to the\n\
12572character at the same position in y. If there is a third argument, it\n\
12573must be a string, whose characters will be mapped to None in the result.");
12574
12575static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012576unicode_maketrans(PyObject *null, PyObject *args)
Georg Brandlceee0772007-11-27 23:48:05 +000012577{
12578 PyObject *x, *y = NULL, *z = NULL;
12579 PyObject *new = NULL, *key, *value;
12580 Py_ssize_t i = 0;
12581 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012582
Georg Brandlceee0772007-11-27 23:48:05 +000012583 if (!PyArg_ParseTuple(args, "O|UU:maketrans", &x, &y, &z))
12584 return NULL;
12585 new = PyDict_New();
12586 if (!new)
12587 return NULL;
12588 if (y != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012589 int x_kind, y_kind, z_kind;
12590 void *x_data, *y_data, *z_data;
12591
Georg Brandlceee0772007-11-27 23:48:05 +000012592 /* x must be a string too, of equal length */
Georg Brandlceee0772007-11-27 23:48:05 +000012593 if (!PyUnicode_Check(x)) {
12594 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
12595 "be a string if there is a second argument");
12596 goto err;
12597 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012598 if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012599 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
12600 "arguments must have equal length");
12601 goto err;
12602 }
12603 /* create entries for translating chars in x to those in y */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012604 x_kind = PyUnicode_KIND(x);
12605 y_kind = PyUnicode_KIND(y);
12606 x_data = PyUnicode_DATA(x);
12607 y_data = PyUnicode_DATA(y);
12608 for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
12609 key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
12610 value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000012611 if (!key || !value)
12612 goto err;
12613 res = PyDict_SetItem(new, key, value);
12614 Py_DECREF(key);
12615 Py_DECREF(value);
12616 if (res < 0)
12617 goto err;
12618 }
12619 /* create entries for deleting chars in z */
12620 if (z != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012621 z_kind = PyUnicode_KIND(z);
12622 z_data = PyUnicode_DATA(z);
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012623 for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012624 key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000012625 if (!key)
12626 goto err;
12627 res = PyDict_SetItem(new, key, Py_None);
12628 Py_DECREF(key);
12629 if (res < 0)
12630 goto err;
12631 }
12632 }
12633 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012634 int kind;
12635 void *data;
12636
Georg Brandlceee0772007-11-27 23:48:05 +000012637 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +000012638 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012639 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
12640 "to maketrans it must be a dict");
12641 goto err;
12642 }
12643 /* copy entries into the new dict, converting string keys to int keys */
12644 while (PyDict_Next(x, &i, &key, &value)) {
12645 if (PyUnicode_Check(key)) {
12646 /* convert string keys to integer keys */
12647 PyObject *newkey;
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012648 if (PyUnicode_GET_LENGTH(key) != 1) {
Georg Brandlceee0772007-11-27 23:48:05 +000012649 PyErr_SetString(PyExc_ValueError, "string keys in translate "
12650 "table must be of length 1");
12651 goto err;
12652 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012653 kind = PyUnicode_KIND(key);
12654 data = PyUnicode_DATA(key);
12655 newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
Georg Brandlceee0772007-11-27 23:48:05 +000012656 if (!newkey)
12657 goto err;
12658 res = PyDict_SetItem(new, newkey, value);
12659 Py_DECREF(newkey);
12660 if (res < 0)
12661 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +000012662 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012663 /* just keep integer keys */
12664 if (PyDict_SetItem(new, key, value) < 0)
12665 goto err;
12666 } else {
12667 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
12668 "be strings or integers");
12669 goto err;
12670 }
12671 }
12672 }
12673 return new;
12674 err:
12675 Py_DECREF(new);
12676 return NULL;
12677}
12678
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012679PyDoc_STRVAR(translate__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012680 "S.translate(table) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012681\n\
12682Return a copy of the string S, where all characters have been mapped\n\
12683through the given translation table, which must be a mapping of\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012684Unicode ordinals to Unicode ordinals, strings, or None.\n\
Walter Dörwald5c1ee172002-09-04 20:31:32 +000012685Unmapped characters are left untouched. Characters mapped to None\n\
12686are deleted.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012687
12688static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012689unicode_translate(PyObject *self, PyObject *table)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012690{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012691 return _PyUnicode_TranslateCharmap(self, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012692}
12693
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012694PyDoc_STRVAR(upper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012695 "S.upper() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012696\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012697Return a copy of S converted to uppercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012698
12699static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012700unicode_upper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012701{
Guido van Rossumd57fd912000-03-10 22:53:23 +000012702 return fixup(self, fixupper);
12703}
12704
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012705PyDoc_STRVAR(zfill__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012706 "S.zfill(width) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012707\n\
Benjamin Peterson9aa42992008-09-10 21:57:34 +000012708Pad a numeric string S with zeros on the left, to fill a field\n\
12709of the specified width. The string S is never truncated.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012710
12711static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012712unicode_zfill(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012713{
Martin v. Löwis18e16552006-02-15 17:27:45 +000012714 Py_ssize_t fill;
Victor Stinner9310abb2011-10-05 00:59:23 +020012715 PyObject *u;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012716 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012717 int kind;
12718 void *data;
12719 Py_UCS4 chr;
12720
Martin v. Löwis18e16552006-02-15 17:27:45 +000012721 if (!PyArg_ParseTuple(args, "n:zfill", &width))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012722 return NULL;
12723
Victor Stinnerc4b49542011-12-11 22:44:26 +010012724 if (PyUnicode_READY(self) < 0)
12725 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012726
Victor Stinnerc4b49542011-12-11 22:44:26 +010012727 if (PyUnicode_GET_LENGTH(self) >= width)
12728 return unicode_result_unchanged(self);
12729
12730 fill = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012731
12732 u = pad(self, fill, 0, '0');
12733
Walter Dörwald068325e2002-04-15 13:36:47 +000012734 if (u == NULL)
12735 return NULL;
12736
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012737 kind = PyUnicode_KIND(u);
12738 data = PyUnicode_DATA(u);
12739 chr = PyUnicode_READ(kind, data, fill);
12740
12741 if (chr == '+' || chr == '-') {
Guido van Rossumd57fd912000-03-10 22:53:23 +000012742 /* move sign to beginning of string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012743 PyUnicode_WRITE(kind, data, 0, chr);
12744 PyUnicode_WRITE(kind, data, fill, '0');
Guido van Rossumd57fd912000-03-10 22:53:23 +000012745 }
12746
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012747 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +010012748 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012749}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012750
12751#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012752static PyObject *
12753unicode__decimal2ascii(PyObject *self)
12754{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012755 return PyUnicode_TransformDecimalAndSpaceToASCII(self);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012756}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012757#endif
12758
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012759PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012760 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012761\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000012762Return True if S starts with the specified prefix, False otherwise.\n\
12763With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012764With optional end, stop comparing S at that position.\n\
12765prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012766
12767static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012768unicode_startswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000012769 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012770{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012771 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012772 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012773 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012774 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012775 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012776
Jesus Ceaac451502011-04-20 17:09:23 +020012777 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000012778 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012779 if (PyTuple_Check(subobj)) {
12780 Py_ssize_t i;
12781 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012782 substring = PyUnicode_FromObject(PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012783 if (substring == NULL)
12784 return NULL;
12785 result = tailmatch(self, substring, start, end, -1);
12786 Py_DECREF(substring);
12787 if (result) {
12788 Py_RETURN_TRUE;
12789 }
12790 }
12791 /* nothing matched */
12792 Py_RETURN_FALSE;
12793 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012794 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030012795 if (substring == NULL) {
12796 if (PyErr_ExceptionMatches(PyExc_TypeError))
12797 PyErr_Format(PyExc_TypeError, "startswith first arg must be str or "
12798 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000012799 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030012800 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012801 result = tailmatch(self, substring, start, end, -1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012802 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012803 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012804}
12805
12806
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012807PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012808 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012809\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000012810Return True if S ends with the specified suffix, False otherwise.\n\
12811With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012812With optional end, stop comparing S at that position.\n\
12813suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012814
12815static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012816unicode_endswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000012817 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012818{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012819 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012820 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012821 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012822 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012823 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012824
Jesus Ceaac451502011-04-20 17:09:23 +020012825 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000012826 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012827 if (PyTuple_Check(subobj)) {
12828 Py_ssize_t i;
12829 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012830 substring = PyUnicode_FromObject(
Benjamin Peterson29060642009-01-31 22:14:21 +000012831 PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012832 if (substring == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000012833 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012834 result = tailmatch(self, substring, start, end, +1);
12835 Py_DECREF(substring);
12836 if (result) {
12837 Py_RETURN_TRUE;
12838 }
12839 }
12840 Py_RETURN_FALSE;
12841 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012842 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030012843 if (substring == NULL) {
12844 if (PyErr_ExceptionMatches(PyExc_TypeError))
12845 PyErr_Format(PyExc_TypeError, "endswith first arg must be str or "
12846 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000012847 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030012848 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012849 result = tailmatch(self, substring, start, end, +1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012850 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012851 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012852}
12853
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012854#include "stringlib/unicode_format.h"
Eric Smith8c663262007-08-25 02:26:07 +000012855
12856PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012857 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000012858\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012859Return a formatted version of S, using substitutions from args and kwargs.\n\
12860The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +000012861
Eric Smith27bbca62010-11-04 17:06:58 +000012862PyDoc_STRVAR(format_map__doc__,
12863 "S.format_map(mapping) -> str\n\
12864\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012865Return a formatted version of S, using substitutions from mapping.\n\
12866The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +000012867
Eric Smith4a7d76d2008-05-30 18:10:19 +000012868static PyObject *
12869unicode__format__(PyObject* self, PyObject* args)
12870{
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012871 PyObject *format_spec, *out;
Eric Smith4a7d76d2008-05-30 18:10:19 +000012872
12873 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
12874 return NULL;
12875
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012876 out = _PyUnicode_FormatAdvanced(self, format_spec, 0,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012877 PyUnicode_GET_LENGTH(format_spec));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012878 return out;
Eric Smith4a7d76d2008-05-30 18:10:19 +000012879}
12880
Eric Smith8c663262007-08-25 02:26:07 +000012881PyDoc_STRVAR(p_format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012882 "S.__format__(format_spec) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000012883\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012884Return a formatted version of S as described by format_spec.");
Eric Smith8c663262007-08-25 02:26:07 +000012885
12886static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012887unicode__sizeof__(PyObject *v)
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012888{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012889 Py_ssize_t size;
12890
12891 /* If it's a compact object, account for base structure +
12892 character data. */
12893 if (PyUnicode_IS_COMPACT_ASCII(v))
12894 size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(v) + 1;
12895 else if (PyUnicode_IS_COMPACT(v))
12896 size = sizeof(PyCompactUnicodeObject) +
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012897 (PyUnicode_GET_LENGTH(v) + 1) * PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012898 else {
12899 /* If it is a two-block object, account for base object, and
12900 for character block if present. */
12901 size = sizeof(PyUnicodeObject);
Victor Stinnerc3c74152011-10-02 20:39:55 +020012902 if (_PyUnicode_DATA_ANY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012903 size += (PyUnicode_GET_LENGTH(v) + 1) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012904 PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012905 }
12906 /* If the wstr pointer is present, account for it unless it is shared
Victor Stinnera3be6132011-10-03 02:16:37 +020012907 with the data pointer. Check if the data is not shared. */
Victor Stinner03490912011-10-03 23:45:12 +020012908 if (_PyUnicode_HAS_WSTR_MEMORY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012909 size += (PyUnicode_WSTR_LENGTH(v) + 1) * sizeof(wchar_t);
Victor Stinner829c0ad2011-10-03 01:08:02 +020012910 if (_PyUnicode_HAS_UTF8_MEMORY(v))
Victor Stinnere90fe6a2011-10-01 16:48:13 +020012911 size += PyUnicode_UTF8_LENGTH(v) + 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012912
12913 return PyLong_FromSsize_t(size);
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012914}
12915
12916PyDoc_STRVAR(sizeof__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012917 "S.__sizeof__() -> size of S in memory, in bytes");
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012918
12919static PyObject *
Victor Stinner034f6cf2011-09-30 02:26:44 +020012920unicode_getnewargs(PyObject *v)
Guido van Rossum5d9113d2003-01-29 17:58:45 +000012921{
Victor Stinnerbf6e5602011-12-12 01:53:47 +010012922 PyObject *copy = _PyUnicode_Copy(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012923 if (!copy)
12924 return NULL;
12925 return Py_BuildValue("(N)", copy);
Guido van Rossum5d9113d2003-01-29 17:58:45 +000012926}
12927
Guido van Rossumd57fd912000-03-10 22:53:23 +000012928static PyMethodDef unicode_methods[] = {
12929
12930 /* Order is according to common usage: often used methods should
12931 appear first, since lookup is done sequentially. */
12932
Benjamin Peterson28a4dce2010-12-12 01:33:04 +000012933 {"encode", (PyCFunction) unicode_encode, METH_VARARGS | METH_KEYWORDS, encode__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012934 {"replace", (PyCFunction) unicode_replace, METH_VARARGS, replace__doc__},
12935 {"split", (PyCFunction) unicode_split, METH_VARARGS, split__doc__},
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012936 {"rsplit", (PyCFunction) unicode_rsplit, METH_VARARGS, rsplit__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012937 {"join", (PyCFunction) unicode_join, METH_O, join__doc__},
12938 {"capitalize", (PyCFunction) unicode_capitalize, METH_NOARGS, capitalize__doc__},
12939 {"title", (PyCFunction) unicode_title, METH_NOARGS, title__doc__},
12940 {"center", (PyCFunction) unicode_center, METH_VARARGS, center__doc__},
12941 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
12942 {"expandtabs", (PyCFunction) unicode_expandtabs, METH_VARARGS, expandtabs__doc__},
12943 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000012944 {"partition", (PyCFunction) unicode_partition, METH_O, partition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012945 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
12946 {"ljust", (PyCFunction) unicode_ljust, METH_VARARGS, ljust__doc__},
12947 {"lower", (PyCFunction) unicode_lower, METH_NOARGS, lower__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012948 {"lstrip", (PyCFunction) unicode_lstrip, METH_VARARGS, lstrip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012949 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
12950 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
12951 {"rjust", (PyCFunction) unicode_rjust, METH_VARARGS, rjust__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012952 {"rstrip", (PyCFunction) unicode_rstrip, METH_VARARGS, rstrip__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000012953 {"rpartition", (PyCFunction) unicode_rpartition, METH_O, rpartition__doc__},
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012954 {"splitlines", (PyCFunction) unicode_splitlines, METH_VARARGS | METH_KEYWORDS, splitlines__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012955 {"strip", (PyCFunction) unicode_strip, METH_VARARGS, strip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012956 {"swapcase", (PyCFunction) unicode_swapcase, METH_NOARGS, swapcase__doc__},
12957 {"translate", (PyCFunction) unicode_translate, METH_O, translate__doc__},
12958 {"upper", (PyCFunction) unicode_upper, METH_NOARGS, upper__doc__},
12959 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
12960 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
12961 {"islower", (PyCFunction) unicode_islower, METH_NOARGS, islower__doc__},
12962 {"isupper", (PyCFunction) unicode_isupper, METH_NOARGS, isupper__doc__},
12963 {"istitle", (PyCFunction) unicode_istitle, METH_NOARGS, istitle__doc__},
12964 {"isspace", (PyCFunction) unicode_isspace, METH_NOARGS, isspace__doc__},
12965 {"isdecimal", (PyCFunction) unicode_isdecimal, METH_NOARGS, isdecimal__doc__},
12966 {"isdigit", (PyCFunction) unicode_isdigit, METH_NOARGS, isdigit__doc__},
12967 {"isnumeric", (PyCFunction) unicode_isnumeric, METH_NOARGS, isnumeric__doc__},
12968 {"isalpha", (PyCFunction) unicode_isalpha, METH_NOARGS, isalpha__doc__},
12969 {"isalnum", (PyCFunction) unicode_isalnum, METH_NOARGS, isalnum__doc__},
Martin v. Löwis47383402007-08-15 07:32:56 +000012970 {"isidentifier", (PyCFunction) unicode_isidentifier, METH_NOARGS, isidentifier__doc__},
Georg Brandl559e5d72008-06-11 18:37:52 +000012971 {"isprintable", (PyCFunction) unicode_isprintable, METH_NOARGS, isprintable__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012972 {"zfill", (PyCFunction) unicode_zfill, METH_VARARGS, zfill__doc__},
Eric Smith9cd1e092007-08-31 18:39:38 +000012973 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +000012974 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
Eric Smith4a7d76d2008-05-30 18:10:19 +000012975 {"__format__", (PyCFunction) unicode__format__, METH_VARARGS, p_format__doc__},
Georg Brandlceee0772007-11-27 23:48:05 +000012976 {"maketrans", (PyCFunction) unicode_maketrans,
12977 METH_VARARGS | METH_STATIC, maketrans__doc__},
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012978 {"__sizeof__", (PyCFunction) unicode__sizeof__, METH_NOARGS, sizeof__doc__},
Walter Dörwald068325e2002-04-15 13:36:47 +000012979#if 0
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012980 {"capwords", (PyCFunction) unicode_capwords, METH_NOARGS, capwords__doc__},
Guido van Rossumd57fd912000-03-10 22:53:23 +000012981#endif
12982
12983#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012984 /* These methods are just used for debugging the implementation. */
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012985 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000012986#endif
12987
Benjamin Peterson14339b62009-01-31 16:36:08 +000012988 {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000012989 {NULL, NULL}
12990};
12991
Neil Schemenauerce30bc92002-11-18 16:10:18 +000012992static PyObject *
12993unicode_mod(PyObject *v, PyObject *w)
12994{
Brian Curtindfc80e32011-08-10 20:28:54 -050012995 if (!PyUnicode_Check(v))
12996 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson29060642009-01-31 22:14:21 +000012997 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +000012998}
12999
13000static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013001 0, /*nb_add*/
13002 0, /*nb_subtract*/
13003 0, /*nb_multiply*/
13004 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013005};
13006
Guido van Rossumd57fd912000-03-10 22:53:23 +000013007static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013008 (lenfunc) unicode_length, /* sq_length */
13009 PyUnicode_Concat, /* sq_concat */
13010 (ssizeargfunc) unicode_repeat, /* sq_repeat */
13011 (ssizeargfunc) unicode_getitem, /* sq_item */
13012 0, /* sq_slice */
13013 0, /* sq_ass_item */
13014 0, /* sq_ass_slice */
13015 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013016};
13017
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013018static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013019unicode_subscript(PyObject* self, PyObject* item)
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013020{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013021 if (PyUnicode_READY(self) == -1)
13022 return NULL;
13023
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000013024 if (PyIndex_Check(item)) {
13025 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013026 if (i == -1 && PyErr_Occurred())
13027 return NULL;
13028 if (i < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013029 i += PyUnicode_GET_LENGTH(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013030 return unicode_getitem(self, i);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013031 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000013032 Py_ssize_t start, stop, step, slicelength, cur, i;
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013033 PyObject *result;
13034 void *src_data, *dest_data;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013035 int src_kind, dest_kind;
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013036 Py_UCS4 ch, max_char, kind_limit;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013037
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013038 if (PySlice_GetIndicesEx(item, PyUnicode_GET_LENGTH(self),
Benjamin Peterson29060642009-01-31 22:14:21 +000013039 &start, &stop, &step, &slicelength) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013040 return NULL;
13041 }
13042
13043 if (slicelength <= 0) {
Victor Stinner382955f2011-12-11 21:44:00 +010013044 Py_INCREF(unicode_empty);
13045 return unicode_empty;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013046 } else if (start == 0 && step == 1 &&
Victor Stinnerc4b49542011-12-11 22:44:26 +010013047 slicelength == PyUnicode_GET_LENGTH(self)) {
13048 return unicode_result_unchanged(self);
Thomas Woutersed03b412007-08-28 21:37:11 +000013049 } else if (step == 1) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013050 return PyUnicode_Substring(self,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013051 start, start + slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013052 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013053 /* General case */
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013054 src_kind = PyUnicode_KIND(self);
13055 src_data = PyUnicode_DATA(self);
Victor Stinner55c99112011-10-13 01:17:06 +020013056 if (!PyUnicode_IS_ASCII(self)) {
13057 kind_limit = kind_maxchar_limit(src_kind);
13058 max_char = 0;
13059 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
13060 ch = PyUnicode_READ(src_kind, src_data, cur);
13061 if (ch > max_char) {
13062 max_char = ch;
13063 if (max_char >= kind_limit)
13064 break;
13065 }
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013066 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013067 }
Victor Stinner55c99112011-10-13 01:17:06 +020013068 else
13069 max_char = 127;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013070 result = PyUnicode_New(slicelength, max_char);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013071 if (result == NULL)
13072 return NULL;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013073 dest_kind = PyUnicode_KIND(result);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013074 dest_data = PyUnicode_DATA(result);
13075
13076 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013077 Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
13078 PyUnicode_WRITE(dest_kind, dest_data, i, ch);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013079 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013080 assert(_PyUnicode_CheckConsistency(result, 1));
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013081 return result;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013082 } else {
13083 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
13084 return NULL;
13085 }
13086}
13087
13088static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013089 (lenfunc)unicode_length, /* mp_length */
13090 (binaryfunc)unicode_subscript, /* mp_subscript */
13091 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013092};
13093
Guido van Rossumd57fd912000-03-10 22:53:23 +000013094
Guido van Rossumd57fd912000-03-10 22:53:23 +000013095/* Helpers for PyUnicode_Format() */
13096
13097static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +000013098getnextarg(PyObject *args, Py_ssize_t arglen, Py_ssize_t *p_argidx)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013099{
Martin v. Löwis18e16552006-02-15 17:27:45 +000013100 Py_ssize_t argidx = *p_argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013101 if (argidx < arglen) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013102 (*p_argidx)++;
13103 if (arglen < 0)
13104 return args;
13105 else
13106 return PyTuple_GetItem(args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013107 }
13108 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013109 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013110 return NULL;
13111}
13112
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013113/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013114
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013115static PyObject *
13116formatfloat(PyObject *v, int flags, int prec, int type)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013117{
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013118 char *p;
13119 PyObject *result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013120 double x;
Tim Petersced69f82003-09-16 20:30:58 +000013121
Guido van Rossumd57fd912000-03-10 22:53:23 +000013122 x = PyFloat_AsDouble(v);
13123 if (x == -1.0 && PyErr_Occurred())
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013124 return NULL;
13125
Guido van Rossumd57fd912000-03-10 22:53:23 +000013126 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000013127 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +000013128
Eric Smith0923d1d2009-04-16 20:16:10 +000013129 p = PyOS_double_to_string(x, type, prec,
13130 (flags & F_ALT) ? Py_DTSF_ALT : 0, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013131 if (p == NULL)
13132 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013133 result = PyUnicode_DecodeASCII(p, strlen(p), NULL);
Eric Smith0923d1d2009-04-16 20:16:10 +000013134 PyMem_Free(p);
13135 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013136}
13137
Tim Peters38fd5b62000-09-21 05:43:11 +000013138static PyObject*
13139formatlong(PyObject *val, int flags, int prec, int type)
13140{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013141 char *buf;
13142 int len;
13143 PyObject *str; /* temporary string object. */
13144 PyObject *result;
Tim Peters38fd5b62000-09-21 05:43:11 +000013145
Benjamin Peterson14339b62009-01-31 16:36:08 +000013146 str = _PyBytes_FormatLong(val, flags, prec, type, &buf, &len);
13147 if (!str)
13148 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013149 result = PyUnicode_DecodeASCII(buf, len, NULL);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013150 Py_DECREF(str);
13151 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +000013152}
13153
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013154static Py_UCS4
13155formatchar(PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013156{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000013157 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000013158 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013159 if (PyUnicode_GET_LENGTH(v) == 1) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013160 return PyUnicode_READ_CHAR(v, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +000013161 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013162 goto onError;
13163 }
13164 else {
13165 /* Integer input truncated to a character */
13166 long x;
13167 x = PyLong_AsLong(v);
13168 if (x == -1 && PyErr_Occurred())
13169 goto onError;
13170
Victor Stinner8faf8212011-12-08 22:14:11 +010013171 if (x < 0 || x > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013172 PyErr_SetString(PyExc_OverflowError,
13173 "%c arg not in range(0x110000)");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013174 return (Py_UCS4) -1;
Benjamin Peterson29060642009-01-31 22:14:21 +000013175 }
13176
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013177 return (Py_UCS4) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013178 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000013179
Benjamin Peterson29060642009-01-31 22:14:21 +000013180 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000013181 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013182 "%c requires int or char");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013183 return (Py_UCS4) -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013184}
13185
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013186static int
13187repeat_accumulate(_PyAccu *acc, PyObject *obj, Py_ssize_t count)
13188{
13189 int r;
13190 assert(count > 0);
13191 assert(PyUnicode_Check(obj));
13192 if (count > 5) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013193 PyObject *repeated = unicode_repeat(obj, count);
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013194 if (repeated == NULL)
13195 return -1;
13196 r = _PyAccu_Accumulate(acc, repeated);
13197 Py_DECREF(repeated);
13198 return r;
13199 }
13200 else {
13201 do {
13202 if (_PyAccu_Accumulate(acc, obj))
13203 return -1;
13204 } while (--count);
13205 return 0;
13206 }
13207}
13208
Alexander Belopolsky40018472011-02-26 01:02:56 +000013209PyObject *
13210PyUnicode_Format(PyObject *format, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013211{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013212 void *fmt;
13213 int fmtkind;
13214 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013215 int kind;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013216 int r;
13217 Py_ssize_t fmtcnt, fmtpos, arglen, argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013218 int args_owned = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013219 PyObject *dict = NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013220 PyObject *temp = NULL;
13221 PyObject *second = NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013222 PyObject *uformat;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013223 _PyAccu acc;
13224 static PyObject *plus, *minus, *blank, *zero, *percent;
13225
13226 if (!plus && !(plus = get_latin1_char('+')))
13227 return NULL;
13228 if (!minus && !(minus = get_latin1_char('-')))
13229 return NULL;
13230 if (!blank && !(blank = get_latin1_char(' ')))
13231 return NULL;
13232 if (!zero && !(zero = get_latin1_char('0')))
13233 return NULL;
13234 if (!percent && !(percent = get_latin1_char('%')))
13235 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000013236
Guido van Rossumd57fd912000-03-10 22:53:23 +000013237 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013238 PyErr_BadInternalCall();
13239 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013240 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013241 uformat = PyUnicode_FromObject(format);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013242 if (uformat == NULL || PyUnicode_READY(uformat) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000013243 return NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013244 if (_PyAccu_Init(&acc))
13245 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013246 fmt = PyUnicode_DATA(uformat);
13247 fmtkind = PyUnicode_KIND(uformat);
13248 fmtcnt = PyUnicode_GET_LENGTH(uformat);
13249 fmtpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013250
Guido van Rossumd57fd912000-03-10 22:53:23 +000013251 if (PyTuple_Check(args)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013252 arglen = PyTuple_Size(args);
13253 argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013254 }
13255 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013256 arglen = -1;
13257 argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013258 }
Christian Heimes90aa7642007-12-19 02:45:37 +000013259 if (Py_TYPE(args)->tp_as_mapping && !PyTuple_Check(args) &&
Christian Heimesf3863112007-11-22 07:46:41 +000013260 !PyUnicode_Check(args))
Benjamin Peterson29060642009-01-31 22:14:21 +000013261 dict = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013262
13263 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013264 if (PyUnicode_READ(fmtkind, fmt, fmtpos) != '%') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013265 PyObject *nonfmt;
13266 Py_ssize_t nonfmtpos;
13267 nonfmtpos = fmtpos++;
13268 while (fmtcnt >= 0 &&
13269 PyUnicode_READ(fmtkind, fmt, fmtpos) != '%') {
13270 fmtpos++;
13271 fmtcnt--;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013272 }
Victor Stinner7931d9a2011-11-04 00:22:48 +010013273 nonfmt = PyUnicode_Substring(uformat, nonfmtpos, fmtpos);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013274 if (nonfmt == NULL)
13275 goto onError;
13276 r = _PyAccu_Accumulate(&acc, nonfmt);
13277 Py_DECREF(nonfmt);
13278 if (r)
13279 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013280 }
13281 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013282 /* Got a format specifier */
13283 int flags = 0;
13284 Py_ssize_t width = -1;
13285 int prec = -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013286 Py_UCS4 c = '\0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013287 Py_UCS4 fill, sign;
Benjamin Peterson29060642009-01-31 22:14:21 +000013288 int isnumok;
13289 PyObject *v = NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013290 void *pbuf = NULL;
13291 Py_ssize_t pindex, len;
13292 PyObject *signobj = NULL, *fillobj = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013293
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013294 fmtpos++;
13295 if (PyUnicode_READ(fmtkind, fmt, fmtpos) == '(') {
13296 Py_ssize_t keystart;
Benjamin Peterson29060642009-01-31 22:14:21 +000013297 Py_ssize_t keylen;
13298 PyObject *key;
13299 int pcount = 1;
Christian Heimesa612dc02008-02-24 13:08:18 +000013300
Benjamin Peterson29060642009-01-31 22:14:21 +000013301 if (dict == NULL) {
13302 PyErr_SetString(PyExc_TypeError,
13303 "format requires a mapping");
13304 goto onError;
13305 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013306 ++fmtpos;
Benjamin Peterson29060642009-01-31 22:14:21 +000013307 --fmtcnt;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013308 keystart = fmtpos;
Benjamin Peterson29060642009-01-31 22:14:21 +000013309 /* Skip over balanced parentheses */
13310 while (pcount > 0 && --fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013311 if (PyUnicode_READ(fmtkind, fmt, fmtpos) == ')')
Benjamin Peterson29060642009-01-31 22:14:21 +000013312 --pcount;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013313 else 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 fmtpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +000013316 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013317 keylen = fmtpos - keystart - 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000013318 if (fmtcnt < 0 || pcount > 0) {
13319 PyErr_SetString(PyExc_ValueError,
13320 "incomplete format key");
13321 goto onError;
13322 }
Victor Stinner7931d9a2011-11-04 00:22:48 +010013323 key = PyUnicode_Substring(uformat,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013324 keystart, keystart + keylen);
Benjamin Peterson29060642009-01-31 22:14:21 +000013325 if (key == NULL)
13326 goto onError;
13327 if (args_owned) {
13328 Py_DECREF(args);
13329 args_owned = 0;
13330 }
13331 args = PyObject_GetItem(dict, key);
13332 Py_DECREF(key);
13333 if (args == NULL) {
13334 goto onError;
13335 }
13336 args_owned = 1;
13337 arglen = -1;
13338 argidx = -2;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013339 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013340 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013341 switch (c = PyUnicode_READ(fmtkind, fmt, fmtpos++)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013342 case '-': flags |= F_LJUST; continue;
13343 case '+': flags |= F_SIGN; continue;
13344 case ' ': flags |= F_BLANK; continue;
13345 case '#': flags |= F_ALT; continue;
13346 case '0': flags |= F_ZERO; continue;
13347 }
13348 break;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013349 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013350 if (c == '*') {
13351 v = getnextarg(args, arglen, &argidx);
13352 if (v == NULL)
13353 goto onError;
13354 if (!PyLong_Check(v)) {
13355 PyErr_SetString(PyExc_TypeError,
13356 "* wants int");
13357 goto onError;
13358 }
13359 width = PyLong_AsLong(v);
13360 if (width == -1 && PyErr_Occurred())
13361 goto onError;
13362 if (width < 0) {
13363 flags |= F_LJUST;
13364 width = -width;
13365 }
13366 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013367 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013368 }
13369 else if (c >= '0' && c <= '9') {
13370 width = c - '0';
13371 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013372 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013373 if (c < '0' || c > '9')
13374 break;
13375 if ((width*10) / 10 != width) {
13376 PyErr_SetString(PyExc_ValueError,
13377 "width too big");
Benjamin Peterson14339b62009-01-31 16:36:08 +000013378 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +000013379 }
13380 width = width*10 + (c - '0');
13381 }
13382 }
13383 if (c == '.') {
13384 prec = 0;
13385 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013386 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013387 if (c == '*') {
13388 v = getnextarg(args, arglen, &argidx);
13389 if (v == NULL)
13390 goto onError;
13391 if (!PyLong_Check(v)) {
13392 PyErr_SetString(PyExc_TypeError,
13393 "* wants int");
13394 goto onError;
13395 }
13396 prec = PyLong_AsLong(v);
13397 if (prec == -1 && PyErr_Occurred())
13398 goto onError;
13399 if (prec < 0)
13400 prec = 0;
13401 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013402 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013403 }
13404 else if (c >= '0' && c <= '9') {
13405 prec = c - '0';
13406 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013407 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013408 if (c < '0' || c > '9')
13409 break;
13410 if ((prec*10) / 10 != prec) {
13411 PyErr_SetString(PyExc_ValueError,
13412 "prec too big");
13413 goto onError;
13414 }
13415 prec = prec*10 + (c - '0');
13416 }
13417 }
13418 } /* prec */
13419 if (fmtcnt >= 0) {
13420 if (c == 'h' || c == 'l' || c == 'L') {
13421 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013422 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013423 }
13424 }
13425 if (fmtcnt < 0) {
13426 PyErr_SetString(PyExc_ValueError,
13427 "incomplete format");
13428 goto onError;
13429 }
13430 if (c != '%') {
13431 v = getnextarg(args, arglen, &argidx);
13432 if (v == NULL)
13433 goto onError;
13434 }
13435 sign = 0;
13436 fill = ' ';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013437 fillobj = blank;
Benjamin Peterson29060642009-01-31 22:14:21 +000013438 switch (c) {
13439
13440 case '%':
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013441 _PyAccu_Accumulate(&acc, percent);
13442 continue;
Benjamin Peterson29060642009-01-31 22:14:21 +000013443
13444 case 's':
13445 case 'r':
13446 case 'a':
Victor Stinner808fc0a2010-03-22 12:50:40 +000013447 if (PyUnicode_CheckExact(v) && c == 's') {
Benjamin Peterson29060642009-01-31 22:14:21 +000013448 temp = v;
13449 Py_INCREF(temp);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013450 }
13451 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013452 if (c == 's')
13453 temp = PyObject_Str(v);
13454 else if (c == 'r')
13455 temp = PyObject_Repr(v);
13456 else
13457 temp = PyObject_ASCII(v);
13458 if (temp == NULL)
13459 goto onError;
13460 if (PyUnicode_Check(temp))
13461 /* nothing to do */;
13462 else {
13463 Py_DECREF(temp);
13464 PyErr_SetString(PyExc_TypeError,
13465 "%s argument has non-string str()");
13466 goto onError;
13467 }
13468 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013469 if (PyUnicode_READY(temp) == -1) {
13470 Py_CLEAR(temp);
13471 goto onError;
13472 }
13473 pbuf = PyUnicode_DATA(temp);
13474 kind = PyUnicode_KIND(temp);
13475 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013476 if (prec >= 0 && len > prec)
13477 len = prec;
13478 break;
13479
13480 case 'i':
13481 case 'd':
13482 case 'u':
13483 case 'o':
13484 case 'x':
13485 case 'X':
Benjamin Peterson29060642009-01-31 22:14:21 +000013486 isnumok = 0;
13487 if (PyNumber_Check(v)) {
13488 PyObject *iobj=NULL;
13489
13490 if (PyLong_Check(v)) {
13491 iobj = v;
13492 Py_INCREF(iobj);
13493 }
13494 else {
13495 iobj = PyNumber_Long(v);
13496 }
13497 if (iobj!=NULL) {
13498 if (PyLong_Check(iobj)) {
13499 isnumok = 1;
Senthil Kumaran9ebe08d2011-07-03 21:03:16 -070013500 temp = formatlong(iobj, flags, prec, (c == 'i'? 'd': c));
Benjamin Peterson29060642009-01-31 22:14:21 +000013501 Py_DECREF(iobj);
13502 if (!temp)
13503 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013504 if (PyUnicode_READY(temp) == -1) {
13505 Py_CLEAR(temp);
13506 goto onError;
13507 }
13508 pbuf = PyUnicode_DATA(temp);
13509 kind = PyUnicode_KIND(temp);
13510 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013511 sign = 1;
13512 }
13513 else {
13514 Py_DECREF(iobj);
13515 }
13516 }
13517 }
13518 if (!isnumok) {
13519 PyErr_Format(PyExc_TypeError,
13520 "%%%c format: a number is required, "
13521 "not %.200s", (char)c, Py_TYPE(v)->tp_name);
13522 goto onError;
13523 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013524 if (flags & F_ZERO) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013525 fill = '0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013526 fillobj = zero;
13527 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013528 break;
13529
13530 case 'e':
13531 case 'E':
13532 case 'f':
13533 case 'F':
13534 case 'g':
13535 case 'G':
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013536 temp = formatfloat(v, flags, prec, c);
13537 if (!temp)
Benjamin Peterson29060642009-01-31 22:14:21 +000013538 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013539 if (PyUnicode_READY(temp) == -1) {
13540 Py_CLEAR(temp);
13541 goto onError;
13542 }
13543 pbuf = PyUnicode_DATA(temp);
13544 kind = PyUnicode_KIND(temp);
13545 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013546 sign = 1;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013547 if (flags & F_ZERO) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013548 fill = '0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013549 fillobj = zero;
13550 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013551 break;
13552
13553 case 'c':
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013554 {
13555 Py_UCS4 ch = formatchar(v);
13556 if (ch == (Py_UCS4) -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000013557 goto onError;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013558 temp = _PyUnicode_FromUCS4(&ch, 1);
13559 if (temp == NULL)
13560 goto onError;
13561 pbuf = PyUnicode_DATA(temp);
13562 kind = PyUnicode_KIND(temp);
13563 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013564 break;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013565 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013566
13567 default:
13568 PyErr_Format(PyExc_ValueError,
13569 "unsupported format character '%c' (0x%x) "
13570 "at index %zd",
13571 (31<=c && c<=126) ? (char)c : '?',
13572 (int)c,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013573 fmtpos - 1);
Benjamin Peterson29060642009-01-31 22:14:21 +000013574 goto onError;
13575 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013576 /* pbuf is initialized here. */
13577 pindex = 0;
Benjamin Peterson29060642009-01-31 22:14:21 +000013578 if (sign) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013579 if (PyUnicode_READ(kind, pbuf, pindex) == '-') {
13580 signobj = minus;
Benjamin Peterson29060642009-01-31 22:14:21 +000013581 len--;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013582 pindex++;
13583 }
13584 else if (PyUnicode_READ(kind, pbuf, pindex) == '+') {
13585 signobj = plus;
13586 len--;
13587 pindex++;
Benjamin Peterson29060642009-01-31 22:14:21 +000013588 }
13589 else if (flags & F_SIGN)
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013590 signobj = plus;
Benjamin Peterson29060642009-01-31 22:14:21 +000013591 else if (flags & F_BLANK)
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013592 signobj = blank;
Benjamin Peterson29060642009-01-31 22:14:21 +000013593 else
13594 sign = 0;
13595 }
13596 if (width < len)
13597 width = len;
Benjamin Peterson29060642009-01-31 22:14:21 +000013598 if (sign) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013599 if (fill != ' ') {
13600 assert(signobj != NULL);
13601 if (_PyAccu_Accumulate(&acc, signobj))
13602 goto onError;
13603 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013604 if (width > len)
13605 width--;
13606 }
13607 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013608 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013609 assert(PyUnicode_READ(kind, pbuf, pindex + 1) == c);
Benjamin Peterson29060642009-01-31 22:14:21 +000013610 if (fill != ' ') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013611 second = get_latin1_char(
13612 PyUnicode_READ(kind, pbuf, pindex + 1));
13613 pindex += 2;
13614 if (second == NULL ||
13615 _PyAccu_Accumulate(&acc, zero) ||
13616 _PyAccu_Accumulate(&acc, second))
13617 goto onError;
13618 Py_CLEAR(second);
Benjamin Peterson29060642009-01-31 22:14:21 +000013619 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013620 width -= 2;
13621 if (width < 0)
13622 width = 0;
13623 len -= 2;
13624 }
13625 if (width > len && !(flags & F_LJUST)) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013626 assert(fillobj != NULL);
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013627 if (repeat_accumulate(&acc, fillobj, width - len))
13628 goto onError;
13629 width = len;
Benjamin Peterson29060642009-01-31 22:14:21 +000013630 }
13631 if (fill == ' ') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013632 if (sign) {
13633 assert(signobj != NULL);
13634 if (_PyAccu_Accumulate(&acc, signobj))
13635 goto onError;
13636 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013637 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013638 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
13639 assert(PyUnicode_READ(kind, pbuf, pindex+1) == c);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013640 second = get_latin1_char(
13641 PyUnicode_READ(kind, pbuf, pindex + 1));
13642 pindex += 2;
13643 if (second == NULL ||
13644 _PyAccu_Accumulate(&acc, zero) ||
13645 _PyAccu_Accumulate(&acc, second))
13646 goto onError;
13647 Py_CLEAR(second);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013648 }
13649 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013650 /* Copy all characters, preserving len */
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013651 if (temp != NULL) {
13652 assert(pbuf == PyUnicode_DATA(temp));
13653 v = PyUnicode_Substring(temp, pindex, pindex + len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013654 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013655 else {
13656 const char *p = (const char *) pbuf;
13657 assert(pbuf != NULL);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013658 p += kind * pindex;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013659 v = PyUnicode_FromKindAndData(kind, p, len);
13660 }
13661 if (v == NULL)
13662 goto onError;
13663 r = _PyAccu_Accumulate(&acc, v);
13664 Py_DECREF(v);
13665 if (r)
13666 goto onError;
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013667 if (width > len && repeat_accumulate(&acc, blank, width - len))
13668 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +000013669 if (dict && (argidx < arglen) && c != '%') {
13670 PyErr_SetString(PyExc_TypeError,
13671 "not all arguments converted during string formatting");
Benjamin Peterson29060642009-01-31 22:14:21 +000013672 goto onError;
13673 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013674 Py_CLEAR(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013675 } /* '%' */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013676 } /* until end */
13677 if (argidx < arglen && !dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013678 PyErr_SetString(PyExc_TypeError,
13679 "not all arguments converted during string formatting");
13680 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013681 }
13682
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013683 result = _PyAccu_Finish(&acc);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013684 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013685 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013686 }
13687 Py_DECREF(uformat);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013688 Py_XDECREF(temp);
13689 Py_XDECREF(second);
Victor Stinner7931d9a2011-11-04 00:22:48 +010013690 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013691
Benjamin Peterson29060642009-01-31 22:14:21 +000013692 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000013693 Py_DECREF(uformat);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013694 Py_XDECREF(temp);
13695 Py_XDECREF(second);
13696 _PyAccu_Destroy(&acc);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013697 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013698 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013699 }
13700 return NULL;
13701}
13702
Jeremy Hylton938ace62002-07-17 16:30:39 +000013703static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +000013704unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
13705
Tim Peters6d6c1a32001-08-02 04:15:00 +000013706static PyObject *
13707unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
13708{
Benjamin Peterson29060642009-01-31 22:14:21 +000013709 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013710 static char *kwlist[] = {"object", "encoding", "errors", 0};
13711 char *encoding = NULL;
13712 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000013713
Benjamin Peterson14339b62009-01-31 16:36:08 +000013714 if (type != &PyUnicode_Type)
13715 return unicode_subtype_new(type, args, kwds);
13716 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +000013717 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +000013718 return NULL;
Victor Stinner382955f2011-12-11 21:44:00 +010013719 if (x == NULL) {
13720 Py_INCREF(unicode_empty);
13721 return unicode_empty;
13722 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000013723 if (encoding == NULL && errors == NULL)
13724 return PyObject_Str(x);
13725 else
Benjamin Peterson29060642009-01-31 22:14:21 +000013726 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +000013727}
13728
Guido van Rossume023fe02001-08-30 03:12:59 +000013729static PyObject *
13730unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
13731{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013732 PyObject *unicode, *self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013733 Py_ssize_t length, char_size;
13734 int share_wstr, share_utf8;
13735 unsigned int kind;
13736 void *data;
Guido van Rossume023fe02001-08-30 03:12:59 +000013737
Benjamin Peterson14339b62009-01-31 16:36:08 +000013738 assert(PyType_IsSubtype(type, &PyUnicode_Type));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013739
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013740 unicode = unicode_new(&PyUnicode_Type, args, kwds);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013741 if (unicode == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000013742 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020013743 assert(_PyUnicode_CHECK(unicode));
Victor Stinnere06e1452011-10-04 20:52:31 +020013744 if (PyUnicode_READY(unicode))
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013745 return NULL;
13746
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013747 self = type->tp_alloc(type, 0);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013748 if (self == NULL) {
13749 Py_DECREF(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013750 return NULL;
13751 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013752 kind = PyUnicode_KIND(unicode);
13753 length = PyUnicode_GET_LENGTH(unicode);
13754
13755 _PyUnicode_LENGTH(self) = length;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020013756#ifdef Py_DEBUG
13757 _PyUnicode_HASH(self) = -1;
13758#else
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013759 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020013760#endif
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013761 _PyUnicode_STATE(self).interned = 0;
13762 _PyUnicode_STATE(self).kind = kind;
13763 _PyUnicode_STATE(self).compact = 0;
Victor Stinner3cf46372011-10-03 14:42:15 +020013764 _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013765 _PyUnicode_STATE(self).ready = 1;
13766 _PyUnicode_WSTR(self) = NULL;
13767 _PyUnicode_UTF8_LENGTH(self) = 0;
13768 _PyUnicode_UTF8(self) = NULL;
13769 _PyUnicode_WSTR_LENGTH(self) = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +020013770 _PyUnicode_DATA_ANY(self) = NULL;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013771
13772 share_utf8 = 0;
13773 share_wstr = 0;
13774 if (kind == PyUnicode_1BYTE_KIND) {
13775 char_size = 1;
13776 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
13777 share_utf8 = 1;
13778 }
13779 else if (kind == PyUnicode_2BYTE_KIND) {
13780 char_size = 2;
13781 if (sizeof(wchar_t) == 2)
13782 share_wstr = 1;
13783 }
13784 else {
13785 assert(kind == PyUnicode_4BYTE_KIND);
13786 char_size = 4;
13787 if (sizeof(wchar_t) == 4)
13788 share_wstr = 1;
13789 }
13790
13791 /* Ensure we won't overflow the length. */
13792 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
13793 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013794 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013795 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013796 data = PyObject_MALLOC((length + 1) * char_size);
13797 if (data == NULL) {
13798 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013799 goto onError;
13800 }
13801
Victor Stinnerc3c74152011-10-02 20:39:55 +020013802 _PyUnicode_DATA_ANY(self) = data;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013803 if (share_utf8) {
13804 _PyUnicode_UTF8_LENGTH(self) = length;
13805 _PyUnicode_UTF8(self) = data;
13806 }
13807 if (share_wstr) {
13808 _PyUnicode_WSTR_LENGTH(self) = length;
13809 _PyUnicode_WSTR(self) = (wchar_t *)data;
13810 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013811
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013812 Py_MEMCPY(data, PyUnicode_DATA(unicode),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013813 kind * (length + 1));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013814 assert(_PyUnicode_CheckConsistency(self, 1));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020013815#ifdef Py_DEBUG
13816 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
13817#endif
Victor Stinnerdd18d3a2011-10-22 11:08:10 +020013818 Py_DECREF(unicode);
Victor Stinner7931d9a2011-11-04 00:22:48 +010013819 return self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013820
13821onError:
13822 Py_DECREF(unicode);
13823 Py_DECREF(self);
13824 return NULL;
Guido van Rossume023fe02001-08-30 03:12:59 +000013825}
13826
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013827PyDoc_STRVAR(unicode_doc,
Benjamin Peterson29060642009-01-31 22:14:21 +000013828 "str(string[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +000013829\n\
Collin Winterd474ce82007-08-07 19:42:11 +000013830Create a new string object from the given encoded string.\n\
Skip Montanaro35b37a52002-07-26 16:22:46 +000013831encoding defaults to the current default string encoding.\n\
13832errors can be 'strict', 'replace' or 'ignore' and defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +000013833
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013834static PyObject *unicode_iter(PyObject *seq);
13835
Guido van Rossumd57fd912000-03-10 22:53:23 +000013836PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000013837 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Benjamin Peterson14339b62009-01-31 16:36:08 +000013838 "str", /* tp_name */
13839 sizeof(PyUnicodeObject), /* tp_size */
13840 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013841 /* Slots */
Benjamin Peterson14339b62009-01-31 16:36:08 +000013842 (destructor)unicode_dealloc, /* tp_dealloc */
13843 0, /* tp_print */
13844 0, /* tp_getattr */
13845 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000013846 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000013847 unicode_repr, /* tp_repr */
13848 &unicode_as_number, /* tp_as_number */
13849 &unicode_as_sequence, /* tp_as_sequence */
13850 &unicode_as_mapping, /* tp_as_mapping */
13851 (hashfunc) unicode_hash, /* tp_hash*/
13852 0, /* tp_call*/
13853 (reprfunc) unicode_str, /* tp_str */
13854 PyObject_GenericGetAttr, /* tp_getattro */
13855 0, /* tp_setattro */
13856 0, /* tp_as_buffer */
13857 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Benjamin Peterson29060642009-01-31 22:14:21 +000013858 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
Benjamin Peterson14339b62009-01-31 16:36:08 +000013859 unicode_doc, /* tp_doc */
13860 0, /* tp_traverse */
13861 0, /* tp_clear */
13862 PyUnicode_RichCompare, /* tp_richcompare */
13863 0, /* tp_weaklistoffset */
13864 unicode_iter, /* tp_iter */
13865 0, /* tp_iternext */
13866 unicode_methods, /* tp_methods */
13867 0, /* tp_members */
13868 0, /* tp_getset */
13869 &PyBaseObject_Type, /* tp_base */
13870 0, /* tp_dict */
13871 0, /* tp_descr_get */
13872 0, /* tp_descr_set */
13873 0, /* tp_dictoffset */
13874 0, /* tp_init */
13875 0, /* tp_alloc */
13876 unicode_new, /* tp_new */
13877 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013878};
13879
13880/* Initialize the Unicode implementation */
13881
Victor Stinner3a50e702011-10-18 21:21:00 +020013882int _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013883{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013884 int i;
13885
Thomas Wouters477c8d52006-05-27 19:21:47 +000013886 /* XXX - move this array to unicodectype.c ? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013887 Py_UCS2 linebreak[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +000013888 0x000A, /* LINE FEED */
13889 0x000D, /* CARRIAGE RETURN */
13890 0x001C, /* FILE SEPARATOR */
13891 0x001D, /* GROUP SEPARATOR */
13892 0x001E, /* RECORD SEPARATOR */
13893 0x0085, /* NEXT LINE */
13894 0x2028, /* LINE SEPARATOR */
13895 0x2029, /* PARAGRAPH SEPARATOR */
13896 };
13897
Fred Drakee4315f52000-05-09 19:53:39 +000013898 /* Init the implementation */
Victor Stinnera464fc12011-10-02 20:39:30 +020013899 unicode_empty = PyUnicode_New(0, 0);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013900 if (!unicode_empty)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013901 Py_FatalError("Can't create empty string");
Victor Stinnerd3df8ab2011-11-22 01:22:34 +010013902 assert(_PyUnicode_CheckConsistency(unicode_empty, 1));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013903
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013904 for (i = 0; i < 256; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +000013905 unicode_latin1[i] = NULL;
Guido van Rossumcacfc072002-05-24 19:01:59 +000013906 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000013907 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +000013908
13909 /* initialize the linebreak bloom filter */
13910 bloom_linebreak = make_bloom_mask(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013911 PyUnicode_2BYTE_KIND, linebreak,
Victor Stinner63941882011-09-29 00:42:28 +020013912 Py_ARRAY_LENGTH(linebreak));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013913
13914 PyType_Ready(&EncodingMapType);
Victor Stinner3a50e702011-10-18 21:21:00 +020013915
13916#ifdef HAVE_MBCS
13917 winver.dwOSVersionInfoSize = sizeof(winver);
13918 if (!GetVersionEx((OSVERSIONINFO*)&winver)) {
13919 PyErr_SetFromWindowsErr(0);
13920 return -1;
13921 }
13922#endif
13923 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013924}
13925
13926/* Finalize the Unicode implementation */
13927
Christian Heimesa156e092008-02-16 07:38:31 +000013928int
13929PyUnicode_ClearFreeList(void)
13930{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013931 return 0;
Christian Heimesa156e092008-02-16 07:38:31 +000013932}
13933
Guido van Rossumd57fd912000-03-10 22:53:23 +000013934void
Thomas Wouters78890102000-07-22 19:25:51 +000013935_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013936{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013937 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013938
Guido van Rossum4ae8ef82000-10-03 18:09:04 +000013939 Py_XDECREF(unicode_empty);
13940 unicode_empty = NULL;
Barry Warsaw5b4c2282000-10-03 20:45:26 +000013941
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013942 for (i = 0; i < 256; i++) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013943 if (unicode_latin1[i]) {
13944 Py_DECREF(unicode_latin1[i]);
13945 unicode_latin1[i] = NULL;
13946 }
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013947 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020013948 _PyUnicode_ClearStaticStrings();
Christian Heimesa156e092008-02-16 07:38:31 +000013949 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +000013950}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000013951
Walter Dörwald16807132007-05-25 13:52:07 +000013952void
13953PyUnicode_InternInPlace(PyObject **p)
13954{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013955 register PyObject *s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013956 PyObject *t;
Victor Stinner4fae54c2011-10-03 02:01:52 +020013957#ifdef Py_DEBUG
13958 assert(s != NULL);
13959 assert(_PyUnicode_CHECK(s));
13960#else
Benjamin Peterson14339b62009-01-31 16:36:08 +000013961 if (s == NULL || !PyUnicode_Check(s))
Victor Stinner4fae54c2011-10-03 02:01:52 +020013962 return;
13963#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000013964 /* If it's a subclass, we don't really know what putting
13965 it in the interned dict might do. */
13966 if (!PyUnicode_CheckExact(s))
13967 return;
13968 if (PyUnicode_CHECK_INTERNED(s))
13969 return;
13970 if (interned == NULL) {
13971 interned = PyDict_New();
13972 if (interned == NULL) {
13973 PyErr_Clear(); /* Don't leave an exception */
13974 return;
13975 }
13976 }
13977 /* It might be that the GetItem call fails even
13978 though the key is present in the dictionary,
13979 namely when this happens during a stack overflow. */
13980 Py_ALLOW_RECURSION
Victor Stinner7931d9a2011-11-04 00:22:48 +010013981 t = PyDict_GetItem(interned, s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013982 Py_END_ALLOW_RECURSION
Martin v. Löwis5b222132007-06-10 09:51:05 +000013983
Benjamin Peterson29060642009-01-31 22:14:21 +000013984 if (t) {
13985 Py_INCREF(t);
13986 Py_DECREF(*p);
13987 *p = t;
13988 return;
13989 }
Walter Dörwald16807132007-05-25 13:52:07 +000013990
Benjamin Peterson14339b62009-01-31 16:36:08 +000013991 PyThreadState_GET()->recursion_critical = 1;
Victor Stinner7931d9a2011-11-04 00:22:48 +010013992 if (PyDict_SetItem(interned, s, s) < 0) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013993 PyErr_Clear();
13994 PyThreadState_GET()->recursion_critical = 0;
13995 return;
13996 }
13997 PyThreadState_GET()->recursion_critical = 0;
13998 /* The two references in interned are not counted by refcnt.
13999 The deallocator will take care of this */
14000 Py_REFCNT(s) -= 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014001 _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000014002}
14003
14004void
14005PyUnicode_InternImmortal(PyObject **p)
14006{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014007 PyUnicode_InternInPlace(p);
14008 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
Victor Stinneraf9e4b82011-10-23 20:07:00 +020014009 _PyUnicode_STATE(*p).interned = SSTATE_INTERNED_IMMORTAL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014010 Py_INCREF(*p);
14011 }
Walter Dörwald16807132007-05-25 13:52:07 +000014012}
14013
14014PyObject *
14015PyUnicode_InternFromString(const char *cp)
14016{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014017 PyObject *s = PyUnicode_FromString(cp);
14018 if (s == NULL)
14019 return NULL;
14020 PyUnicode_InternInPlace(&s);
14021 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000014022}
14023
Alexander Belopolsky40018472011-02-26 01:02:56 +000014024void
14025_Py_ReleaseInternedUnicodeStrings(void)
Walter Dörwald16807132007-05-25 13:52:07 +000014026{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014027 PyObject *keys;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014028 PyObject *s;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014029 Py_ssize_t i, n;
14030 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000014031
Benjamin Peterson14339b62009-01-31 16:36:08 +000014032 if (interned == NULL || !PyDict_Check(interned))
14033 return;
14034 keys = PyDict_Keys(interned);
14035 if (keys == NULL || !PyList_Check(keys)) {
14036 PyErr_Clear();
14037 return;
14038 }
Walter Dörwald16807132007-05-25 13:52:07 +000014039
Benjamin Peterson14339b62009-01-31 16:36:08 +000014040 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
14041 detector, interned unicode strings are not forcibly deallocated;
14042 rather, we give them their stolen references back, and then clear
14043 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000014044
Benjamin Peterson14339b62009-01-31 16:36:08 +000014045 n = PyList_GET_SIZE(keys);
14046 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000014047 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014048 for (i = 0; i < n; i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014049 s = PyList_GET_ITEM(keys, i);
Victor Stinner6b56a7f2011-10-04 20:04:52 +020014050 if (PyUnicode_READY(s) == -1) {
14051 assert(0 && "could not ready string");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014052 fprintf(stderr, "could not ready string\n");
Victor Stinner6b56a7f2011-10-04 20:04:52 +020014053 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014054 switch (PyUnicode_CHECK_INTERNED(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014055 case SSTATE_NOT_INTERNED:
14056 /* XXX Shouldn't happen */
14057 break;
14058 case SSTATE_INTERNED_IMMORTAL:
14059 Py_REFCNT(s) += 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014060 immortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014061 break;
14062 case SSTATE_INTERNED_MORTAL:
14063 Py_REFCNT(s) += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014064 mortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014065 break;
14066 default:
14067 Py_FatalError("Inconsistent interned string state.");
14068 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014069 _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014070 }
14071 fprintf(stderr, "total size of all interned strings: "
14072 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
14073 "mortal/immortal\n", mortal_size, immortal_size);
14074 Py_DECREF(keys);
14075 PyDict_Clear(interned);
14076 Py_DECREF(interned);
14077 interned = NULL;
Walter Dörwald16807132007-05-25 13:52:07 +000014078}
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014079
14080
14081/********************* Unicode Iterator **************************/
14082
14083typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014084 PyObject_HEAD
14085 Py_ssize_t it_index;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014086 PyObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014087} unicodeiterobject;
14088
14089static void
14090unicodeiter_dealloc(unicodeiterobject *it)
14091{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014092 _PyObject_GC_UNTRACK(it);
14093 Py_XDECREF(it->it_seq);
14094 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014095}
14096
14097static int
14098unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
14099{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014100 Py_VISIT(it->it_seq);
14101 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014102}
14103
14104static PyObject *
14105unicodeiter_next(unicodeiterobject *it)
14106{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014107 PyObject *seq, *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014108
Benjamin Peterson14339b62009-01-31 16:36:08 +000014109 assert(it != NULL);
14110 seq = it->it_seq;
14111 if (seq == NULL)
14112 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020014113 assert(_PyUnicode_CHECK(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014114
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014115 if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
14116 int kind = PyUnicode_KIND(seq);
14117 void *data = PyUnicode_DATA(seq);
14118 Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
14119 item = PyUnicode_FromOrdinal(chr);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014120 if (item != NULL)
14121 ++it->it_index;
14122 return item;
14123 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014124
Benjamin Peterson14339b62009-01-31 16:36:08 +000014125 Py_DECREF(seq);
14126 it->it_seq = NULL;
14127 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014128}
14129
14130static PyObject *
14131unicodeiter_len(unicodeiterobject *it)
14132{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014133 Py_ssize_t len = 0;
14134 if (it->it_seq)
Victor Stinnerc4f281e2011-10-11 22:11:42 +020014135 len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014136 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014137}
14138
14139PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
14140
14141static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014142 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000014143 length_hint_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000014144 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014145};
14146
14147PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014148 PyVarObject_HEAD_INIT(&PyType_Type, 0)
14149 "str_iterator", /* tp_name */
14150 sizeof(unicodeiterobject), /* tp_basicsize */
14151 0, /* tp_itemsize */
14152 /* methods */
14153 (destructor)unicodeiter_dealloc, /* tp_dealloc */
14154 0, /* tp_print */
14155 0, /* tp_getattr */
14156 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000014157 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014158 0, /* tp_repr */
14159 0, /* tp_as_number */
14160 0, /* tp_as_sequence */
14161 0, /* tp_as_mapping */
14162 0, /* tp_hash */
14163 0, /* tp_call */
14164 0, /* tp_str */
14165 PyObject_GenericGetAttr, /* tp_getattro */
14166 0, /* tp_setattro */
14167 0, /* tp_as_buffer */
14168 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
14169 0, /* tp_doc */
14170 (traverseproc)unicodeiter_traverse, /* tp_traverse */
14171 0, /* tp_clear */
14172 0, /* tp_richcompare */
14173 0, /* tp_weaklistoffset */
14174 PyObject_SelfIter, /* tp_iter */
14175 (iternextfunc)unicodeiter_next, /* tp_iternext */
14176 unicodeiter_methods, /* tp_methods */
14177 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014178};
14179
14180static PyObject *
14181unicode_iter(PyObject *seq)
14182{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014183 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014184
Benjamin Peterson14339b62009-01-31 16:36:08 +000014185 if (!PyUnicode_Check(seq)) {
14186 PyErr_BadInternalCall();
14187 return NULL;
14188 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014189 if (PyUnicode_READY(seq) == -1)
14190 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014191 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
14192 if (it == NULL)
14193 return NULL;
14194 it->it_index = 0;
14195 Py_INCREF(seq);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014196 it->it_seq = seq;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014197 _PyObject_GC_TRACK(it);
14198 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014199}
14200
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010014201
14202size_t
14203Py_UNICODE_strlen(const Py_UNICODE *u)
14204{
14205 int res = 0;
14206 while(*u++)
14207 res++;
14208 return res;
14209}
14210
14211Py_UNICODE*
14212Py_UNICODE_strcpy(Py_UNICODE *s1, const Py_UNICODE *s2)
14213{
14214 Py_UNICODE *u = s1;
14215 while ((*u++ = *s2++));
14216 return s1;
14217}
14218
14219Py_UNICODE*
14220Py_UNICODE_strncpy(Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
14221{
14222 Py_UNICODE *u = s1;
14223 while ((*u++ = *s2++))
14224 if (n-- == 0)
14225 break;
14226 return s1;
14227}
14228
14229Py_UNICODE*
14230Py_UNICODE_strcat(Py_UNICODE *s1, const Py_UNICODE *s2)
14231{
14232 Py_UNICODE *u1 = s1;
14233 u1 += Py_UNICODE_strlen(u1);
14234 Py_UNICODE_strcpy(u1, s2);
14235 return s1;
14236}
14237
14238int
14239Py_UNICODE_strcmp(const Py_UNICODE *s1, const Py_UNICODE *s2)
14240{
14241 while (*s1 && *s2 && *s1 == *s2)
14242 s1++, s2++;
14243 if (*s1 && *s2)
14244 return (*s1 < *s2) ? -1 : +1;
14245 if (*s1)
14246 return 1;
14247 if (*s2)
14248 return -1;
14249 return 0;
14250}
14251
14252int
14253Py_UNICODE_strncmp(const Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
14254{
14255 register Py_UNICODE u1, u2;
14256 for (; n != 0; n--) {
14257 u1 = *s1;
14258 u2 = *s2;
14259 if (u1 != u2)
14260 return (u1 < u2) ? -1 : +1;
14261 if (u1 == '\0')
14262 return 0;
14263 s1++;
14264 s2++;
14265 }
14266 return 0;
14267}
14268
14269Py_UNICODE*
14270Py_UNICODE_strchr(const Py_UNICODE *s, Py_UNICODE c)
14271{
14272 const Py_UNICODE *p;
14273 for (p = s; *p; p++)
14274 if (*p == c)
14275 return (Py_UNICODE*)p;
14276 return NULL;
14277}
14278
14279Py_UNICODE*
14280Py_UNICODE_strrchr(const Py_UNICODE *s, Py_UNICODE c)
14281{
14282 const Py_UNICODE *p;
14283 p = s + Py_UNICODE_strlen(s);
14284 while (p != s) {
14285 p--;
14286 if (*p == c)
14287 return (Py_UNICODE*)p;
14288 }
14289 return NULL;
14290}
Victor Stinner331ea922010-08-10 16:37:20 +000014291
Victor Stinner71133ff2010-09-01 23:43:53 +000014292Py_UNICODE*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014293PyUnicode_AsUnicodeCopy(PyObject *unicode)
Victor Stinner71133ff2010-09-01 23:43:53 +000014294{
Victor Stinner577db2c2011-10-11 22:12:48 +020014295 Py_UNICODE *u, *copy;
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014296 Py_ssize_t len, size;
Victor Stinner71133ff2010-09-01 23:43:53 +000014297
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014298 if (!PyUnicode_Check(unicode)) {
14299 PyErr_BadArgument();
14300 return NULL;
14301 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014302 u = PyUnicode_AsUnicodeAndSize(unicode, &len);
Victor Stinner577db2c2011-10-11 22:12:48 +020014303 if (u == NULL)
14304 return NULL;
Victor Stinner71133ff2010-09-01 23:43:53 +000014305 /* Ensure we won't overflow the size. */
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014306 if (len > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
Victor Stinner71133ff2010-09-01 23:43:53 +000014307 PyErr_NoMemory();
14308 return NULL;
14309 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014310 size = len + 1; /* copy the null character */
Victor Stinner71133ff2010-09-01 23:43:53 +000014311 size *= sizeof(Py_UNICODE);
14312 copy = PyMem_Malloc(size);
14313 if (copy == NULL) {
14314 PyErr_NoMemory();
14315 return NULL;
14316 }
Victor Stinner577db2c2011-10-11 22:12:48 +020014317 memcpy(copy, u, size);
Victor Stinner71133ff2010-09-01 23:43:53 +000014318 return copy;
14319}
Martin v. Löwis5b222132007-06-10 09:51:05 +000014320
Georg Brandl66c221e2010-10-14 07:04:07 +000014321/* A _string module, to export formatter_parser and formatter_field_name_split
14322 to the string.Formatter class implemented in Python. */
14323
14324static PyMethodDef _string_methods[] = {
14325 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
14326 METH_O, PyDoc_STR("split the argument as a field name")},
14327 {"formatter_parser", (PyCFunction) formatter_parser,
14328 METH_O, PyDoc_STR("parse the argument as a format string")},
14329 {NULL, NULL}
14330};
14331
14332static struct PyModuleDef _string_module = {
14333 PyModuleDef_HEAD_INIT,
14334 "_string",
14335 PyDoc_STR("string helper module"),
14336 0,
14337 _string_methods,
14338 NULL,
14339 NULL,
14340 NULL,
14341 NULL
14342};
14343
14344PyMODINIT_FUNC
14345PyInit__string(void)
14346{
14347 return PyModule_Create(&_string_module);
14348}
14349
14350
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000014351#ifdef __cplusplus
14352}
14353#endif