blob: 46578128bf92a62211654d53ab72f2b1ac984dcf [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/* Limit for the Unicode object free list */
50
Christian Heimes2202f872008-02-06 14:31:34 +000051#define PyUnicode_MAXFREELIST 1024
Guido van Rossumd57fd912000-03-10 22:53:23 +000052
53/* Limit for the Unicode object free list stay alive optimization.
54
55 The implementation will keep allocated Unicode memory intact for
56 all objects on the free list having a size less than this
Tim Petersced69f82003-09-16 20:30:58 +000057 limit. This reduces malloc() overhead for small Unicode objects.
Guido van Rossumd57fd912000-03-10 22:53:23 +000058
Christian Heimes2202f872008-02-06 14:31:34 +000059 At worst this will result in PyUnicode_MAXFREELIST *
Guido van Rossumfd4b9572000-04-10 13:51:10 +000060 (sizeof(PyUnicodeObject) + KEEPALIVE_SIZE_LIMIT +
Guido van Rossumd57fd912000-03-10 22:53:23 +000061 malloc()-overhead) bytes of unused garbage.
62
63 Setting the limit to 0 effectively turns the feature off.
64
Guido van Rossumfd4b9572000-04-10 13:51:10 +000065 Note: This is an experimental feature ! If you get core dumps when
66 using Unicode objects, turn this feature off.
Guido van Rossumd57fd912000-03-10 22:53:23 +000067
68*/
69
Guido van Rossumfd4b9572000-04-10 13:51:10 +000070#define KEEPALIVE_SIZE_LIMIT 9
Guido van Rossumd57fd912000-03-10 22:53:23 +000071
72/* Endianness switches; defaults to little endian */
73
74#ifdef WORDS_BIGENDIAN
75# define BYTEORDER_IS_BIG_ENDIAN
76#else
77# define BYTEORDER_IS_LITTLE_ENDIAN
78#endif
79
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000080/* --- Globals ------------------------------------------------------------
81
82 The globals are initialized by the _PyUnicode_Init() API and should
83 not be used before calling that API.
84
85*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000086
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000087
88#ifdef __cplusplus
89extern "C" {
90#endif
91
Victor Stinner910337b2011-10-03 03:20:16 +020092#ifdef Py_DEBUG
93# define _PyUnicode_CHECK(op) _PyUnicode_CheckConsistency(op)
94#else
95# define _PyUnicode_CHECK(op) PyUnicode_Check(op)
96#endif
Victor Stinnerfb5f5f22011-09-28 21:39:49 +020097
Victor Stinnere90fe6a2011-10-01 16:48:13 +020098#define _PyUnicode_UTF8(op) \
99 (((PyCompactUnicodeObject*)(op))->utf8)
100#define PyUnicode_UTF8(op) \
Victor Stinner910337b2011-10-03 03:20:16 +0200101 (assert(_PyUnicode_CHECK(op)), \
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200102 assert(PyUnicode_IS_READY(op)), \
103 PyUnicode_IS_COMPACT_ASCII(op) ? \
104 ((char*)((PyASCIIObject*)(op) + 1)) : \
105 _PyUnicode_UTF8(op))
Victor Stinnerbc8b81b2011-09-29 19:31:34 +0200106#define _PyUnicode_UTF8_LENGTH(op) \
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200107 (((PyCompactUnicodeObject*)(op))->utf8_length)
108#define PyUnicode_UTF8_LENGTH(op) \
Victor Stinner910337b2011-10-03 03:20:16 +0200109 (assert(_PyUnicode_CHECK(op)), \
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200110 assert(PyUnicode_IS_READY(op)), \
111 PyUnicode_IS_COMPACT_ASCII(op) ? \
112 ((PyASCIIObject*)(op))->length : \
113 _PyUnicode_UTF8_LENGTH(op))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200114#define _PyUnicode_WSTR(op) (((PyASCIIObject*)(op))->wstr)
115#define _PyUnicode_WSTR_LENGTH(op) (((PyCompactUnicodeObject*)(op))->wstr_length)
116#define _PyUnicode_LENGTH(op) (((PyASCIIObject *)(op))->length)
117#define _PyUnicode_STATE(op) (((PyASCIIObject *)(op))->state)
118#define _PyUnicode_HASH(op) (((PyASCIIObject *)(op))->hash)
Victor Stinner910337b2011-10-03 03:20:16 +0200119#define _PyUnicode_KIND(op) \
120 (assert(_PyUnicode_CHECK(op)), \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200121 ((PyASCIIObject *)(op))->state.kind)
Victor Stinner910337b2011-10-03 03:20:16 +0200122#define _PyUnicode_GET_LENGTH(op) \
123 (assert(_PyUnicode_CHECK(op)), \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200124 ((PyASCIIObject *)(op))->length)
Victor Stinnerc3c74152011-10-02 20:39:55 +0200125#define _PyUnicode_DATA_ANY(op) (((PyUnicodeObject*)(op))->data.any)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200126
Victor Stinner910337b2011-10-03 03:20:16 +0200127#undef PyUnicode_READY
128#define PyUnicode_READY(op) \
129 (assert(_PyUnicode_CHECK(op)), \
130 (PyUnicode_IS_READY(op) ? \
131 0 : _PyUnicode_Ready((PyObject *)(op))))
132
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200133#define _PyUnicode_READY_REPLACE(p_obj) \
134 (assert(_PyUnicode_CHECK(*p_obj)), \
135 (PyUnicode_IS_READY(*p_obj) ? \
136 0 : _PyUnicode_ReadyReplace((PyObject **)(p_obj))))
137
Victor Stinnerc379ead2011-10-03 12:52:27 +0200138#define _PyUnicode_SHARE_UTF8(op) \
139 (assert(_PyUnicode_CHECK(op)), \
140 assert(!PyUnicode_IS_COMPACT_ASCII(op)), \
141 (_PyUnicode_UTF8(op) == PyUnicode_DATA(op)))
142#define _PyUnicode_SHARE_WSTR(op) \
143 (assert(_PyUnicode_CHECK(op)), \
144 (_PyUnicode_WSTR(unicode) == PyUnicode_DATA(op)))
145
Victor Stinner829c0ad2011-10-03 01:08:02 +0200146/* true if the Unicode object has an allocated UTF-8 memory block
147 (not shared with other data) */
Victor Stinner910337b2011-10-03 03:20:16 +0200148#define _PyUnicode_HAS_UTF8_MEMORY(op) \
149 (assert(_PyUnicode_CHECK(op)), \
150 (!PyUnicode_IS_COMPACT_ASCII(op) \
151 && _PyUnicode_UTF8(op) \
Victor Stinner829c0ad2011-10-03 01:08:02 +0200152 && _PyUnicode_UTF8(op) != PyUnicode_DATA(op)))
153
Victor Stinner03490912011-10-03 23:45:12 +0200154/* true if the Unicode object has an allocated wstr memory block
155 (not shared with other data) */
156#define _PyUnicode_HAS_WSTR_MEMORY(op) \
157 (assert(_PyUnicode_CHECK(op)), \
158 (_PyUnicode_WSTR(op) && \
159 (!PyUnicode_IS_READY(op) || \
160 _PyUnicode_WSTR(op) != PyUnicode_DATA(op))))
161
Victor Stinner910337b2011-10-03 03:20:16 +0200162/* Generic helper macro to convert characters of different types.
163 from_type and to_type have to be valid type names, begin and end
164 are pointers to the source characters which should be of type
165 "from_type *". to is a pointer of type "to_type *" and points to the
166 buffer where the result characters are written to. */
167#define _PyUnicode_CONVERT_BYTES(from_type, to_type, begin, end, to) \
168 do { \
169 const from_type *iter_; to_type *to_; \
170 for (iter_ = (begin), to_ = (to_type *)(to); \
171 iter_ < (end); \
172 ++iter_, ++to_) { \
173 *to_ = (to_type)*iter_; \
174 } \
175 } while (0)
Victor Stinner829c0ad2011-10-03 01:08:02 +0200176
Victor Stinnerb15d4d82011-09-28 23:59:20 +0200177/* The Unicode string has been modified: reset the hash */
178#define _PyUnicode_DIRTY(op) do { _PyUnicode_HASH(op) = -1; } while (0)
179
Walter Dörwald16807132007-05-25 13:52:07 +0000180/* This dictionary holds all interned unicode strings. Note that references
181 to strings in this dictionary are *not* counted in the string's ob_refcnt.
182 When the interned string reaches a refcnt of 0 the string deallocation
183 function will delete the reference from this dictionary.
184
185 Another way to look at this is that to say that the actual reference
Guido van Rossum98297ee2007-11-06 21:34:58 +0000186 count of a string is: s->ob_refcnt + (s->state ? 2 : 0)
Walter Dörwald16807132007-05-25 13:52:07 +0000187*/
188static PyObject *interned;
189
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000190/* The empty Unicode object is shared to improve performance. */
Victor Stinnera464fc12011-10-02 20:39:30 +0200191static PyObject *unicode_empty;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000192
193/* Single character Unicode strings in the Latin-1 range are being
194 shared as well. */
Victor Stinnera464fc12011-10-02 20:39:30 +0200195static PyObject *unicode_latin1[256];
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000196
Christian Heimes190d79e2008-01-30 11:58:22 +0000197/* Fast detection of the most frequent whitespace characters */
198const unsigned char _Py_ascii_whitespace[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000199 0, 0, 0, 0, 0, 0, 0, 0,
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000200/* case 0x0009: * CHARACTER TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000201/* case 0x000A: * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000202/* case 0x000B: * LINE TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000203/* case 0x000C: * FORM FEED */
204/* case 0x000D: * CARRIAGE RETURN */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000205 0, 1, 1, 1, 1, 1, 0, 0,
206 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000207/* case 0x001C: * FILE SEPARATOR */
208/* case 0x001D: * GROUP SEPARATOR */
209/* case 0x001E: * RECORD SEPARATOR */
210/* case 0x001F: * UNIT SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000211 0, 0, 0, 0, 1, 1, 1, 1,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000212/* case 0x0020: * SPACE */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000213 1, 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
Benjamin Peterson14339b62009-01-31 16:36:08 +0000218 0, 0, 0, 0, 0, 0, 0, 0,
219 0, 0, 0, 0, 0, 0, 0, 0,
220 0, 0, 0, 0, 0, 0, 0, 0,
221 0, 0, 0, 0, 0, 0, 0, 0,
222 0, 0, 0, 0, 0, 0, 0, 0,
223 0, 0, 0, 0, 0, 0, 0, 0,
224 0, 0, 0, 0, 0, 0, 0, 0,
225 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000226};
227
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200228/* forward */
Victor Stinnerfe226c02011-10-03 03:52:20 +0200229static PyUnicodeObject *_PyUnicode_New(Py_ssize_t length);
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200230static PyObject* get_latin1_char(unsigned char ch);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200231
Alexander Belopolsky40018472011-02-26 01:02:56 +0000232static PyObject *
233unicode_encode_call_errorhandler(const char *errors,
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000234 PyObject **errorHandler,const char *encoding, const char *reason,
235 const Py_UNICODE *unicode, Py_ssize_t size, PyObject **exceptionObject,
236 Py_ssize_t startpos, Py_ssize_t endpos, Py_ssize_t *newpos);
237
Alexander Belopolsky40018472011-02-26 01:02:56 +0000238static void
239raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +0300240 const char *encoding,
241 const Py_UNICODE *unicode, Py_ssize_t size,
242 Py_ssize_t startpos, Py_ssize_t endpos,
243 const char *reason);
Victor Stinner31be90b2010-04-22 19:38:16 +0000244
Christian Heimes190d79e2008-01-30 11:58:22 +0000245/* Same for linebreaks */
246static unsigned char ascii_linebreak[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000247 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000248/* 0x000A, * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000249/* 0x000B, * LINE TABULATION */
250/* 0x000C, * FORM FEED */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000251/* 0x000D, * CARRIAGE RETURN */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000252 0, 0, 1, 1, 1, 1, 0, 0,
Benjamin Peterson14339b62009-01-31 16:36:08 +0000253 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000254/* 0x001C, * FILE SEPARATOR */
255/* 0x001D, * GROUP SEPARATOR */
256/* 0x001E, * RECORD SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000257 0, 0, 0, 0, 1, 1, 1, 0,
258 0, 0, 0, 0, 0, 0, 0, 0,
259 0, 0, 0, 0, 0, 0, 0, 0,
260 0, 0, 0, 0, 0, 0, 0, 0,
261 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes190d79e2008-01-30 11:58:22 +0000262
Benjamin Peterson14339b62009-01-31 16:36:08 +0000263 0, 0, 0, 0, 0, 0, 0, 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,
268 0, 0, 0, 0, 0, 0, 0, 0,
269 0, 0, 0, 0, 0, 0, 0, 0,
270 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000271};
272
Ezio Melotti48a2f8f2011-09-29 00:18:19 +0300273/* The max unicode value is always 0x10FFFF while using the PEP-393 API.
274 This function is kept for backward compatibility with the old API. */
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000275Py_UNICODE
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +0000276PyUnicode_GetMax(void)
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000277{
Fredrik Lundh8f455852001-06-27 18:59:43 +0000278#ifdef Py_UNICODE_WIDE
Benjamin Peterson14339b62009-01-31 16:36:08 +0000279 return 0x10FFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000280#else
Benjamin Peterson14339b62009-01-31 16:36:08 +0000281 /* This is actually an illegal character, so it should
282 not be passed to unichr. */
283 return 0xFFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000284#endif
285}
286
Victor Stinner910337b2011-10-03 03:20:16 +0200287#ifdef Py_DEBUG
288static int
289_PyUnicode_CheckConsistency(void *op)
290{
291 PyASCIIObject *ascii;
292 unsigned int kind;
293
294 assert(PyUnicode_Check(op));
295
296 ascii = (PyASCIIObject *)op;
297 kind = ascii->state.kind;
298
Victor Stinnera3b334d2011-10-03 13:53:37 +0200299 if (ascii->state.ascii == 1 && ascii->state.compact == 1) {
Victor Stinner910337b2011-10-03 03:20:16 +0200300 assert(kind == PyUnicode_1BYTE_KIND);
Victor Stinner910337b2011-10-03 03:20:16 +0200301 assert(ascii->state.ready == 1);
302 }
303 else if (ascii->state.compact == 1) {
Victor Stinner85041a52011-10-03 14:42:39 +0200304 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
Victor Stinner7f11ad42011-10-04 00:00:20 +0200305 void *data;
Victor Stinner910337b2011-10-03 03:20:16 +0200306 assert(kind == PyUnicode_1BYTE_KIND
307 || kind == PyUnicode_2BYTE_KIND
308 || kind == PyUnicode_4BYTE_KIND);
Victor Stinner910337b2011-10-03 03:20:16 +0200309 assert(ascii->state.ascii == 0);
310 assert(ascii->state.ready == 1);
Victor Stinner7f11ad42011-10-04 00:00:20 +0200311 data = compact + 1;
312 assert (compact->utf8 != data);
313 if (
314#if SIZEOF_WCHAR_T == 2
315 kind == PyUnicode_2BYTE_KIND
316#else
317 kind == PyUnicode_4BYTE_KIND
318#endif
319 )
320 assert(ascii->wstr == data);
321 else
322 assert(ascii->wstr != data);
Victor Stinner910337b2011-10-03 03:20:16 +0200323 } else {
324 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
325 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
326
327 if (kind == PyUnicode_WCHAR_KIND) {
Victor Stinnera3b334d2011-10-03 13:53:37 +0200328 assert(ascii->state.compact == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200329 assert(ascii->state.ascii == 0);
Victor Stinnera3b334d2011-10-03 13:53:37 +0200330 assert(ascii->state.ready == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200331 assert(ascii->wstr != NULL);
332 assert(unicode->data.any == NULL);
333 assert(compact->utf8 == NULL);
334 assert(ascii->state.interned == SSTATE_NOT_INTERNED);
335 }
336 else {
337 assert(kind == PyUnicode_1BYTE_KIND
338 || kind == PyUnicode_2BYTE_KIND
339 || kind == PyUnicode_4BYTE_KIND);
Victor Stinnera3b334d2011-10-03 13:53:37 +0200340 assert(ascii->state.compact == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200341 assert(ascii->state.ready == 1);
342 assert(unicode->data.any != NULL);
Victor Stinner85041a52011-10-03 14:42:39 +0200343 if (ascii->state.ascii)
344 assert (compact->utf8 == unicode->data.any);
345 else
346 assert (compact->utf8 != unicode->data.any);
Victor Stinner7f11ad42011-10-04 00:00:20 +0200347 if (
348#if SIZEOF_WCHAR_T == 2
349 kind == PyUnicode_2BYTE_KIND
350#else
351 kind == PyUnicode_4BYTE_KIND
352#endif
353 )
354 assert(ascii->wstr == unicode->data.any);
355 else
356 assert(ascii->wstr != unicode->data.any);
Victor Stinner910337b2011-10-03 03:20:16 +0200357 }
358 }
359 return 1;
360}
361#endif
362
Thomas Wouters477c8d52006-05-27 19:21:47 +0000363/* --- Bloom Filters ----------------------------------------------------- */
364
365/* stuff to implement simple "bloom filters" for Unicode characters.
366 to keep things simple, we use a single bitmask, using the least 5
367 bits from each unicode characters as the bit index. */
368
369/* the linebreak mask is set up by Unicode_Init below */
370
Antoine Pitrouf068f942010-01-13 14:19:12 +0000371#if LONG_BIT >= 128
372#define BLOOM_WIDTH 128
373#elif LONG_BIT >= 64
374#define BLOOM_WIDTH 64
375#elif LONG_BIT >= 32
376#define BLOOM_WIDTH 32
377#else
378#error "LONG_BIT is smaller than 32"
379#endif
380
Thomas Wouters477c8d52006-05-27 19:21:47 +0000381#define BLOOM_MASK unsigned long
382
383static BLOOM_MASK bloom_linebreak;
384
Antoine Pitrouf068f942010-01-13 14:19:12 +0000385#define BLOOM_ADD(mask, ch) ((mask |= (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
386#define BLOOM(mask, ch) ((mask & (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000387
Benjamin Peterson29060642009-01-31 22:14:21 +0000388#define BLOOM_LINEBREAK(ch) \
389 ((ch) < 128U ? ascii_linebreak[(ch)] : \
390 (BLOOM(bloom_linebreak, (ch)) && Py_UNICODE_ISLINEBREAK(ch)))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000391
Alexander Belopolsky40018472011-02-26 01:02:56 +0000392Py_LOCAL_INLINE(BLOOM_MASK)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200393make_bloom_mask(int kind, void* ptr, Py_ssize_t len)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000394{
395 /* calculate simple bloom-style bitmask for a given unicode string */
396
Antoine Pitrouf068f942010-01-13 14:19:12 +0000397 BLOOM_MASK mask;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000398 Py_ssize_t i;
399
400 mask = 0;
401 for (i = 0; i < len; i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200402 BLOOM_ADD(mask, PyUnicode_READ(kind, ptr, i));
Thomas Wouters477c8d52006-05-27 19:21:47 +0000403
404 return mask;
405}
406
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200407#define BLOOM_MEMBER(mask, chr, str) \
408 (BLOOM(mask, chr) \
409 && (PyUnicode_FindChar(str, chr, 0, PyUnicode_GET_LENGTH(str), 1) >= 0))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000410
Guido van Rossumd57fd912000-03-10 22:53:23 +0000411/* --- Unicode Object ----------------------------------------------------- */
412
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200413static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200414fixup(PyUnicodeObject *self, Py_UCS4 (*fixfct)(PyUnicodeObject *s));
415
416Py_LOCAL_INLINE(char *) findchar(void *s, int kind,
417 Py_ssize_t size, Py_UCS4 ch,
418 int direction)
419{
420 /* like wcschr, but doesn't stop at NULL characters */
421 Py_ssize_t i;
422 if (direction == 1) {
423 for(i = 0; i < size; i++)
424 if (PyUnicode_READ(kind, s, i) == ch)
425 return (char*)s + PyUnicode_KIND_SIZE(kind, i);
426 }
427 else {
428 for(i = size-1; i >= 0; i--)
429 if (PyUnicode_READ(kind, s, i) == ch)
430 return (char*)s + PyUnicode_KIND_SIZE(kind, i);
431 }
432 return NULL;
433}
434
Victor Stinnerfe226c02011-10-03 03:52:20 +0200435static PyObject*
436resize_compact(PyObject *unicode, Py_ssize_t length)
437{
438 Py_ssize_t char_size;
439 Py_ssize_t struct_size;
440 Py_ssize_t new_size;
441 int share_wstr;
442
443 assert(PyUnicode_IS_READY(unicode));
444 char_size = PyUnicode_CHARACTER_SIZE(unicode);
445 if (PyUnicode_IS_COMPACT_ASCII(unicode))
446 struct_size = sizeof(PyASCIIObject);
447 else
448 struct_size = sizeof(PyCompactUnicodeObject);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200449 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200450
451 _Py_DEC_REFTOTAL;
452 _Py_ForgetReference(unicode);
453
454 if (length > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1)) {
455 PyErr_NoMemory();
456 return NULL;
457 }
458 new_size = (struct_size + (length + 1) * char_size);
459
460 unicode = (PyObject *)PyObject_REALLOC((char *)unicode, new_size);
461 if (unicode == NULL) {
462 PyObject_Del(unicode);
463 PyErr_NoMemory();
464 return NULL;
465 }
466 _Py_NewReference(unicode);
467 _PyUnicode_LENGTH(unicode) = length;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200468 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200469 _PyUnicode_WSTR(unicode) = PyUnicode_DATA(unicode);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200470 if (!PyUnicode_IS_COMPACT_ASCII(unicode))
471 _PyUnicode_WSTR_LENGTH(unicode) = length;
472 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200473 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
474 length, 0);
475 return unicode;
476}
477
Alexander Belopolsky40018472011-02-26 01:02:56 +0000478static int
Victor Stinnerfe226c02011-10-03 03:52:20 +0200479resize_inplace(register PyUnicodeObject *unicode, Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000480{
481 void *oldstr;
Tim Petersced69f82003-09-16 20:30:58 +0000482
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200483 assert(!PyUnicode_IS_COMPACT(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200484
Victor Stinnerfe226c02011-10-03 03:52:20 +0200485 assert(Py_REFCNT(unicode) == 1);
Victor Stinnerb15d4d82011-09-28 23:59:20 +0200486 _PyUnicode_DIRTY(unicode);
Tim Petersced69f82003-09-16 20:30:58 +0000487
Victor Stinnerfe226c02011-10-03 03:52:20 +0200488 if (_PyUnicode_HAS_UTF8_MEMORY(unicode))
489 {
490 PyObject_DEL(_PyUnicode_UTF8(unicode));
491 _PyUnicode_UTF8(unicode) = NULL;
492 }
493
494 if (PyUnicode_IS_READY(unicode)) {
495 Py_ssize_t char_size;
496 Py_ssize_t new_size;
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200497 int share_wstr, share_utf8;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200498 void *data;
499
500 data = _PyUnicode_DATA_ANY(unicode);
501 assert(data != NULL);
502 char_size = PyUnicode_CHARACTER_SIZE(unicode);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200503 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
504 share_utf8 = _PyUnicode_SHARE_UTF8(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200505
506 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
507 PyErr_NoMemory();
508 return -1;
509 }
510 new_size = (length + 1) * char_size;
511
512 data = (PyObject *)PyObject_REALLOC(data, new_size);
513 if (data == NULL) {
514 PyErr_NoMemory();
515 return -1;
516 }
517 _PyUnicode_DATA_ANY(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200518 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200519 _PyUnicode_WSTR(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200520 _PyUnicode_WSTR_LENGTH(unicode) = length;
521 }
522 if (share_utf8) {
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200523 _PyUnicode_UTF8(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200524 _PyUnicode_UTF8_LENGTH(unicode) = length;
525 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200526 _PyUnicode_LENGTH(unicode) = length;
527 PyUnicode_WRITE(PyUnicode_KIND(unicode), data, length, 0);
528 if (share_wstr)
529 return 0;
530 }
531 if (_PyUnicode_WSTR(unicode) != NULL) {
532 assert(_PyUnicode_WSTR(unicode) != NULL);
533
534 oldstr = _PyUnicode_WSTR(unicode);
535 _PyUnicode_WSTR(unicode) = PyObject_REALLOC(_PyUnicode_WSTR(unicode),
536 sizeof(Py_UNICODE) * (length + 1));
537 if (!_PyUnicode_WSTR(unicode)) {
538 _PyUnicode_WSTR(unicode) = (Py_UNICODE *)oldstr;
539 PyErr_NoMemory();
540 return -1;
541 }
542 _PyUnicode_WSTR(unicode)[length] = 0;
543 _PyUnicode_WSTR_LENGTH(unicode) = length;
544 }
Guido van Rossumd57fd912000-03-10 22:53:23 +0000545 return 0;
546}
547
Victor Stinnerfe226c02011-10-03 03:52:20 +0200548static PyObject*
549resize_copy(PyObject *unicode, Py_ssize_t length)
550{
551 Py_ssize_t copy_length;
552 if (PyUnicode_IS_COMPACT(unicode)) {
553 PyObject *copy;
554 assert(PyUnicode_IS_READY(unicode));
555
556 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
557 if (copy == NULL)
558 return NULL;
559
560 copy_length = Py_MIN(length, PyUnicode_GET_LENGTH(unicode));
561 if (PyUnicode_CopyCharacters(copy, 0,
562 unicode, 0,
563 copy_length) < 0)
564 {
565 Py_DECREF(copy);
566 return NULL;
567 }
568 return copy;
Victor Stinner8cfcbed2011-10-03 23:19:21 +0200569 }
570 else {
Victor Stinner2fd82272011-10-03 04:06:05 +0200571 PyUnicodeObject *w;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200572 assert(_PyUnicode_WSTR(unicode) != NULL);
573 assert(_PyUnicode_DATA_ANY(unicode) == NULL);
Victor Stinner2fd82272011-10-03 04:06:05 +0200574 w = _PyUnicode_New(length);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200575 if (w == NULL)
576 return NULL;
577 copy_length = _PyUnicode_WSTR_LENGTH(unicode);
578 copy_length = Py_MIN(copy_length, length);
579 Py_UNICODE_COPY(_PyUnicode_WSTR(w), _PyUnicode_WSTR(unicode),
580 copy_length);
581 return (PyObject*)w;
582 }
583}
584
Guido van Rossumd57fd912000-03-10 22:53:23 +0000585/* We allocate one more byte to make sure the string is
Martin v. Löwis47383402007-08-15 07:32:56 +0000586 Ux0000 terminated; some code (e.g. new_identifier)
587 relies on that.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000588
589 XXX This allocator could further be enhanced by assuring that the
Benjamin Peterson29060642009-01-31 22:14:21 +0000590 free list never reduces its size below 1.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000591
592*/
593
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200594#ifdef Py_DEBUG
595int unicode_old_new_calls = 0;
596#endif
597
Alexander Belopolsky40018472011-02-26 01:02:56 +0000598static PyUnicodeObject *
599_PyUnicode_New(Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000600{
601 register PyUnicodeObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200602 size_t new_size;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000603
Thomas Wouters477c8d52006-05-27 19:21:47 +0000604 /* Optimization for empty strings */
Guido van Rossumd57fd912000-03-10 22:53:23 +0000605 if (length == 0 && unicode_empty != NULL) {
606 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +0200607 return (PyUnicodeObject*)unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000608 }
609
Neal Norwitz3ce5d922008-08-24 07:08:55 +0000610 /* Ensure we won't overflow the size. */
611 if (length > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
612 return (PyUnicodeObject *)PyErr_NoMemory();
613 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200614 if (length < 0) {
615 PyErr_SetString(PyExc_SystemError,
616 "Negative size passed to _PyUnicode_New");
617 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000618 }
619
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200620#ifdef Py_DEBUG
621 ++unicode_old_new_calls;
622#endif
623
624 unicode = PyObject_New(PyUnicodeObject, &PyUnicode_Type);
625 if (unicode == NULL)
626 return NULL;
627 new_size = sizeof(Py_UNICODE) * ((size_t)length + 1);
628 _PyUnicode_WSTR(unicode) = (Py_UNICODE*) PyObject_MALLOC(new_size);
629 if (!_PyUnicode_WSTR(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +0000630 PyErr_NoMemory();
631 goto onError;
Guido van Rossum3c1bb802000-04-27 20:13:50 +0000632 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200633
Jeremy Hyltond8082792003-09-16 19:41:39 +0000634 /* Initialize the first element to guard against cases where
Tim Petersced69f82003-09-16 20:30:58 +0000635 * the caller fails before initializing str -- unicode_resize()
636 * reads str[0], and the Keep-Alive optimization can keep memory
637 * allocated for str alive across a call to unicode_dealloc(unicode).
638 * We don't want unicode_resize to read uninitialized memory in
639 * that case.
640 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200641 _PyUnicode_WSTR(unicode)[0] = 0;
642 _PyUnicode_WSTR(unicode)[length] = 0;
643 _PyUnicode_WSTR_LENGTH(unicode) = length;
644 _PyUnicode_HASH(unicode) = -1;
645 _PyUnicode_STATE(unicode).interned = 0;
646 _PyUnicode_STATE(unicode).kind = 0;
647 _PyUnicode_STATE(unicode).compact = 0;
648 _PyUnicode_STATE(unicode).ready = 0;
649 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +0200650 _PyUnicode_DATA_ANY(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200651 _PyUnicode_LENGTH(unicode) = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200652 _PyUnicode_UTF8(unicode) = NULL;
653 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000654 return unicode;
Barry Warsaw51ac5802000-03-20 16:36:48 +0000655
Benjamin Peterson29060642009-01-31 22:14:21 +0000656 onError:
Amaury Forgeot d'Arc7888d082008-08-01 01:06:32 +0000657 /* XXX UNREF/NEWREF interface should be more symmetrical */
658 _Py_DEC_REFTOTAL;
Barry Warsaw51ac5802000-03-20 16:36:48 +0000659 _Py_ForgetReference((PyObject *)unicode);
Neil Schemenauer58aa8612002-04-12 03:07:20 +0000660 PyObject_Del(unicode);
Barry Warsaw51ac5802000-03-20 16:36:48 +0000661 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000662}
663
Victor Stinnerf42dc442011-10-02 23:33:16 +0200664static const char*
665unicode_kind_name(PyObject *unicode)
666{
Victor Stinner42dfd712011-10-03 14:41:45 +0200667 /* don't check consistency: unicode_kind_name() is called from
668 _PyUnicode_Dump() */
Victor Stinnerf42dc442011-10-02 23:33:16 +0200669 if (!PyUnicode_IS_COMPACT(unicode))
670 {
671 if (!PyUnicode_IS_READY(unicode))
672 return "wstr";
673 switch(PyUnicode_KIND(unicode))
674 {
675 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200676 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200677 return "legacy ascii";
678 else
679 return "legacy latin1";
680 case PyUnicode_2BYTE_KIND:
681 return "legacy UCS2";
682 case PyUnicode_4BYTE_KIND:
683 return "legacy UCS4";
684 default:
685 return "<legacy invalid kind>";
686 }
687 }
688 assert(PyUnicode_IS_READY(unicode));
689 switch(PyUnicode_KIND(unicode))
690 {
691 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200692 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200693 return "ascii";
694 else
Victor Stinnera3b334d2011-10-03 13:53:37 +0200695 return "latin1";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200696 case PyUnicode_2BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200697 return "UCS2";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200698 case PyUnicode_4BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200699 return "UCS4";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200700 default:
701 return "<invalid compact kind>";
702 }
703}
704
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200705#ifdef Py_DEBUG
706int unicode_new_new_calls = 0;
707
708/* Functions wrapping macros for use in debugger */
709char *_PyUnicode_utf8(void *unicode){
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200710 return PyUnicode_UTF8(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200711}
712
713void *_PyUnicode_compact_data(void *unicode) {
714 return _PyUnicode_COMPACT_DATA(unicode);
715}
716void *_PyUnicode_data(void *unicode){
717 printf("obj %p\n", unicode);
718 printf("compact %d\n", PyUnicode_IS_COMPACT(unicode));
719 printf("compact ascii %d\n", PyUnicode_IS_COMPACT_ASCII(unicode));
720 printf("ascii op %p\n", ((void*)((PyASCIIObject*)(unicode) + 1)));
721 printf("compact op %p\n", ((void*)((PyCompactUnicodeObject*)(unicode) + 1)));
722 printf("compact data %p\n", _PyUnicode_COMPACT_DATA(unicode));
723 return PyUnicode_DATA(unicode);
724}
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200725
726void
727_PyUnicode_Dump(PyObject *op)
728{
729 PyASCIIObject *ascii = (PyASCIIObject *)op;
Victor Stinnera849a4b2011-10-03 12:12:11 +0200730 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
731 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
732 void *data;
733 printf("%s: len=%zu, ",unicode_kind_name(op), ascii->length);
734 if (ascii->state.compact)
735 data = (compact + 1);
736 else
737 data = unicode->data.any;
738 if (ascii->wstr == data)
739 printf("shared ");
740 printf("wstr=%p", ascii->wstr);
Victor Stinnera3b334d2011-10-03 13:53:37 +0200741 if (!(ascii->state.ascii == 1 && ascii->state.compact == 1)) {
Victor Stinnera849a4b2011-10-03 12:12:11 +0200742 printf(" (%zu), ", compact->wstr_length);
743 if (!ascii->state.compact && compact->utf8 == unicode->data.any)
744 printf("shared ");
745 printf("utf8=%p (%zu)", compact->utf8, compact->utf8_length);
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200746 }
Victor Stinnera849a4b2011-10-03 12:12:11 +0200747 printf(", data=%p\n", data);
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200748}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200749#endif
750
751PyObject *
752PyUnicode_New(Py_ssize_t size, Py_UCS4 maxchar)
753{
754 PyObject *obj;
755 PyCompactUnicodeObject *unicode;
756 void *data;
757 int kind_state;
758 int is_sharing = 0, is_ascii = 0;
759 Py_ssize_t char_size;
760 Py_ssize_t struct_size;
761
762 /* Optimization for empty strings */
763 if (size == 0 && unicode_empty != NULL) {
764 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +0200765 return unicode_empty;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200766 }
767
768#ifdef Py_DEBUG
769 ++unicode_new_new_calls;
770#endif
771
772 struct_size = sizeof(PyCompactUnicodeObject);
773 if (maxchar < 128) {
774 kind_state = PyUnicode_1BYTE_KIND;
775 char_size = 1;
776 is_ascii = 1;
777 struct_size = sizeof(PyASCIIObject);
778 }
779 else if (maxchar < 256) {
780 kind_state = PyUnicode_1BYTE_KIND;
781 char_size = 1;
782 }
783 else if (maxchar < 65536) {
784 kind_state = PyUnicode_2BYTE_KIND;
785 char_size = 2;
786 if (sizeof(wchar_t) == 2)
787 is_sharing = 1;
788 }
789 else {
790 kind_state = PyUnicode_4BYTE_KIND;
791 char_size = 4;
792 if (sizeof(wchar_t) == 4)
793 is_sharing = 1;
794 }
795
796 /* Ensure we won't overflow the size. */
797 if (size < 0) {
798 PyErr_SetString(PyExc_SystemError,
799 "Negative size passed to PyUnicode_New");
800 return NULL;
801 }
802 if (size > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1))
803 return PyErr_NoMemory();
804
805 /* Duplicated allocation code from _PyObject_New() instead of a call to
806 * PyObject_New() so we are able to allocate space for the object and
807 * it's data buffer.
808 */
809 obj = (PyObject *) PyObject_MALLOC(struct_size + (size + 1) * char_size);
810 if (obj == NULL)
811 return PyErr_NoMemory();
812 obj = PyObject_INIT(obj, &PyUnicode_Type);
813 if (obj == NULL)
814 return NULL;
815
816 unicode = (PyCompactUnicodeObject *)obj;
817 if (is_ascii)
818 data = ((PyASCIIObject*)obj) + 1;
819 else
820 data = unicode + 1;
821 _PyUnicode_LENGTH(unicode) = size;
822 _PyUnicode_HASH(unicode) = -1;
823 _PyUnicode_STATE(unicode).interned = 0;
824 _PyUnicode_STATE(unicode).kind = kind_state;
825 _PyUnicode_STATE(unicode).compact = 1;
826 _PyUnicode_STATE(unicode).ready = 1;
827 _PyUnicode_STATE(unicode).ascii = is_ascii;
828 if (is_ascii) {
829 ((char*)data)[size] = 0;
830 _PyUnicode_WSTR(unicode) = NULL;
831 }
832 else if (kind_state == PyUnicode_1BYTE_KIND) {
833 ((char*)data)[size] = 0;
834 _PyUnicode_WSTR(unicode) = NULL;
835 _PyUnicode_WSTR_LENGTH(unicode) = 0;
836 unicode->utf8_length = 0;
837 unicode->utf8 = NULL;
838 }
839 else {
840 unicode->utf8 = NULL;
841 if (kind_state == PyUnicode_2BYTE_KIND)
842 ((Py_UCS2*)data)[size] = 0;
843 else /* kind_state == PyUnicode_4BYTE_KIND */
844 ((Py_UCS4*)data)[size] = 0;
845 if (is_sharing) {
846 _PyUnicode_WSTR_LENGTH(unicode) = size;
847 _PyUnicode_WSTR(unicode) = (wchar_t *)data;
848 }
849 else {
850 _PyUnicode_WSTR_LENGTH(unicode) = 0;
851 _PyUnicode_WSTR(unicode) = NULL;
852 }
853 }
854 return obj;
855}
856
857#if SIZEOF_WCHAR_T == 2
858/* Helper function to convert a 16-bits wchar_t representation to UCS4, this
859 will decode surrogate pairs, the other conversions are implemented as macros
860 for efficency.
861
862 This function assumes that unicode can hold one more code point than wstr
863 characters for a terminating null character. */
Victor Stinnerc53be962011-10-02 21:33:54 +0200864static void
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200865unicode_convert_wchar_to_ucs4(const wchar_t *begin, const wchar_t *end,
866 PyUnicodeObject *unicode)
867{
868 const wchar_t *iter;
869 Py_UCS4 *ucs4_out;
870
Victor Stinner910337b2011-10-03 03:20:16 +0200871 assert(unicode != NULL);
872 assert(_PyUnicode_CHECK(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200873 assert(_PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
874 ucs4_out = PyUnicode_4BYTE_DATA(unicode);
875
876 for (iter = begin; iter < end; ) {
877 assert(ucs4_out < (PyUnicode_4BYTE_DATA(unicode) +
878 _PyUnicode_GET_LENGTH(unicode)));
879 if (*iter >= 0xD800 && *iter <= 0xDBFF
880 && (iter+1) < end && iter[1] >= 0xDC00 && iter[1] <= 0xDFFF)
881 {
882 *ucs4_out++ = (((iter[0] & 0x3FF)<<10) | (iter[1] & 0x3FF)) + 0x10000;
883 iter += 2;
884 }
885 else {
886 *ucs4_out++ = *iter;
887 iter++;
888 }
889 }
890 assert(ucs4_out == (PyUnicode_4BYTE_DATA(unicode) +
891 _PyUnicode_GET_LENGTH(unicode)));
892
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200893}
894#endif
895
Victor Stinnercd9950f2011-10-02 00:34:53 +0200896static int
897_PyUnicode_Dirty(PyObject *unicode)
898{
Victor Stinner910337b2011-10-03 03:20:16 +0200899 assert(_PyUnicode_CHECK(unicode));
Victor Stinnercd9950f2011-10-02 00:34:53 +0200900 if (Py_REFCNT(unicode) != 1) {
901 PyErr_SetString(PyExc_ValueError,
902 "Cannot modify a string having more than 1 reference");
903 return -1;
904 }
905 _PyUnicode_DIRTY(unicode);
906 return 0;
907}
908
Victor Stinnerbe78eaf2011-09-28 21:37:03 +0200909Py_ssize_t
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200910PyUnicode_CopyCharacters(PyObject *to, Py_ssize_t to_start,
911 PyObject *from, Py_ssize_t from_start,
912 Py_ssize_t how_many)
913{
Victor Stinnera0702ab2011-09-29 14:14:38 +0200914 unsigned int from_kind, to_kind;
915 void *from_data, *to_data;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200916
Victor Stinnerb1536152011-09-30 02:26:10 +0200917 if (!PyUnicode_Check(from) || !PyUnicode_Check(to)) {
918 PyErr_BadInternalCall();
919 return -1;
920 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200921
922 if (PyUnicode_READY(from))
923 return -1;
924 if (PyUnicode_READY(to))
925 return -1;
926
Victor Stinnerff9e50f2011-09-28 22:17:19 +0200927 how_many = Py_MIN(PyUnicode_GET_LENGTH(from), how_many);
Victor Stinnerbe78eaf2011-09-28 21:37:03 +0200928 if (to_start + how_many > PyUnicode_GET_LENGTH(to)) {
929 PyErr_Format(PyExc_ValueError,
930 "Cannot write %zi characters at %zi "
931 "in a string of %zi characters",
932 how_many, to_start, PyUnicode_GET_LENGTH(to));
933 return -1;
934 }
Victor Stinnerf5ca1a22011-09-28 23:54:59 +0200935 if (how_many == 0)
936 return 0;
937
Victor Stinnercd9950f2011-10-02 00:34:53 +0200938 if (_PyUnicode_Dirty(to))
Victor Stinnerf5ca1a22011-09-28 23:54:59 +0200939 return -1;
Victor Stinnerbe78eaf2011-09-28 21:37:03 +0200940
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200941 from_kind = PyUnicode_KIND(from);
Victor Stinnera0702ab2011-09-29 14:14:38 +0200942 from_data = PyUnicode_DATA(from);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200943 to_kind = PyUnicode_KIND(to);
Victor Stinnera0702ab2011-09-29 14:14:38 +0200944 to_data = PyUnicode_DATA(to);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200945
Victor Stinnerf42dc442011-10-02 23:33:16 +0200946 if (from_kind == to_kind
947 /* deny latin1 => ascii */
948 && PyUnicode_MAX_CHAR_VALUE(to) >= PyUnicode_MAX_CHAR_VALUE(from))
949 {
Victor Stinnera0702ab2011-09-29 14:14:38 +0200950 Py_MEMCPY((char*)to_data
Victor Stinnerbe78eaf2011-09-28 21:37:03 +0200951 + PyUnicode_KIND_SIZE(to_kind, to_start),
Victor Stinnera0702ab2011-09-29 14:14:38 +0200952 (char*)from_data
Victor Stinnerbe78eaf2011-09-28 21:37:03 +0200953 + PyUnicode_KIND_SIZE(from_kind, from_start),
954 PyUnicode_KIND_SIZE(to_kind, how_many));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200955 }
Victor Stinnera0702ab2011-09-29 14:14:38 +0200956 else if (from_kind == PyUnicode_1BYTE_KIND
957 && to_kind == PyUnicode_2BYTE_KIND)
Victor Stinnerbe78eaf2011-09-28 21:37:03 +0200958 {
959 _PyUnicode_CONVERT_BYTES(
960 Py_UCS1, Py_UCS2,
961 PyUnicode_1BYTE_DATA(from) + from_start,
962 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
963 PyUnicode_2BYTE_DATA(to) + to_start
964 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +0200965 }
Victor Stinner157f83f2011-09-28 21:41:31 +0200966 else if (from_kind == PyUnicode_1BYTE_KIND
Victor Stinnerbe78eaf2011-09-28 21:37:03 +0200967 && to_kind == PyUnicode_4BYTE_KIND)
968 {
969 _PyUnicode_CONVERT_BYTES(
970 Py_UCS1, Py_UCS4,
971 PyUnicode_1BYTE_DATA(from) + from_start,
972 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
973 PyUnicode_4BYTE_DATA(to) + to_start
974 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +0200975 }
976 else if (from_kind == PyUnicode_2BYTE_KIND
977 && to_kind == PyUnicode_4BYTE_KIND)
978 {
979 _PyUnicode_CONVERT_BYTES(
980 Py_UCS2, Py_UCS4,
981 PyUnicode_2BYTE_DATA(from) + from_start,
982 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
983 PyUnicode_4BYTE_DATA(to) + to_start
984 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +0200985 }
Victor Stinnera0702ab2011-09-29 14:14:38 +0200986 else {
987 int invalid_kinds;
Victor Stinnerf42dc442011-10-02 23:33:16 +0200988
989 /* check if max_char(from substring) <= max_char(to) */
990 if (from_kind > to_kind
991 /* latin1 => ascii */
Victor Stinnera3b334d2011-10-03 13:53:37 +0200992 || (PyUnicode_IS_ASCII(to)
Victor Stinnerf42dc442011-10-02 23:33:16 +0200993 && to_kind == PyUnicode_1BYTE_KIND
Victor Stinnera3b334d2011-10-03 13:53:37 +0200994 && !PyUnicode_IS_ASCII(from)))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200995 {
Victor Stinnera0702ab2011-09-29 14:14:38 +0200996 /* slow path to check for character overflow */
997 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
998 Py_UCS4 ch, maxchar;
999 Py_ssize_t i;
1000
1001 maxchar = 0;
1002 invalid_kinds = 0;
1003 for (i=0; i < how_many; i++) {
1004 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1005 if (ch > maxchar) {
1006 maxchar = ch;
1007 if (maxchar > to_maxchar) {
1008 invalid_kinds = 1;
1009 break;
1010 }
1011 }
1012 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1013 }
1014 }
1015 else
1016 invalid_kinds = 1;
1017 if (invalid_kinds) {
1018 PyErr_Format(PyExc_ValueError,
Victor Stinnerf42dc442011-10-02 23:33:16 +02001019 "Cannot copy %s characters "
1020 "into a string of %s characters",
1021 unicode_kind_name(from),
1022 unicode_kind_name(to));
Victor Stinnera0702ab2011-09-29 14:14:38 +02001023 return -1;
1024 }
1025 }
1026 return how_many;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001027}
1028
Victor Stinner17222162011-09-28 22:15:37 +02001029/* Find the maximum code point and count the number of surrogate pairs so a
1030 correct string length can be computed before converting a string to UCS4.
1031 This function counts single surrogates as a character and not as a pair.
1032
1033 Return 0 on success, or -1 on error. */
1034static int
1035find_maxchar_surrogates(const wchar_t *begin, const wchar_t *end,
1036 Py_UCS4 *maxchar, Py_ssize_t *num_surrogates)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001037{
1038 const wchar_t *iter;
1039
Victor Stinnerc53be962011-10-02 21:33:54 +02001040 assert(num_surrogates != NULL && maxchar != NULL);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001041 if (num_surrogates == NULL || maxchar == NULL) {
1042 PyErr_SetString(PyExc_SystemError,
1043 "unexpected NULL arguments to "
1044 "PyUnicode_FindMaxCharAndNumSurrogatePairs");
1045 return -1;
1046 }
1047
1048 *num_surrogates = 0;
1049 *maxchar = 0;
1050
1051 for (iter = begin; iter < end; ) {
1052 if (*iter > *maxchar)
1053 *maxchar = *iter;
1054#if SIZEOF_WCHAR_T == 2
1055 if (*iter >= 0xD800 && *iter <= 0xDBFF
1056 && (iter+1) < end && iter[1] >= 0xDC00 && iter[1] <= 0xDFFF)
1057 {
1058 Py_UCS4 surrogate_val;
1059 surrogate_val = (((iter[0] & 0x3FF)<<10)
1060 | (iter[1] & 0x3FF)) + 0x10000;
1061 ++(*num_surrogates);
1062 if (surrogate_val > *maxchar)
1063 *maxchar = surrogate_val;
1064 iter += 2;
1065 }
1066 else
1067 iter++;
1068#else
1069 iter++;
1070#endif
1071 }
1072 return 0;
1073}
1074
1075#ifdef Py_DEBUG
1076int unicode_ready_calls = 0;
1077#endif
1078
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02001079static int
1080unicode_ready(PyObject **p_obj, int replace)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001081{
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02001082 PyUnicodeObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001083 wchar_t *end;
1084 Py_UCS4 maxchar = 0;
1085 Py_ssize_t num_surrogates;
1086#if SIZEOF_WCHAR_T == 2
1087 Py_ssize_t length_wo_surrogates;
1088#endif
1089
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02001090 assert(p_obj != NULL);
1091 unicode = (PyUnicodeObject *)*p_obj;
1092
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001093 /* _PyUnicode_Ready() is only intented for old-style API usage where
Victor Stinnerd8f65102011-09-29 19:43:17 +02001094 strings were created using _PyObject_New() and where no canonical
1095 representation (the str field) has been set yet aka strings
1096 which are not yet ready. */
Victor Stinner910337b2011-10-03 03:20:16 +02001097 assert(_PyUnicode_CHECK(unicode));
1098 assert(_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001099 assert(_PyUnicode_WSTR(unicode) != NULL);
Victor Stinnerc3c74152011-10-02 20:39:55 +02001100 assert(_PyUnicode_DATA_ANY(unicode) == NULL);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001101 assert(_PyUnicode_UTF8(unicode) == NULL);
Victor Stinnerd8f65102011-09-29 19:43:17 +02001102 /* Actually, it should neither be interned nor be anything else: */
1103 assert(_PyUnicode_STATE(unicode).interned == SSTATE_NOT_INTERNED);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001104
1105#ifdef Py_DEBUG
1106 ++unicode_ready_calls;
1107#endif
1108
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02001109#ifdef Py_DEBUG
1110 assert(!replace || Py_REFCNT(unicode) == 1);
1111#else
1112 if (replace && Py_REFCNT(unicode) != 1)
1113 replace = 0;
1114#endif
1115 if (replace) {
1116 Py_ssize_t len = _PyUnicode_WSTR_LENGTH(unicode);
1117 wchar_t *wstr = _PyUnicode_WSTR(unicode);
1118 /* Optimization for empty strings */
1119 if (len == 0) {
1120 Py_INCREF(unicode_empty);
1121 Py_DECREF(*p_obj);
1122 *p_obj = unicode_empty;
1123 return 0;
1124 }
1125 if (len == 1 && wstr[0] < 256) {
1126 PyObject *latin1_char = get_latin1_char((unsigned char)wstr[0]);
1127 if (latin1_char == NULL)
1128 return -1;
1129 Py_DECREF(*p_obj);
1130 *p_obj = latin1_char;
1131 return 0;
1132 }
1133 }
1134
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001135 end = _PyUnicode_WSTR(unicode) + _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinner17222162011-09-28 22:15:37 +02001136 if (find_maxchar_surrogates(_PyUnicode_WSTR(unicode), end,
Victor Stinnerd8f65102011-09-29 19:43:17 +02001137 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001138 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001139
1140 if (maxchar < 256) {
Victor Stinnerc3c74152011-10-02 20:39:55 +02001141 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(_PyUnicode_WSTR_LENGTH(unicode) + 1);
1142 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001143 PyErr_NoMemory();
1144 return -1;
1145 }
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001146 _PyUnicode_CONVERT_BYTES(wchar_t, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001147 _PyUnicode_WSTR(unicode), end,
1148 PyUnicode_1BYTE_DATA(unicode));
1149 PyUnicode_1BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1150 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1151 _PyUnicode_STATE(unicode).kind = PyUnicode_1BYTE_KIND;
1152 if (maxchar < 128) {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001153 _PyUnicode_STATE(unicode).ascii = 1;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001154 _PyUnicode_UTF8(unicode) = _PyUnicode_DATA_ANY(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001155 _PyUnicode_UTF8_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001156 }
1157 else {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001158 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001159 _PyUnicode_UTF8(unicode) = NULL;
1160 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001161 }
1162 PyObject_FREE(_PyUnicode_WSTR(unicode));
1163 _PyUnicode_WSTR(unicode) = NULL;
1164 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1165 }
1166 /* In this case we might have to convert down from 4-byte native
1167 wchar_t to 2-byte unicode. */
1168 else if (maxchar < 65536) {
1169 assert(num_surrogates == 0 &&
1170 "FindMaxCharAndNumSurrogatePairs() messed up");
1171
Victor Stinner506f5922011-09-28 22:34:18 +02001172#if SIZEOF_WCHAR_T == 2
1173 /* We can share representations and are done. */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001174 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Victor Stinner506f5922011-09-28 22:34:18 +02001175 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1176 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1177 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001178 _PyUnicode_UTF8(unicode) = NULL;
1179 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001180#else
1181 /* sizeof(wchar_t) == 4 */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001182 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(
Victor Stinner506f5922011-09-28 22:34:18 +02001183 2 * (_PyUnicode_WSTR_LENGTH(unicode) + 1));
Victor Stinnerc3c74152011-10-02 20:39:55 +02001184 if (!_PyUnicode_DATA_ANY(unicode)) {
Victor Stinner506f5922011-09-28 22:34:18 +02001185 PyErr_NoMemory();
1186 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001187 }
Victor Stinner506f5922011-09-28 22:34:18 +02001188 _PyUnicode_CONVERT_BYTES(wchar_t, Py_UCS2,
1189 _PyUnicode_WSTR(unicode), end,
1190 PyUnicode_2BYTE_DATA(unicode));
1191 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1192 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1193 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001194 _PyUnicode_UTF8(unicode) = NULL;
1195 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001196 PyObject_FREE(_PyUnicode_WSTR(unicode));
1197 _PyUnicode_WSTR(unicode) = NULL;
1198 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1199#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001200 }
1201 /* maxchar exeeds 16 bit, wee need 4 bytes for unicode characters */
1202 else {
1203#if SIZEOF_WCHAR_T == 2
1204 /* in case the native representation is 2-bytes, we need to allocate a
1205 new normalized 4-byte version. */
1206 length_wo_surrogates = _PyUnicode_WSTR_LENGTH(unicode) - num_surrogates;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001207 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(4 * (length_wo_surrogates + 1));
1208 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001209 PyErr_NoMemory();
1210 return -1;
1211 }
1212 _PyUnicode_LENGTH(unicode) = length_wo_surrogates;
1213 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001214 _PyUnicode_UTF8(unicode) = NULL;
1215 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner126c5592011-10-03 04:17:10 +02001216 /* unicode_convert_wchar_to_ucs4() requires a ready string */
1217 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerc53be962011-10-02 21:33:54 +02001218 unicode_convert_wchar_to_ucs4(_PyUnicode_WSTR(unicode), end, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001219 PyObject_FREE(_PyUnicode_WSTR(unicode));
1220 _PyUnicode_WSTR(unicode) = NULL;
1221 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1222#else
1223 assert(num_surrogates == 0);
1224
Victor Stinnerc3c74152011-10-02 20:39:55 +02001225 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001226 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001227 _PyUnicode_UTF8(unicode) = NULL;
1228 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001229 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
1230#endif
1231 PyUnicode_4BYTE_DATA(unicode)[_PyUnicode_LENGTH(unicode)] = '\0';
1232 }
1233 _PyUnicode_STATE(unicode).ready = 1;
1234 return 0;
1235}
1236
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02001237int
1238_PyUnicode_ReadyReplace(PyObject **op)
1239{
1240 return unicode_ready(op, 1);
1241}
1242
1243int
1244_PyUnicode_Ready(PyObject *op)
1245{
1246 return unicode_ready(&op, 0);
1247}
1248
Alexander Belopolsky40018472011-02-26 01:02:56 +00001249static void
1250unicode_dealloc(register PyUnicodeObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001251{
Walter Dörwald16807132007-05-25 13:52:07 +00001252 switch (PyUnicode_CHECK_INTERNED(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001253 case SSTATE_NOT_INTERNED:
1254 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001255
Benjamin Peterson29060642009-01-31 22:14:21 +00001256 case SSTATE_INTERNED_MORTAL:
1257 /* revive dead object temporarily for DelItem */
1258 Py_REFCNT(unicode) = 3;
1259 if (PyDict_DelItem(interned, (PyObject *)unicode) != 0)
1260 Py_FatalError(
1261 "deletion of interned string failed");
1262 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001263
Benjamin Peterson29060642009-01-31 22:14:21 +00001264 case SSTATE_INTERNED_IMMORTAL:
1265 Py_FatalError("Immortal interned string died.");
Walter Dörwald16807132007-05-25 13:52:07 +00001266
Benjamin Peterson29060642009-01-31 22:14:21 +00001267 default:
1268 Py_FatalError("Inconsistent interned string state.");
Walter Dörwald16807132007-05-25 13:52:07 +00001269 }
1270
Victor Stinner03490912011-10-03 23:45:12 +02001271 if (_PyUnicode_HAS_WSTR_MEMORY(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001272 PyObject_DEL(_PyUnicode_WSTR(unicode));
Victor Stinner829c0ad2011-10-03 01:08:02 +02001273 if (_PyUnicode_HAS_UTF8_MEMORY(unicode))
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001274 PyObject_DEL(_PyUnicode_UTF8(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001275
1276 if (PyUnicode_IS_COMPACT(unicode)) {
1277 Py_TYPE(unicode)->tp_free((PyObject *)unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001278 }
1279 else {
Victor Stinnerc3c74152011-10-02 20:39:55 +02001280 if (_PyUnicode_DATA_ANY(unicode))
1281 PyObject_DEL(_PyUnicode_DATA_ANY(unicode));
Benjamin Peterson29060642009-01-31 22:14:21 +00001282 Py_TYPE(unicode)->tp_free((PyObject *)unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001283 }
1284}
1285
Alexander Belopolsky40018472011-02-26 01:02:56 +00001286static int
Victor Stinnerfe226c02011-10-03 03:52:20 +02001287unicode_resizable(PyObject *unicode)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001288{
Victor Stinnerfe226c02011-10-03 03:52:20 +02001289 if (Py_REFCNT(unicode) != 1)
1290 return 0;
1291 if (PyUnicode_CHECK_INTERNED(unicode))
1292 return 0;
Victor Stinner77bb47b2011-10-03 20:06:05 +02001293 assert (unicode != unicode_empty);
1294#ifdef Py_DEBUG
1295 if (_PyUnicode_KIND(unicode) != PyUnicode_WCHAR_KIND
1296 && PyUnicode_GET_LENGTH(unicode) == 1)
1297 {
1298 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, 0);
Victor Stinnerfe226c02011-10-03 03:52:20 +02001299 if (ch < 256 && unicode_latin1[ch] == unicode)
1300 return 0;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001301 }
Victor Stinner77bb47b2011-10-03 20:06:05 +02001302#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +02001303 return 1;
1304}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001305
Victor Stinnerfe226c02011-10-03 03:52:20 +02001306static int
1307unicode_resize(PyObject **p_unicode, Py_ssize_t length)
1308{
1309 PyObject *unicode;
1310 Py_ssize_t old_length;
1311
1312 assert(p_unicode != NULL);
1313 unicode = *p_unicode;
1314
1315 assert(unicode != NULL);
1316 assert(PyUnicode_Check(unicode));
1317 assert(0 <= length);
1318
Victor Stinner910337b2011-10-03 03:20:16 +02001319 if (_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001320 old_length = PyUnicode_WSTR_LENGTH(unicode);
1321 else
1322 old_length = PyUnicode_GET_LENGTH(unicode);
1323 if (old_length == length)
1324 return 0;
1325
Victor Stinnerfe226c02011-10-03 03:52:20 +02001326 if (!unicode_resizable(unicode)) {
1327 PyObject *copy = resize_copy(unicode, length);
1328 if (copy == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001329 return -1;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001330 Py_DECREF(*p_unicode);
1331 *p_unicode = copy;
Benjamin Peterson29060642009-01-31 22:14:21 +00001332 return 0;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001333 }
1334
Victor Stinnerfe226c02011-10-03 03:52:20 +02001335 if (PyUnicode_IS_COMPACT(unicode)) {
1336 *p_unicode = resize_compact(unicode, length);
1337 if (*p_unicode == NULL)
1338 return -1;
1339 return 0;
1340 } else
1341 return resize_inplace((PyUnicodeObject*)unicode, length);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001342}
1343
Alexander Belopolsky40018472011-02-26 01:02:56 +00001344int
Victor Stinnerfe226c02011-10-03 03:52:20 +02001345PyUnicode_Resize(PyObject **p_unicode, Py_ssize_t length)
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001346{
Victor Stinnerfe226c02011-10-03 03:52:20 +02001347 PyObject *unicode;
1348 if (p_unicode == NULL) {
1349 PyErr_BadInternalCall();
1350 return -1;
1351 }
1352 unicode = *p_unicode;
1353 if (unicode == NULL || !PyUnicode_Check(unicode) || length < 0
1354 || _PyUnicode_KIND(unicode) != PyUnicode_WCHAR_KIND)
1355 {
1356 PyErr_BadInternalCall();
1357 return -1;
1358 }
1359 return unicode_resize(p_unicode, length);
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001360}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001361
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001362static PyObject*
1363get_latin1_char(unsigned char ch)
1364{
Victor Stinnera464fc12011-10-02 20:39:30 +02001365 PyObject *unicode = unicode_latin1[ch];
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001366 if (!unicode) {
Victor Stinnera464fc12011-10-02 20:39:30 +02001367 unicode = PyUnicode_New(1, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001368 if (!unicode)
1369 return NULL;
1370 PyUnicode_1BYTE_DATA(unicode)[0] = ch;
1371 unicode_latin1[ch] = unicode;
1372 }
1373 Py_INCREF(unicode);
Victor Stinnera464fc12011-10-02 20:39:30 +02001374 return unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001375}
1376
Alexander Belopolsky40018472011-02-26 01:02:56 +00001377PyObject *
1378PyUnicode_FromUnicode(const Py_UNICODE *u, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001379{
1380 PyUnicodeObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001381 Py_UCS4 maxchar = 0;
1382 Py_ssize_t num_surrogates;
1383
1384 if (u == NULL)
1385 return (PyObject*)_PyUnicode_New(size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001386
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001387 /* If the Unicode data is known at construction time, we can apply
1388 some optimizations which share commonly used objects. */
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001389
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001390 /* Optimization for empty strings */
1391 if (size == 0 && unicode_empty != NULL) {
1392 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001393 return unicode_empty;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001394 }
Tim Petersced69f82003-09-16 20:30:58 +00001395
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001396 /* Single character Unicode objects in the Latin-1 range are
1397 shared when using this constructor */
1398 if (size == 1 && *u < 256)
1399 return get_latin1_char((unsigned char)*u);
1400
1401 /* If not empty and not single character, copy the Unicode data
1402 into the new object */
Victor Stinnerd8f65102011-09-29 19:43:17 +02001403 if (find_maxchar_surrogates(u, u + size,
1404 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001405 return NULL;
1406
1407 unicode = (PyUnicodeObject *) PyUnicode_New(size - num_surrogates,
1408 maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001409 if (!unicode)
1410 return NULL;
1411
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001412 switch (PyUnicode_KIND(unicode)) {
1413 case PyUnicode_1BYTE_KIND:
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001414 _PyUnicode_CONVERT_BYTES(Py_UNICODE, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001415 u, u + size, PyUnicode_1BYTE_DATA(unicode));
1416 break;
1417 case PyUnicode_2BYTE_KIND:
1418#if Py_UNICODE_SIZE == 2
1419 Py_MEMCPY(PyUnicode_2BYTE_DATA(unicode), u, size * 2);
1420#else
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001421 _PyUnicode_CONVERT_BYTES(Py_UNICODE, Py_UCS2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001422 u, u + size, PyUnicode_2BYTE_DATA(unicode));
1423#endif
1424 break;
1425 case PyUnicode_4BYTE_KIND:
1426#if SIZEOF_WCHAR_T == 2
1427 /* This is the only case which has to process surrogates, thus
1428 a simple copy loop is not enough and we need a function. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001429 unicode_convert_wchar_to_ucs4(u, u + size, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001430#else
1431 assert(num_surrogates == 0);
1432 Py_MEMCPY(PyUnicode_4BYTE_DATA(unicode), u, size * 4);
1433#endif
1434 break;
1435 default:
1436 assert(0 && "Impossible state");
1437 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00001438
1439 return (PyObject *)unicode;
1440}
1441
Alexander Belopolsky40018472011-02-26 01:02:56 +00001442PyObject *
1443PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size)
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001444{
1445 PyUnicodeObject *unicode;
Christian Heimes33fe8092008-04-13 13:53:33 +00001446
Benjamin Peterson14339b62009-01-31 16:36:08 +00001447 if (size < 0) {
1448 PyErr_SetString(PyExc_SystemError,
Benjamin Peterson29060642009-01-31 22:14:21 +00001449 "Negative size passed to PyUnicode_FromStringAndSize");
Benjamin Peterson14339b62009-01-31 16:36:08 +00001450 return NULL;
1451 }
Christian Heimes33fe8092008-04-13 13:53:33 +00001452
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001453 /* If the Unicode data is known at construction time, we can apply
Martin v. Löwis9c121062007-08-05 20:26:11 +00001454 some optimizations which share commonly used objects.
1455 Also, this means the input must be UTF-8, so fall back to the
1456 UTF-8 decoder at the end. */
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001457 if (u != NULL) {
1458
Benjamin Peterson29060642009-01-31 22:14:21 +00001459 /* Optimization for empty strings */
1460 if (size == 0 && unicode_empty != NULL) {
1461 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001462 return unicode_empty;
Benjamin Peterson14339b62009-01-31 16:36:08 +00001463 }
Benjamin Peterson29060642009-01-31 22:14:21 +00001464
1465 /* Single characters are shared when using this constructor.
1466 Restrict to ASCII, since the input must be UTF-8. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001467 if (size == 1 && Py_CHARMASK(*u) < 128)
1468 return get_latin1_char(Py_CHARMASK(*u));
Martin v. Löwis9c121062007-08-05 20:26:11 +00001469
1470 return PyUnicode_DecodeUTF8(u, size, NULL);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001471 }
1472
Walter Dörwald55507312007-05-18 13:12:10 +00001473 unicode = _PyUnicode_New(size);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001474 if (!unicode)
1475 return NULL;
1476
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001477 return (PyObject *)unicode;
1478}
1479
Alexander Belopolsky40018472011-02-26 01:02:56 +00001480PyObject *
1481PyUnicode_FromString(const char *u)
Walter Dörwaldd2034312007-05-18 16:29:38 +00001482{
1483 size_t size = strlen(u);
1484 if (size > PY_SSIZE_T_MAX) {
1485 PyErr_SetString(PyExc_OverflowError, "input too long");
1486 return NULL;
1487 }
1488
1489 return PyUnicode_FromStringAndSize(u, size);
1490}
1491
Victor Stinnere57b1c02011-09-28 22:20:48 +02001492static PyObject*
1493_PyUnicode_FromUCS1(const unsigned char* u, Py_ssize_t size)
Mark Dickinson081dfee2009-03-18 14:47:41 +00001494{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001495 PyObject *res;
1496 unsigned char max = 127;
1497 Py_ssize_t i;
1498 for (i = 0; i < size; i++) {
1499 if (u[i] & 0x80) {
1500 max = 255;
1501 break;
Mark Dickinson081dfee2009-03-18 14:47:41 +00001502 }
1503 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001504 res = PyUnicode_New(size, max);
1505 if (!res)
1506 return NULL;
1507 memcpy(PyUnicode_1BYTE_DATA(res), u, size);
1508 return res;
Mark Dickinson081dfee2009-03-18 14:47:41 +00001509}
1510
Victor Stinnere57b1c02011-09-28 22:20:48 +02001511static PyObject*
1512_PyUnicode_FromUCS2(const Py_UCS2 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001513{
1514 PyObject *res;
1515 Py_UCS2 max = 0;
1516 Py_ssize_t i;
1517 for (i = 0; i < size; i++)
1518 if (u[i] > max)
1519 max = u[i];
1520 res = PyUnicode_New(size, max);
1521 if (!res)
1522 return NULL;
1523 if (max >= 256)
1524 memcpy(PyUnicode_2BYTE_DATA(res), u, sizeof(Py_UCS2)*size);
1525 else
1526 for (i = 0; i < size; i++)
1527 PyUnicode_1BYTE_DATA(res)[i] = (Py_UCS1)u[i];
1528 return res;
1529}
1530
Victor Stinnere57b1c02011-09-28 22:20:48 +02001531static PyObject*
1532_PyUnicode_FromUCS4(const Py_UCS4 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001533{
1534 PyObject *res;
1535 Py_UCS4 max = 0;
1536 Py_ssize_t i;
1537 for (i = 0; i < size; i++)
1538 if (u[i] > max)
1539 max = u[i];
1540 res = PyUnicode_New(size, max);
1541 if (!res)
1542 return NULL;
1543 if (max >= 0x10000)
1544 memcpy(PyUnicode_4BYTE_DATA(res), u, sizeof(Py_UCS4)*size);
1545 else {
1546 int kind = PyUnicode_KIND(res);
1547 void *data = PyUnicode_DATA(res);
1548 for (i = 0; i < size; i++)
1549 PyUnicode_WRITE(kind, data, i, u[i]);
1550 }
1551 return res;
1552}
1553
1554PyObject*
1555PyUnicode_FromKindAndData(int kind, const void *buffer, Py_ssize_t size)
1556{
1557 switch(kind) {
1558 case PyUnicode_1BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02001559 return _PyUnicode_FromUCS1(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001560 case PyUnicode_2BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02001561 return _PyUnicode_FromUCS2(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001562 case PyUnicode_4BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02001563 return _PyUnicode_FromUCS4(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001564 }
Victor Stinner202b62b2011-10-01 23:48:37 +02001565 PyErr_SetString(PyExc_ValueError, "invalid kind");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001566 return NULL;
1567}
1568
Victor Stinner034f6cf2011-09-30 02:26:44 +02001569PyObject*
1570PyUnicode_Copy(PyObject *unicode)
1571{
Victor Stinnerc841e7d2011-10-01 01:34:32 +02001572 Py_ssize_t size;
1573 PyObject *copy;
1574 void *data;
1575
Victor Stinner034f6cf2011-09-30 02:26:44 +02001576 if (!PyUnicode_Check(unicode)) {
1577 PyErr_BadInternalCall();
1578 return NULL;
1579 }
1580 if (PyUnicode_READY(unicode))
1581 return NULL;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02001582
1583 size = PyUnicode_GET_LENGTH(unicode);
1584 copy = PyUnicode_New(size, PyUnicode_MAX_CHAR_VALUE(unicode));
1585 if (!copy)
1586 return NULL;
1587 assert(PyUnicode_KIND(copy) == PyUnicode_KIND(unicode));
1588
1589 data = PyUnicode_DATA(unicode);
1590 switch (PyUnicode_KIND(unicode))
1591 {
1592 case PyUnicode_1BYTE_KIND:
1593 memcpy(PyUnicode_1BYTE_DATA(copy), data, size);
1594 break;
1595 case PyUnicode_2BYTE_KIND:
1596 memcpy(PyUnicode_2BYTE_DATA(copy), data, sizeof(Py_UCS2) * size);
1597 break;
1598 case PyUnicode_4BYTE_KIND:
1599 memcpy(PyUnicode_4BYTE_DATA(copy), data, sizeof(Py_UCS4) * size);
1600 break;
1601 default:
1602 assert(0);
1603 break;
1604 }
1605 return copy;
Victor Stinner034f6cf2011-09-30 02:26:44 +02001606}
1607
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001608
Victor Stinnerbc603d12011-10-02 01:00:40 +02001609/* Widen Unicode objects to larger buffers. Don't write terminating null
1610 character. Return NULL on error. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001611
1612void*
1613_PyUnicode_AsKind(PyObject *s, unsigned int kind)
1614{
Victor Stinnerbc603d12011-10-02 01:00:40 +02001615 Py_ssize_t len;
1616 void *result;
1617 unsigned int skind;
1618
1619 if (PyUnicode_READY(s))
1620 return NULL;
1621
1622 len = PyUnicode_GET_LENGTH(s);
1623 skind = PyUnicode_KIND(s);
1624 if (skind >= kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001625 PyErr_SetString(PyExc_RuntimeError, "invalid widening attempt");
1626 return NULL;
1627 }
1628 switch(kind) {
Victor Stinnerbc603d12011-10-02 01:00:40 +02001629 case PyUnicode_2BYTE_KIND:
1630 result = PyMem_Malloc(len * sizeof(Py_UCS2));
1631 if (!result)
1632 return PyErr_NoMemory();
1633 assert(skind == PyUnicode_1BYTE_KIND);
1634 _PyUnicode_CONVERT_BYTES(
1635 Py_UCS1, Py_UCS2,
1636 PyUnicode_1BYTE_DATA(s),
1637 PyUnicode_1BYTE_DATA(s) + len,
1638 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001639 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02001640 case PyUnicode_4BYTE_KIND:
1641 result = PyMem_Malloc(len * sizeof(Py_UCS4));
1642 if (!result)
1643 return PyErr_NoMemory();
1644 if (skind == PyUnicode_2BYTE_KIND) {
1645 _PyUnicode_CONVERT_BYTES(
1646 Py_UCS2, Py_UCS4,
1647 PyUnicode_2BYTE_DATA(s),
1648 PyUnicode_2BYTE_DATA(s) + len,
1649 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001650 }
Victor Stinnerbc603d12011-10-02 01:00:40 +02001651 else {
1652 assert(skind == PyUnicode_1BYTE_KIND);
1653 _PyUnicode_CONVERT_BYTES(
1654 Py_UCS1, Py_UCS4,
1655 PyUnicode_1BYTE_DATA(s),
1656 PyUnicode_1BYTE_DATA(s) + len,
1657 result);
1658 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001659 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02001660 default:
1661 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001662 }
Victor Stinnerbc603d12011-10-02 01:00:40 +02001663 PyErr_SetString(PyExc_ValueError, "invalid kind");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001664 return NULL;
1665}
1666
1667static Py_UCS4*
1668as_ucs4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
1669 int copy_null)
1670{
1671 int kind;
1672 void *data;
1673 Py_ssize_t len, targetlen;
1674 if (PyUnicode_READY(string) == -1)
1675 return NULL;
1676 kind = PyUnicode_KIND(string);
1677 data = PyUnicode_DATA(string);
1678 len = PyUnicode_GET_LENGTH(string);
1679 targetlen = len;
1680 if (copy_null)
1681 targetlen++;
1682 if (!target) {
1683 if (PY_SSIZE_T_MAX / sizeof(Py_UCS4) < targetlen) {
1684 PyErr_NoMemory();
1685 return NULL;
1686 }
1687 target = PyMem_Malloc(targetlen * sizeof(Py_UCS4));
1688 if (!target) {
1689 PyErr_NoMemory();
1690 return NULL;
1691 }
1692 }
1693 else {
1694 if (targetsize < targetlen) {
1695 PyErr_Format(PyExc_SystemError,
1696 "string is longer than the buffer");
1697 if (copy_null && 0 < targetsize)
1698 target[0] = 0;
1699 return NULL;
1700 }
1701 }
1702 if (kind != PyUnicode_4BYTE_KIND) {
1703 Py_ssize_t i;
1704 for (i = 0; i < len; i++)
1705 target[i] = PyUnicode_READ(kind, data, i);
1706 }
1707 else
1708 Py_MEMCPY(target, data, len * sizeof(Py_UCS4));
1709 if (copy_null)
1710 target[len] = 0;
1711 return target;
1712}
1713
1714Py_UCS4*
1715PyUnicode_AsUCS4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
1716 int copy_null)
1717{
1718 if (target == NULL || targetsize < 1) {
1719 PyErr_BadInternalCall();
1720 return NULL;
1721 }
1722 return as_ucs4(string, target, targetsize, copy_null);
1723}
1724
1725Py_UCS4*
1726PyUnicode_AsUCS4Copy(PyObject *string)
1727{
1728 return as_ucs4(string, NULL, 0, 1);
1729}
1730
1731#ifdef HAVE_WCHAR_H
Mark Dickinson081dfee2009-03-18 14:47:41 +00001732
Alexander Belopolsky40018472011-02-26 01:02:56 +00001733PyObject *
1734PyUnicode_FromWideChar(register const wchar_t *w, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001735{
Guido van Rossumd57fd912000-03-10 22:53:23 +00001736 if (w == NULL) {
Martin v. Löwis790465f2008-04-05 20:41:37 +00001737 if (size == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001738 return PyUnicode_New(0, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +00001739 PyErr_BadInternalCall();
1740 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001741 }
1742
Martin v. Löwis790465f2008-04-05 20:41:37 +00001743 if (size == -1) {
1744 size = wcslen(w);
1745 }
1746
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001747 return PyUnicode_FromUnicode(w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001748}
1749
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001750#endif /* HAVE_WCHAR_H */
Mark Dickinson081dfee2009-03-18 14:47:41 +00001751
Walter Dörwald346737f2007-05-31 10:44:43 +00001752static void
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00001753makefmt(char *fmt, int longflag, int longlongflag, int size_tflag,
1754 int zeropad, int width, int precision, char c)
Walter Dörwald346737f2007-05-31 10:44:43 +00001755{
Benjamin Peterson14339b62009-01-31 16:36:08 +00001756 *fmt++ = '%';
1757 if (width) {
1758 if (zeropad)
1759 *fmt++ = '0';
1760 fmt += sprintf(fmt, "%d", width);
1761 }
1762 if (precision)
1763 fmt += sprintf(fmt, ".%d", precision);
1764 if (longflag)
1765 *fmt++ = 'l';
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00001766 else if (longlongflag) {
1767 /* longlongflag should only ever be nonzero on machines with
1768 HAVE_LONG_LONG defined */
1769#ifdef HAVE_LONG_LONG
1770 char *f = PY_FORMAT_LONG_LONG;
1771 while (*f)
1772 *fmt++ = *f++;
1773#else
1774 /* we shouldn't ever get here */
1775 assert(0);
1776 *fmt++ = 'l';
1777#endif
1778 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00001779 else if (size_tflag) {
1780 char *f = PY_FORMAT_SIZE_T;
1781 while (*f)
1782 *fmt++ = *f++;
1783 }
1784 *fmt++ = c;
1785 *fmt = '\0';
Walter Dörwald346737f2007-05-31 10:44:43 +00001786}
1787
Victor Stinner96865452011-03-01 23:44:09 +00001788/* helper for PyUnicode_FromFormatV() */
1789
1790static const char*
1791parse_format_flags(const char *f,
1792 int *p_width, int *p_precision,
1793 int *p_longflag, int *p_longlongflag, int *p_size_tflag)
1794{
1795 int width, precision, longflag, longlongflag, size_tflag;
1796
1797 /* parse the width.precision part, e.g. "%2.5s" => width=2, precision=5 */
1798 f++;
1799 width = 0;
1800 while (Py_ISDIGIT((unsigned)*f))
1801 width = (width*10) + *f++ - '0';
1802 precision = 0;
1803 if (*f == '.') {
1804 f++;
1805 while (Py_ISDIGIT((unsigned)*f))
1806 precision = (precision*10) + *f++ - '0';
1807 if (*f == '%') {
1808 /* "%.3%s" => f points to "3" */
1809 f--;
1810 }
1811 }
1812 if (*f == '\0') {
1813 /* bogus format "%.1" => go backward, f points to "1" */
1814 f--;
1815 }
1816 if (p_width != NULL)
1817 *p_width = width;
1818 if (p_precision != NULL)
1819 *p_precision = precision;
1820
1821 /* Handle %ld, %lu, %lld and %llu. */
1822 longflag = 0;
1823 longlongflag = 0;
Victor Stinnere7faec12011-03-02 00:01:53 +00001824 size_tflag = 0;
Victor Stinner96865452011-03-01 23:44:09 +00001825
1826 if (*f == 'l') {
Victor Stinner6d970f42011-03-02 00:04:25 +00001827 if (f[1] == 'd' || f[1] == 'u' || f[1] == 'i') {
Victor Stinner96865452011-03-01 23:44:09 +00001828 longflag = 1;
1829 ++f;
1830 }
1831#ifdef HAVE_LONG_LONG
1832 else if (f[1] == 'l' &&
Victor Stinner6d970f42011-03-02 00:04:25 +00001833 (f[2] == 'd' || f[2] == 'u' || f[2] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00001834 longlongflag = 1;
1835 f += 2;
1836 }
1837#endif
1838 }
1839 /* handle the size_t flag. */
Victor Stinner6d970f42011-03-02 00:04:25 +00001840 else if (*f == 'z' && (f[1] == 'd' || f[1] == 'u' || f[1] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00001841 size_tflag = 1;
1842 ++f;
1843 }
1844 if (p_longflag != NULL)
1845 *p_longflag = longflag;
1846 if (p_longlongflag != NULL)
1847 *p_longlongflag = longlongflag;
1848 if (p_size_tflag != NULL)
1849 *p_size_tflag = size_tflag;
1850 return f;
1851}
1852
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00001853/* maximum number of characters required for output of %ld. 21 characters
1854 allows for 64-bit integers (in decimal) and an optional sign. */
1855#define MAX_LONG_CHARS 21
1856/* maximum number of characters required for output of %lld.
1857 We need at most ceil(log10(256)*SIZEOF_LONG_LONG) digits,
1858 plus 1 for the sign. 53/22 is an upper bound for log10(256). */
1859#define MAX_LONG_LONG_CHARS (2 + (SIZEOF_LONG_LONG*53-1) / 22)
1860
Walter Dörwaldd2034312007-05-18 16:29:38 +00001861PyObject *
1862PyUnicode_FromFormatV(const char *format, va_list vargs)
1863{
Benjamin Peterson14339b62009-01-31 16:36:08 +00001864 va_list count;
1865 Py_ssize_t callcount = 0;
1866 PyObject **callresults = NULL;
1867 PyObject **callresult = NULL;
1868 Py_ssize_t n = 0;
1869 int width = 0;
1870 int precision = 0;
1871 int zeropad;
1872 const char* f;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001873 PyUnicodeObject *string;
Benjamin Peterson14339b62009-01-31 16:36:08 +00001874 /* used by sprintf */
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00001875 char fmt[61]; /* should be enough for %0width.precisionlld */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001876 Py_UCS4 maxchar = 127; /* result is ASCII by default */
1877 Py_UCS4 argmaxchar;
1878 Py_ssize_t numbersize = 0;
1879 char *numberresults = NULL;
1880 char *numberresult = NULL;
1881 Py_ssize_t i;
1882 int kind;
1883 void *data;
Walter Dörwaldd2034312007-05-18 16:29:38 +00001884
Victor Stinner4a2b7a12010-08-13 14:03:48 +00001885 Py_VA_COPY(count, vargs);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00001886 /* step 1: count the number of %S/%R/%A/%s format specifications
1887 * (we call PyObject_Str()/PyObject_Repr()/PyObject_ASCII()/
1888 * PyUnicode_DecodeUTF8() for these objects once during step 3 and put the
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001889 * result in an array)
1890 * also esimate a upper bound for all the number formats in the string,
1891 * numbers will be formated in step 3 and be keept in a '\0'-separated
1892 * buffer before putting everything together. */
Benjamin Peterson14339b62009-01-31 16:36:08 +00001893 for (f = format; *f; f++) {
1894 if (*f == '%') {
Victor Stinner96865452011-03-01 23:44:09 +00001895 int longlongflag;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001896 /* skip width or width.precision (eg. "1.2" of "%1.2f") */
1897 f = parse_format_flags(f, &width, NULL, NULL, &longlongflag, NULL);
1898 if (*f == 's' || *f=='S' || *f=='R' || *f=='A' || *f=='V')
1899 ++callcount;
Walter Dörwaldd2034312007-05-18 16:29:38 +00001900
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001901 else if (*f == 'd' || *f=='u' || *f=='i' || *f=='x' || *f=='p') {
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00001902#ifdef HAVE_LONG_LONG
1903 if (longlongflag) {
1904 if (width < MAX_LONG_LONG_CHARS)
1905 width = MAX_LONG_LONG_CHARS;
1906 }
1907 else
1908#endif
1909 /* MAX_LONG_CHARS is enough to hold a 64-bit integer,
1910 including sign. Decimal takes the most space. This
1911 isn't enough for octal. If a width is specified we
1912 need more (which we allocate later). */
1913 if (width < MAX_LONG_CHARS)
1914 width = MAX_LONG_CHARS;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001915
1916 /* account for the size + '\0' to separate numbers
1917 inside of the numberresults buffer */
1918 numbersize += (width + 1);
1919 }
1920 }
1921 else if ((unsigned char)*f > 127) {
1922 PyErr_Format(PyExc_ValueError,
1923 "PyUnicode_FromFormatV() expects an ASCII-encoded format "
1924 "string, got a non-ASCII byte: 0x%02x",
1925 (unsigned char)*f);
1926 return NULL;
1927 }
1928 }
1929 /* step 2: allocate memory for the results of
1930 * PyObject_Str()/PyObject_Repr()/PyUnicode_DecodeUTF8() calls */
1931 if (callcount) {
1932 callresults = PyObject_Malloc(sizeof(PyObject *) * callcount);
1933 if (!callresults) {
1934 PyErr_NoMemory();
1935 return NULL;
1936 }
1937 callresult = callresults;
1938 }
1939 /* step 2.5: allocate memory for the results of formating numbers */
1940 if (numbersize) {
1941 numberresults = PyObject_Malloc(numbersize);
1942 if (!numberresults) {
1943 PyErr_NoMemory();
1944 goto fail;
1945 }
1946 numberresult = numberresults;
1947 }
1948
1949 /* step 3: format numbers and figure out how large a buffer we need */
1950 for (f = format; *f; f++) {
1951 if (*f == '%') {
1952 const char* p;
1953 int longflag;
1954 int longlongflag;
1955 int size_tflag;
1956 int numprinted;
1957
1958 p = f;
1959 zeropad = (f[1] == '0');
1960 f = parse_format_flags(f, &width, &precision,
1961 &longflag, &longlongflag, &size_tflag);
1962 switch (*f) {
1963 case 'c':
1964 {
1965 Py_UCS4 ordinal = va_arg(count, int);
Georg Brandl4cb0de22011-09-28 21:49:49 +02001966 maxchar = Py_MAX(maxchar, ordinal);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001967 n++;
1968 break;
1969 }
1970 case '%':
1971 n++;
1972 break;
1973 case 'i':
1974 case 'd':
1975 makefmt(fmt, longflag, longlongflag, size_tflag, zeropad,
1976 width, precision, *f);
1977 if (longflag)
1978 numprinted = sprintf(numberresult, fmt,
1979 va_arg(count, long));
1980#ifdef HAVE_LONG_LONG
1981 else if (longlongflag)
1982 numprinted = sprintf(numberresult, fmt,
1983 va_arg(count, PY_LONG_LONG));
1984#endif
1985 else if (size_tflag)
1986 numprinted = sprintf(numberresult, fmt,
1987 va_arg(count, Py_ssize_t));
1988 else
1989 numprinted = sprintf(numberresult, fmt,
1990 va_arg(count, int));
1991 n += numprinted;
1992 /* advance by +1 to skip over the '\0' */
1993 numberresult += (numprinted + 1);
1994 assert(*(numberresult - 1) == '\0');
1995 assert(*(numberresult - 2) != '\0');
1996 assert(numprinted >= 0);
1997 assert(numberresult <= numberresults + numbersize);
1998 break;
1999 case 'u':
2000 makefmt(fmt, longflag, longlongflag, size_tflag, zeropad,
2001 width, precision, 'u');
2002 if (longflag)
2003 numprinted = sprintf(numberresult, fmt,
2004 va_arg(count, unsigned long));
2005#ifdef HAVE_LONG_LONG
2006 else if (longlongflag)
2007 numprinted = sprintf(numberresult, fmt,
2008 va_arg(count, unsigned PY_LONG_LONG));
2009#endif
2010 else if (size_tflag)
2011 numprinted = sprintf(numberresult, fmt,
2012 va_arg(count, size_t));
2013 else
2014 numprinted = sprintf(numberresult, fmt,
2015 va_arg(count, unsigned int));
2016 n += numprinted;
2017 numberresult += (numprinted + 1);
2018 assert(*(numberresult - 1) == '\0');
2019 assert(*(numberresult - 2) != '\0');
2020 assert(numprinted >= 0);
2021 assert(numberresult <= numberresults + numbersize);
2022 break;
2023 case 'x':
2024 makefmt(fmt, 0, 0, 0, zeropad, width, precision, 'x');
2025 numprinted = sprintf(numberresult, fmt, va_arg(count, int));
2026 n += numprinted;
2027 numberresult += (numprinted + 1);
2028 assert(*(numberresult - 1) == '\0');
2029 assert(*(numberresult - 2) != '\0');
2030 assert(numprinted >= 0);
2031 assert(numberresult <= numberresults + numbersize);
2032 break;
2033 case 'p':
2034 numprinted = sprintf(numberresult, "%p", va_arg(count, void*));
2035 /* %p is ill-defined: ensure leading 0x. */
2036 if (numberresult[1] == 'X')
2037 numberresult[1] = 'x';
2038 else if (numberresult[1] != 'x') {
2039 memmove(numberresult + 2, numberresult,
2040 strlen(numberresult) + 1);
2041 numberresult[0] = '0';
2042 numberresult[1] = 'x';
2043 numprinted += 2;
2044 }
2045 n += numprinted;
2046 numberresult += (numprinted + 1);
2047 assert(*(numberresult - 1) == '\0');
2048 assert(*(numberresult - 2) != '\0');
2049 assert(numprinted >= 0);
2050 assert(numberresult <= numberresults + numbersize);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002051 break;
2052 case 's':
2053 {
2054 /* UTF-8 */
Georg Brandl780b2a62009-05-05 09:19:59 +00002055 const char *s = va_arg(count, const char*);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002056 PyObject *str = PyUnicode_DecodeUTF8(s, strlen(s), "replace");
2057 if (!str)
2058 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002059 /* since PyUnicode_DecodeUTF8 returns already flexible
2060 unicode objects, there is no need to call ready on them */
2061 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002062 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002063 n += PyUnicode_GET_LENGTH(str);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002064 /* Remember the str and switch to the next slot */
2065 *callresult++ = str;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002066 break;
2067 }
2068 case 'U':
2069 {
2070 PyObject *obj = va_arg(count, PyObject *);
Victor Stinner910337b2011-10-03 03:20:16 +02002071 assert(obj && _PyUnicode_CHECK(obj));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002072 if (PyUnicode_READY(obj) == -1)
2073 goto fail;
2074 argmaxchar = PyUnicode_MAX_CHAR_VALUE(obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002075 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002076 n += PyUnicode_GET_LENGTH(obj);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002077 break;
2078 }
2079 case 'V':
2080 {
2081 PyObject *obj = va_arg(count, PyObject *);
2082 const char *str = va_arg(count, const char *);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002083 PyObject *str_obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002084 assert(obj || str);
Victor Stinner910337b2011-10-03 03:20:16 +02002085 assert(!obj || _PyUnicode_CHECK(obj));
Victor Stinner2512a8b2011-03-01 22:46:52 +00002086 if (obj) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002087 if (PyUnicode_READY(obj) == -1)
2088 goto fail;
2089 argmaxchar = PyUnicode_MAX_CHAR_VALUE(obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002090 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002091 n += PyUnicode_GET_LENGTH(obj);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002092 *callresult++ = NULL;
2093 }
2094 else {
2095 str_obj = PyUnicode_DecodeUTF8(str, strlen(str), "replace");
2096 if (!str_obj)
2097 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002098 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str_obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002099 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002100 n += PyUnicode_GET_LENGTH(str_obj);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002101 *callresult++ = str_obj;
2102 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002103 break;
2104 }
2105 case 'S':
2106 {
2107 PyObject *obj = va_arg(count, PyObject *);
2108 PyObject *str;
2109 assert(obj);
2110 str = PyObject_Str(obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002111 if (!str || PyUnicode_READY(str) == -1)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002112 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002113 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002114 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002115 n += PyUnicode_GET_LENGTH(str);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002116 /* Remember the str and switch to the next slot */
2117 *callresult++ = str;
2118 break;
2119 }
2120 case 'R':
2121 {
2122 PyObject *obj = va_arg(count, PyObject *);
2123 PyObject *repr;
2124 assert(obj);
2125 repr = PyObject_Repr(obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002126 if (!repr || PyUnicode_READY(repr) == -1)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002127 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002128 argmaxchar = PyUnicode_MAX_CHAR_VALUE(repr);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002129 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002130 n += PyUnicode_GET_LENGTH(repr);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002131 /* Remember the repr and switch to the next slot */
2132 *callresult++ = repr;
2133 break;
2134 }
2135 case 'A':
2136 {
2137 PyObject *obj = va_arg(count, PyObject *);
2138 PyObject *ascii;
2139 assert(obj);
2140 ascii = PyObject_ASCII(obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002141 if (!ascii || PyUnicode_READY(ascii) == -1)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002142 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002143 argmaxchar = PyUnicode_MAX_CHAR_VALUE(ascii);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002144 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002145 n += PyUnicode_GET_LENGTH(ascii);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002146 /* Remember the repr and switch to the next slot */
2147 *callresult++ = ascii;
2148 break;
2149 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002150 default:
2151 /* if we stumble upon an unknown
2152 formatting code, copy the rest of
2153 the format string to the output
2154 string. (we cannot just skip the
2155 code, since there's no way to know
2156 what's in the argument list) */
2157 n += strlen(p);
2158 goto expand;
2159 }
2160 } else
2161 n++;
2162 }
Benjamin Peterson29060642009-01-31 22:14:21 +00002163 expand:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002164 /* step 4: fill the buffer */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002165 /* Since we've analyzed how much space we need,
Benjamin Peterson14339b62009-01-31 16:36:08 +00002166 we don't have to resize the string.
2167 There can be no errors beyond this point. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002168 string = (PyUnicodeObject *)PyUnicode_New(n, maxchar);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002169 if (!string)
2170 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002171 kind = PyUnicode_KIND(string);
2172 data = PyUnicode_DATA(string);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002173 callresult = callresults;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002174 numberresult = numberresults;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002175
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002176 for (i = 0, f = format; *f; f++) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00002177 if (*f == '%') {
Victor Stinner96865452011-03-01 23:44:09 +00002178 const char* p;
Victor Stinner96865452011-03-01 23:44:09 +00002179
2180 p = f;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002181 f = parse_format_flags(f, NULL, NULL, NULL, NULL, NULL);
2182 /* checking for == because the last argument could be a empty
2183 string, which causes i to point to end, the assert at the end of
2184 the loop */
2185 assert(i <= PyUnicode_GET_LENGTH(string));
Walter Dörwaldd2034312007-05-18 16:29:38 +00002186
Benjamin Peterson14339b62009-01-31 16:36:08 +00002187 switch (*f) {
2188 case 'c':
Victor Stinner5ed8b2c2011-02-21 21:13:44 +00002189 {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002190 const int ordinal = va_arg(vargs, int);
2191 PyUnicode_WRITE(kind, data, i++, ordinal);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002192 break;
Victor Stinner5ed8b2c2011-02-21 21:13:44 +00002193 }
Victor Stinner6d970f42011-03-02 00:04:25 +00002194 case 'i':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002195 case 'd':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002196 case 'u':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002197 case 'x':
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002198 case 'p':
2199 /* unused, since we already have the result */
2200 if (*f == 'p')
2201 (void) va_arg(vargs, void *);
2202 else
2203 (void) va_arg(vargs, int);
2204 /* extract the result from numberresults and append. */
2205 for (; *numberresult; ++i, ++numberresult)
2206 PyUnicode_WRITE(kind, data, i, *numberresult);
2207 /* skip over the separating '\0' */
2208 assert(*numberresult == '\0');
2209 numberresult++;
2210 assert(numberresult <= numberresults + numbersize);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002211 break;
2212 case 's':
2213 {
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002214 /* unused, since we already have the result */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002215 Py_ssize_t size;
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002216 (void) va_arg(vargs, char *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002217 size = PyUnicode_GET_LENGTH(*callresult);
2218 assert(PyUnicode_KIND(*callresult) <= PyUnicode_KIND(string));
Victor Stinner6c7a52a2011-09-28 21:39:17 +02002219 if (PyUnicode_CopyCharacters((PyObject*)string, i,
2220 *callresult, 0,
2221 size) < 0)
2222 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002223 i += size;
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002224 /* We're done with the unicode()/repr() => forget it */
2225 Py_DECREF(*callresult);
2226 /* switch to next unicode()/repr() result */
2227 ++callresult;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002228 break;
2229 }
2230 case 'U':
2231 {
2232 PyObject *obj = va_arg(vargs, PyObject *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002233 Py_ssize_t size;
2234 assert(PyUnicode_KIND(obj) <= PyUnicode_KIND(string));
2235 size = PyUnicode_GET_LENGTH(obj);
Victor Stinner6c7a52a2011-09-28 21:39:17 +02002236 if (PyUnicode_CopyCharacters((PyObject*)string, i,
2237 obj, 0,
2238 size) < 0)
2239 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002240 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002241 break;
2242 }
2243 case 'V':
2244 {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002245 Py_ssize_t size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002246 PyObject *obj = va_arg(vargs, PyObject *);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002247 va_arg(vargs, const char *);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002248 if (obj) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002249 size = PyUnicode_GET_LENGTH(obj);
2250 assert(PyUnicode_KIND(obj) <= PyUnicode_KIND(string));
Victor Stinner6c7a52a2011-09-28 21:39:17 +02002251 if (PyUnicode_CopyCharacters((PyObject*)string, i,
2252 obj, 0,
2253 size) < 0)
2254 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002255 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002256 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002257 size = PyUnicode_GET_LENGTH(*callresult);
2258 assert(PyUnicode_KIND(*callresult) <=
2259 PyUnicode_KIND(string));
Victor Stinner6c7a52a2011-09-28 21:39:17 +02002260 if (PyUnicode_CopyCharacters((PyObject*)string, i,
2261 *callresult,
2262 0, size) < 0)
2263 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002264 i += size;
Victor Stinner2512a8b2011-03-01 22:46:52 +00002265 Py_DECREF(*callresult);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002266 }
Victor Stinner2512a8b2011-03-01 22:46:52 +00002267 ++callresult;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002268 break;
2269 }
2270 case 'S':
2271 case 'R':
Victor Stinner9a909002010-10-18 20:59:24 +00002272 case 'A':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002273 {
Benjamin Peterson14339b62009-01-31 16:36:08 +00002274 /* unused, since we already have the result */
2275 (void) va_arg(vargs, PyObject *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002276 assert(PyUnicode_KIND(*callresult) <= PyUnicode_KIND(string));
Victor Stinner6c7a52a2011-09-28 21:39:17 +02002277 if (PyUnicode_CopyCharacters((PyObject*)string, i,
2278 *callresult, 0,
2279 PyUnicode_GET_LENGTH(*callresult)) < 0)
2280 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002281 i += PyUnicode_GET_LENGTH(*callresult);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002282 /* We're done with the unicode()/repr() => forget it */
2283 Py_DECREF(*callresult);
2284 /* switch to next unicode()/repr() result */
2285 ++callresult;
2286 break;
2287 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002288 case '%':
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002289 PyUnicode_WRITE(kind, data, i++, '%');
Benjamin Peterson14339b62009-01-31 16:36:08 +00002290 break;
2291 default:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002292 for (; *p; ++p, ++i)
2293 PyUnicode_WRITE(kind, data, i, *p);
2294 assert(i == PyUnicode_GET_LENGTH(string));
Benjamin Peterson14339b62009-01-31 16:36:08 +00002295 goto end;
2296 }
Victor Stinner1205f272010-09-11 00:54:47 +00002297 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002298 else {
2299 assert(i < PyUnicode_GET_LENGTH(string));
2300 PyUnicode_WRITE(kind, data, i++, *f);
2301 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002302 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002303 assert(i == PyUnicode_GET_LENGTH(string));
Walter Dörwaldd2034312007-05-18 16:29:38 +00002304
Benjamin Peterson29060642009-01-31 22:14:21 +00002305 end:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002306 if (callresults)
2307 PyObject_Free(callresults);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002308 if (numberresults)
2309 PyObject_Free(numberresults);
2310 return (PyObject *)string;
Benjamin Peterson29060642009-01-31 22:14:21 +00002311 fail:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002312 if (callresults) {
2313 PyObject **callresult2 = callresults;
2314 while (callresult2 < callresult) {
Victor Stinner2512a8b2011-03-01 22:46:52 +00002315 Py_XDECREF(*callresult2);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002316 ++callresult2;
2317 }
2318 PyObject_Free(callresults);
2319 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002320 if (numberresults)
2321 PyObject_Free(numberresults);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002322 return NULL;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002323}
2324
Walter Dörwaldd2034312007-05-18 16:29:38 +00002325PyObject *
2326PyUnicode_FromFormat(const char *format, ...)
2327{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002328 PyObject* ret;
2329 va_list vargs;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002330
2331#ifdef HAVE_STDARG_PROTOTYPES
Benjamin Peterson14339b62009-01-31 16:36:08 +00002332 va_start(vargs, format);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002333#else
Benjamin Peterson14339b62009-01-31 16:36:08 +00002334 va_start(vargs);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002335#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00002336 ret = PyUnicode_FromFormatV(format, vargs);
2337 va_end(vargs);
2338 return ret;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002339}
2340
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002341#ifdef HAVE_WCHAR_H
2342
Victor Stinner5593d8a2010-10-02 11:11:27 +00002343/* Helper function for PyUnicode_AsWideChar() and PyUnicode_AsWideCharString():
2344 convert a Unicode object to a wide character string.
2345
Victor Stinnerd88d9832011-09-06 02:00:05 +02002346 - If w is NULL: return the number of wide characters (including the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002347 character) required to convert the unicode object. Ignore size argument.
2348
Victor Stinnerd88d9832011-09-06 02:00:05 +02002349 - Otherwise: return the number of wide characters (excluding the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002350 character) written into w. Write at most size wide characters (including
Victor Stinnerd88d9832011-09-06 02:00:05 +02002351 the null character). */
Victor Stinner5593d8a2010-10-02 11:11:27 +00002352static Py_ssize_t
Victor Stinner137c34c2010-09-29 10:25:54 +00002353unicode_aswidechar(PyUnicodeObject *unicode,
2354 wchar_t *w,
2355 Py_ssize_t size)
2356{
Victor Stinner5593d8a2010-10-02 11:11:27 +00002357 Py_ssize_t res;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002358 const wchar_t *wstr;
2359
2360 wstr = PyUnicode_AsUnicodeAndSize((PyObject *)unicode, &res);
2361 if (wstr == NULL)
2362 return -1;
2363
Victor Stinner5593d8a2010-10-02 11:11:27 +00002364 if (w != NULL) {
Victor Stinner5593d8a2010-10-02 11:11:27 +00002365 if (size > res)
2366 size = res + 1;
2367 else
2368 res = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002369 Py_MEMCPY(w, wstr, size * sizeof(wchar_t));
Victor Stinner5593d8a2010-10-02 11:11:27 +00002370 return res;
2371 }
2372 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002373 return res + 1;
Victor Stinner137c34c2010-09-29 10:25:54 +00002374}
2375
2376Py_ssize_t
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002377PyUnicode_AsWideChar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002378 wchar_t *w,
2379 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002380{
2381 if (unicode == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002382 PyErr_BadInternalCall();
2383 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002384 }
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002385 return unicode_aswidechar((PyUnicodeObject*)unicode, w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002386}
2387
Victor Stinner137c34c2010-09-29 10:25:54 +00002388wchar_t*
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00002389PyUnicode_AsWideCharString(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002390 Py_ssize_t *size)
2391{
2392 wchar_t* buffer;
2393 Py_ssize_t buflen;
2394
2395 if (unicode == NULL) {
2396 PyErr_BadInternalCall();
2397 return NULL;
2398 }
2399
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00002400 buflen = unicode_aswidechar((PyUnicodeObject *)unicode, NULL, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002401 if (buflen == -1)
2402 return NULL;
Victor Stinner5593d8a2010-10-02 11:11:27 +00002403 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < buflen) {
Victor Stinner137c34c2010-09-29 10:25:54 +00002404 PyErr_NoMemory();
2405 return NULL;
2406 }
2407
Victor Stinner137c34c2010-09-29 10:25:54 +00002408 buffer = PyMem_MALLOC(buflen * sizeof(wchar_t));
2409 if (buffer == NULL) {
2410 PyErr_NoMemory();
2411 return NULL;
2412 }
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00002413 buflen = unicode_aswidechar((PyUnicodeObject *)unicode, buffer, buflen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002414 if (buflen == -1)
2415 return NULL;
Victor Stinner5593d8a2010-10-02 11:11:27 +00002416 if (size != NULL)
2417 *size = buflen;
Victor Stinner137c34c2010-09-29 10:25:54 +00002418 return buffer;
2419}
2420
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002421#endif /* HAVE_WCHAR_H */
Guido van Rossumd57fd912000-03-10 22:53:23 +00002422
Alexander Belopolsky40018472011-02-26 01:02:56 +00002423PyObject *
2424PyUnicode_FromOrdinal(int ordinal)
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002425{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002426 PyObject *v;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002427 if (ordinal < 0 || ordinal > 0x10ffff) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002428 PyErr_SetString(PyExc_ValueError,
2429 "chr() arg not in range(0x110000)");
2430 return NULL;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002431 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00002432
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002433 if (ordinal < 256)
2434 return get_latin1_char(ordinal);
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002435
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002436 v = PyUnicode_New(1, ordinal);
2437 if (v == NULL)
2438 return NULL;
2439 PyUnicode_WRITE(PyUnicode_KIND(v), PyUnicode_DATA(v), 0, ordinal);
2440 return v;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002441}
2442
Alexander Belopolsky40018472011-02-26 01:02:56 +00002443PyObject *
2444PyUnicode_FromObject(register PyObject *obj)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002445{
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002446 /* XXX Perhaps we should make this API an alias of
Benjamin Peterson29060642009-01-31 22:14:21 +00002447 PyObject_Str() instead ?! */
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002448 if (PyUnicode_CheckExact(obj)) {
Victor Stinnerd3a83d52011-10-01 03:09:33 +02002449 if (PyUnicode_READY(obj))
2450 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +00002451 Py_INCREF(obj);
2452 return obj;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002453 }
2454 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002455 /* For a Unicode subtype that's not a Unicode object,
2456 return a true Unicode object with the same data. */
Victor Stinner2219e0a2011-10-01 01:16:59 +02002457 return PyUnicode_Copy(obj);
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002458 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00002459 PyErr_Format(PyExc_TypeError,
2460 "Can't convert '%.100s' object to str implicitly",
Christian Heimes90aa7642007-12-19 02:45:37 +00002461 Py_TYPE(obj)->tp_name);
Guido van Rossum98297ee2007-11-06 21:34:58 +00002462 return NULL;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002463}
2464
Alexander Belopolsky40018472011-02-26 01:02:56 +00002465PyObject *
2466PyUnicode_FromEncodedObject(register PyObject *obj,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002467 const char *encoding,
2468 const char *errors)
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002469{
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002470 Py_buffer buffer;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002471 PyObject *v;
Tim Petersced69f82003-09-16 20:30:58 +00002472
Guido van Rossumd57fd912000-03-10 22:53:23 +00002473 if (obj == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002474 PyErr_BadInternalCall();
2475 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002476 }
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002477
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002478 /* Decoding bytes objects is the most common case and should be fast */
2479 if (PyBytes_Check(obj)) {
2480 if (PyBytes_GET_SIZE(obj) == 0) {
2481 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02002482 v = unicode_empty;
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002483 }
2484 else {
2485 v = PyUnicode_Decode(
2486 PyBytes_AS_STRING(obj), PyBytes_GET_SIZE(obj),
2487 encoding, errors);
2488 }
2489 return v;
2490 }
2491
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002492 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002493 PyErr_SetString(PyExc_TypeError,
2494 "decoding str is not supported");
2495 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002496 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002497
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002498 /* Retrieve a bytes buffer view through the PEP 3118 buffer interface */
2499 if (PyObject_GetBuffer(obj, &buffer, PyBUF_SIMPLE) < 0) {
2500 PyErr_Format(PyExc_TypeError,
2501 "coercing to str: need bytes, bytearray "
2502 "or buffer-like object, %.80s found",
2503 Py_TYPE(obj)->tp_name);
2504 return NULL;
Marc-André Lemburg6871f6a2001-09-20 12:53:16 +00002505 }
Tim Petersced69f82003-09-16 20:30:58 +00002506
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002507 if (buffer.len == 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002508 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02002509 v = unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002510 }
Tim Petersced69f82003-09-16 20:30:58 +00002511 else
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002512 v = PyUnicode_Decode((char*) buffer.buf, buffer.len, encoding, errors);
Marc-André Lemburgad7c98e2001-01-17 17:09:53 +00002513
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002514 PyBuffer_Release(&buffer);
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002515 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002516}
2517
Victor Stinner600d3be2010-06-10 12:00:55 +00002518/* Convert encoding to lower case and replace '_' with '-' in order to
Victor Stinner37296e82010-06-10 13:36:23 +00002519 catch e.g. UTF_8. Return 0 on error (encoding is longer than lower_len-1),
2520 1 on success. */
2521static int
2522normalize_encoding(const char *encoding,
2523 char *lower,
2524 size_t lower_len)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002525{
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002526 const char *e;
Victor Stinner600d3be2010-06-10 12:00:55 +00002527 char *l;
2528 char *l_end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002529
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002530 e = encoding;
2531 l = lower;
Victor Stinner600d3be2010-06-10 12:00:55 +00002532 l_end = &lower[lower_len - 1];
Victor Stinner37296e82010-06-10 13:36:23 +00002533 while (*e) {
2534 if (l == l_end)
2535 return 0;
David Malcolm96960882010-11-05 17:23:41 +00002536 if (Py_ISUPPER(*e)) {
2537 *l++ = Py_TOLOWER(*e++);
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002538 }
2539 else if (*e == '_') {
2540 *l++ = '-';
2541 e++;
2542 }
2543 else {
2544 *l++ = *e++;
2545 }
2546 }
2547 *l = '\0';
Victor Stinner37296e82010-06-10 13:36:23 +00002548 return 1;
Victor Stinner600d3be2010-06-10 12:00:55 +00002549}
2550
Alexander Belopolsky40018472011-02-26 01:02:56 +00002551PyObject *
2552PyUnicode_Decode(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002553 Py_ssize_t size,
2554 const char *encoding,
2555 const char *errors)
Victor Stinner600d3be2010-06-10 12:00:55 +00002556{
2557 PyObject *buffer = NULL, *unicode;
2558 Py_buffer info;
2559 char lower[11]; /* Enough for any encoding shortcut */
2560
2561 if (encoding == NULL)
Alexander Belopolsky1d521462011-02-25 19:19:57 +00002562 return PyUnicode_DecodeUTF8(s, size, errors);
Fred Drakee4315f52000-05-09 19:53:39 +00002563
2564 /* Shortcuts for common default encodings */
Victor Stinner37296e82010-06-10 13:36:23 +00002565 if (normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00002566 if ((strcmp(lower, "utf-8") == 0) ||
2567 (strcmp(lower, "utf8") == 0))
Victor Stinner37296e82010-06-10 13:36:23 +00002568 return PyUnicode_DecodeUTF8(s, size, errors);
2569 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00002570 (strcmp(lower, "latin1") == 0) ||
Victor Stinner37296e82010-06-10 13:36:23 +00002571 (strcmp(lower, "iso-8859-1") == 0))
2572 return PyUnicode_DecodeLatin1(s, size, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02002573#ifdef HAVE_MBCS
Victor Stinner37296e82010-06-10 13:36:23 +00002574 else if (strcmp(lower, "mbcs") == 0)
2575 return PyUnicode_DecodeMBCS(s, size, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00002576#endif
Victor Stinner37296e82010-06-10 13:36:23 +00002577 else if (strcmp(lower, "ascii") == 0)
2578 return PyUnicode_DecodeASCII(s, size, errors);
2579 else if (strcmp(lower, "utf-16") == 0)
2580 return PyUnicode_DecodeUTF16(s, size, errors, 0);
2581 else if (strcmp(lower, "utf-32") == 0)
2582 return PyUnicode_DecodeUTF32(s, size, errors, 0);
2583 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002584
2585 /* Decode via the codec registry */
Guido van Rossumbe801ac2007-10-08 03:32:34 +00002586 buffer = NULL;
Antoine Pitrouc3b39242009-01-03 16:59:18 +00002587 if (PyBuffer_FillInfo(&info, NULL, (void *)s, size, 1, PyBUF_FULL_RO) < 0)
Guido van Rossumbe801ac2007-10-08 03:32:34 +00002588 goto onError;
Antoine Pitrouee58fa42008-08-19 18:22:14 +00002589 buffer = PyMemoryView_FromBuffer(&info);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002590 if (buffer == NULL)
2591 goto onError;
2592 unicode = PyCodec_Decode(buffer, encoding, errors);
2593 if (unicode == NULL)
2594 goto onError;
2595 if (!PyUnicode_Check(unicode)) {
2596 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00002597 "decoder did not return a str object (type=%.400s)",
Christian Heimes90aa7642007-12-19 02:45:37 +00002598 Py_TYPE(unicode)->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002599 Py_DECREF(unicode);
2600 goto onError;
2601 }
2602 Py_DECREF(buffer);
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02002603 if (_PyUnicode_READY_REPLACE(&unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002604 Py_DECREF(unicode);
2605 return NULL;
2606 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002607 return unicode;
Tim Petersced69f82003-09-16 20:30:58 +00002608
Benjamin Peterson29060642009-01-31 22:14:21 +00002609 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00002610 Py_XDECREF(buffer);
2611 return NULL;
2612}
2613
Alexander Belopolsky40018472011-02-26 01:02:56 +00002614PyObject *
2615PyUnicode_AsDecodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002616 const char *encoding,
2617 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002618{
2619 PyObject *v;
2620
2621 if (!PyUnicode_Check(unicode)) {
2622 PyErr_BadArgument();
2623 goto onError;
2624 }
2625
2626 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00002627 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002628
2629 /* Decode via the codec registry */
2630 v = PyCodec_Decode(unicode, encoding, errors);
2631 if (v == NULL)
2632 goto onError;
2633 return v;
2634
Benjamin Peterson29060642009-01-31 22:14:21 +00002635 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002636 return NULL;
2637}
2638
Alexander Belopolsky40018472011-02-26 01:02:56 +00002639PyObject *
2640PyUnicode_AsDecodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002641 const char *encoding,
2642 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002643{
2644 PyObject *v;
2645
2646 if (!PyUnicode_Check(unicode)) {
2647 PyErr_BadArgument();
2648 goto onError;
2649 }
2650
2651 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00002652 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002653
2654 /* Decode via the codec registry */
2655 v = PyCodec_Decode(unicode, encoding, errors);
2656 if (v == NULL)
2657 goto onError;
2658 if (!PyUnicode_Check(v)) {
2659 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00002660 "decoder did not return a str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002661 Py_TYPE(v)->tp_name);
2662 Py_DECREF(v);
2663 goto onError;
2664 }
2665 return v;
2666
Benjamin Peterson29060642009-01-31 22:14:21 +00002667 onError:
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002668 return NULL;
2669}
2670
Alexander Belopolsky40018472011-02-26 01:02:56 +00002671PyObject *
2672PyUnicode_Encode(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002673 Py_ssize_t size,
2674 const char *encoding,
2675 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002676{
2677 PyObject *v, *unicode;
Tim Petersced69f82003-09-16 20:30:58 +00002678
Guido van Rossumd57fd912000-03-10 22:53:23 +00002679 unicode = PyUnicode_FromUnicode(s, size);
2680 if (unicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00002681 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002682 v = PyUnicode_AsEncodedString(unicode, encoding, errors);
2683 Py_DECREF(unicode);
2684 return v;
2685}
2686
Alexander Belopolsky40018472011-02-26 01:02:56 +00002687PyObject *
2688PyUnicode_AsEncodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002689 const char *encoding,
2690 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002691{
2692 PyObject *v;
2693
2694 if (!PyUnicode_Check(unicode)) {
2695 PyErr_BadArgument();
2696 goto onError;
2697 }
2698
2699 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00002700 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002701
2702 /* Encode via the codec registry */
2703 v = PyCodec_Encode(unicode, encoding, errors);
2704 if (v == NULL)
2705 goto onError;
2706 return v;
2707
Benjamin Peterson29060642009-01-31 22:14:21 +00002708 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002709 return NULL;
2710}
2711
Victor Stinnerad158722010-10-27 00:25:46 +00002712PyObject *
2713PyUnicode_EncodeFSDefault(PyObject *unicode)
Victor Stinnerae6265f2010-05-15 16:27:27 +00002714{
Victor Stinner99b95382011-07-04 14:23:54 +02002715#ifdef HAVE_MBCS
Victor Stinnerad158722010-10-27 00:25:46 +00002716 return PyUnicode_EncodeMBCS(PyUnicode_AS_UNICODE(unicode),
2717 PyUnicode_GET_SIZE(unicode),
2718 NULL);
2719#elif defined(__APPLE__)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002720 return _PyUnicode_AsUTF8String(unicode, "surrogateescape");
Victor Stinnerad158722010-10-27 00:25:46 +00002721#else
Victor Stinner793b5312011-04-27 00:24:21 +02002722 PyInterpreterState *interp = PyThreadState_GET()->interp;
2723 /* Bootstrap check: if the filesystem codec is implemented in Python, we
2724 cannot use it to encode and decode filenames before it is loaded. Load
2725 the Python codec requires to encode at least its own filename. Use the C
2726 version of the locale codec until the codec registry is initialized and
2727 the Python codec is loaded.
2728
2729 Py_FileSystemDefaultEncoding is shared between all interpreters, we
2730 cannot only rely on it: check also interp->fscodec_initialized for
2731 subinterpreters. */
2732 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Victor Stinnerae6265f2010-05-15 16:27:27 +00002733 return PyUnicode_AsEncodedString(unicode,
2734 Py_FileSystemDefaultEncoding,
2735 "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00002736 }
2737 else {
Victor Stinnerf3170cc2010-10-15 12:04:23 +00002738 /* locale encoding with surrogateescape */
2739 wchar_t *wchar;
2740 char *bytes;
2741 PyObject *bytes_obj;
Victor Stinner2f02a512010-11-08 22:43:46 +00002742 size_t error_pos;
Victor Stinnerf3170cc2010-10-15 12:04:23 +00002743
2744 wchar = PyUnicode_AsWideCharString(unicode, NULL);
2745 if (wchar == NULL)
2746 return NULL;
Victor Stinner2f02a512010-11-08 22:43:46 +00002747 bytes = _Py_wchar2char(wchar, &error_pos);
2748 if (bytes == NULL) {
2749 if (error_pos != (size_t)-1) {
2750 char *errmsg = strerror(errno);
2751 PyObject *exc = NULL;
2752 if (errmsg == NULL)
2753 errmsg = "Py_wchar2char() failed";
2754 raise_encode_exception(&exc,
2755 "filesystemencoding",
2756 PyUnicode_AS_UNICODE(unicode), PyUnicode_GET_SIZE(unicode),
2757 error_pos, error_pos+1,
2758 errmsg);
2759 Py_XDECREF(exc);
2760 }
2761 else
2762 PyErr_NoMemory();
2763 PyMem_Free(wchar);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00002764 return NULL;
Victor Stinner2f02a512010-11-08 22:43:46 +00002765 }
2766 PyMem_Free(wchar);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00002767
2768 bytes_obj = PyBytes_FromString(bytes);
2769 PyMem_Free(bytes);
2770 return bytes_obj;
Victor Stinnerc39211f2010-09-29 16:35:47 +00002771 }
Victor Stinnerad158722010-10-27 00:25:46 +00002772#endif
Victor Stinnerae6265f2010-05-15 16:27:27 +00002773}
2774
Alexander Belopolsky40018472011-02-26 01:02:56 +00002775PyObject *
2776PyUnicode_AsEncodedString(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002777 const char *encoding,
2778 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002779{
2780 PyObject *v;
Victor Stinner600d3be2010-06-10 12:00:55 +00002781 char lower[11]; /* Enough for any encoding shortcut */
Tim Petersced69f82003-09-16 20:30:58 +00002782
Guido van Rossumd57fd912000-03-10 22:53:23 +00002783 if (!PyUnicode_Check(unicode)) {
2784 PyErr_BadArgument();
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00002785 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002786 }
Fred Drakee4315f52000-05-09 19:53:39 +00002787
Victor Stinner2f283c22011-03-02 01:21:46 +00002788 if (encoding == NULL) {
2789 if (errors == NULL || strcmp(errors, "strict") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002790 return _PyUnicode_AsUTF8String(unicode, NULL);
Victor Stinner2f283c22011-03-02 01:21:46 +00002791 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002792 return _PyUnicode_AsUTF8String(unicode, errors);
Victor Stinner2f283c22011-03-02 01:21:46 +00002793 }
Fred Drakee4315f52000-05-09 19:53:39 +00002794
2795 /* Shortcuts for common default encodings */
Victor Stinner37296e82010-06-10 13:36:23 +00002796 if (normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00002797 if ((strcmp(lower, "utf-8") == 0) ||
2798 (strcmp(lower, "utf8") == 0))
Victor Stinnera5c68c32011-03-02 01:03:14 +00002799 {
Victor Stinner2f283c22011-03-02 01:21:46 +00002800 if (errors == NULL || strcmp(errors, "strict") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002801 return _PyUnicode_AsUTF8String(unicode, NULL);
Victor Stinner2f283c22011-03-02 01:21:46 +00002802 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002803 return _PyUnicode_AsUTF8String(unicode, errors);
Victor Stinnera5c68c32011-03-02 01:03:14 +00002804 }
Victor Stinner37296e82010-06-10 13:36:23 +00002805 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00002806 (strcmp(lower, "latin1") == 0) ||
Victor Stinner37296e82010-06-10 13:36:23 +00002807 (strcmp(lower, "iso-8859-1") == 0))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002808 return _PyUnicode_AsLatin1String(unicode, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02002809#ifdef HAVE_MBCS
Victor Stinner37296e82010-06-10 13:36:23 +00002810 else if (strcmp(lower, "mbcs") == 0)
2811 return PyUnicode_EncodeMBCS(PyUnicode_AS_UNICODE(unicode),
2812 PyUnicode_GET_SIZE(unicode),
2813 errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00002814#endif
Victor Stinner37296e82010-06-10 13:36:23 +00002815 else if (strcmp(lower, "ascii") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002816 return _PyUnicode_AsASCIIString(unicode, errors);
Victor Stinner37296e82010-06-10 13:36:23 +00002817 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002818
2819 /* Encode via the codec registry */
2820 v = PyCodec_Encode(unicode, encoding, errors);
2821 if (v == NULL)
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00002822 return NULL;
2823
2824 /* The normal path */
2825 if (PyBytes_Check(v))
2826 return v;
2827
2828 /* If the codec returns a buffer, raise a warning and convert to bytes */
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002829 if (PyByteArray_Check(v)) {
Victor Stinner4a2b7a12010-08-13 14:03:48 +00002830 int error;
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00002831 PyObject *b;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00002832
2833 error = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
2834 "encoder %s returned bytearray instead of bytes",
2835 encoding);
2836 if (error) {
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00002837 Py_DECREF(v);
2838 return NULL;
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002839 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002840
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00002841 b = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(v), Py_SIZE(v));
2842 Py_DECREF(v);
2843 return b;
2844 }
2845
2846 PyErr_Format(PyExc_TypeError,
2847 "encoder did not return a bytes object (type=%.400s)",
2848 Py_TYPE(v)->tp_name);
2849 Py_DECREF(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002850 return NULL;
2851}
2852
Alexander Belopolsky40018472011-02-26 01:02:56 +00002853PyObject *
2854PyUnicode_AsEncodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002855 const char *encoding,
2856 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002857{
2858 PyObject *v;
2859
2860 if (!PyUnicode_Check(unicode)) {
2861 PyErr_BadArgument();
2862 goto onError;
2863 }
2864
2865 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00002866 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002867
2868 /* Encode via the codec registry */
2869 v = PyCodec_Encode(unicode, encoding, errors);
2870 if (v == NULL)
2871 goto onError;
2872 if (!PyUnicode_Check(v)) {
2873 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00002874 "encoder did not return an str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002875 Py_TYPE(v)->tp_name);
2876 Py_DECREF(v);
2877 goto onError;
2878 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002879 return v;
Tim Petersced69f82003-09-16 20:30:58 +00002880
Benjamin Peterson29060642009-01-31 22:14:21 +00002881 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00002882 return NULL;
2883}
2884
Guido van Rossum00bc0e02007-10-15 02:52:41 +00002885PyObject*
Christian Heimes5894ba72007-11-04 11:43:14 +00002886PyUnicode_DecodeFSDefault(const char *s) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00002887 Py_ssize_t size = (Py_ssize_t)strlen(s);
Christian Heimes5894ba72007-11-04 11:43:14 +00002888 return PyUnicode_DecodeFSDefaultAndSize(s, size);
2889}
Guido van Rossum00bc0e02007-10-15 02:52:41 +00002890
Christian Heimes5894ba72007-11-04 11:43:14 +00002891PyObject*
2892PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
2893{
Victor Stinner99b95382011-07-04 14:23:54 +02002894#ifdef HAVE_MBCS
Victor Stinnerad158722010-10-27 00:25:46 +00002895 return PyUnicode_DecodeMBCS(s, size, NULL);
2896#elif defined(__APPLE__)
2897 return PyUnicode_DecodeUTF8(s, size, "surrogateescape");
2898#else
Victor Stinner793b5312011-04-27 00:24:21 +02002899 PyInterpreterState *interp = PyThreadState_GET()->interp;
2900 /* Bootstrap check: if the filesystem codec is implemented in Python, we
2901 cannot use it to encode and decode filenames before it is loaded. Load
2902 the Python codec requires to encode at least its own filename. Use the C
2903 version of the locale codec until the codec registry is initialized and
2904 the Python codec is loaded.
2905
2906 Py_FileSystemDefaultEncoding is shared between all interpreters, we
2907 cannot only rely on it: check also interp->fscodec_initialized for
2908 subinterpreters. */
2909 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00002910 return PyUnicode_Decode(s, size,
2911 Py_FileSystemDefaultEncoding,
Victor Stinnerb9a20ad2010-04-30 16:37:52 +00002912 "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00002913 }
2914 else {
Victor Stinnerf3170cc2010-10-15 12:04:23 +00002915 /* locale encoding with surrogateescape */
2916 wchar_t *wchar;
2917 PyObject *unicode;
Victor Stinner168e1172010-10-16 23:16:16 +00002918 size_t len;
Victor Stinnerf3170cc2010-10-15 12:04:23 +00002919
2920 if (s[size] != '\0' || size != strlen(s)) {
2921 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
2922 return NULL;
2923 }
2924
Victor Stinner168e1172010-10-16 23:16:16 +00002925 wchar = _Py_char2wchar(s, &len);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00002926 if (wchar == NULL)
Victor Stinnerd5af0a52010-11-08 23:34:29 +00002927 return PyErr_NoMemory();
Victor Stinnerf3170cc2010-10-15 12:04:23 +00002928
Victor Stinner168e1172010-10-16 23:16:16 +00002929 unicode = PyUnicode_FromWideChar(wchar, len);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00002930 PyMem_Free(wchar);
2931 return unicode;
Guido van Rossum00bc0e02007-10-15 02:52:41 +00002932 }
Victor Stinnerad158722010-10-27 00:25:46 +00002933#endif
Guido van Rossum00bc0e02007-10-15 02:52:41 +00002934}
2935
Martin v. Löwis011e8422009-05-05 04:43:17 +00002936
2937int
2938PyUnicode_FSConverter(PyObject* arg, void* addr)
2939{
2940 PyObject *output = NULL;
2941 Py_ssize_t size;
2942 void *data;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00002943 if (arg == NULL) {
2944 Py_DECREF(*(PyObject**)addr);
2945 return 1;
2946 }
Victor Stinnerdcb24032010-04-22 12:08:36 +00002947 if (PyBytes_Check(arg)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00002948 output = arg;
2949 Py_INCREF(output);
2950 }
2951 else {
2952 arg = PyUnicode_FromObject(arg);
2953 if (!arg)
2954 return 0;
Victor Stinnerae6265f2010-05-15 16:27:27 +00002955 output = PyUnicode_EncodeFSDefault(arg);
Martin v. Löwis011e8422009-05-05 04:43:17 +00002956 Py_DECREF(arg);
2957 if (!output)
2958 return 0;
2959 if (!PyBytes_Check(output)) {
2960 Py_DECREF(output);
2961 PyErr_SetString(PyExc_TypeError, "encoder failed to return bytes");
2962 return 0;
2963 }
2964 }
Victor Stinner0ea2a462010-04-30 00:22:08 +00002965 size = PyBytes_GET_SIZE(output);
2966 data = PyBytes_AS_STRING(output);
Martin v. Löwis011e8422009-05-05 04:43:17 +00002967 if (size != strlen(data)) {
Benjamin Peterson7a6b44a2011-08-18 13:51:47 -05002968 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
Martin v. Löwis011e8422009-05-05 04:43:17 +00002969 Py_DECREF(output);
2970 return 0;
2971 }
2972 *(PyObject**)addr = output;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00002973 return Py_CLEANUP_SUPPORTED;
Martin v. Löwis011e8422009-05-05 04:43:17 +00002974}
2975
2976
Victor Stinner47fcb5b2010-08-13 23:59:58 +00002977int
2978PyUnicode_FSDecoder(PyObject* arg, void* addr)
2979{
2980 PyObject *output = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00002981 if (arg == NULL) {
2982 Py_DECREF(*(PyObject**)addr);
2983 return 1;
2984 }
2985 if (PyUnicode_Check(arg)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002986 if (PyUnicode_READY(arg))
2987 return 0;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00002988 output = arg;
2989 Py_INCREF(output);
2990 }
2991 else {
2992 arg = PyBytes_FromObject(arg);
2993 if (!arg)
2994 return 0;
2995 output = PyUnicode_DecodeFSDefaultAndSize(PyBytes_AS_STRING(arg),
2996 PyBytes_GET_SIZE(arg));
2997 Py_DECREF(arg);
2998 if (!output)
2999 return 0;
3000 if (!PyUnicode_Check(output)) {
3001 Py_DECREF(output);
3002 PyErr_SetString(PyExc_TypeError, "decoder failed to return unicode");
3003 return 0;
3004 }
3005 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003006 if (findchar(PyUnicode_DATA(output), PyUnicode_KIND(output),
3007 PyUnicode_GET_LENGTH(output), 0, 1)) {
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003008 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
3009 Py_DECREF(output);
3010 return 0;
3011 }
3012 *(PyObject**)addr = output;
3013 return Py_CLEANUP_SUPPORTED;
3014}
3015
3016
Martin v. Löwis5b222132007-06-10 09:51:05 +00003017char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003018PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *psize)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003019{
Christian Heimesf3863112007-11-22 07:46:41 +00003020 PyObject *bytes;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003021 PyUnicodeObject *u = (PyUnicodeObject *)unicode;
3022
Neal Norwitze0a0a6e2007-08-25 01:04:21 +00003023 if (!PyUnicode_Check(unicode)) {
3024 PyErr_BadArgument();
3025 return NULL;
3026 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003027 if (PyUnicode_READY(u) == -1)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003028 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003029
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003030 if (PyUnicode_UTF8(unicode) == NULL) {
3031 assert(!PyUnicode_IS_COMPACT_ASCII(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003032 bytes = _PyUnicode_AsUTF8String(unicode, "strict");
3033 if (bytes == NULL)
3034 return NULL;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003035 _PyUnicode_UTF8(u) = PyObject_MALLOC(PyBytes_GET_SIZE(bytes) + 1);
3036 if (_PyUnicode_UTF8(u) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003037 Py_DECREF(bytes);
3038 return NULL;
3039 }
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003040 _PyUnicode_UTF8_LENGTH(u) = PyBytes_GET_SIZE(bytes);
3041 Py_MEMCPY(_PyUnicode_UTF8(u), PyBytes_AS_STRING(bytes), _PyUnicode_UTF8_LENGTH(u) + 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003042 Py_DECREF(bytes);
3043 }
3044
3045 if (psize)
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003046 *psize = PyUnicode_UTF8_LENGTH(unicode);
3047 return PyUnicode_UTF8(unicode);
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003048}
3049
3050char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003051PyUnicode_AsUTF8(PyObject *unicode)
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003052{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003053 return PyUnicode_AsUTF8AndSize(unicode, NULL);
3054}
3055
3056#ifdef Py_DEBUG
3057int unicode_as_unicode_calls = 0;
3058#endif
3059
3060
3061Py_UNICODE *
3062PyUnicode_AsUnicodeAndSize(PyObject *unicode, Py_ssize_t *size)
3063{
3064 PyUnicodeObject *u;
3065 const unsigned char *one_byte;
3066#if SIZEOF_WCHAR_T == 4
3067 const Py_UCS2 *two_bytes;
3068#else
3069 const Py_UCS4 *four_bytes;
3070 const Py_UCS4 *ucs4_end;
3071 Py_ssize_t num_surrogates;
3072#endif
3073 wchar_t *w;
3074 wchar_t *wchar_end;
3075
3076 if (!PyUnicode_Check(unicode)) {
3077 PyErr_BadArgument();
3078 return NULL;
3079 }
3080 u = (PyUnicodeObject*)unicode;
3081 if (_PyUnicode_WSTR(u) == NULL) {
3082 /* Non-ASCII compact unicode object */
3083 assert(_PyUnicode_KIND(u) != 0);
3084 assert(PyUnicode_IS_READY(u));
3085
3086#ifdef Py_DEBUG
3087 ++unicode_as_unicode_calls;
3088#endif
3089
3090 if (PyUnicode_KIND(u) == PyUnicode_4BYTE_KIND) {
3091#if SIZEOF_WCHAR_T == 2
3092 four_bytes = PyUnicode_4BYTE_DATA(u);
3093 ucs4_end = four_bytes + _PyUnicode_LENGTH(u);
3094 num_surrogates = 0;
3095
3096 for (; four_bytes < ucs4_end; ++four_bytes) {
3097 if (*four_bytes > 0xFFFF)
3098 ++num_surrogates;
3099 }
3100
3101 _PyUnicode_WSTR(u) = (wchar_t *) PyObject_MALLOC(
3102 sizeof(wchar_t) * (_PyUnicode_LENGTH(u) + 1 + num_surrogates));
3103 if (!_PyUnicode_WSTR(u)) {
3104 PyErr_NoMemory();
3105 return NULL;
3106 }
3107 _PyUnicode_WSTR_LENGTH(u) = _PyUnicode_LENGTH(u) + num_surrogates;
3108
3109 w = _PyUnicode_WSTR(u);
3110 wchar_end = w + _PyUnicode_WSTR_LENGTH(u);
3111 four_bytes = PyUnicode_4BYTE_DATA(u);
3112 for (; four_bytes < ucs4_end; ++four_bytes, ++w) {
3113 if (*four_bytes > 0xFFFF) {
3114 /* encode surrogate pair in this case */
3115 *w++ = 0xD800 | ((*four_bytes - 0x10000) >> 10);
3116 *w = 0xDC00 | ((*four_bytes - 0x10000) & 0x3FF);
3117 }
3118 else
3119 *w = *four_bytes;
3120
3121 if (w > wchar_end) {
3122 assert(0 && "Miscalculated string end");
3123 }
3124 }
3125 *w = 0;
3126#else
3127 /* sizeof(wchar_t) == 4 */
3128 Py_FatalError("Impossible unicode object state, wstr and str "
3129 "should share memory already.");
3130 return NULL;
3131#endif
3132 }
3133 else {
3134 _PyUnicode_WSTR(u) = (wchar_t *) PyObject_MALLOC(sizeof(wchar_t) *
3135 (_PyUnicode_LENGTH(u) + 1));
3136 if (!_PyUnicode_WSTR(u)) {
3137 PyErr_NoMemory();
3138 return NULL;
3139 }
3140 if (!PyUnicode_IS_COMPACT_ASCII(u))
3141 _PyUnicode_WSTR_LENGTH(u) = _PyUnicode_LENGTH(u);
3142 w = _PyUnicode_WSTR(u);
3143 wchar_end = w + _PyUnicode_LENGTH(u);
3144
3145 if (PyUnicode_KIND(u) == PyUnicode_1BYTE_KIND) {
3146 one_byte = PyUnicode_1BYTE_DATA(u);
3147 for (; w < wchar_end; ++one_byte, ++w)
3148 *w = *one_byte;
3149 /* null-terminate the wstr */
3150 *w = 0;
3151 }
3152 else if (PyUnicode_KIND(u) == PyUnicode_2BYTE_KIND) {
3153#if SIZEOF_WCHAR_T == 4
3154 two_bytes = PyUnicode_2BYTE_DATA(u);
3155 for (; w < wchar_end; ++two_bytes, ++w)
3156 *w = *two_bytes;
3157 /* null-terminate the wstr */
3158 *w = 0;
3159#else
3160 /* sizeof(wchar_t) == 2 */
3161 PyObject_FREE(_PyUnicode_WSTR(u));
3162 _PyUnicode_WSTR(u) = NULL;
3163 Py_FatalError("Impossible unicode object state, wstr "
3164 "and str should share memory already.");
3165 return NULL;
3166#endif
3167 }
3168 else {
3169 assert(0 && "This should never happen.");
3170 }
3171 }
3172 }
3173 if (size != NULL)
3174 *size = PyUnicode_WSTR_LENGTH(u);
3175 return _PyUnicode_WSTR(u);
Martin v. Löwis5b222132007-06-10 09:51:05 +00003176}
3177
Alexander Belopolsky40018472011-02-26 01:02:56 +00003178Py_UNICODE *
3179PyUnicode_AsUnicode(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003180{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003181 return PyUnicode_AsUnicodeAndSize(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003182}
3183
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003184
Alexander Belopolsky40018472011-02-26 01:02:56 +00003185Py_ssize_t
3186PyUnicode_GetSize(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003187{
3188 if (!PyUnicode_Check(unicode)) {
3189 PyErr_BadArgument();
3190 goto onError;
3191 }
3192 return PyUnicode_GET_SIZE(unicode);
3193
Benjamin Peterson29060642009-01-31 22:14:21 +00003194 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003195 return -1;
3196}
3197
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003198Py_ssize_t
3199PyUnicode_GetLength(PyObject *unicode)
3200{
Victor Stinner5a706cf2011-10-02 00:36:53 +02003201 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003202 PyErr_BadArgument();
3203 return -1;
3204 }
3205
3206 return PyUnicode_GET_LENGTH(unicode);
3207}
3208
3209Py_UCS4
3210PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
3211{
Victor Stinner2fe5ced2011-10-02 00:25:40 +02003212 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
3213 PyErr_BadArgument();
3214 return (Py_UCS4)-1;
3215 }
3216 if (index < 0 || index >= _PyUnicode_LENGTH(unicode)) {
3217 PyErr_SetString(PyExc_IndexError, "string index out of range");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003218 return (Py_UCS4)-1;
3219 }
3220 return PyUnicode_READ_CHAR(unicode, index);
3221}
3222
3223int
3224PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 ch)
3225{
3226 if (!PyUnicode_Check(unicode) || !PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02003227 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003228 return -1;
3229 }
Victor Stinnercd9950f2011-10-02 00:34:53 +02003230 if (index < 0 || index >= _PyUnicode_LENGTH(unicode)) {
3231 PyErr_SetString(PyExc_IndexError, "string index out of range");
3232 return -1;
3233 }
3234 if (_PyUnicode_Dirty(unicode))
3235 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003236 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
3237 index, ch);
3238 return 0;
3239}
3240
Alexander Belopolsky40018472011-02-26 01:02:56 +00003241const char *
3242PyUnicode_GetDefaultEncoding(void)
Fred Drakee4315f52000-05-09 19:53:39 +00003243{
Victor Stinner42cb4622010-09-01 19:39:01 +00003244 return "utf-8";
Fred Drakee4315f52000-05-09 19:53:39 +00003245}
3246
Victor Stinner554f3f02010-06-16 23:33:54 +00003247/* create or adjust a UnicodeDecodeError */
3248static void
3249make_decode_exception(PyObject **exceptionObject,
3250 const char *encoding,
3251 const char *input, Py_ssize_t length,
3252 Py_ssize_t startpos, Py_ssize_t endpos,
3253 const char *reason)
3254{
3255 if (*exceptionObject == NULL) {
3256 *exceptionObject = PyUnicodeDecodeError_Create(
3257 encoding, input, length, startpos, endpos, reason);
3258 }
3259 else {
3260 if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
3261 goto onError;
3262 if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
3263 goto onError;
3264 if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
3265 goto onError;
3266 }
3267 return;
3268
3269onError:
3270 Py_DECREF(*exceptionObject);
3271 *exceptionObject = NULL;
3272}
3273
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003274/* error handling callback helper:
3275 build arguments, call the callback and check the arguments,
Fred Drakedb390c12005-10-28 14:39:47 +00003276 if no exception occurred, copy the replacement to the output
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003277 and adjust various state variables.
3278 return 0 on success, -1 on error
3279*/
3280
Alexander Belopolsky40018472011-02-26 01:02:56 +00003281static int
3282unicode_decode_call_errorhandler(const char *errors, PyObject **errorHandler,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003283 const char *encoding, const char *reason,
3284 const char **input, const char **inend, Py_ssize_t *startinpos,
3285 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
3286 PyUnicodeObject **output, Py_ssize_t *outpos, Py_UNICODE **outptr)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003287{
Benjamin Peterson142957c2008-07-04 19:55:29 +00003288 static char *argparse = "O!n;decoding error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003289
3290 PyObject *restuple = NULL;
3291 PyObject *repunicode = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003292 Py_ssize_t outsize = PyUnicode_GET_SIZE(*output);
Walter Dörwalde78178e2007-07-30 13:31:40 +00003293 Py_ssize_t insize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003294 Py_ssize_t requiredsize;
3295 Py_ssize_t newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003296 const Py_UNICODE *repptr;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003297 PyObject *inputobj = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003298 Py_ssize_t repsize;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003299 int res = -1;
3300
3301 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003302 *errorHandler = PyCodec_LookupError(errors);
3303 if (*errorHandler == NULL)
3304 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003305 }
3306
Victor Stinner554f3f02010-06-16 23:33:54 +00003307 make_decode_exception(exceptionObject,
3308 encoding,
3309 *input, *inend - *input,
3310 *startinpos, *endinpos,
3311 reason);
3312 if (*exceptionObject == NULL)
3313 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003314
3315 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
3316 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003317 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003318 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00003319 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00003320 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003321 }
3322 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00003323 goto onError;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003324
3325 /* Copy back the bytes variables, which might have been modified by the
3326 callback */
3327 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
3328 if (!inputobj)
3329 goto onError;
Christian Heimes72b710a2008-05-26 13:28:38 +00003330 if (!PyBytes_Check(inputobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003331 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
Walter Dörwalde78178e2007-07-30 13:31:40 +00003332 }
Christian Heimes72b710a2008-05-26 13:28:38 +00003333 *input = PyBytes_AS_STRING(inputobj);
3334 insize = PyBytes_GET_SIZE(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00003335 *inend = *input + insize;
Walter Dörwald36f938f2007-08-10 10:11:43 +00003336 /* we can DECREF safely, as the exception has another reference,
3337 so the object won't go away. */
3338 Py_DECREF(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00003339
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003340 if (newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00003341 newpos = insize+newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00003342 if (newpos<0 || newpos>insize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003343 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
3344 goto onError;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00003345 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003346
3347 /* need more space? (at least enough for what we
3348 have+the replacement+the rest of the string (starting
3349 at the new input position), so we won't have to check space
3350 when there are no errors in the rest of the string) */
3351 repptr = PyUnicode_AS_UNICODE(repunicode);
3352 repsize = PyUnicode_GET_SIZE(repunicode);
3353 requiredsize = *outpos + repsize + insize-newpos;
3354 if (requiredsize > outsize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003355 if (requiredsize<2*outsize)
3356 requiredsize = 2*outsize;
Victor Stinnerfe226c02011-10-03 03:52:20 +02003357 if (PyUnicode_Resize((PyObject**)output, requiredsize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00003358 goto onError;
3359 *outptr = PyUnicode_AS_UNICODE(*output) + *outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003360 }
3361 *endinpos = newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003362 *inptr = *input + newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003363 Py_UNICODE_COPY(*outptr, repptr, repsize);
3364 *outptr += repsize;
3365 *outpos += repsize;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003366
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003367 /* we made it! */
3368 res = 0;
3369
Benjamin Peterson29060642009-01-31 22:14:21 +00003370 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003371 Py_XDECREF(restuple);
3372 return res;
3373}
3374
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003375/* --- UTF-7 Codec -------------------------------------------------------- */
3376
Antoine Pitrou244651a2009-05-04 18:56:13 +00003377/* See RFC2152 for details. We encode conservatively and decode liberally. */
3378
3379/* Three simple macros defining base-64. */
3380
3381/* Is c a base-64 character? */
3382
3383#define IS_BASE64(c) \
3384 (((c) >= 'A' && (c) <= 'Z') || \
3385 ((c) >= 'a' && (c) <= 'z') || \
3386 ((c) >= '0' && (c) <= '9') || \
3387 (c) == '+' || (c) == '/')
3388
3389/* given that c is a base-64 character, what is its base-64 value? */
3390
3391#define FROM_BASE64(c) \
3392 (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' : \
3393 ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 : \
3394 ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 : \
3395 (c) == '+' ? 62 : 63)
3396
3397/* What is the base-64 character of the bottom 6 bits of n? */
3398
3399#define TO_BASE64(n) \
3400 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
3401
3402/* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
3403 * decoded as itself. We are permissive on decoding; the only ASCII
3404 * byte not decoding to itself is the + which begins a base64
3405 * string. */
3406
3407#define DECODE_DIRECT(c) \
3408 ((c) <= 127 && (c) != '+')
3409
3410/* The UTF-7 encoder treats ASCII characters differently according to
3411 * whether they are Set D, Set O, Whitespace, or special (i.e. none of
3412 * the above). See RFC2152. This array identifies these different
3413 * sets:
3414 * 0 : "Set D"
3415 * alphanumeric and '(),-./:?
3416 * 1 : "Set O"
3417 * !"#$%&*;<=>@[]^_`{|}
3418 * 2 : "whitespace"
3419 * ht nl cr sp
3420 * 3 : special (must be base64 encoded)
3421 * everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
3422 */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003423
Tim Petersced69f82003-09-16 20:30:58 +00003424static
Antoine Pitrou244651a2009-05-04 18:56:13 +00003425char utf7_category[128] = {
3426/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
3427 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
3428/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
3429 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
3430/* sp ! " # $ % & ' ( ) * + , - . / */
3431 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
3432/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
3433 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
3434/* @ A B C D E F G H I J K L M N O */
3435 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
3436/* P Q R S T U V W X Y Z [ \ ] ^ _ */
3437 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
3438/* ` a b c d e f g h i j k l m n o */
3439 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
3440/* p q r s t u v w x y z { | } ~ del */
3441 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003442};
3443
Antoine Pitrou244651a2009-05-04 18:56:13 +00003444/* ENCODE_DIRECT: this character should be encoded as itself. The
3445 * answer depends on whether we are encoding set O as itself, and also
3446 * on whether we are encoding whitespace as itself. RFC2152 makes it
3447 * clear that the answers to these questions vary between
3448 * applications, so this code needs to be flexible. */
Marc-André Lemburge115ec82005-10-19 22:33:31 +00003449
Antoine Pitrou244651a2009-05-04 18:56:13 +00003450#define ENCODE_DIRECT(c, directO, directWS) \
3451 ((c) < 128 && (c) > 0 && \
3452 ((utf7_category[(c)] == 0) || \
3453 (directWS && (utf7_category[(c)] == 2)) || \
3454 (directO && (utf7_category[(c)] == 1))))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003455
Alexander Belopolsky40018472011-02-26 01:02:56 +00003456PyObject *
3457PyUnicode_DecodeUTF7(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003458 Py_ssize_t size,
3459 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003460{
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003461 return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
3462}
3463
Antoine Pitrou244651a2009-05-04 18:56:13 +00003464/* The decoder. The only state we preserve is our read position,
3465 * i.e. how many characters we have consumed. So if we end in the
3466 * middle of a shift sequence we have to back off the read position
3467 * and the output to the beginning of the sequence, otherwise we lose
3468 * all the shift state (seen bits, number of bits seen, high
3469 * surrogate). */
3470
Alexander Belopolsky40018472011-02-26 01:02:56 +00003471PyObject *
3472PyUnicode_DecodeUTF7Stateful(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003473 Py_ssize_t size,
3474 const char *errors,
3475 Py_ssize_t *consumed)
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003476{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003477 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003478 Py_ssize_t startinpos;
3479 Py_ssize_t endinpos;
3480 Py_ssize_t outpos;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003481 const char *e;
3482 PyUnicodeObject *unicode;
3483 Py_UNICODE *p;
3484 const char *errmsg = "";
3485 int inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003486 Py_UNICODE *shiftOutStart;
3487 unsigned int base64bits = 0;
3488 unsigned long base64buffer = 0;
3489 Py_UNICODE surrogate = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003490 PyObject *errorHandler = NULL;
3491 PyObject *exc = NULL;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003492
3493 unicode = _PyUnicode_New(size);
3494 if (!unicode)
3495 return NULL;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003496 if (size == 0) {
3497 if (consumed)
3498 *consumed = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003499 return (PyObject *)unicode;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003500 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003501
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003502 p = PyUnicode_AS_UNICODE(unicode);
Antoine Pitrou244651a2009-05-04 18:56:13 +00003503 shiftOutStart = p;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003504 e = s + size;
3505
3506 while (s < e) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003507 Py_UNICODE ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00003508 restart:
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00003509 ch = (unsigned char) *s;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003510
Antoine Pitrou244651a2009-05-04 18:56:13 +00003511 if (inShift) { /* in a base-64 section */
3512 if (IS_BASE64(ch)) { /* consume a base-64 character */
3513 base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
3514 base64bits += 6;
3515 s++;
3516 if (base64bits >= 16) {
3517 /* we have enough bits for a UTF-16 value */
3518 Py_UNICODE outCh = (Py_UNICODE)
3519 (base64buffer >> (base64bits-16));
3520 base64bits -= 16;
3521 base64buffer &= (1 << base64bits) - 1; /* clear high bits */
3522 if (surrogate) {
3523 /* expecting a second surrogate */
3524 if (outCh >= 0xDC00 && outCh <= 0xDFFF) {
3525#ifdef Py_UNICODE_WIDE
3526 *p++ = (((surrogate & 0x3FF)<<10)
3527 | (outCh & 0x3FF)) + 0x10000;
3528#else
3529 *p++ = surrogate;
3530 *p++ = outCh;
3531#endif
3532 surrogate = 0;
3533 }
3534 else {
3535 surrogate = 0;
3536 errmsg = "second surrogate missing";
3537 goto utf7Error;
3538 }
3539 }
3540 else if (outCh >= 0xD800 && outCh <= 0xDBFF) {
3541 /* first surrogate */
3542 surrogate = outCh;
3543 }
3544 else if (outCh >= 0xDC00 && outCh <= 0xDFFF) {
3545 errmsg = "unexpected second surrogate";
3546 goto utf7Error;
3547 }
3548 else {
3549 *p++ = outCh;
3550 }
3551 }
3552 }
3553 else { /* now leaving a base-64 section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003554 inShift = 0;
3555 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003556 if (surrogate) {
3557 errmsg = "second surrogate missing at end of shift sequence";
Tim Petersced69f82003-09-16 20:30:58 +00003558 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003559 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003560 if (base64bits > 0) { /* left-over bits */
3561 if (base64bits >= 6) {
3562 /* We've seen at least one base-64 character */
3563 errmsg = "partial character in shift sequence";
3564 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003565 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003566 else {
3567 /* Some bits remain; they should be zero */
3568 if (base64buffer != 0) {
3569 errmsg = "non-zero padding bits in shift sequence";
3570 goto utf7Error;
3571 }
3572 }
3573 }
3574 if (ch != '-') {
3575 /* '-' is absorbed; other terminating
3576 characters are preserved */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003577 *p++ = ch;
3578 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003579 }
3580 }
3581 else if ( ch == '+' ) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003582 startinpos = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003583 s++; /* consume '+' */
3584 if (s < e && *s == '-') { /* '+-' encodes '+' */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003585 s++;
3586 *p++ = '+';
Antoine Pitrou244651a2009-05-04 18:56:13 +00003587 }
3588 else { /* begin base64-encoded section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003589 inShift = 1;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003590 shiftOutStart = p;
3591 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003592 }
3593 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003594 else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003595 *p++ = ch;
3596 s++;
3597 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003598 else {
3599 startinpos = s-starts;
3600 s++;
3601 errmsg = "unexpected special character";
3602 goto utf7Error;
3603 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003604 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003605utf7Error:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003606 outpos = p-PyUnicode_AS_UNICODE(unicode);
3607 endinpos = s-starts;
3608 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00003609 errors, &errorHandler,
3610 "utf7", errmsg,
3611 &starts, &e, &startinpos, &endinpos, &exc, &s,
3612 &unicode, &outpos, &p))
3613 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003614 }
3615
Antoine Pitrou244651a2009-05-04 18:56:13 +00003616 /* end of string */
3617
3618 if (inShift && !consumed) { /* in shift sequence, no more to follow */
3619 /* if we're in an inconsistent state, that's an error */
3620 if (surrogate ||
3621 (base64bits >= 6) ||
3622 (base64bits > 0 && base64buffer != 0)) {
3623 outpos = p-PyUnicode_AS_UNICODE(unicode);
3624 endinpos = size;
3625 if (unicode_decode_call_errorhandler(
3626 errors, &errorHandler,
3627 "utf7", "unterminated shift sequence",
3628 &starts, &e, &startinpos, &endinpos, &exc, &s,
3629 &unicode, &outpos, &p))
3630 goto onError;
3631 if (s < e)
3632 goto restart;
3633 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003634 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003635
3636 /* return state */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003637 if (consumed) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00003638 if (inShift) {
3639 p = shiftOutStart; /* back off output */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003640 *consumed = startinpos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003641 }
3642 else {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003643 *consumed = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003644 }
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003645 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003646
Victor Stinnerfe226c02011-10-03 03:52:20 +02003647 if (PyUnicode_Resize((PyObject**)&unicode, p - PyUnicode_AS_UNICODE(unicode)) < 0)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003648 goto onError;
3649
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003650 Py_XDECREF(errorHandler);
3651 Py_XDECREF(exc);
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02003652 if (_PyUnicode_READY_REPLACE(&unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003653 Py_DECREF(unicode);
3654 return NULL;
3655 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003656 return (PyObject *)unicode;
3657
Benjamin Peterson29060642009-01-31 22:14:21 +00003658 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003659 Py_XDECREF(errorHandler);
3660 Py_XDECREF(exc);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003661 Py_DECREF(unicode);
3662 return NULL;
3663}
3664
3665
Alexander Belopolsky40018472011-02-26 01:02:56 +00003666PyObject *
3667PyUnicode_EncodeUTF7(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003668 Py_ssize_t size,
3669 int base64SetO,
3670 int base64WhiteSpace,
3671 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003672{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003673 PyObject *v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003674 /* It might be possible to tighten this worst case */
Alexandre Vassalottie85bd982009-07-21 00:39:03 +00003675 Py_ssize_t allocated = 8 * size;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003676 int inShift = 0;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003677 Py_ssize_t i = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003678 unsigned int base64bits = 0;
3679 unsigned long base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003680 char * out;
3681 char * start;
3682
3683 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00003684 return PyBytes_FromStringAndSize(NULL, 0);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003685
Alexandre Vassalottie85bd982009-07-21 00:39:03 +00003686 if (allocated / 8 != size)
Neal Norwitz3ce5d922008-08-24 07:08:55 +00003687 return PyErr_NoMemory();
3688
Antoine Pitrou244651a2009-05-04 18:56:13 +00003689 v = PyBytes_FromStringAndSize(NULL, allocated);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003690 if (v == NULL)
3691 return NULL;
3692
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003693 start = out = PyBytes_AS_STRING(v);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003694 for (;i < size; ++i) {
3695 Py_UNICODE ch = s[i];
3696
Antoine Pitrou244651a2009-05-04 18:56:13 +00003697 if (inShift) {
3698 if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
3699 /* shifting out */
3700 if (base64bits) { /* output remaining bits */
3701 *out++ = TO_BASE64(base64buffer << (6-base64bits));
3702 base64buffer = 0;
3703 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003704 }
3705 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003706 /* Characters not in the BASE64 set implicitly unshift the sequence
3707 so no '-' is required, except if the character is itself a '-' */
3708 if (IS_BASE64(ch) || ch == '-') {
3709 *out++ = '-';
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003710 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003711 *out++ = (char) ch;
3712 }
3713 else {
3714 goto encode_char;
Tim Petersced69f82003-09-16 20:30:58 +00003715 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003716 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003717 else { /* not in a shift sequence */
3718 if (ch == '+') {
3719 *out++ = '+';
3720 *out++ = '-';
3721 }
3722 else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
3723 *out++ = (char) ch;
3724 }
3725 else {
3726 *out++ = '+';
3727 inShift = 1;
3728 goto encode_char;
3729 }
3730 }
3731 continue;
3732encode_char:
3733#ifdef Py_UNICODE_WIDE
3734 if (ch >= 0x10000) {
3735 /* code first surrogate */
3736 base64bits += 16;
3737 base64buffer = (base64buffer << 16) | 0xd800 | ((ch-0x10000) >> 10);
3738 while (base64bits >= 6) {
3739 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
3740 base64bits -= 6;
3741 }
3742 /* prepare second surrogate */
3743 ch = 0xDC00 | ((ch-0x10000) & 0x3FF);
3744 }
3745#endif
3746 base64bits += 16;
3747 base64buffer = (base64buffer << 16) | ch;
3748 while (base64bits >= 6) {
3749 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
3750 base64bits -= 6;
3751 }
Hye-Shik Chang1bc09b72004-01-03 19:35:43 +00003752 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003753 if (base64bits)
3754 *out++= TO_BASE64(base64buffer << (6-base64bits) );
3755 if (inShift)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003756 *out++ = '-';
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003757 if (_PyBytes_Resize(&v, out - start) < 0)
3758 return NULL;
3759 return v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003760}
3761
Antoine Pitrou244651a2009-05-04 18:56:13 +00003762#undef IS_BASE64
3763#undef FROM_BASE64
3764#undef TO_BASE64
3765#undef DECODE_DIRECT
3766#undef ENCODE_DIRECT
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003767
Guido van Rossumd57fd912000-03-10 22:53:23 +00003768/* --- UTF-8 Codec -------------------------------------------------------- */
3769
Tim Petersced69f82003-09-16 20:30:58 +00003770static
Guido van Rossumd57fd912000-03-10 22:53:23 +00003771char utf8_code_length[256] = {
Ezio Melotti57221d02010-07-01 07:32:02 +00003772 /* Map UTF-8 encoded prefix byte to sequence length. Zero means
3773 illegal prefix. See RFC 3629 for details */
3774 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 00-0F */
3775 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003776 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Guido van Rossumd57fd912000-03-10 22:53:23 +00003777 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
3778 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
3779 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
3780 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Ezio Melotti57221d02010-07-01 07:32:02 +00003781 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 70-7F */
3782 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 +00003783 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
3784 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
Ezio Melotti57221d02010-07-01 07:32:02 +00003785 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* B0-BF */
3786 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* C0-C1 + C2-CF */
3787 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* D0-DF */
3788 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, /* E0-EF */
3789 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 +00003790};
3791
Alexander Belopolsky40018472011-02-26 01:02:56 +00003792PyObject *
3793PyUnicode_DecodeUTF8(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003794 Py_ssize_t size,
3795 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003796{
Walter Dörwald69652032004-09-07 20:24:22 +00003797 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
3798}
3799
Antoine Pitrouab868312009-01-10 15:40:25 +00003800/* Mask to check or force alignment of a pointer to C 'long' boundaries */
3801#define LONG_PTR_MASK (size_t) (SIZEOF_LONG - 1)
3802
3803/* Mask to quickly check whether a C 'long' contains a
3804 non-ASCII, UTF8-encoded char. */
3805#if (SIZEOF_LONG == 8)
3806# define ASCII_CHAR_MASK 0x8080808080808080L
3807#elif (SIZEOF_LONG == 4)
3808# define ASCII_CHAR_MASK 0x80808080L
3809#else
3810# error C 'long' size should be either 4 or 8!
3811#endif
3812
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003813/* Scans a UTF-8 string and returns the maximum character to be expected,
3814 the size of the decoded unicode string and if any major errors were
3815 encountered.
3816
3817 This function does check basic UTF-8 sanity, it does however NOT CHECK
3818 if the string contains surrogates, and if all continuation bytes are
3819 within the correct ranges, these checks are performed in
3820 PyUnicode_DecodeUTF8Stateful.
3821
3822 If it sets has_errors to 1, it means the value of unicode_size and max_char
3823 will be bogus and you should not rely on useful information in them.
3824 */
3825static Py_UCS4
3826utf8_max_char_size_and_has_errors(const char *s, Py_ssize_t string_size,
3827 Py_ssize_t *unicode_size, Py_ssize_t* consumed,
3828 int *has_errors)
3829{
3830 Py_ssize_t n;
3831 Py_ssize_t char_count = 0;
3832 Py_UCS4 max_char = 127, new_max;
3833 Py_UCS4 upper_bound;
3834 const unsigned char *p = (const unsigned char *)s;
3835 const unsigned char *end = p + string_size;
3836 const unsigned char *aligned_end = (const unsigned char *) ((size_t) end & ~LONG_PTR_MASK);
3837 int err = 0;
3838
3839 for (; p < end && !err; ++p, ++char_count) {
3840 /* Only check value if it's not a ASCII char... */
3841 if (*p < 0x80) {
3842 /* Fast path, see below in PyUnicode_DecodeUTF8Stateful for
3843 an explanation. */
3844 if (!((size_t) p & LONG_PTR_MASK)) {
3845 /* Help register allocation */
3846 register const unsigned char *_p = p;
3847 while (_p < aligned_end) {
3848 unsigned long value = *(unsigned long *) _p;
3849 if (value & ASCII_CHAR_MASK)
3850 break;
3851 _p += SIZEOF_LONG;
3852 char_count += SIZEOF_LONG;
3853 }
3854 p = _p;
3855 if (p == end)
3856 break;
3857 }
3858 }
3859 if (*p >= 0x80) {
3860 n = utf8_code_length[*p];
3861 new_max = max_char;
3862 switch (n) {
3863 /* invalid start byte */
3864 case 0:
3865 err = 1;
3866 break;
3867 case 2:
3868 /* Code points between 0x00FF and 0x07FF inclusive.
3869 Approximate the upper bound of the code point,
3870 if this flips over 255 we can be sure it will be more
3871 than 255 and the string will need 2 bytes per code coint,
3872 if it stays under or equal to 255, we can be sure 1 byte
3873 is enough.
3874 ((*p & 0b00011111) << 6) | 0b00111111 */
3875 upper_bound = ((*p & 0x1F) << 6) | 0x3F;
3876 if (max_char < upper_bound)
3877 new_max = upper_bound;
3878 /* Ensure we track at least that we left ASCII space. */
3879 if (new_max < 128)
3880 new_max = 128;
3881 break;
3882 case 3:
3883 /* Between 0x0FFF and 0xFFFF inclusive, so values are
3884 always > 255 and <= 65535 and will always need 2 bytes. */
3885 if (max_char < 65535)
3886 new_max = 65535;
3887 break;
3888 case 4:
3889 /* Code point will be above 0xFFFF for sure in this case. */
3890 new_max = 65537;
3891 break;
3892 /* Internal error, this should be caught by the first if */
3893 case 1:
3894 default:
3895 assert(0 && "Impossible case in utf8_max_char_and_size");
3896 err = 1;
3897 }
3898 /* Instead of number of overall bytes for this code point,
3899 n containts the number of following bytes: */
3900 --n;
3901 /* Check if the follow up chars are all valid continuation bytes */
3902 if (n >= 1) {
3903 const unsigned char *cont;
3904 if ((p + n) >= end) {
3905 if (consumed == 0)
3906 /* incomplete data, non-incremental decoding */
3907 err = 1;
3908 break;
3909 }
3910 for (cont = p + 1; cont < (p + n); ++cont) {
3911 if ((*cont & 0xc0) != 0x80) {
3912 err = 1;
3913 break;
3914 }
3915 }
3916 p += n;
3917 }
3918 else
3919 err = 1;
3920 max_char = new_max;
3921 }
3922 }
3923
3924 if (unicode_size)
3925 *unicode_size = char_count;
3926 if (has_errors)
3927 *has_errors = err;
3928 return max_char;
3929}
3930
3931/* Similar to PyUnicode_WRITE but can also write into wstr field
3932 of the legacy unicode representation */
3933#define WRITE_FLEXIBLE_OR_WSTR(kind, buf, index, value) \
3934 do { \
3935 const int k_ = (kind); \
3936 if (k_ == PyUnicode_WCHAR_KIND) \
3937 ((Py_UNICODE *)(buf))[(index)] = (Py_UNICODE)(value); \
3938 else if (k_ == PyUnicode_1BYTE_KIND) \
3939 ((unsigned char *)(buf))[(index)] = (unsigned char)(value); \
3940 else if (k_ == PyUnicode_2BYTE_KIND) \
3941 ((Py_UCS2 *)(buf))[(index)] = (Py_UCS2)(value); \
3942 else \
3943 ((Py_UCS4 *)(buf))[(index)] = (Py_UCS4)(value); \
3944 } while (0)
3945
Alexander Belopolsky40018472011-02-26 01:02:56 +00003946PyObject *
3947PyUnicode_DecodeUTF8Stateful(const char *s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003948 Py_ssize_t size,
3949 const char *errors,
3950 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00003951{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003952 const char *starts = s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003953 int n;
Ezio Melotti57221d02010-07-01 07:32:02 +00003954 int k;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003955 Py_ssize_t startinpos;
3956 Py_ssize_t endinpos;
Antoine Pitrouab868312009-01-10 15:40:25 +00003957 const char *e, *aligned_end;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003958 PyUnicodeObject *unicode;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00003959 const char *errmsg = "";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003960 PyObject *errorHandler = NULL;
3961 PyObject *exc = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003962 Py_UCS4 maxchar = 0;
3963 Py_ssize_t unicode_size;
3964 Py_ssize_t i;
3965 int kind;
3966 void *data;
3967 int has_errors;
3968 Py_UNICODE *error_outptr;
3969#if SIZEOF_WCHAR_T == 2
3970 Py_ssize_t wchar_offset = 0;
3971#endif
Guido van Rossumd57fd912000-03-10 22:53:23 +00003972
Walter Dörwald69652032004-09-07 20:24:22 +00003973 if (size == 0) {
3974 if (consumed)
3975 *consumed = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003976 return (PyObject *)PyUnicode_New(0, 0);
Walter Dörwald69652032004-09-07 20:24:22 +00003977 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003978 maxchar = utf8_max_char_size_and_has_errors(s, size, &unicode_size,
3979 consumed, &has_errors);
3980 if (has_errors) {
3981 unicode = _PyUnicode_New(size);
3982 if (!unicode)
3983 return NULL;
3984 kind = PyUnicode_WCHAR_KIND;
3985 data = PyUnicode_AS_UNICODE(unicode);
3986 assert(data != NULL);
3987 }
3988 else {
3989 unicode = (PyUnicodeObject *)PyUnicode_New(unicode_size, maxchar);
3990 if (!unicode)
3991 return NULL;
3992 /* When the string is ASCII only, just use memcpy and return.
3993 unicode_size may be != size if there is an incomplete UTF-8
3994 sequence at the end of the ASCII block. */
3995 if (maxchar < 128 && size == unicode_size) {
3996 Py_MEMCPY(PyUnicode_1BYTE_DATA(unicode), s, unicode_size);
3997 return (PyObject *)unicode;
3998 }
3999 kind = PyUnicode_KIND(unicode);
4000 data = PyUnicode_DATA(unicode);
4001 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004002 /* Unpack UTF-8 encoded data */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004003 i = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004004 e = s + size;
Antoine Pitrouab868312009-01-10 15:40:25 +00004005 aligned_end = (const char *) ((size_t) e & ~LONG_PTR_MASK);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004006
4007 while (s < e) {
Marc-André Lemburge12896e2000-07-07 17:51:08 +00004008 Py_UCS4 ch = (unsigned char)*s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004009
4010 if (ch < 0x80) {
Antoine Pitrouab868312009-01-10 15:40:25 +00004011 /* Fast path for runs of ASCII characters. Given that common UTF-8
4012 input will consist of an overwhelming majority of ASCII
4013 characters, we try to optimize for this case by checking
4014 as many characters as a C 'long' can contain.
4015 First, check if we can do an aligned read, as most CPUs have
4016 a penalty for unaligned reads.
4017 */
4018 if (!((size_t) s & LONG_PTR_MASK)) {
4019 /* Help register allocation */
4020 register const char *_s = s;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004021 register Py_ssize_t _i = i;
Antoine Pitrouab868312009-01-10 15:40:25 +00004022 while (_s < aligned_end) {
4023 /* Read a whole long at a time (either 4 or 8 bytes),
4024 and do a fast unrolled copy if it only contains ASCII
4025 characters. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004026 unsigned long value = *(unsigned long *) _s;
4027 if (value & ASCII_CHAR_MASK)
Antoine Pitrouab868312009-01-10 15:40:25 +00004028 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004029 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+0, _s[0]);
4030 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+1, _s[1]);
4031 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+2, _s[2]);
4032 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+3, _s[3]);
Antoine Pitrouab868312009-01-10 15:40:25 +00004033#if (SIZEOF_LONG == 8)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004034 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+4, _s[4]);
4035 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+5, _s[5]);
4036 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+6, _s[6]);
4037 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+7, _s[7]);
Antoine Pitrouab868312009-01-10 15:40:25 +00004038#endif
4039 _s += SIZEOF_LONG;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004040 _i += SIZEOF_LONG;
Antoine Pitrouab868312009-01-10 15:40:25 +00004041 }
4042 s = _s;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004043 i = _i;
Antoine Pitrouab868312009-01-10 15:40:25 +00004044 if (s == e)
4045 break;
4046 ch = (unsigned char)*s;
4047 }
4048 }
4049
4050 if (ch < 0x80) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004051 WRITE_FLEXIBLE_OR_WSTR(kind, data, i++, ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004052 s++;
4053 continue;
4054 }
4055
4056 n = utf8_code_length[ch];
4057
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004058 if (s + n > e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004059 if (consumed)
4060 break;
4061 else {
4062 errmsg = "unexpected end of data";
4063 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004064 endinpos = startinpos+1;
4065 for (k=1; (k < size-startinpos) && ((s[k]&0xC0) == 0x80); k++)
4066 endinpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00004067 goto utf8Error;
4068 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00004069 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004070
4071 switch (n) {
4072
4073 case 0:
Ezio Melotti57221d02010-07-01 07:32:02 +00004074 errmsg = "invalid start byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004075 startinpos = s-starts;
4076 endinpos = startinpos+1;
4077 goto utf8Error;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004078
4079 case 1:
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004080 errmsg = "internal error";
Benjamin Peterson29060642009-01-31 22:14:21 +00004081 startinpos = s-starts;
4082 endinpos = startinpos+1;
4083 goto utf8Error;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004084
4085 case 2:
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004086 if ((s[1] & 0xc0) != 0x80) {
Ezio Melotti57221d02010-07-01 07:32:02 +00004087 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004088 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004089 endinpos = startinpos + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00004090 goto utf8Error;
4091 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004092 ch = ((s[0] & 0x1f) << 6) + (s[1] & 0x3f);
Ezio Melotti57221d02010-07-01 07:32:02 +00004093 assert ((ch > 0x007F) && (ch <= 0x07FF));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004094 WRITE_FLEXIBLE_OR_WSTR(kind, data, i++, ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004095 break;
4096
4097 case 3:
Ezio Melotti9bf2b3a2010-07-03 04:52:19 +00004098 /* Decoding UTF-8 sequences in range \xed\xa0\x80-\xed\xbf\xbf
4099 will result in surrogates in range d800-dfff. Surrogates are
4100 not valid UTF-8 so they are rejected.
4101 See http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf
4102 (table 3-7) and http://www.rfc-editor.org/rfc/rfc3629.txt */
Tim Petersced69f82003-09-16 20:30:58 +00004103 if ((s[1] & 0xc0) != 0x80 ||
Ezio Melotti57221d02010-07-01 07:32:02 +00004104 (s[2] & 0xc0) != 0x80 ||
4105 ((unsigned char)s[0] == 0xE0 &&
4106 (unsigned char)s[1] < 0xA0) ||
4107 ((unsigned char)s[0] == 0xED &&
4108 (unsigned char)s[1] > 0x9F)) {
4109 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004110 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004111 endinpos = startinpos + 1;
4112
4113 /* if s[1] first two bits are 1 and 0, then the invalid
4114 continuation byte is s[2], so increment endinpos by 1,
4115 if not, s[1] is invalid and endinpos doesn't need to
4116 be incremented. */
4117 if ((s[1] & 0xC0) == 0x80)
4118 endinpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00004119 goto utf8Error;
4120 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004121 ch = ((s[0] & 0x0f) << 12) + ((s[1] & 0x3f) << 6) + (s[2] & 0x3f);
Ezio Melotti57221d02010-07-01 07:32:02 +00004122 assert ((ch > 0x07FF) && (ch <= 0xFFFF));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004123 WRITE_FLEXIBLE_OR_WSTR(kind, data, i++, ch);
Marc-André Lemburge12896e2000-07-07 17:51:08 +00004124 break;
4125
4126 case 4:
4127 if ((s[1] & 0xc0) != 0x80 ||
4128 (s[2] & 0xc0) != 0x80 ||
Ezio Melotti57221d02010-07-01 07:32:02 +00004129 (s[3] & 0xc0) != 0x80 ||
4130 ((unsigned char)s[0] == 0xF0 &&
4131 (unsigned char)s[1] < 0x90) ||
4132 ((unsigned char)s[0] == 0xF4 &&
4133 (unsigned char)s[1] > 0x8F)) {
4134 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004135 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004136 endinpos = startinpos + 1;
4137 if ((s[1] & 0xC0) == 0x80) {
4138 endinpos++;
4139 if ((s[2] & 0xC0) == 0x80)
4140 endinpos++;
4141 }
Benjamin Peterson29060642009-01-31 22:14:21 +00004142 goto utf8Error;
4143 }
Marc-André Lemburge12896e2000-07-07 17:51:08 +00004144 ch = ((s[0] & 0x7) << 18) + ((s[1] & 0x3f) << 12) +
Ezio Melotti57221d02010-07-01 07:32:02 +00004145 ((s[2] & 0x3f) << 6) + (s[3] & 0x3f);
4146 assert ((ch > 0xFFFF) && (ch <= 0x10ffff));
4147
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004148 /* If the string is flexible or we have native UCS-4, write
4149 directly.. */
4150 if (sizeof(Py_UNICODE) > 2 || kind != PyUnicode_WCHAR_KIND)
4151 WRITE_FLEXIBLE_OR_WSTR(kind, data, i++, ch);
Tim Petersced69f82003-09-16 20:30:58 +00004152
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004153 else {
4154 /* compute and append the two surrogates: */
Tim Petersced69f82003-09-16 20:30:58 +00004155
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004156 /* translate from 10000..10FFFF to 0..FFFF */
4157 ch -= 0x10000;
Tim Petersced69f82003-09-16 20:30:58 +00004158
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004159 /* high surrogate = top 10 bits added to D800 */
4160 WRITE_FLEXIBLE_OR_WSTR(kind, data, i++,
4161 (Py_UNICODE)(0xD800 + (ch >> 10)));
4162
4163 /* low surrogate = bottom 10 bits added to DC00 */
4164 WRITE_FLEXIBLE_OR_WSTR(kind, data, i++,
4165 (Py_UNICODE)(0xDC00 + (ch & 0x03FF)));
4166 }
4167#if SIZEOF_WCHAR_T == 2
4168 wchar_offset++;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00004169#endif
Guido van Rossumd57fd912000-03-10 22:53:23 +00004170 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004171 }
4172 s += n;
Benjamin Peterson29060642009-01-31 22:14:21 +00004173 continue;
Tim Petersced69f82003-09-16 20:30:58 +00004174
Benjamin Peterson29060642009-01-31 22:14:21 +00004175 utf8Error:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004176 /* If this is not yet a resizable string, make it one.. */
4177 if (kind != PyUnicode_WCHAR_KIND) {
4178 const Py_UNICODE *u;
4179 PyUnicodeObject *new_unicode = _PyUnicode_New(size);
4180 if (!new_unicode)
4181 goto onError;
4182 u = PyUnicode_AsUnicode((PyObject *)unicode);
4183 if (!u)
4184 goto onError;
4185#if SIZEOF_WCHAR_T == 2
4186 i += wchar_offset;
4187#endif
4188 Py_UNICODE_COPY(PyUnicode_AS_UNICODE(new_unicode), u, i);
4189 Py_DECREF(unicode);
4190 unicode = new_unicode;
4191 kind = 0;
4192 data = PyUnicode_AS_UNICODE(new_unicode);
4193 assert(data != NULL);
4194 }
4195 error_outptr = PyUnicode_AS_UNICODE(unicode) + i;
Benjamin Peterson29060642009-01-31 22:14:21 +00004196 if (unicode_decode_call_errorhandler(
4197 errors, &errorHandler,
4198 "utf8", errmsg,
4199 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004200 &unicode, &i, &error_outptr))
Benjamin Peterson29060642009-01-31 22:14:21 +00004201 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004202 /* Update data because unicode_decode_call_errorhandler might have
4203 re-created or resized the unicode object. */
4204 data = PyUnicode_AS_UNICODE(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00004205 aligned_end = (const char *) ((size_t) e & ~LONG_PTR_MASK);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004206 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004207 /* Ensure the unicode_size calculation above was correct: */
4208 assert(kind == PyUnicode_WCHAR_KIND || i == unicode_size);
4209
Walter Dörwald69652032004-09-07 20:24:22 +00004210 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00004211 *consumed = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004212
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004213 /* Adjust length and ready string when it contained errors and
4214 is of the old resizable kind. */
4215 if (kind == PyUnicode_WCHAR_KIND) {
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02004216 if (PyUnicode_Resize((PyObject**)&unicode, i) < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004217 goto onError;
4218 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004219
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004220 Py_XDECREF(errorHandler);
4221 Py_XDECREF(exc);
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02004222 if (_PyUnicode_READY_REPLACE(&unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004223 Py_DECREF(unicode);
4224 return NULL;
4225 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004226 return (PyObject *)unicode;
4227
Benjamin Peterson29060642009-01-31 22:14:21 +00004228 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004229 Py_XDECREF(errorHandler);
4230 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004231 Py_DECREF(unicode);
4232 return NULL;
4233}
4234
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004235#undef WRITE_FLEXIBLE_OR_WSTR
Antoine Pitrouab868312009-01-10 15:40:25 +00004236
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004237#ifdef __APPLE__
4238
4239/* Simplified UTF-8 decoder using surrogateescape error handler,
4240 used to decode the command line arguments on Mac OS X. */
4241
4242wchar_t*
4243_Py_DecodeUTF8_surrogateescape(const char *s, Py_ssize_t size)
4244{
4245 int n;
4246 const char *e;
4247 wchar_t *unicode, *p;
4248
4249 /* Note: size will always be longer than the resulting Unicode
4250 character count */
4251 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < (size + 1)) {
4252 PyErr_NoMemory();
4253 return NULL;
4254 }
4255 unicode = PyMem_Malloc((size + 1) * sizeof(wchar_t));
4256 if (!unicode)
4257 return NULL;
4258
4259 /* Unpack UTF-8 encoded data */
4260 p = unicode;
4261 e = s + size;
4262 while (s < e) {
4263 Py_UCS4 ch = (unsigned char)*s;
4264
4265 if (ch < 0x80) {
4266 *p++ = (wchar_t)ch;
4267 s++;
4268 continue;
4269 }
4270
4271 n = utf8_code_length[ch];
4272 if (s + n > e) {
4273 goto surrogateescape;
4274 }
4275
4276 switch (n) {
4277 case 0:
4278 case 1:
4279 goto surrogateescape;
4280
4281 case 2:
4282 if ((s[1] & 0xc0) != 0x80)
4283 goto surrogateescape;
4284 ch = ((s[0] & 0x1f) << 6) + (s[1] & 0x3f);
4285 assert ((ch > 0x007F) && (ch <= 0x07FF));
4286 *p++ = (wchar_t)ch;
4287 break;
4288
4289 case 3:
4290 /* Decoding UTF-8 sequences in range \xed\xa0\x80-\xed\xbf\xbf
4291 will result in surrogates in range d800-dfff. Surrogates are
4292 not valid UTF-8 so they are rejected.
4293 See http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf
4294 (table 3-7) and http://www.rfc-editor.org/rfc/rfc3629.txt */
4295 if ((s[1] & 0xc0) != 0x80 ||
4296 (s[2] & 0xc0) != 0x80 ||
4297 ((unsigned char)s[0] == 0xE0 &&
4298 (unsigned char)s[1] < 0xA0) ||
4299 ((unsigned char)s[0] == 0xED &&
4300 (unsigned char)s[1] > 0x9F)) {
4301
4302 goto surrogateescape;
4303 }
4304 ch = ((s[0] & 0x0f) << 12) + ((s[1] & 0x3f) << 6) + (s[2] & 0x3f);
4305 assert ((ch > 0x07FF) && (ch <= 0xFFFF));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004306 *p++ = (wchar_t)ch;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004307 break;
4308
4309 case 4:
4310 if ((s[1] & 0xc0) != 0x80 ||
4311 (s[2] & 0xc0) != 0x80 ||
4312 (s[3] & 0xc0) != 0x80 ||
4313 ((unsigned char)s[0] == 0xF0 &&
4314 (unsigned char)s[1] < 0x90) ||
4315 ((unsigned char)s[0] == 0xF4 &&
4316 (unsigned char)s[1] > 0x8F)) {
4317 goto surrogateescape;
4318 }
4319 ch = ((s[0] & 0x7) << 18) + ((s[1] & 0x3f) << 12) +
4320 ((s[2] & 0x3f) << 6) + (s[3] & 0x3f);
4321 assert ((ch > 0xFFFF) && (ch <= 0x10ffff));
4322
4323#if SIZEOF_WCHAR_T == 4
4324 *p++ = (wchar_t)ch;
4325#else
4326 /* compute and append the two surrogates: */
4327
4328 /* translate from 10000..10FFFF to 0..FFFF */
4329 ch -= 0x10000;
4330
4331 /* high surrogate = top 10 bits added to D800 */
4332 *p++ = (wchar_t)(0xD800 + (ch >> 10));
4333
4334 /* low surrogate = bottom 10 bits added to DC00 */
4335 *p++ = (wchar_t)(0xDC00 + (ch & 0x03FF));
4336#endif
4337 break;
4338 }
4339 s += n;
4340 continue;
4341
4342 surrogateescape:
4343 *p++ = 0xDC00 + ch;
4344 s++;
4345 }
4346 *p = L'\0';
4347 return unicode;
4348}
4349
4350#endif /* __APPLE__ */
Antoine Pitrouab868312009-01-10 15:40:25 +00004351
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004352/* Primary internal function which creates utf8 encoded bytes objects.
4353
4354 Allocation strategy: if the string is short, convert into a stack buffer
Tim Peters602f7402002-04-27 18:03:26 +00004355 and allocate exactly as much space needed at the end. Else allocate the
4356 maximum possible needed (4 result bytes per Unicode character), and return
4357 the excess memory at the end.
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004358*/
Tim Peters7e3d9612002-04-21 03:26:37 +00004359PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004360_PyUnicode_AsUTF8String(PyObject *obj, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004361{
Tim Peters602f7402002-04-27 18:03:26 +00004362#define MAX_SHORT_UNICHARS 300 /* largest size we'll do on the stack */
Tim Peters0eca65c2002-04-21 17:28:06 +00004363
Guido van Rossum98297ee2007-11-06 21:34:58 +00004364 Py_ssize_t i; /* index into s of next input byte */
4365 PyObject *result; /* result string object */
4366 char *p; /* next free byte in output buffer */
4367 Py_ssize_t nallocated; /* number of result bytes allocated */
4368 Py_ssize_t nneeded; /* number of result bytes needed */
Tim Peters602f7402002-04-27 18:03:26 +00004369 char stackbuf[MAX_SHORT_UNICHARS * 4];
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004370 PyObject *errorHandler = NULL;
4371 PyObject *exc = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004372 int kind;
4373 void *data;
4374 Py_ssize_t size;
4375 PyUnicodeObject *unicode = (PyUnicodeObject *)obj;
4376#if SIZEOF_WCHAR_T == 2
4377 Py_ssize_t wchar_offset = 0;
4378#endif
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00004379
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004380 if (!PyUnicode_Check(unicode)) {
4381 PyErr_BadArgument();
4382 return NULL;
4383 }
4384
4385 if (PyUnicode_READY(unicode) == -1)
4386 return NULL;
4387
Victor Stinnere90fe6a2011-10-01 16:48:13 +02004388 if (PyUnicode_UTF8(unicode))
4389 return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode),
4390 PyUnicode_UTF8_LENGTH(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004391
4392 kind = PyUnicode_KIND(unicode);
4393 data = PyUnicode_DATA(unicode);
4394 size = PyUnicode_GET_LENGTH(unicode);
4395
Tim Peters602f7402002-04-27 18:03:26 +00004396 assert(size >= 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004397
Tim Peters602f7402002-04-27 18:03:26 +00004398 if (size <= MAX_SHORT_UNICHARS) {
4399 /* Write into the stack buffer; nallocated can't overflow.
4400 * At the end, we'll allocate exactly as much heap space as it
4401 * turns out we need.
4402 */
4403 nallocated = Py_SAFE_DOWNCAST(sizeof(stackbuf), size_t, int);
Guido van Rossum98297ee2007-11-06 21:34:58 +00004404 result = NULL; /* will allocate after we're done */
Tim Peters602f7402002-04-27 18:03:26 +00004405 p = stackbuf;
4406 }
4407 else {
4408 /* Overallocate on the heap, and give the excess back at the end. */
4409 nallocated = size * 4;
4410 if (nallocated / 4 != size) /* overflow! */
4411 return PyErr_NoMemory();
Christian Heimes72b710a2008-05-26 13:28:38 +00004412 result = PyBytes_FromStringAndSize(NULL, nallocated);
Guido van Rossum98297ee2007-11-06 21:34:58 +00004413 if (result == NULL)
Tim Peters602f7402002-04-27 18:03:26 +00004414 return NULL;
Christian Heimes72b710a2008-05-26 13:28:38 +00004415 p = PyBytes_AS_STRING(result);
Tim Peters602f7402002-04-27 18:03:26 +00004416 }
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004417
Tim Peters602f7402002-04-27 18:03:26 +00004418 for (i = 0; i < size;) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004419 Py_UCS4 ch = PyUnicode_READ(kind, data, i++);
Marc-André Lemburg3688a882002-02-06 18:09:02 +00004420
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004421 if (ch < 0x80)
Tim Peters602f7402002-04-27 18:03:26 +00004422 /* Encode ASCII */
Guido van Rossumd57fd912000-03-10 22:53:23 +00004423 *p++ = (char) ch;
Marc-André Lemburg3688a882002-02-06 18:09:02 +00004424
Guido van Rossumd57fd912000-03-10 22:53:23 +00004425 else if (ch < 0x0800) {
Tim Peters602f7402002-04-27 18:03:26 +00004426 /* Encode Latin-1 */
Marc-André Lemburgdc724d62002-02-06 18:20:19 +00004427 *p++ = (char)(0xc0 | (ch >> 6));
4428 *p++ = (char)(0x80 | (ch & 0x3f));
Victor Stinner31be90b2010-04-22 19:38:16 +00004429 } else if (0xD800 <= ch && ch <= 0xDFFF) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004430 Py_ssize_t newpos;
4431 PyObject *rep;
4432 Py_ssize_t repsize, k, startpos;
4433 startpos = i-1;
4434#if SIZEOF_WCHAR_T == 2
4435 startpos += wchar_offset;
Victor Stinner445a6232010-04-22 20:01:57 +00004436#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004437 rep = unicode_encode_call_errorhandler(
4438 errors, &errorHandler, "utf-8", "surrogates not allowed",
4439 PyUnicode_AS_UNICODE(unicode), PyUnicode_GET_SIZE(unicode),
4440 &exc, startpos, startpos+1, &newpos);
4441 if (!rep)
4442 goto error;
Victor Stinner31be90b2010-04-22 19:38:16 +00004443
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004444 if (PyBytes_Check(rep))
4445 repsize = PyBytes_GET_SIZE(rep);
4446 else
4447 repsize = PyUnicode_GET_SIZE(rep);
4448
4449 if (repsize > 4) {
4450 Py_ssize_t offset;
4451
4452 if (result == NULL)
4453 offset = p - stackbuf;
Victor Stinner31be90b2010-04-22 19:38:16 +00004454 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004455 offset = p - PyBytes_AS_STRING(result);
Victor Stinner31be90b2010-04-22 19:38:16 +00004456
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004457 if (nallocated > PY_SSIZE_T_MAX - repsize + 4) {
4458 /* integer overflow */
4459 PyErr_NoMemory();
4460 goto error;
4461 }
4462 nallocated += repsize - 4;
4463 if (result != NULL) {
4464 if (_PyBytes_Resize(&result, nallocated) < 0)
4465 goto error;
4466 } else {
4467 result = PyBytes_FromStringAndSize(NULL, nallocated);
Victor Stinner31be90b2010-04-22 19:38:16 +00004468 if (result == NULL)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004469 goto error;
4470 Py_MEMCPY(PyBytes_AS_STRING(result), stackbuf, offset);
4471 }
4472 p = PyBytes_AS_STRING(result) + offset;
4473 }
Victor Stinner31be90b2010-04-22 19:38:16 +00004474
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004475 if (PyBytes_Check(rep)) {
4476 char *prep = PyBytes_AS_STRING(rep);
4477 for(k = repsize; k > 0; k--)
4478 *p++ = *prep++;
4479 } else /* rep is unicode */ {
4480 const Py_UNICODE *prep = PyUnicode_AS_UNICODE(rep);
4481 Py_UNICODE c;
4482
4483 for(k=0; k<repsize; k++) {
4484 c = prep[k];
4485 if (0x80 <= c) {
4486 raise_encode_exception(&exc, "utf-8",
4487 PyUnicode_AS_UNICODE(unicode),
4488 size, i-1, i,
4489 "surrogates not allowed");
Victor Stinner31be90b2010-04-22 19:38:16 +00004490 goto error;
4491 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004492 *p++ = (char)prep[k];
Victor Stinner31be90b2010-04-22 19:38:16 +00004493 }
Victor Stinner31be90b2010-04-22 19:38:16 +00004494 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004495 Py_DECREF(rep);
Victor Stinner31be90b2010-04-22 19:38:16 +00004496 } else if (ch < 0x10000) {
4497 *p++ = (char)(0xe0 | (ch >> 12));
4498 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
4499 *p++ = (char)(0x80 | (ch & 0x3f));
4500 } else /* ch >= 0x10000 */ {
Tim Peters602f7402002-04-27 18:03:26 +00004501 /* Encode UCS4 Unicode ordinals */
4502 *p++ = (char)(0xf0 | (ch >> 18));
4503 *p++ = (char)(0x80 | ((ch >> 12) & 0x3f));
4504 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
4505 *p++ = (char)(0x80 | (ch & 0x3f));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004506#if SIZEOF_WCHAR_T == 2
4507 wchar_offset++;
4508#endif
Tim Peters602f7402002-04-27 18:03:26 +00004509 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004510 }
Tim Peters0eca65c2002-04-21 17:28:06 +00004511
Guido van Rossum98297ee2007-11-06 21:34:58 +00004512 if (result == NULL) {
Tim Peters602f7402002-04-27 18:03:26 +00004513 /* This was stack allocated. */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004514 nneeded = p - stackbuf;
Tim Peters602f7402002-04-27 18:03:26 +00004515 assert(nneeded <= nallocated);
Christian Heimes72b710a2008-05-26 13:28:38 +00004516 result = PyBytes_FromStringAndSize(stackbuf, nneeded);
Tim Peters602f7402002-04-27 18:03:26 +00004517 }
4518 else {
Christian Heimesf3863112007-11-22 07:46:41 +00004519 /* Cut back to size actually needed. */
Christian Heimes72b710a2008-05-26 13:28:38 +00004520 nneeded = p - PyBytes_AS_STRING(result);
Tim Peters602f7402002-04-27 18:03:26 +00004521 assert(nneeded <= nallocated);
Christian Heimes72b710a2008-05-26 13:28:38 +00004522 _PyBytes_Resize(&result, nneeded);
Tim Peters602f7402002-04-27 18:03:26 +00004523 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004524
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004525 Py_XDECREF(errorHandler);
4526 Py_XDECREF(exc);
Guido van Rossum98297ee2007-11-06 21:34:58 +00004527 return result;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004528 error:
4529 Py_XDECREF(errorHandler);
4530 Py_XDECREF(exc);
4531 Py_XDECREF(result);
4532 return NULL;
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004533
Tim Peters602f7402002-04-27 18:03:26 +00004534#undef MAX_SHORT_UNICHARS
Guido van Rossumd57fd912000-03-10 22:53:23 +00004535}
4536
Alexander Belopolsky40018472011-02-26 01:02:56 +00004537PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004538PyUnicode_EncodeUTF8(const Py_UNICODE *s,
4539 Py_ssize_t size,
4540 const char *errors)
4541{
4542 PyObject *v, *unicode;
4543
4544 unicode = PyUnicode_FromUnicode(s, size);
4545 if (unicode == NULL)
4546 return NULL;
4547 v = _PyUnicode_AsUTF8String(unicode, errors);
4548 Py_DECREF(unicode);
4549 return v;
4550}
4551
4552PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00004553PyUnicode_AsUTF8String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004554{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004555 return _PyUnicode_AsUTF8String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004556}
4557
Walter Dörwald41980ca2007-08-16 21:55:45 +00004558/* --- UTF-32 Codec ------------------------------------------------------- */
4559
4560PyObject *
4561PyUnicode_DecodeUTF32(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004562 Py_ssize_t size,
4563 const char *errors,
4564 int *byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004565{
4566 return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
4567}
4568
4569PyObject *
4570PyUnicode_DecodeUTF32Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004571 Py_ssize_t size,
4572 const char *errors,
4573 int *byteorder,
4574 Py_ssize_t *consumed)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004575{
4576 const char *starts = s;
4577 Py_ssize_t startinpos;
4578 Py_ssize_t endinpos;
4579 Py_ssize_t outpos;
4580 PyUnicodeObject *unicode;
4581 Py_UNICODE *p;
4582#ifndef Py_UNICODE_WIDE
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00004583 int pairs = 0;
Mark Dickinson7db923c2010-06-12 09:10:14 +00004584 const unsigned char *qq;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004585#else
4586 const int pairs = 0;
4587#endif
Mark Dickinson7db923c2010-06-12 09:10:14 +00004588 const unsigned char *q, *e;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004589 int bo = 0; /* assume native ordering by default */
4590 const char *errmsg = "";
Walter Dörwald41980ca2007-08-16 21:55:45 +00004591 /* Offsets from q for retrieving bytes in the right order. */
4592#ifdef BYTEORDER_IS_LITTLE_ENDIAN
4593 int iorder[] = {0, 1, 2, 3};
4594#else
4595 int iorder[] = {3, 2, 1, 0};
4596#endif
4597 PyObject *errorHandler = NULL;
4598 PyObject *exc = NULL;
Victor Stinner313a1202010-06-11 23:56:51 +00004599
Walter Dörwald41980ca2007-08-16 21:55:45 +00004600 q = (unsigned char *)s;
4601 e = q + size;
4602
4603 if (byteorder)
4604 bo = *byteorder;
4605
4606 /* Check for BOM marks (U+FEFF) in the input and adjust current
4607 byte order setting accordingly. In native mode, the leading BOM
4608 mark is skipped, in all other modes, it is copied to the output
4609 stream as-is (giving a ZWNBSP character). */
4610 if (bo == 0) {
4611 if (size >= 4) {
4612 const Py_UCS4 bom = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
Benjamin Peterson29060642009-01-31 22:14:21 +00004613 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00004614#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Benjamin Peterson29060642009-01-31 22:14:21 +00004615 if (bom == 0x0000FEFF) {
4616 q += 4;
4617 bo = -1;
4618 }
4619 else if (bom == 0xFFFE0000) {
4620 q += 4;
4621 bo = 1;
4622 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004623#else
Benjamin Peterson29060642009-01-31 22:14:21 +00004624 if (bom == 0x0000FEFF) {
4625 q += 4;
4626 bo = 1;
4627 }
4628 else if (bom == 0xFFFE0000) {
4629 q += 4;
4630 bo = -1;
4631 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004632#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00004633 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004634 }
4635
4636 if (bo == -1) {
4637 /* force LE */
4638 iorder[0] = 0;
4639 iorder[1] = 1;
4640 iorder[2] = 2;
4641 iorder[3] = 3;
4642 }
4643 else if (bo == 1) {
4644 /* force BE */
4645 iorder[0] = 3;
4646 iorder[1] = 2;
4647 iorder[2] = 1;
4648 iorder[3] = 0;
4649 }
4650
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00004651 /* On narrow builds we split characters outside the BMP into two
4652 codepoints => count how much extra space we need. */
4653#ifndef Py_UNICODE_WIDE
4654 for (qq = q; qq < e; qq += 4)
4655 if (qq[iorder[2]] != 0 || qq[iorder[3]] != 0)
4656 pairs++;
4657#endif
4658
4659 /* This might be one to much, because of a BOM */
4660 unicode = _PyUnicode_New((size+3)/4+pairs);
4661 if (!unicode)
4662 return NULL;
4663 if (size == 0)
4664 return (PyObject *)unicode;
4665
4666 /* Unpack UTF-32 encoded data */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004667 p = PyUnicode_AS_UNICODE(unicode);
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00004668
Walter Dörwald41980ca2007-08-16 21:55:45 +00004669 while (q < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004670 Py_UCS4 ch;
4671 /* remaining bytes at the end? (size should be divisible by 4) */
4672 if (e-q<4) {
4673 if (consumed)
4674 break;
4675 errmsg = "truncated data";
4676 startinpos = ((const char *)q)-starts;
4677 endinpos = ((const char *)e)-starts;
4678 goto utf32Error;
4679 /* The remaining input chars are ignored if the callback
4680 chooses to skip the input */
4681 }
4682 ch = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
4683 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00004684
Benjamin Peterson29060642009-01-31 22:14:21 +00004685 if (ch >= 0x110000)
4686 {
4687 errmsg = "codepoint not in range(0x110000)";
4688 startinpos = ((const char *)q)-starts;
4689 endinpos = startinpos+4;
4690 goto utf32Error;
4691 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004692#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00004693 if (ch >= 0x10000)
4694 {
4695 *p++ = 0xD800 | ((ch-0x10000) >> 10);
4696 *p++ = 0xDC00 | ((ch-0x10000) & 0x3FF);
4697 }
4698 else
Walter Dörwald41980ca2007-08-16 21:55:45 +00004699#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00004700 *p++ = ch;
4701 q += 4;
4702 continue;
4703 utf32Error:
4704 outpos = p-PyUnicode_AS_UNICODE(unicode);
4705 if (unicode_decode_call_errorhandler(
4706 errors, &errorHandler,
4707 "utf32", errmsg,
4708 &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
4709 &unicode, &outpos, &p))
4710 goto onError;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004711 }
4712
4713 if (byteorder)
4714 *byteorder = bo;
4715
4716 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00004717 *consumed = (const char *)q-starts;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004718
4719 /* Adjust length */
Victor Stinnerfe226c02011-10-03 03:52:20 +02004720 if (PyUnicode_Resize((PyObject**)&unicode, p - PyUnicode_AS_UNICODE(unicode)) < 0)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004721 goto onError;
4722
4723 Py_XDECREF(errorHandler);
4724 Py_XDECREF(exc);
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02004725 if (_PyUnicode_READY_REPLACE(&unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004726 Py_DECREF(unicode);
4727 return NULL;
4728 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004729 return (PyObject *)unicode;
4730
Benjamin Peterson29060642009-01-31 22:14:21 +00004731 onError:
Walter Dörwald41980ca2007-08-16 21:55:45 +00004732 Py_DECREF(unicode);
4733 Py_XDECREF(errorHandler);
4734 Py_XDECREF(exc);
4735 return NULL;
4736}
4737
4738PyObject *
4739PyUnicode_EncodeUTF32(const Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004740 Py_ssize_t size,
4741 const char *errors,
4742 int byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004743{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004744 PyObject *v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004745 unsigned char *p;
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004746 Py_ssize_t nsize, bytesize;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004747#ifndef Py_UNICODE_WIDE
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004748 Py_ssize_t i, pairs;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004749#else
4750 const int pairs = 0;
4751#endif
4752 /* Offsets from p for storing byte pairs in the right order. */
4753#ifdef BYTEORDER_IS_LITTLE_ENDIAN
4754 int iorder[] = {0, 1, 2, 3};
4755#else
4756 int iorder[] = {3, 2, 1, 0};
4757#endif
4758
Benjamin Peterson29060642009-01-31 22:14:21 +00004759#define STORECHAR(CH) \
4760 do { \
4761 p[iorder[3]] = ((CH) >> 24) & 0xff; \
4762 p[iorder[2]] = ((CH) >> 16) & 0xff; \
4763 p[iorder[1]] = ((CH) >> 8) & 0xff; \
4764 p[iorder[0]] = (CH) & 0xff; \
4765 p += 4; \
Walter Dörwald41980ca2007-08-16 21:55:45 +00004766 } while(0)
4767
4768 /* In narrow builds we can output surrogate pairs as one codepoint,
4769 so we need less space. */
4770#ifndef Py_UNICODE_WIDE
4771 for (i = pairs = 0; i < size-1; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +00004772 if (0xD800 <= s[i] && s[i] <= 0xDBFF &&
4773 0xDC00 <= s[i+1] && s[i+1] <= 0xDFFF)
4774 pairs++;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004775#endif
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004776 nsize = (size - pairs + (byteorder == 0));
4777 bytesize = nsize * 4;
4778 if (bytesize / 4 != nsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00004779 return PyErr_NoMemory();
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004780 v = PyBytes_FromStringAndSize(NULL, bytesize);
Walter Dörwald41980ca2007-08-16 21:55:45 +00004781 if (v == NULL)
4782 return NULL;
4783
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004784 p = (unsigned char *)PyBytes_AS_STRING(v);
Walter Dörwald41980ca2007-08-16 21:55:45 +00004785 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004786 STORECHAR(0xFEFF);
Walter Dörwald41980ca2007-08-16 21:55:45 +00004787 if (size == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00004788 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004789
4790 if (byteorder == -1) {
4791 /* force LE */
4792 iorder[0] = 0;
4793 iorder[1] = 1;
4794 iorder[2] = 2;
4795 iorder[3] = 3;
4796 }
4797 else if (byteorder == 1) {
4798 /* force BE */
4799 iorder[0] = 3;
4800 iorder[1] = 2;
4801 iorder[2] = 1;
4802 iorder[3] = 0;
4803 }
4804
4805 while (size-- > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004806 Py_UCS4 ch = *s++;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004807#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00004808 if (0xD800 <= ch && ch <= 0xDBFF && size > 0) {
4809 Py_UCS4 ch2 = *s;
4810 if (0xDC00 <= ch2 && ch2 <= 0xDFFF) {
4811 ch = (((ch & 0x3FF)<<10) | (ch2 & 0x3FF)) + 0x10000;
4812 s++;
4813 size--;
4814 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00004815 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004816#endif
4817 STORECHAR(ch);
4818 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00004819
4820 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004821 return v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004822#undef STORECHAR
4823}
4824
Alexander Belopolsky40018472011-02-26 01:02:56 +00004825PyObject *
4826PyUnicode_AsUTF32String(PyObject *unicode)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004827{
4828 if (!PyUnicode_Check(unicode)) {
4829 PyErr_BadArgument();
4830 return NULL;
4831 }
4832 return PyUnicode_EncodeUTF32(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00004833 PyUnicode_GET_SIZE(unicode),
4834 NULL,
4835 0);
Walter Dörwald41980ca2007-08-16 21:55:45 +00004836}
4837
Guido van Rossumd57fd912000-03-10 22:53:23 +00004838/* --- UTF-16 Codec ------------------------------------------------------- */
4839
Tim Peters772747b2001-08-09 22:21:55 +00004840PyObject *
4841PyUnicode_DecodeUTF16(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004842 Py_ssize_t size,
4843 const char *errors,
4844 int *byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004845{
Walter Dörwald69652032004-09-07 20:24:22 +00004846 return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
4847}
4848
Antoine Pitrouab868312009-01-10 15:40:25 +00004849/* Two masks for fast checking of whether a C 'long' may contain
4850 UTF16-encoded surrogate characters. This is an efficient heuristic,
4851 assuming that non-surrogate characters with a code point >= 0x8000 are
4852 rare in most input.
4853 FAST_CHAR_MASK is used when the input is in native byte ordering,
4854 SWAPPED_FAST_CHAR_MASK when the input is in byteswapped ordering.
Benjamin Peterson29060642009-01-31 22:14:21 +00004855*/
Antoine Pitrouab868312009-01-10 15:40:25 +00004856#if (SIZEOF_LONG == 8)
4857# define FAST_CHAR_MASK 0x8000800080008000L
4858# define SWAPPED_FAST_CHAR_MASK 0x0080008000800080L
4859#elif (SIZEOF_LONG == 4)
4860# define FAST_CHAR_MASK 0x80008000L
4861# define SWAPPED_FAST_CHAR_MASK 0x00800080L
4862#else
4863# error C 'long' size should be either 4 or 8!
4864#endif
4865
Walter Dörwald69652032004-09-07 20:24:22 +00004866PyObject *
4867PyUnicode_DecodeUTF16Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004868 Py_ssize_t size,
4869 const char *errors,
4870 int *byteorder,
4871 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00004872{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004873 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004874 Py_ssize_t startinpos;
4875 Py_ssize_t endinpos;
4876 Py_ssize_t outpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004877 PyUnicodeObject *unicode;
4878 Py_UNICODE *p;
Antoine Pitrouab868312009-01-10 15:40:25 +00004879 const unsigned char *q, *e, *aligned_end;
Tim Peters772747b2001-08-09 22:21:55 +00004880 int bo = 0; /* assume native ordering by default */
Antoine Pitrouab868312009-01-10 15:40:25 +00004881 int native_ordering = 0;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004882 const char *errmsg = "";
Tim Peters772747b2001-08-09 22:21:55 +00004883 /* Offsets from q for retrieving byte pairs in the right order. */
4884#ifdef BYTEORDER_IS_LITTLE_ENDIAN
4885 int ihi = 1, ilo = 0;
4886#else
4887 int ihi = 0, ilo = 1;
4888#endif
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004889 PyObject *errorHandler = NULL;
4890 PyObject *exc = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004891
4892 /* Note: size will always be longer than the resulting Unicode
4893 character count */
4894 unicode = _PyUnicode_New(size);
4895 if (!unicode)
4896 return NULL;
4897 if (size == 0)
4898 return (PyObject *)unicode;
4899
4900 /* Unpack UTF-16 encoded data */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004901 p = PyUnicode_AS_UNICODE(unicode);
Tim Peters772747b2001-08-09 22:21:55 +00004902 q = (unsigned char *)s;
Antoine Pitrouab868312009-01-10 15:40:25 +00004903 e = q + size - 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004904
4905 if (byteorder)
Tim Peters772747b2001-08-09 22:21:55 +00004906 bo = *byteorder;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004907
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00004908 /* Check for BOM marks (U+FEFF) in the input and adjust current
4909 byte order setting accordingly. In native mode, the leading BOM
4910 mark is skipped, in all other modes, it is copied to the output
4911 stream as-is (giving a ZWNBSP character). */
4912 if (bo == 0) {
Walter Dörwald69652032004-09-07 20:24:22 +00004913 if (size >= 2) {
4914 const Py_UNICODE bom = (q[ihi] << 8) | q[ilo];
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00004915#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Benjamin Peterson29060642009-01-31 22:14:21 +00004916 if (bom == 0xFEFF) {
4917 q += 2;
4918 bo = -1;
4919 }
4920 else if (bom == 0xFFFE) {
4921 q += 2;
4922 bo = 1;
4923 }
Tim Petersced69f82003-09-16 20:30:58 +00004924#else
Benjamin Peterson29060642009-01-31 22:14:21 +00004925 if (bom == 0xFEFF) {
4926 q += 2;
4927 bo = 1;
4928 }
4929 else if (bom == 0xFFFE) {
4930 q += 2;
4931 bo = -1;
4932 }
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00004933#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00004934 }
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00004935 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004936
Tim Peters772747b2001-08-09 22:21:55 +00004937 if (bo == -1) {
4938 /* force LE */
4939 ihi = 1;
4940 ilo = 0;
4941 }
4942 else if (bo == 1) {
4943 /* force BE */
4944 ihi = 0;
4945 ilo = 1;
4946 }
Antoine Pitrouab868312009-01-10 15:40:25 +00004947#ifdef BYTEORDER_IS_LITTLE_ENDIAN
4948 native_ordering = ilo < ihi;
4949#else
4950 native_ordering = ilo > ihi;
4951#endif
Tim Peters772747b2001-08-09 22:21:55 +00004952
Antoine Pitrouab868312009-01-10 15:40:25 +00004953 aligned_end = (const unsigned char *) ((size_t) e & ~LONG_PTR_MASK);
Tim Peters772747b2001-08-09 22:21:55 +00004954 while (q < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004955 Py_UNICODE ch;
Antoine Pitrouab868312009-01-10 15:40:25 +00004956 /* First check for possible aligned read of a C 'long'. Unaligned
4957 reads are more expensive, better to defer to another iteration. */
4958 if (!((size_t) q & LONG_PTR_MASK)) {
4959 /* Fast path for runs of non-surrogate chars. */
4960 register const unsigned char *_q = q;
4961 Py_UNICODE *_p = p;
4962 if (native_ordering) {
4963 /* Native ordering is simple: as long as the input cannot
4964 possibly contain a surrogate char, do an unrolled copy
4965 of several 16-bit code points to the target object.
4966 The non-surrogate check is done on several input bytes
4967 at a time (as many as a C 'long' can contain). */
4968 while (_q < aligned_end) {
4969 unsigned long data = * (unsigned long *) _q;
4970 if (data & FAST_CHAR_MASK)
4971 break;
4972 _p[0] = ((unsigned short *) _q)[0];
4973 _p[1] = ((unsigned short *) _q)[1];
4974#if (SIZEOF_LONG == 8)
4975 _p[2] = ((unsigned short *) _q)[2];
4976 _p[3] = ((unsigned short *) _q)[3];
4977#endif
4978 _q += SIZEOF_LONG;
4979 _p += SIZEOF_LONG / 2;
4980 }
4981 }
4982 else {
4983 /* Byteswapped ordering is similar, but we must decompose
4984 the copy bytewise, and take care of zero'ing out the
4985 upper bytes if the target object is in 32-bit units
4986 (that is, in UCS-4 builds). */
4987 while (_q < aligned_end) {
4988 unsigned long data = * (unsigned long *) _q;
4989 if (data & SWAPPED_FAST_CHAR_MASK)
4990 break;
4991 /* Zero upper bytes in UCS-4 builds */
4992#if (Py_UNICODE_SIZE > 2)
4993 _p[0] = 0;
4994 _p[1] = 0;
4995#if (SIZEOF_LONG == 8)
4996 _p[2] = 0;
4997 _p[3] = 0;
4998#endif
4999#endif
Antoine Pitroud6e8de12009-01-11 23:56:55 +00005000 /* Issue #4916; UCS-4 builds on big endian machines must
5001 fill the two last bytes of each 4-byte unit. */
5002#if (!defined(BYTEORDER_IS_LITTLE_ENDIAN) && Py_UNICODE_SIZE > 2)
5003# define OFF 2
5004#else
5005# define OFF 0
Antoine Pitrouab868312009-01-10 15:40:25 +00005006#endif
Antoine Pitroud6e8de12009-01-11 23:56:55 +00005007 ((unsigned char *) _p)[OFF + 1] = _q[0];
5008 ((unsigned char *) _p)[OFF + 0] = _q[1];
5009 ((unsigned char *) _p)[OFF + 1 + Py_UNICODE_SIZE] = _q[2];
5010 ((unsigned char *) _p)[OFF + 0 + Py_UNICODE_SIZE] = _q[3];
5011#if (SIZEOF_LONG == 8)
5012 ((unsigned char *) _p)[OFF + 1 + 2 * Py_UNICODE_SIZE] = _q[4];
5013 ((unsigned char *) _p)[OFF + 0 + 2 * Py_UNICODE_SIZE] = _q[5];
5014 ((unsigned char *) _p)[OFF + 1 + 3 * Py_UNICODE_SIZE] = _q[6];
5015 ((unsigned char *) _p)[OFF + 0 + 3 * Py_UNICODE_SIZE] = _q[7];
5016#endif
5017#undef OFF
Antoine Pitrouab868312009-01-10 15:40:25 +00005018 _q += SIZEOF_LONG;
5019 _p += SIZEOF_LONG / 2;
5020 }
5021 }
5022 p = _p;
5023 q = _q;
5024 if (q >= e)
5025 break;
5026 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005027 ch = (q[ihi] << 8) | q[ilo];
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005028
Benjamin Peterson14339b62009-01-31 16:36:08 +00005029 q += 2;
Benjamin Peterson29060642009-01-31 22:14:21 +00005030
5031 if (ch < 0xD800 || ch > 0xDFFF) {
5032 *p++ = ch;
5033 continue;
5034 }
5035
5036 /* UTF-16 code pair: */
5037 if (q > e) {
5038 errmsg = "unexpected end of data";
5039 startinpos = (((const char *)q) - 2) - starts;
5040 endinpos = ((const char *)e) + 1 - starts;
5041 goto utf16Error;
5042 }
5043 if (0xD800 <= ch && ch <= 0xDBFF) {
5044 Py_UNICODE ch2 = (q[ihi] << 8) | q[ilo];
5045 q += 2;
5046 if (0xDC00 <= ch2 && ch2 <= 0xDFFF) {
Fredrik Lundh8f455852001-06-27 18:59:43 +00005047#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00005048 *p++ = ch;
5049 *p++ = ch2;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005050#else
Benjamin Peterson29060642009-01-31 22:14:21 +00005051 *p++ = (((ch & 0x3FF)<<10) | (ch2 & 0x3FF)) + 0x10000;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005052#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00005053 continue;
5054 }
5055 else {
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005056 errmsg = "illegal UTF-16 surrogate";
Benjamin Peterson29060642009-01-31 22:14:21 +00005057 startinpos = (((const char *)q)-4)-starts;
5058 endinpos = startinpos+2;
5059 goto utf16Error;
5060 }
5061
Benjamin Peterson14339b62009-01-31 16:36:08 +00005062 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005063 errmsg = "illegal encoding";
5064 startinpos = (((const char *)q)-2)-starts;
5065 endinpos = startinpos+2;
5066 /* Fall through to report the error */
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005067
Benjamin Peterson29060642009-01-31 22:14:21 +00005068 utf16Error:
5069 outpos = p - PyUnicode_AS_UNICODE(unicode);
5070 if (unicode_decode_call_errorhandler(
Antoine Pitrouab868312009-01-10 15:40:25 +00005071 errors,
5072 &errorHandler,
5073 "utf16", errmsg,
5074 &starts,
5075 (const char **)&e,
5076 &startinpos,
5077 &endinpos,
5078 &exc,
5079 (const char **)&q,
5080 &unicode,
5081 &outpos,
5082 &p))
Benjamin Peterson29060642009-01-31 22:14:21 +00005083 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005084 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005085 /* remaining byte at the end? (size should be even) */
5086 if (e == q) {
5087 if (!consumed) {
5088 errmsg = "truncated data";
5089 startinpos = ((const char *)q) - starts;
5090 endinpos = ((const char *)e) + 1 - starts;
5091 outpos = p - PyUnicode_AS_UNICODE(unicode);
5092 if (unicode_decode_call_errorhandler(
5093 errors,
5094 &errorHandler,
5095 "utf16", errmsg,
5096 &starts,
5097 (const char **)&e,
5098 &startinpos,
5099 &endinpos,
5100 &exc,
5101 (const char **)&q,
5102 &unicode,
5103 &outpos,
5104 &p))
5105 goto onError;
5106 /* The remaining input chars are ignored if the callback
5107 chooses to skip the input */
5108 }
5109 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005110
5111 if (byteorder)
5112 *byteorder = bo;
5113
Walter Dörwald69652032004-09-07 20:24:22 +00005114 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005115 *consumed = (const char *)q-starts;
Walter Dörwald69652032004-09-07 20:24:22 +00005116
Guido van Rossumd57fd912000-03-10 22:53:23 +00005117 /* Adjust length */
Victor Stinnerfe226c02011-10-03 03:52:20 +02005118 if (PyUnicode_Resize((PyObject**)&unicode, p - PyUnicode_AS_UNICODE(unicode)) < 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005119 goto onError;
5120
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005121 Py_XDECREF(errorHandler);
5122 Py_XDECREF(exc);
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02005123 if (_PyUnicode_READY_REPLACE(&unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005124 Py_DECREF(unicode);
5125 return NULL;
5126 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005127 return (PyObject *)unicode;
5128
Benjamin Peterson29060642009-01-31 22:14:21 +00005129 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00005130 Py_DECREF(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005131 Py_XDECREF(errorHandler);
5132 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005133 return NULL;
5134}
5135
Antoine Pitrouab868312009-01-10 15:40:25 +00005136#undef FAST_CHAR_MASK
5137#undef SWAPPED_FAST_CHAR_MASK
5138
Tim Peters772747b2001-08-09 22:21:55 +00005139PyObject *
5140PyUnicode_EncodeUTF16(const Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005141 Py_ssize_t size,
5142 const char *errors,
5143 int byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005144{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005145 PyObject *v;
Tim Peters772747b2001-08-09 22:21:55 +00005146 unsigned char *p;
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005147 Py_ssize_t nsize, bytesize;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00005148#ifdef Py_UNICODE_WIDE
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005149 Py_ssize_t i, pairs;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00005150#else
5151 const int pairs = 0;
5152#endif
Tim Peters772747b2001-08-09 22:21:55 +00005153 /* Offsets from p for storing byte pairs in the right order. */
5154#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5155 int ihi = 1, ilo = 0;
5156#else
5157 int ihi = 0, ilo = 1;
5158#endif
5159
Benjamin Peterson29060642009-01-31 22:14:21 +00005160#define STORECHAR(CH) \
5161 do { \
5162 p[ihi] = ((CH) >> 8) & 0xff; \
5163 p[ilo] = (CH) & 0xff; \
5164 p += 2; \
Tim Peters772747b2001-08-09 22:21:55 +00005165 } while(0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005166
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00005167#ifdef Py_UNICODE_WIDE
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005168 for (i = pairs = 0; i < size; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +00005169 if (s[i] >= 0x10000)
5170 pairs++;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00005171#endif
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005172 /* 2 * (size + pairs + (byteorder == 0)) */
5173 if (size > PY_SSIZE_T_MAX ||
5174 size > PY_SSIZE_T_MAX - pairs - (byteorder == 0))
Benjamin Peterson29060642009-01-31 22:14:21 +00005175 return PyErr_NoMemory();
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005176 nsize = size + pairs + (byteorder == 0);
5177 bytesize = nsize * 2;
5178 if (bytesize / 2 != nsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005179 return PyErr_NoMemory();
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005180 v = PyBytes_FromStringAndSize(NULL, bytesize);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005181 if (v == NULL)
5182 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005183
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005184 p = (unsigned char *)PyBytes_AS_STRING(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005185 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005186 STORECHAR(0xFEFF);
Marc-André Lemburg063e0cb2000-07-07 11:27:45 +00005187 if (size == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005188 goto done;
Tim Peters772747b2001-08-09 22:21:55 +00005189
5190 if (byteorder == -1) {
5191 /* force LE */
5192 ihi = 1;
5193 ilo = 0;
5194 }
5195 else if (byteorder == 1) {
5196 /* force BE */
5197 ihi = 0;
5198 ilo = 1;
5199 }
5200
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005201 while (size-- > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005202 Py_UNICODE ch = *s++;
5203 Py_UNICODE ch2 = 0;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00005204#ifdef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00005205 if (ch >= 0x10000) {
5206 ch2 = 0xDC00 | ((ch-0x10000) & 0x3FF);
5207 ch = 0xD800 | ((ch-0x10000) >> 10);
5208 }
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00005209#endif
Tim Peters772747b2001-08-09 22:21:55 +00005210 STORECHAR(ch);
5211 if (ch2)
5212 STORECHAR(ch2);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005213 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005214
5215 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005216 return v;
Tim Peters772747b2001-08-09 22:21:55 +00005217#undef STORECHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00005218}
5219
Alexander Belopolsky40018472011-02-26 01:02:56 +00005220PyObject *
5221PyUnicode_AsUTF16String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005222{
5223 if (!PyUnicode_Check(unicode)) {
5224 PyErr_BadArgument();
5225 return NULL;
5226 }
5227 return PyUnicode_EncodeUTF16(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00005228 PyUnicode_GET_SIZE(unicode),
5229 NULL,
5230 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005231}
5232
5233/* --- Unicode Escape Codec ----------------------------------------------- */
5234
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005235/* Helper function for PyUnicode_DecodeUnicodeEscape, determines
5236 if all the escapes in the string make it still a valid ASCII string.
5237 Returns -1 if any escapes were found which cause the string to
5238 pop out of ASCII range. Otherwise returns the length of the
5239 required buffer to hold the string.
5240 */
5241Py_ssize_t
5242length_of_escaped_ascii_string(const char *s, Py_ssize_t size)
5243{
5244 const unsigned char *p = (const unsigned char *)s;
5245 const unsigned char *end = p + size;
5246 Py_ssize_t length = 0;
5247
5248 if (size < 0)
5249 return -1;
5250
5251 for (; p < end; ++p) {
5252 if (*p > 127) {
5253 /* Non-ASCII */
5254 return -1;
5255 }
5256 else if (*p != '\\') {
5257 /* Normal character */
5258 ++length;
5259 }
5260 else {
5261 /* Backslash-escape, check next char */
5262 ++p;
5263 /* Escape sequence reaches till end of string or
5264 non-ASCII follow-up. */
5265 if (p >= end || *p > 127)
5266 return -1;
5267 switch (*p) {
5268 case '\n':
5269 /* backslash + \n result in zero characters */
5270 break;
5271 case '\\': case '\'': case '\"':
5272 case 'b': case 'f': case 't':
5273 case 'n': case 'r': case 'v': case 'a':
5274 ++length;
5275 break;
5276 case '0': case '1': case '2': case '3':
5277 case '4': case '5': case '6': case '7':
5278 case 'x': case 'u': case 'U': case 'N':
5279 /* these do not guarantee ASCII characters */
5280 return -1;
5281 default:
5282 /* count the backslash + the other character */
5283 length += 2;
5284 }
5285 }
5286 }
5287 return length;
5288}
5289
5290/* Similar to PyUnicode_WRITE but either write into wstr field
5291 or treat string as ASCII. */
5292#define WRITE_ASCII_OR_WSTR(kind, buf, index, value) \
5293 do { \
5294 if ((kind) != PyUnicode_WCHAR_KIND) \
5295 ((unsigned char *)(buf))[(index)] = (unsigned char)(value); \
5296 else \
5297 ((Py_UNICODE *)(buf))[(index)] = (Py_UNICODE)(value); \
5298 } while (0)
5299
5300#define WRITE_WSTR(buf, index, value) \
5301 assert(kind == PyUnicode_WCHAR_KIND), \
5302 ((Py_UNICODE *)(buf))[(index)] = (Py_UNICODE)(value)
5303
5304
Fredrik Lundh06d12682001-01-24 07:59:11 +00005305static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
Marc-André Lemburg0f774e32000-06-28 16:43:35 +00005306
Alexander Belopolsky40018472011-02-26 01:02:56 +00005307PyObject *
5308PyUnicode_DecodeUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005309 Py_ssize_t size,
Victor Stinnerc17f5402011-09-29 00:16:58 +02005310 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005311{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005312 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005313 Py_ssize_t startinpos;
5314 Py_ssize_t endinpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005315 int j;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005316 PyUnicodeObject *v;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005317 Py_UNICODE *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005318 const char *end;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005319 char* message;
5320 Py_UCS4 chr = 0xffffffff; /* in case 'getcode' messes up */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005321 PyObject *errorHandler = NULL;
5322 PyObject *exc = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005323 Py_ssize_t ascii_length;
5324 Py_ssize_t i;
5325 int kind;
5326 void *data;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005327
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005328 ascii_length = length_of_escaped_ascii_string(s, size);
5329
5330 /* After length_of_escaped_ascii_string() there are two alternatives,
5331 either the string is pure ASCII with named escapes like \n, etc.
5332 and we determined it's exact size (common case)
5333 or it contains \x, \u, ... escape sequences. then we create a
5334 legacy wchar string and resize it at the end of this function. */
5335 if (ascii_length >= 0) {
5336 v = (PyUnicodeObject *)PyUnicode_New(ascii_length, 127);
5337 if (!v)
5338 goto onError;
5339 assert(PyUnicode_KIND(v) == PyUnicode_1BYTE_KIND);
5340 kind = PyUnicode_1BYTE_KIND;
5341 data = PyUnicode_DATA(v);
5342 }
5343 else {
5344 /* Escaped strings will always be longer than the resulting
5345 Unicode string, so we start with size here and then reduce the
5346 length after conversion to the true value.
5347 (but if the error callback returns a long replacement string
5348 we'll have to allocate more space) */
5349 v = _PyUnicode_New(size);
5350 if (!v)
5351 goto onError;
5352 kind = PyUnicode_WCHAR_KIND;
5353 data = PyUnicode_AS_UNICODE(v);
5354 }
5355
Guido van Rossumd57fd912000-03-10 22:53:23 +00005356 if (size == 0)
5357 return (PyObject *)v;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005358 i = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005359 end = s + size;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005360
Guido van Rossumd57fd912000-03-10 22:53:23 +00005361 while (s < end) {
5362 unsigned char c;
Marc-André Lemburg063e0cb2000-07-07 11:27:45 +00005363 Py_UNICODE x;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005364 int digits;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005365
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005366 if (kind == PyUnicode_WCHAR_KIND) {
5367 assert(i < _PyUnicode_WSTR_LENGTH(v));
5368 }
5369 else {
5370 /* The only case in which i == ascii_length is a backslash
5371 followed by a newline. */
5372 assert(i <= ascii_length);
5373 }
5374
Guido van Rossumd57fd912000-03-10 22:53:23 +00005375 /* Non-escape characters are interpreted as Unicode ordinals */
5376 if (*s != '\\') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005377 WRITE_ASCII_OR_WSTR(kind, data, i++, (unsigned char) *s++);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005378 continue;
5379 }
5380
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005381 startinpos = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005382 /* \ - Escapes */
5383 s++;
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005384 c = *s++;
5385 if (s > end)
5386 c = '\0'; /* Invalid after \ */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005387
5388 if (kind == PyUnicode_WCHAR_KIND) {
5389 assert(i < _PyUnicode_WSTR_LENGTH(v));
5390 }
5391 else {
5392 /* The only case in which i == ascii_length is a backslash
5393 followed by a newline. */
5394 assert(i < ascii_length || (i == ascii_length && c == '\n'));
5395 }
5396
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005397 switch (c) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005398
Benjamin Peterson29060642009-01-31 22:14:21 +00005399 /* \x escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005400 case '\n': break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005401 case '\\': WRITE_ASCII_OR_WSTR(kind, data, i++, '\\'); break;
5402 case '\'': WRITE_ASCII_OR_WSTR(kind, data, i++, '\''); break;
5403 case '\"': WRITE_ASCII_OR_WSTR(kind, data, i++, '\"'); break;
5404 case 'b': WRITE_ASCII_OR_WSTR(kind, data, i++, '\b'); break;
5405 /* FF */
5406 case 'f': WRITE_ASCII_OR_WSTR(kind, data, i++, '\014'); break;
5407 case 't': WRITE_ASCII_OR_WSTR(kind, data, i++, '\t'); break;
5408 case 'n': WRITE_ASCII_OR_WSTR(kind, data, i++, '\n'); break;
5409 case 'r': WRITE_ASCII_OR_WSTR(kind, data, i++, '\r'); break;
5410 /* VT */
5411 case 'v': WRITE_ASCII_OR_WSTR(kind, data, i++, '\013'); break;
5412 /* BEL, not classic C */
5413 case 'a': WRITE_ASCII_OR_WSTR(kind, data, i++, '\007'); break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005414
Benjamin Peterson29060642009-01-31 22:14:21 +00005415 /* \OOO (octal) escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005416 case '0': case '1': case '2': case '3':
5417 case '4': case '5': case '6': case '7':
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005418 x = s[-1] - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005419 if (s < end && '0' <= *s && *s <= '7') {
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005420 x = (x<<3) + *s++ - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005421 if (s < end && '0' <= *s && *s <= '7')
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005422 x = (x<<3) + *s++ - '0';
Guido van Rossumd57fd912000-03-10 22:53:23 +00005423 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005424 WRITE_WSTR(data, i++, x);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005425 break;
5426
Benjamin Peterson29060642009-01-31 22:14:21 +00005427 /* hex escapes */
5428 /* \xXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005429 case 'x':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005430 digits = 2;
5431 message = "truncated \\xXX escape";
5432 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005433
Benjamin Peterson29060642009-01-31 22:14:21 +00005434 /* \uXXXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005435 case 'u':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005436 digits = 4;
5437 message = "truncated \\uXXXX escape";
5438 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005439
Benjamin Peterson29060642009-01-31 22:14:21 +00005440 /* \UXXXXXXXX */
Fredrik Lundhdf846752000-09-03 11:29:49 +00005441 case 'U':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005442 digits = 8;
5443 message = "truncated \\UXXXXXXXX escape";
5444 hexescape:
5445 chr = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005446 p = PyUnicode_AS_UNICODE(v) + i;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005447 if (s+digits>end) {
5448 endinpos = size;
5449 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005450 errors, &errorHandler,
5451 "unicodeescape", "end of string in escape sequence",
5452 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005453 &v, &i, &p))
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005454 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005455 data = PyUnicode_AS_UNICODE(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005456 goto nextByte;
5457 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005458 for (j = 0; j < digits; ++j) {
5459 c = (unsigned char) s[j];
David Malcolm96960882010-11-05 17:23:41 +00005460 if (!Py_ISXDIGIT(c)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005461 endinpos = (s+j+1)-starts;
5462 p = PyUnicode_AS_UNICODE(v) + i;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005463 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005464 errors, &errorHandler,
5465 "unicodeescape", message,
5466 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005467 &v, &i, &p))
Fredrik Lundhdf846752000-09-03 11:29:49 +00005468 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005469 data = PyUnicode_AS_UNICODE(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005470 goto nextByte;
Fredrik Lundhdf846752000-09-03 11:29:49 +00005471 }
5472 chr = (chr<<4) & ~0xF;
5473 if (c >= '0' && c <= '9')
5474 chr += c - '0';
5475 else if (c >= 'a' && c <= 'f')
5476 chr += 10 + c - 'a';
5477 else
5478 chr += 10 + c - 'A';
5479 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005480 s += j;
Jeremy Hylton504de6b2003-10-06 05:08:26 +00005481 if (chr == 0xffffffff && PyErr_Occurred())
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005482 /* _decoding_error will have already written into the
5483 target buffer. */
5484 break;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005485 store:
Fredrik Lundhdf846752000-09-03 11:29:49 +00005486 /* when we get here, chr is a 32-bit unicode character */
5487 if (chr <= 0xffff)
5488 /* UCS-2 character */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005489 WRITE_WSTR(data, i++, chr);
Fredrik Lundhdf846752000-09-03 11:29:49 +00005490 else if (chr <= 0x10ffff) {
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005491 /* UCS-4 character. Either store directly, or as
Walter Dörwald8c077222002-03-25 11:16:18 +00005492 surrogate pair. */
Fredrik Lundh8f455852001-06-27 18:59:43 +00005493#ifdef Py_UNICODE_WIDE
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005494 WRITE_WSTR(data, i++, chr);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005495#else
Fredrik Lundhdf846752000-09-03 11:29:49 +00005496 chr -= 0x10000L;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005497 WRITE_WSTR(data, i++, 0xD800 + (Py_UNICODE) (chr >> 10));
5498 WRITE_WSTR(data, i++, 0xDC00 + (Py_UNICODE) (chr & 0x03FF));
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005499#endif
Fredrik Lundhdf846752000-09-03 11:29:49 +00005500 } else {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005501 endinpos = s-starts;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005502 p = PyUnicode_AS_UNICODE(v) + i;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005503 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005504 errors, &errorHandler,
5505 "unicodeescape", "illegal Unicode character",
5506 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005507 &v, &i, &p))
Fredrik Lundhdf846752000-09-03 11:29:49 +00005508 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005509 data = PyUnicode_AS_UNICODE(v);
Fredrik Lundhdf846752000-09-03 11:29:49 +00005510 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00005511 break;
5512
Benjamin Peterson29060642009-01-31 22:14:21 +00005513 /* \N{name} */
Fredrik Lundhccc74732001-02-18 22:13:49 +00005514 case 'N':
5515 message = "malformed \\N character escape";
5516 if (ucnhash_CAPI == NULL) {
5517 /* load the unicode data module */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005518 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
5519 PyUnicodeData_CAPSULE_NAME, 1);
Fredrik Lundhccc74732001-02-18 22:13:49 +00005520 if (ucnhash_CAPI == NULL)
5521 goto ucnhashError;
5522 }
5523 if (*s == '{') {
5524 const char *start = s+1;
5525 /* look for the closing brace */
5526 while (*s != '}' && s < end)
5527 s++;
5528 if (s > start && s < end && *s == '}') {
5529 /* found a name. look it up in the unicode database */
5530 message = "unknown Unicode character name";
5531 s++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005532 if (ucnhash_CAPI->getcode(NULL, start, (int)(s-start-1),
5533 &chr))
Fredrik Lundhccc74732001-02-18 22:13:49 +00005534 goto store;
5535 }
5536 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005537 endinpos = s-starts;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005538 p = PyUnicode_AS_UNICODE(v) + i;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005539 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005540 errors, &errorHandler,
5541 "unicodeescape", message,
5542 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005543 &v, &i, &p))
Fredrik Lundhccc74732001-02-18 22:13:49 +00005544 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005545 data = PyUnicode_AS_UNICODE(v);
Fredrik Lundhccc74732001-02-18 22:13:49 +00005546 break;
5547
5548 default:
Walter Dörwald8c077222002-03-25 11:16:18 +00005549 if (s > end) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005550 assert(kind == PyUnicode_WCHAR_KIND);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005551 message = "\\ at end of string";
5552 s--;
5553 endinpos = s-starts;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005554 p = PyUnicode_AS_UNICODE(v) + i;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005555 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005556 errors, &errorHandler,
5557 "unicodeescape", message,
5558 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005559 &v, &i, &p))
Walter Dörwald8c077222002-03-25 11:16:18 +00005560 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005561 data = PyUnicode_AS_UNICODE(v);
Walter Dörwald8c077222002-03-25 11:16:18 +00005562 }
5563 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005564 WRITE_ASCII_OR_WSTR(kind, data, i++, '\\');
5565 WRITE_ASCII_OR_WSTR(kind, data, i++, (unsigned char)s[-1]);
Walter Dörwald8c077222002-03-25 11:16:18 +00005566 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00005567 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005568 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005569 nextByte:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005570 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005571 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005572 /* Ensure the length prediction worked in case of ASCII strings */
5573 assert(kind == PyUnicode_WCHAR_KIND || i == ascii_length);
5574
Victor Stinnerfe226c02011-10-03 03:52:20 +02005575 if (kind == PyUnicode_WCHAR_KIND)
5576 {
5577 if (PyUnicode_Resize((PyObject**)&v, i) < 0)
5578 goto onError;
Victor Stinnerfe226c02011-10-03 03:52:20 +02005579 }
Walter Dörwaldd4ade082003-08-15 15:00:26 +00005580 Py_XDECREF(errorHandler);
5581 Py_XDECREF(exc);
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02005582 if (_PyUnicode_READY_REPLACE(&v)) {
5583 Py_DECREF(v);
5584 return NULL;
5585 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005586 return (PyObject *)v;
Walter Dörwald8c077222002-03-25 11:16:18 +00005587
Benjamin Peterson29060642009-01-31 22:14:21 +00005588 ucnhashError:
Fredrik Lundh06d12682001-01-24 07:59:11 +00005589 PyErr_SetString(
5590 PyExc_UnicodeError,
5591 "\\N escapes not supported (can't load unicodedata module)"
5592 );
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00005593 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005594 Py_XDECREF(errorHandler);
5595 Py_XDECREF(exc);
Fredrik Lundhf6056062001-01-20 11:15:25 +00005596 return NULL;
5597
Benjamin Peterson29060642009-01-31 22:14:21 +00005598 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00005599 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005600 Py_XDECREF(errorHandler);
5601 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005602 return NULL;
5603}
5604
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005605#undef WRITE_ASCII_OR_WSTR
5606#undef WRITE_WSTR
5607
Guido van Rossumd57fd912000-03-10 22:53:23 +00005608/* Return a Unicode-Escape string version of the Unicode object.
5609
5610 If quotes is true, the string is enclosed in u"" or u'' quotes as
5611 appropriate.
5612
5613*/
5614
Walter Dörwald79e913e2007-05-12 11:08:06 +00005615static const char *hexdigits = "0123456789abcdef";
5616
Alexander Belopolsky40018472011-02-26 01:02:56 +00005617PyObject *
5618PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005619 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005620{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005621 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005622 char *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005623
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005624#ifdef Py_UNICODE_WIDE
5625 const Py_ssize_t expandsize = 10;
5626#else
5627 const Py_ssize_t expandsize = 6;
5628#endif
5629
Thomas Wouters89f507f2006-12-13 04:49:30 +00005630 /* XXX(nnorwitz): rather than over-allocating, it would be
5631 better to choose a different scheme. Perhaps scan the
5632 first N-chars of the string and allocate based on that size.
5633 */
5634 /* Initial allocation is based on the longest-possible unichr
5635 escape.
5636
5637 In wide (UTF-32) builds '\U00xxxxxx' is 10 chars per source
5638 unichr, so in this case it's the longest unichr escape. In
5639 narrow (UTF-16) builds this is five chars per source unichr
5640 since there are two unichrs in the surrogate pair, so in narrow
5641 (UTF-16) builds it's not the longest unichr escape.
5642
5643 In wide or narrow builds '\uxxxx' is 6 chars per source unichr,
5644 so in the narrow (UTF-16) build case it's the longest unichr
5645 escape.
5646 */
5647
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005648 if (size == 0)
5649 return PyBytes_FromStringAndSize(NULL, 0);
5650
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005651 if (size > (PY_SSIZE_T_MAX - 2 - 1) / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005652 return PyErr_NoMemory();
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005653
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005654 repr = PyBytes_FromStringAndSize(NULL,
Benjamin Peterson29060642009-01-31 22:14:21 +00005655 2
5656 + expandsize*size
5657 + 1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005658 if (repr == NULL)
5659 return NULL;
5660
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005661 p = PyBytes_AS_STRING(repr);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005662
Guido van Rossumd57fd912000-03-10 22:53:23 +00005663 while (size-- > 0) {
5664 Py_UNICODE ch = *s++;
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005665
Walter Dörwald79e913e2007-05-12 11:08:06 +00005666 /* Escape backslashes */
5667 if (ch == '\\') {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005668 *p++ = '\\';
5669 *p++ = (char) ch;
Walter Dörwald79e913e2007-05-12 11:08:06 +00005670 continue;
Tim Petersced69f82003-09-16 20:30:58 +00005671 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005672
Guido van Rossum0d42e0c2001-07-20 16:36:21 +00005673#ifdef Py_UNICODE_WIDE
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005674 /* Map 21-bit characters to '\U00xxxxxx' */
5675 else if (ch >= 0x10000) {
5676 *p++ = '\\';
5677 *p++ = 'U';
Walter Dörwald79e913e2007-05-12 11:08:06 +00005678 *p++ = hexdigits[(ch >> 28) & 0x0000000F];
5679 *p++ = hexdigits[(ch >> 24) & 0x0000000F];
5680 *p++ = hexdigits[(ch >> 20) & 0x0000000F];
5681 *p++ = hexdigits[(ch >> 16) & 0x0000000F];
5682 *p++ = hexdigits[(ch >> 12) & 0x0000000F];
5683 *p++ = hexdigits[(ch >> 8) & 0x0000000F];
5684 *p++ = hexdigits[(ch >> 4) & 0x0000000F];
5685 *p++ = hexdigits[ch & 0x0000000F];
Benjamin Peterson29060642009-01-31 22:14:21 +00005686 continue;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005687 }
Thomas Wouters89f507f2006-12-13 04:49:30 +00005688#else
Benjamin Peterson29060642009-01-31 22:14:21 +00005689 /* Map UTF-16 surrogate pairs to '\U00xxxxxx' */
5690 else if (ch >= 0xD800 && ch < 0xDC00) {
5691 Py_UNICODE ch2;
5692 Py_UCS4 ucs;
Tim Petersced69f82003-09-16 20:30:58 +00005693
Benjamin Peterson29060642009-01-31 22:14:21 +00005694 ch2 = *s++;
5695 size--;
Georg Brandl78eef3de2010-08-01 20:51:02 +00005696 if (ch2 >= 0xDC00 && ch2 <= 0xDFFF) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005697 ucs = (((ch & 0x03FF) << 10) | (ch2 & 0x03FF)) + 0x00010000;
5698 *p++ = '\\';
5699 *p++ = 'U';
5700 *p++ = hexdigits[(ucs >> 28) & 0x0000000F];
5701 *p++ = hexdigits[(ucs >> 24) & 0x0000000F];
5702 *p++ = hexdigits[(ucs >> 20) & 0x0000000F];
5703 *p++ = hexdigits[(ucs >> 16) & 0x0000000F];
5704 *p++ = hexdigits[(ucs >> 12) & 0x0000000F];
5705 *p++ = hexdigits[(ucs >> 8) & 0x0000000F];
5706 *p++ = hexdigits[(ucs >> 4) & 0x0000000F];
5707 *p++ = hexdigits[ucs & 0x0000000F];
5708 continue;
5709 }
5710 /* Fall through: isolated surrogates are copied as-is */
5711 s--;
5712 size++;
Benjamin Peterson14339b62009-01-31 16:36:08 +00005713 }
Thomas Wouters89f507f2006-12-13 04:49:30 +00005714#endif
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005715
Guido van Rossumd57fd912000-03-10 22:53:23 +00005716 /* Map 16-bit characters to '\uxxxx' */
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005717 if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005718 *p++ = '\\';
5719 *p++ = 'u';
Walter Dörwald79e913e2007-05-12 11:08:06 +00005720 *p++ = hexdigits[(ch >> 12) & 0x000F];
5721 *p++ = hexdigits[(ch >> 8) & 0x000F];
5722 *p++ = hexdigits[(ch >> 4) & 0x000F];
5723 *p++ = hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00005724 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005725
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005726 /* Map special whitespace to '\t', \n', '\r' */
5727 else if (ch == '\t') {
5728 *p++ = '\\';
5729 *p++ = 't';
5730 }
5731 else if (ch == '\n') {
5732 *p++ = '\\';
5733 *p++ = 'n';
5734 }
5735 else if (ch == '\r') {
5736 *p++ = '\\';
5737 *p++ = 'r';
5738 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005739
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005740 /* Map non-printable US ASCII to '\xhh' */
Marc-André Lemburg11326de2001-11-28 12:56:20 +00005741 else if (ch < ' ' || ch >= 0x7F) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005742 *p++ = '\\';
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005743 *p++ = 'x';
Walter Dörwald79e913e2007-05-12 11:08:06 +00005744 *p++ = hexdigits[(ch >> 4) & 0x000F];
5745 *p++ = hexdigits[ch & 0x000F];
Tim Petersced69f82003-09-16 20:30:58 +00005746 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005747
Guido van Rossumd57fd912000-03-10 22:53:23 +00005748 /* Copy everything else as-is */
5749 else
5750 *p++ = (char) ch;
5751 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005752
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005753 assert(p - PyBytes_AS_STRING(repr) > 0);
5754 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0)
5755 return NULL;
5756 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005757}
5758
Alexander Belopolsky40018472011-02-26 01:02:56 +00005759PyObject *
5760PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005761{
Alexandre Vassalotti9cb6f7f2008-12-27 09:09:15 +00005762 PyObject *s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005763 if (!PyUnicode_Check(unicode)) {
5764 PyErr_BadArgument();
5765 return NULL;
5766 }
Walter Dörwald79e913e2007-05-12 11:08:06 +00005767 s = PyUnicode_EncodeUnicodeEscape(PyUnicode_AS_UNICODE(unicode),
5768 PyUnicode_GET_SIZE(unicode));
Alexandre Vassalotti9cb6f7f2008-12-27 09:09:15 +00005769 return s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005770}
5771
5772/* --- Raw Unicode Escape Codec ------------------------------------------- */
5773
Alexander Belopolsky40018472011-02-26 01:02:56 +00005774PyObject *
5775PyUnicode_DecodeRawUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005776 Py_ssize_t size,
5777 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005778{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005779 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005780 Py_ssize_t startinpos;
5781 Py_ssize_t endinpos;
5782 Py_ssize_t outpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005783 PyUnicodeObject *v;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005784 Py_UNICODE *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005785 const char *end;
5786 const char *bs;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005787 PyObject *errorHandler = NULL;
5788 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00005789
Guido van Rossumd57fd912000-03-10 22:53:23 +00005790 /* Escaped strings will always be longer than the resulting
5791 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005792 length after conversion to the true value. (But decoding error
5793 handler might have to resize the string) */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005794 v = _PyUnicode_New(size);
5795 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005796 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005797 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005798 return (PyObject *)v;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005799 p = PyUnicode_AS_UNICODE(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005800 end = s + size;
5801 while (s < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005802 unsigned char c;
5803 Py_UCS4 x;
5804 int i;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00005805 int count;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005806
Benjamin Peterson29060642009-01-31 22:14:21 +00005807 /* Non-escape characters are interpreted as Unicode ordinals */
5808 if (*s != '\\') {
5809 *p++ = (unsigned char)*s++;
5810 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00005811 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005812 startinpos = s-starts;
5813
5814 /* \u-escapes are only interpreted iff the number of leading
5815 backslashes if odd */
5816 bs = s;
5817 for (;s < end;) {
5818 if (*s != '\\')
5819 break;
5820 *p++ = (unsigned char)*s++;
5821 }
5822 if (((s - bs) & 1) == 0 ||
5823 s >= end ||
5824 (*s != 'u' && *s != 'U')) {
5825 continue;
5826 }
5827 p--;
5828 count = *s=='u' ? 4 : 8;
5829 s++;
5830
5831 /* \uXXXX with 4 hex digits, \Uxxxxxxxx with 8 */
5832 outpos = p-PyUnicode_AS_UNICODE(v);
5833 for (x = 0, i = 0; i < count; ++i, ++s) {
5834 c = (unsigned char)*s;
David Malcolm96960882010-11-05 17:23:41 +00005835 if (!Py_ISXDIGIT(c)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005836 endinpos = s-starts;
5837 if (unicode_decode_call_errorhandler(
5838 errors, &errorHandler,
5839 "rawunicodeescape", "truncated \\uXXXX",
5840 &starts, &end, &startinpos, &endinpos, &exc, &s,
5841 &v, &outpos, &p))
5842 goto onError;
5843 goto nextByte;
5844 }
5845 x = (x<<4) & ~0xF;
5846 if (c >= '0' && c <= '9')
5847 x += c - '0';
5848 else if (c >= 'a' && c <= 'f')
5849 x += 10 + c - 'a';
5850 else
5851 x += 10 + c - 'A';
5852 }
Christian Heimesfe337bf2008-03-23 21:54:12 +00005853 if (x <= 0xffff)
Benjamin Peterson29060642009-01-31 22:14:21 +00005854 /* UCS-2 character */
5855 *p++ = (Py_UNICODE) x;
Christian Heimesfe337bf2008-03-23 21:54:12 +00005856 else if (x <= 0x10ffff) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005857 /* UCS-4 character. Either store directly, or as
5858 surrogate pair. */
Christian Heimesfe337bf2008-03-23 21:54:12 +00005859#ifdef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00005860 *p++ = (Py_UNICODE) x;
Christian Heimesfe337bf2008-03-23 21:54:12 +00005861#else
Benjamin Peterson29060642009-01-31 22:14:21 +00005862 x -= 0x10000L;
5863 *p++ = 0xD800 + (Py_UNICODE) (x >> 10);
5864 *p++ = 0xDC00 + (Py_UNICODE) (x & 0x03FF);
Christian Heimesfe337bf2008-03-23 21:54:12 +00005865#endif
5866 } else {
5867 endinpos = s-starts;
5868 outpos = p-PyUnicode_AS_UNICODE(v);
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00005869 if (unicode_decode_call_errorhandler(
5870 errors, &errorHandler,
5871 "rawunicodeescape", "\\Uxxxxxxxx out of range",
Benjamin Peterson29060642009-01-31 22:14:21 +00005872 &starts, &end, &startinpos, &endinpos, &exc, &s,
5873 &v, &outpos, &p))
5874 goto onError;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00005875 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005876 nextByte:
5877 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005878 }
Victor Stinnerfe226c02011-10-03 03:52:20 +02005879 if (PyUnicode_Resize((PyObject**)&v, p - PyUnicode_AS_UNICODE(v)) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005880 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005881 Py_XDECREF(errorHandler);
5882 Py_XDECREF(exc);
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02005883 if (_PyUnicode_READY_REPLACE(&v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005884 Py_DECREF(v);
5885 return NULL;
5886 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005887 return (PyObject *)v;
Tim Petersced69f82003-09-16 20:30:58 +00005888
Benjamin Peterson29060642009-01-31 22:14:21 +00005889 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00005890 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005891 Py_XDECREF(errorHandler);
5892 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005893 return NULL;
5894}
5895
Alexander Belopolsky40018472011-02-26 01:02:56 +00005896PyObject *
5897PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005898 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005899{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005900 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005901 char *p;
5902 char *q;
5903
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00005904#ifdef Py_UNICODE_WIDE
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005905 const Py_ssize_t expandsize = 10;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00005906#else
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005907 const Py_ssize_t expandsize = 6;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00005908#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00005909
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005910 if (size > PY_SSIZE_T_MAX / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005911 return PyErr_NoMemory();
Benjamin Peterson14339b62009-01-31 16:36:08 +00005912
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005913 repr = PyBytes_FromStringAndSize(NULL, expandsize * size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005914 if (repr == NULL)
5915 return NULL;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00005916 if (size == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005917 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005918
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005919 p = q = PyBytes_AS_STRING(repr);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005920 while (size-- > 0) {
5921 Py_UNICODE ch = *s++;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00005922#ifdef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00005923 /* Map 32-bit characters to '\Uxxxxxxxx' */
5924 if (ch >= 0x10000) {
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00005925 *p++ = '\\';
5926 *p++ = 'U';
Walter Dörwalddb5d33e2007-05-12 11:13:47 +00005927 *p++ = hexdigits[(ch >> 28) & 0xf];
5928 *p++ = hexdigits[(ch >> 24) & 0xf];
5929 *p++ = hexdigits[(ch >> 20) & 0xf];
5930 *p++ = hexdigits[(ch >> 16) & 0xf];
5931 *p++ = hexdigits[(ch >> 12) & 0xf];
5932 *p++ = hexdigits[(ch >> 8) & 0xf];
5933 *p++ = hexdigits[(ch >> 4) & 0xf];
5934 *p++ = hexdigits[ch & 15];
Tim Petersced69f82003-09-16 20:30:58 +00005935 }
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00005936 else
Christian Heimesfe337bf2008-03-23 21:54:12 +00005937#else
Benjamin Peterson29060642009-01-31 22:14:21 +00005938 /* Map UTF-16 surrogate pairs to '\U00xxxxxx' */
5939 if (ch >= 0xD800 && ch < 0xDC00) {
5940 Py_UNICODE ch2;
5941 Py_UCS4 ucs;
Christian Heimesfe337bf2008-03-23 21:54:12 +00005942
Benjamin Peterson29060642009-01-31 22:14:21 +00005943 ch2 = *s++;
5944 size--;
Georg Brandl78eef3de2010-08-01 20:51:02 +00005945 if (ch2 >= 0xDC00 && ch2 <= 0xDFFF) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005946 ucs = (((ch & 0x03FF) << 10) | (ch2 & 0x03FF)) + 0x00010000;
5947 *p++ = '\\';
5948 *p++ = 'U';
5949 *p++ = hexdigits[(ucs >> 28) & 0xf];
5950 *p++ = hexdigits[(ucs >> 24) & 0xf];
5951 *p++ = hexdigits[(ucs >> 20) & 0xf];
5952 *p++ = hexdigits[(ucs >> 16) & 0xf];
5953 *p++ = hexdigits[(ucs >> 12) & 0xf];
5954 *p++ = hexdigits[(ucs >> 8) & 0xf];
5955 *p++ = hexdigits[(ucs >> 4) & 0xf];
5956 *p++ = hexdigits[ucs & 0xf];
5957 continue;
5958 }
5959 /* Fall through: isolated surrogates are copied as-is */
5960 s--;
5961 size++;
5962 }
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00005963#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00005964 /* Map 16-bit characters to '\uxxxx' */
5965 if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005966 *p++ = '\\';
5967 *p++ = 'u';
Walter Dörwalddb5d33e2007-05-12 11:13:47 +00005968 *p++ = hexdigits[(ch >> 12) & 0xf];
5969 *p++ = hexdigits[(ch >> 8) & 0xf];
5970 *p++ = hexdigits[(ch >> 4) & 0xf];
5971 *p++ = hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00005972 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005973 /* Copy everything else as-is */
5974 else
Guido van Rossumd57fd912000-03-10 22:53:23 +00005975 *p++ = (char) ch;
5976 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005977 size = p - q;
5978
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005979 assert(size > 0);
5980 if (_PyBytes_Resize(&repr, size) < 0)
5981 return NULL;
5982 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005983}
5984
Alexander Belopolsky40018472011-02-26 01:02:56 +00005985PyObject *
5986PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005987{
Alexandre Vassalotti9cb6f7f2008-12-27 09:09:15 +00005988 PyObject *s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005989 if (!PyUnicode_Check(unicode)) {
Walter Dörwald711005d2007-05-12 12:03:26 +00005990 PyErr_BadArgument();
5991 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005992 }
Walter Dörwald711005d2007-05-12 12:03:26 +00005993 s = PyUnicode_EncodeRawUnicodeEscape(PyUnicode_AS_UNICODE(unicode),
5994 PyUnicode_GET_SIZE(unicode));
5995
Alexandre Vassalotti9cb6f7f2008-12-27 09:09:15 +00005996 return s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005997}
5998
Walter Dörwalda47d1c02005-08-30 10:23:14 +00005999/* --- Unicode Internal Codec ------------------------------------------- */
6000
Alexander Belopolsky40018472011-02-26 01:02:56 +00006001PyObject *
6002_PyUnicode_DecodeUnicodeInternal(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006003 Py_ssize_t size,
6004 const char *errors)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006005{
6006 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006007 Py_ssize_t startinpos;
6008 Py_ssize_t endinpos;
6009 Py_ssize_t outpos;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006010 PyUnicodeObject *v;
6011 Py_UNICODE *p;
6012 const char *end;
6013 const char *reason;
6014 PyObject *errorHandler = NULL;
6015 PyObject *exc = NULL;
6016
Neal Norwitzd43069c2006-01-08 01:12:10 +00006017#ifdef Py_UNICODE_WIDE
6018 Py_UNICODE unimax = PyUnicode_GetMax();
6019#endif
6020
Thomas Wouters89f507f2006-12-13 04:49:30 +00006021 /* XXX overflow detection missing */
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006022 v = _PyUnicode_New((size+Py_UNICODE_SIZE-1)/ Py_UNICODE_SIZE);
6023 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006024 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006025 /* Intentionally PyUnicode_GET_SIZE instead of PyUnicode_GET_LENGTH
6026 as string was created with the old API. */
6027 if (PyUnicode_GET_SIZE(v) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006028 return (PyObject *)v;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006029 p = PyUnicode_AS_UNICODE(v);
6030 end = s + size;
6031
6032 while (s < end) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00006033 memcpy(p, s, sizeof(Py_UNICODE));
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006034 /* We have to sanity check the raw data, otherwise doom looms for
6035 some malformed UCS-4 data. */
6036 if (
Benjamin Peterson29060642009-01-31 22:14:21 +00006037#ifdef Py_UNICODE_WIDE
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006038 *p > unimax || *p < 0 ||
Benjamin Peterson29060642009-01-31 22:14:21 +00006039#endif
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006040 end-s < Py_UNICODE_SIZE
6041 )
Benjamin Peterson29060642009-01-31 22:14:21 +00006042 {
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006043 startinpos = s - starts;
6044 if (end-s < Py_UNICODE_SIZE) {
6045 endinpos = end-starts;
6046 reason = "truncated input";
6047 }
6048 else {
6049 endinpos = s - starts + Py_UNICODE_SIZE;
6050 reason = "illegal code point (> 0x10FFFF)";
6051 }
6052 outpos = p - PyUnicode_AS_UNICODE(v);
6053 if (unicode_decode_call_errorhandler(
6054 errors, &errorHandler,
6055 "unicode_internal", reason,
Walter Dörwalde78178e2007-07-30 13:31:40 +00006056 &starts, &end, &startinpos, &endinpos, &exc, &s,
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00006057 &v, &outpos, &p)) {
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006058 goto onError;
6059 }
6060 }
6061 else {
6062 p++;
6063 s += Py_UNICODE_SIZE;
6064 }
6065 }
6066
Victor Stinnerfe226c02011-10-03 03:52:20 +02006067 if (PyUnicode_Resize((PyObject**)&v, p - PyUnicode_AS_UNICODE(v)) < 0)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006068 goto onError;
6069 Py_XDECREF(errorHandler);
6070 Py_XDECREF(exc);
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02006071 if (_PyUnicode_READY_REPLACE(&v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006072 Py_DECREF(v);
6073 return NULL;
6074 }
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006075 return (PyObject *)v;
6076
Benjamin Peterson29060642009-01-31 22:14:21 +00006077 onError:
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006078 Py_XDECREF(v);
6079 Py_XDECREF(errorHandler);
6080 Py_XDECREF(exc);
6081 return NULL;
6082}
6083
Guido van Rossumd57fd912000-03-10 22:53:23 +00006084/* --- Latin-1 Codec ------------------------------------------------------ */
6085
Alexander Belopolsky40018472011-02-26 01:02:56 +00006086PyObject *
6087PyUnicode_DecodeLatin1(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006088 Py_ssize_t size,
6089 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006090{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006091 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Victor Stinnere57b1c02011-09-28 22:20:48 +02006092 return _PyUnicode_FromUCS1((unsigned char*)s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006093}
6094
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006095/* create or adjust a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006096static void
6097make_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006098 const char *encoding,
6099 const Py_UNICODE *unicode, Py_ssize_t size,
6100 Py_ssize_t startpos, Py_ssize_t endpos,
6101 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006102{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006103 if (*exceptionObject == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006104 *exceptionObject = PyUnicodeEncodeError_Create(
6105 encoding, unicode, size, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006106 }
6107 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006108 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
6109 goto onError;
6110 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
6111 goto onError;
6112 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
6113 goto onError;
6114 return;
6115 onError:
6116 Py_DECREF(*exceptionObject);
6117 *exceptionObject = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006118 }
6119}
6120
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006121/* raises a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006122static void
6123raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006124 const char *encoding,
6125 const Py_UNICODE *unicode, Py_ssize_t size,
6126 Py_ssize_t startpos, Py_ssize_t endpos,
6127 const char *reason)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006128{
6129 make_encode_exception(exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00006130 encoding, unicode, size, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006131 if (*exceptionObject != NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006132 PyCodec_StrictErrors(*exceptionObject);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006133}
6134
6135/* error handling callback helper:
6136 build arguments, call the callback and check the arguments,
6137 put the result into newpos and return the replacement string, which
6138 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006139static PyObject *
6140unicode_encode_call_errorhandler(const char *errors,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006141 PyObject **errorHandler,
6142 const char *encoding, const char *reason,
6143 const Py_UNICODE *unicode, Py_ssize_t size, PyObject **exceptionObject,
6144 Py_ssize_t startpos, Py_ssize_t endpos,
6145 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006146{
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006147 static char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006148
6149 PyObject *restuple;
6150 PyObject *resunicode;
6151
6152 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006153 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006154 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006155 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006156 }
6157
6158 make_encode_exception(exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00006159 encoding, unicode, size, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006160 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006161 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006162
6163 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00006164 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006165 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006166 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006167 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006168 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00006169 Py_DECREF(restuple);
6170 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006171 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006172 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00006173 &resunicode, newpos)) {
6174 Py_DECREF(restuple);
6175 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006176 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006177 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
6178 PyErr_SetString(PyExc_TypeError, &argparse[3]);
6179 Py_DECREF(restuple);
6180 return NULL;
6181 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006182 if (*newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006183 *newpos = size+*newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00006184 if (*newpos<0 || *newpos>size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006185 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
6186 Py_DECREF(restuple);
6187 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00006188 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006189 Py_INCREF(resunicode);
6190 Py_DECREF(restuple);
6191 return resunicode;
6192}
6193
Alexander Belopolsky40018472011-02-26 01:02:56 +00006194static PyObject *
6195unicode_encode_ucs1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006196 Py_ssize_t size,
6197 const char *errors,
6198 int limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006199{
6200 /* output object */
6201 PyObject *res;
6202 /* pointers to the beginning and end+1 of input */
6203 const Py_UNICODE *startp = p;
6204 const Py_UNICODE *endp = p + size;
6205 /* pointer to the beginning of the unencodable characters */
6206 /* const Py_UNICODE *badp = NULL; */
6207 /* pointer into the output */
6208 char *str;
6209 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00006210 Py_ssize_t ressize;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006211 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
6212 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006213 PyObject *errorHandler = NULL;
6214 PyObject *exc = NULL;
6215 /* the following variable is used for caching string comparisons
6216 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
6217 int known_errorHandler = -1;
6218
6219 /* allocate enough for a simple encoding without
6220 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00006221 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00006222 return PyBytes_FromStringAndSize(NULL, 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006223 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006224 if (res == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00006225 return NULL;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006226 str = PyBytes_AS_STRING(res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006227 ressize = size;
6228
6229 while (p<endp) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006230 Py_UNICODE c = *p;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006231
Benjamin Peterson29060642009-01-31 22:14:21 +00006232 /* can we encode this? */
6233 if (c<limit) {
6234 /* no overflow check, because we know that the space is enough */
6235 *str++ = (char)c;
6236 ++p;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006237 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006238 else {
6239 Py_ssize_t unicodepos = p-startp;
6240 Py_ssize_t requiredsize;
6241 PyObject *repunicode;
6242 Py_ssize_t repsize;
6243 Py_ssize_t newpos;
6244 Py_ssize_t respos;
6245 Py_UNICODE *uni2;
6246 /* startpos for collecting unencodable chars */
6247 const Py_UNICODE *collstart = p;
6248 const Py_UNICODE *collend = p;
6249 /* find all unecodable characters */
6250 while ((collend < endp) && ((*collend)>=limit))
6251 ++collend;
6252 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
6253 if (known_errorHandler==-1) {
6254 if ((errors==NULL) || (!strcmp(errors, "strict")))
6255 known_errorHandler = 1;
6256 else if (!strcmp(errors, "replace"))
6257 known_errorHandler = 2;
6258 else if (!strcmp(errors, "ignore"))
6259 known_errorHandler = 3;
6260 else if (!strcmp(errors, "xmlcharrefreplace"))
6261 known_errorHandler = 4;
6262 else
6263 known_errorHandler = 0;
6264 }
6265 switch (known_errorHandler) {
6266 case 1: /* strict */
6267 raise_encode_exception(&exc, encoding, startp, size, collstart-startp, collend-startp, reason);
6268 goto onError;
6269 case 2: /* replace */
6270 while (collstart++<collend)
6271 *str++ = '?'; /* fall through */
6272 case 3: /* ignore */
6273 p = collend;
6274 break;
6275 case 4: /* xmlcharrefreplace */
6276 respos = str - PyBytes_AS_STRING(res);
6277 /* determine replacement size (temporarily (mis)uses p) */
6278 for (p = collstart, repsize = 0; p < collend; ++p) {
6279 if (*p<10)
6280 repsize += 2+1+1;
6281 else if (*p<100)
6282 repsize += 2+2+1;
6283 else if (*p<1000)
6284 repsize += 2+3+1;
6285 else if (*p<10000)
6286 repsize += 2+4+1;
Hye-Shik Chang40e95092003-12-22 01:31:13 +00006287#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00006288 else
6289 repsize += 2+5+1;
Hye-Shik Chang40e95092003-12-22 01:31:13 +00006290#else
Benjamin Peterson29060642009-01-31 22:14:21 +00006291 else if (*p<100000)
6292 repsize += 2+5+1;
6293 else if (*p<1000000)
6294 repsize += 2+6+1;
6295 else
6296 repsize += 2+7+1;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00006297#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00006298 }
6299 requiredsize = respos+repsize+(endp-collend);
6300 if (requiredsize > ressize) {
6301 if (requiredsize<2*ressize)
6302 requiredsize = 2*ressize;
6303 if (_PyBytes_Resize(&res, requiredsize))
6304 goto onError;
6305 str = PyBytes_AS_STRING(res) + respos;
6306 ressize = requiredsize;
6307 }
6308 /* generate replacement (temporarily (mis)uses p) */
6309 for (p = collstart; p < collend; ++p) {
6310 str += sprintf(str, "&#%d;", (int)*p);
6311 }
6312 p = collend;
6313 break;
6314 default:
6315 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
6316 encoding, reason, startp, size, &exc,
6317 collstart-startp, collend-startp, &newpos);
6318 if (repunicode == NULL)
6319 goto onError;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006320 if (PyBytes_Check(repunicode)) {
6321 /* Directly copy bytes result to output. */
6322 repsize = PyBytes_Size(repunicode);
6323 if (repsize > 1) {
6324 /* Make room for all additional bytes. */
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006325 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006326 if (_PyBytes_Resize(&res, ressize+repsize-1)) {
6327 Py_DECREF(repunicode);
6328 goto onError;
6329 }
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006330 str = PyBytes_AS_STRING(res) + respos;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006331 ressize += repsize-1;
6332 }
6333 memcpy(str, PyBytes_AsString(repunicode), repsize);
6334 str += repsize;
6335 p = startp + newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006336 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006337 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006338 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006339 /* need more space? (at least enough for what we
6340 have+the replacement+the rest of the string, so
6341 we won't have to check space for encodable characters) */
6342 respos = str - PyBytes_AS_STRING(res);
6343 repsize = PyUnicode_GET_SIZE(repunicode);
6344 requiredsize = respos+repsize+(endp-collend);
6345 if (requiredsize > ressize) {
6346 if (requiredsize<2*ressize)
6347 requiredsize = 2*ressize;
6348 if (_PyBytes_Resize(&res, requiredsize)) {
6349 Py_DECREF(repunicode);
6350 goto onError;
6351 }
6352 str = PyBytes_AS_STRING(res) + respos;
6353 ressize = requiredsize;
6354 }
6355 /* check if there is anything unencodable in the replacement
6356 and copy it to the output */
6357 for (uni2 = PyUnicode_AS_UNICODE(repunicode);repsize-->0; ++uni2, ++str) {
6358 c = *uni2;
6359 if (c >= limit) {
6360 raise_encode_exception(&exc, encoding, startp, size,
6361 unicodepos, unicodepos+1, reason);
6362 Py_DECREF(repunicode);
6363 goto onError;
6364 }
6365 *str = (char)c;
6366 }
6367 p = startp + newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006368 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006369 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00006370 }
6371 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006372 /* Resize if we allocated to much */
6373 size = str - PyBytes_AS_STRING(res);
6374 if (size < ressize) { /* If this falls res will be NULL */
Alexandre Vassalottibad1b922008-12-27 09:49:09 +00006375 assert(size >= 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006376 if (_PyBytes_Resize(&res, size) < 0)
6377 goto onError;
6378 }
6379
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006380 Py_XDECREF(errorHandler);
6381 Py_XDECREF(exc);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006382 return res;
6383
6384 onError:
6385 Py_XDECREF(res);
6386 Py_XDECREF(errorHandler);
6387 Py_XDECREF(exc);
6388 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006389}
6390
Alexander Belopolsky40018472011-02-26 01:02:56 +00006391PyObject *
6392PyUnicode_EncodeLatin1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006393 Py_ssize_t size,
6394 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006395{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006396 return unicode_encode_ucs1(p, size, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006397}
6398
Alexander Belopolsky40018472011-02-26 01:02:56 +00006399PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006400_PyUnicode_AsLatin1String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006401{
6402 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006403 PyErr_BadArgument();
6404 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006405 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006406 if (PyUnicode_READY(unicode) == -1)
6407 return NULL;
6408 /* Fast path: if it is a one-byte string, construct
6409 bytes object directly. */
6410 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND)
6411 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6412 PyUnicode_GET_LENGTH(unicode));
6413 /* Non-Latin-1 characters present. Defer to above function to
6414 raise the exception. */
Guido van Rossumd57fd912000-03-10 22:53:23 +00006415 return PyUnicode_EncodeLatin1(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00006416 PyUnicode_GET_SIZE(unicode),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006417 errors);
6418}
6419
6420PyObject*
6421PyUnicode_AsLatin1String(PyObject *unicode)
6422{
6423 return _PyUnicode_AsLatin1String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006424}
6425
6426/* --- 7-bit ASCII Codec -------------------------------------------------- */
6427
Alexander Belopolsky40018472011-02-26 01:02:56 +00006428PyObject *
6429PyUnicode_DecodeASCII(const char *s,
6430 Py_ssize_t size,
6431 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006432{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006433 const char *starts = s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006434 PyUnicodeObject *v;
6435 Py_UNICODE *p;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006436 Py_ssize_t startinpos;
6437 Py_ssize_t endinpos;
6438 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006439 const char *e;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006440 unsigned char* d;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006441 PyObject *errorHandler = NULL;
6442 PyObject *exc = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006443 Py_ssize_t i;
Tim Petersced69f82003-09-16 20:30:58 +00006444
Guido van Rossumd57fd912000-03-10 22:53:23 +00006445 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006446 if (size == 1 && *(unsigned char*)s < 128)
6447 return PyUnicode_FromOrdinal(*(unsigned char*)s);
6448
6449 /* Fast path. Assume the input actually *is* ASCII, and allocate
6450 a single-block Unicode object with that assumption. If there is
6451 an error, drop the object and start over. */
6452 v = (PyUnicodeObject*)PyUnicode_New(size, 127);
6453 if (v == NULL)
6454 goto onError;
6455 d = PyUnicode_1BYTE_DATA(v);
6456 for (i = 0; i < size; i++) {
6457 unsigned char ch = ((unsigned char*)s)[i];
6458 if (ch < 128)
6459 d[i] = ch;
6460 else
6461 break;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00006462 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006463 if (i == size)
6464 return (PyObject*)v;
6465 Py_DECREF(v); /* start over */
Tim Petersced69f82003-09-16 20:30:58 +00006466
Guido van Rossumd57fd912000-03-10 22:53:23 +00006467 v = _PyUnicode_New(size);
6468 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006469 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006470 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006471 return (PyObject *)v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006472 p = PyUnicode_AS_UNICODE(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006473 e = s + size;
6474 while (s < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006475 register unsigned char c = (unsigned char)*s;
6476 if (c < 128) {
6477 *p++ = c;
6478 ++s;
6479 }
6480 else {
6481 startinpos = s-starts;
6482 endinpos = startinpos + 1;
6483 outpos = p - (Py_UNICODE *)PyUnicode_AS_UNICODE(v);
6484 if (unicode_decode_call_errorhandler(
6485 errors, &errorHandler,
6486 "ascii", "ordinal not in range(128)",
6487 &starts, &e, &startinpos, &endinpos, &exc, &s,
6488 &v, &outpos, &p))
6489 goto onError;
6490 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006491 }
Martin v. Löwis5b222132007-06-10 09:51:05 +00006492 if (p - PyUnicode_AS_UNICODE(v) < PyUnicode_GET_SIZE(v))
Victor Stinnerfe226c02011-10-03 03:52:20 +02006493 if (PyUnicode_Resize((PyObject**)&v, p - PyUnicode_AS_UNICODE(v)) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006494 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006495 Py_XDECREF(errorHandler);
6496 Py_XDECREF(exc);
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02006497 if (_PyUnicode_READY_REPLACE(&v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006498 Py_DECREF(v);
6499 return NULL;
6500 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006501 return (PyObject *)v;
Tim Petersced69f82003-09-16 20:30:58 +00006502
Benjamin Peterson29060642009-01-31 22:14:21 +00006503 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00006504 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006505 Py_XDECREF(errorHandler);
6506 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006507 return NULL;
6508}
6509
Alexander Belopolsky40018472011-02-26 01:02:56 +00006510PyObject *
6511PyUnicode_EncodeASCII(const Py_UNICODE *p,
6512 Py_ssize_t size,
6513 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006514{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006515 return unicode_encode_ucs1(p, size, errors, 128);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006516}
6517
Alexander Belopolsky40018472011-02-26 01:02:56 +00006518PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006519_PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006520{
6521 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006522 PyErr_BadArgument();
6523 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006524 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006525 if (PyUnicode_READY(unicode) == -1)
6526 return NULL;
6527 /* Fast path: if it is an ASCII-only string, construct bytes object
6528 directly. Else defer to above function to raise the exception. */
6529 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
6530 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6531 PyUnicode_GET_LENGTH(unicode));
Guido van Rossumd57fd912000-03-10 22:53:23 +00006532 return PyUnicode_EncodeASCII(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00006533 PyUnicode_GET_SIZE(unicode),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006534 errors);
6535}
6536
6537PyObject *
6538PyUnicode_AsASCIIString(PyObject *unicode)
6539{
6540 return _PyUnicode_AsASCIIString(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006541}
6542
Victor Stinner99b95382011-07-04 14:23:54 +02006543#ifdef HAVE_MBCS
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006544
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006545/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006546
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00006547#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006548#define NEED_RETRY
6549#endif
6550
6551/* XXX This code is limited to "true" double-byte encodings, as
6552 a) it assumes an incomplete character consists of a single byte, and
6553 b) IsDBCSLeadByte (probably) does not work for non-DBCS multi-byte
Benjamin Peterson29060642009-01-31 22:14:21 +00006554 encodings, see IsDBCSLeadByteEx documentation. */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006555
Alexander Belopolsky40018472011-02-26 01:02:56 +00006556static int
6557is_dbcs_lead_byte(const char *s, int offset)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006558{
6559 const char *curr = s + offset;
6560
6561 if (IsDBCSLeadByte(*curr)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006562 const char *prev = CharPrev(s, curr);
6563 return (prev == curr) || !IsDBCSLeadByte(*prev) || (curr - prev == 2);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006564 }
6565 return 0;
6566}
6567
6568/*
6569 * Decode MBCS string into unicode object. If 'final' is set, converts
6570 * trailing lead-byte too. Returns consumed size if succeed, -1 otherwise.
6571 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006572static int
6573decode_mbcs(PyUnicodeObject **v,
6574 const char *s, /* MBCS string */
6575 int size, /* sizeof MBCS string */
6576 int final,
6577 const char *errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006578{
6579 Py_UNICODE *p;
Victor Stinner554f3f02010-06-16 23:33:54 +00006580 Py_ssize_t n;
6581 DWORD usize;
6582 DWORD flags;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006583
6584 assert(size >= 0);
6585
Victor Stinner554f3f02010-06-16 23:33:54 +00006586 /* check and handle 'errors' arg */
6587 if (errors==NULL || strcmp(errors, "strict")==0)
6588 flags = MB_ERR_INVALID_CHARS;
6589 else if (strcmp(errors, "ignore")==0)
6590 flags = 0;
6591 else {
6592 PyErr_Format(PyExc_ValueError,
6593 "mbcs encoding does not support errors='%s'",
6594 errors);
6595 return -1;
6596 }
6597
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006598 /* Skip trailing lead-byte unless 'final' is set */
6599 if (!final && size >= 1 && is_dbcs_lead_byte(s, size - 1))
Benjamin Peterson29060642009-01-31 22:14:21 +00006600 --size;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006601
6602 /* First get the size of the result */
6603 if (size > 0) {
Victor Stinner554f3f02010-06-16 23:33:54 +00006604 usize = MultiByteToWideChar(CP_ACP, flags, s, size, NULL, 0);
6605 if (usize==0)
6606 goto mbcs_decode_error;
6607 } else
6608 usize = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006609
6610 if (*v == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006611 /* Create unicode object */
6612 *v = _PyUnicode_New(usize);
6613 if (*v == NULL)
6614 return -1;
Victor Stinner554f3f02010-06-16 23:33:54 +00006615 n = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006616 }
6617 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006618 /* Extend unicode object */
6619 n = PyUnicode_GET_SIZE(*v);
Victor Stinner2fd82272011-10-03 04:06:05 +02006620 if (PyUnicode_Resize((PyObject**)v, n + usize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006621 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006622 }
6623
6624 /* Do the conversion */
Victor Stinner554f3f02010-06-16 23:33:54 +00006625 if (usize > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006626 p = PyUnicode_AS_UNICODE(*v) + n;
Victor Stinner554f3f02010-06-16 23:33:54 +00006627 if (0 == MultiByteToWideChar(CP_ACP, flags, s, size, p, usize)) {
6628 goto mbcs_decode_error;
Benjamin Peterson29060642009-01-31 22:14:21 +00006629 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006630 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006631 return size;
Victor Stinner554f3f02010-06-16 23:33:54 +00006632
6633mbcs_decode_error:
6634 /* If the last error was ERROR_NO_UNICODE_TRANSLATION, then
6635 we raise a UnicodeDecodeError - else it is a 'generic'
6636 windows error
6637 */
6638 if (GetLastError()==ERROR_NO_UNICODE_TRANSLATION) {
6639 /* Ideally, we should get reason from FormatMessage - this
6640 is the Windows 2000 English version of the message
6641 */
6642 PyObject *exc = NULL;
6643 const char *reason = "No mapping for the Unicode character exists "
6644 "in the target multi-byte code page.";
6645 make_decode_exception(&exc, "mbcs", s, size, 0, 0, reason);
6646 if (exc != NULL) {
6647 PyCodec_StrictErrors(exc);
6648 Py_DECREF(exc);
6649 }
6650 } else {
6651 PyErr_SetFromWindowsErrWithFilename(0, NULL);
6652 }
6653 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006654}
6655
Alexander Belopolsky40018472011-02-26 01:02:56 +00006656PyObject *
6657PyUnicode_DecodeMBCSStateful(const char *s,
6658 Py_ssize_t size,
6659 const char *errors,
6660 Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006661{
6662 PyUnicodeObject *v = NULL;
6663 int done;
6664
6665 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00006666 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006667
6668#ifdef NEED_RETRY
6669 retry:
6670 if (size > INT_MAX)
Victor Stinner554f3f02010-06-16 23:33:54 +00006671 done = decode_mbcs(&v, s, INT_MAX, 0, errors);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006672 else
6673#endif
Victor Stinner554f3f02010-06-16 23:33:54 +00006674 done = decode_mbcs(&v, s, (int)size, !consumed, errors);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006675
6676 if (done < 0) {
6677 Py_XDECREF(v);
Benjamin Peterson29060642009-01-31 22:14:21 +00006678 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006679 }
6680
6681 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00006682 *consumed += done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006683
6684#ifdef NEED_RETRY
6685 if (size > INT_MAX) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006686 s += done;
6687 size -= done;
6688 goto retry;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006689 }
6690#endif
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02006691 if (_PyUnicode_READY_REPLACE(&v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006692 Py_DECREF(v);
6693 return NULL;
6694 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006695 return (PyObject *)v;
6696}
6697
Alexander Belopolsky40018472011-02-26 01:02:56 +00006698PyObject *
6699PyUnicode_DecodeMBCS(const char *s,
6700 Py_ssize_t size,
6701 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006702{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006703 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
6704}
6705
6706/*
6707 * Convert unicode into string object (MBCS).
6708 * Returns 0 if succeed, -1 otherwise.
6709 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006710static int
6711encode_mbcs(PyObject **repr,
6712 const Py_UNICODE *p, /* unicode */
6713 int size, /* size of unicode */
6714 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006715{
Victor Stinner554f3f02010-06-16 23:33:54 +00006716 BOOL usedDefaultChar = FALSE;
6717 BOOL *pusedDefaultChar;
6718 int mbcssize;
6719 Py_ssize_t n;
6720 PyObject *exc = NULL;
6721 DWORD flags;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006722
6723 assert(size >= 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006724
Victor Stinner554f3f02010-06-16 23:33:54 +00006725 /* check and handle 'errors' arg */
6726 if (errors==NULL || strcmp(errors, "strict")==0) {
6727 flags = WC_NO_BEST_FIT_CHARS;
6728 pusedDefaultChar = &usedDefaultChar;
6729 } else if (strcmp(errors, "replace")==0) {
6730 flags = 0;
6731 pusedDefaultChar = NULL;
6732 } else {
6733 PyErr_Format(PyExc_ValueError,
6734 "mbcs encoding does not support errors='%s'",
6735 errors);
6736 return -1;
6737 }
6738
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006739 /* First get the size of the result */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006740 if (size > 0) {
Victor Stinner554f3f02010-06-16 23:33:54 +00006741 mbcssize = WideCharToMultiByte(CP_ACP, flags, p, size, NULL, 0,
6742 NULL, pusedDefaultChar);
Benjamin Peterson29060642009-01-31 22:14:21 +00006743 if (mbcssize == 0) {
6744 PyErr_SetFromWindowsErrWithFilename(0, NULL);
6745 return -1;
6746 }
Victor Stinner554f3f02010-06-16 23:33:54 +00006747 /* If we used a default char, then we failed! */
6748 if (pusedDefaultChar && *pusedDefaultChar)
6749 goto mbcs_encode_error;
6750 } else {
6751 mbcssize = 0;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006752 }
6753
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006754 if (*repr == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006755 /* Create string object */
6756 *repr = PyBytes_FromStringAndSize(NULL, mbcssize);
6757 if (*repr == NULL)
6758 return -1;
Victor Stinner554f3f02010-06-16 23:33:54 +00006759 n = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006760 }
6761 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006762 /* Extend string object */
6763 n = PyBytes_Size(*repr);
6764 if (_PyBytes_Resize(repr, n + mbcssize) < 0)
6765 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006766 }
6767
6768 /* Do the conversion */
6769 if (size > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006770 char *s = PyBytes_AS_STRING(*repr) + n;
Victor Stinner554f3f02010-06-16 23:33:54 +00006771 if (0 == WideCharToMultiByte(CP_ACP, flags, p, size, s, mbcssize,
6772 NULL, pusedDefaultChar)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006773 PyErr_SetFromWindowsErrWithFilename(0, NULL);
6774 return -1;
6775 }
Victor Stinner554f3f02010-06-16 23:33:54 +00006776 if (pusedDefaultChar && *pusedDefaultChar)
6777 goto mbcs_encode_error;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006778 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006779 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00006780
6781mbcs_encode_error:
6782 raise_encode_exception(&exc, "mbcs", p, size, 0, 0, "invalid character");
6783 Py_XDECREF(exc);
6784 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006785}
6786
Alexander Belopolsky40018472011-02-26 01:02:56 +00006787PyObject *
6788PyUnicode_EncodeMBCS(const Py_UNICODE *p,
6789 Py_ssize_t size,
6790 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006791{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006792 PyObject *repr = NULL;
6793 int ret;
Guido van Rossum03e29f12000-05-04 15:52:20 +00006794
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006795#ifdef NEED_RETRY
Benjamin Peterson29060642009-01-31 22:14:21 +00006796 retry:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006797 if (size > INT_MAX)
Victor Stinner554f3f02010-06-16 23:33:54 +00006798 ret = encode_mbcs(&repr, p, INT_MAX, errors);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006799 else
6800#endif
Victor Stinner554f3f02010-06-16 23:33:54 +00006801 ret = encode_mbcs(&repr, p, (int)size, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006802
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006803 if (ret < 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006804 Py_XDECREF(repr);
6805 return NULL;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006806 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006807
6808#ifdef NEED_RETRY
6809 if (size > INT_MAX) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006810 p += INT_MAX;
6811 size -= INT_MAX;
6812 goto retry;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006813 }
6814#endif
6815
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006816 return repr;
6817}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006818
Alexander Belopolsky40018472011-02-26 01:02:56 +00006819PyObject *
6820PyUnicode_AsMBCSString(PyObject *unicode)
Mark Hammond0ccda1e2003-07-01 00:13:27 +00006821{
6822 if (!PyUnicode_Check(unicode)) {
6823 PyErr_BadArgument();
6824 return NULL;
6825 }
6826 return PyUnicode_EncodeMBCS(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00006827 PyUnicode_GET_SIZE(unicode),
6828 NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00006829}
6830
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006831#undef NEED_RETRY
6832
Victor Stinner99b95382011-07-04 14:23:54 +02006833#endif /* HAVE_MBCS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006834
Guido van Rossumd57fd912000-03-10 22:53:23 +00006835/* --- Character Mapping Codec -------------------------------------------- */
6836
Alexander Belopolsky40018472011-02-26 01:02:56 +00006837PyObject *
6838PyUnicode_DecodeCharmap(const char *s,
6839 Py_ssize_t size,
6840 PyObject *mapping,
6841 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006842{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006843 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006844 Py_ssize_t startinpos;
6845 Py_ssize_t endinpos;
6846 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006847 const char *e;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006848 PyUnicodeObject *v;
6849 Py_UNICODE *p;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006850 Py_ssize_t extrachars = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006851 PyObject *errorHandler = NULL;
6852 PyObject *exc = NULL;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00006853 Py_UNICODE *mapstring = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006854 Py_ssize_t maplen = 0;
Tim Petersced69f82003-09-16 20:30:58 +00006855
Guido van Rossumd57fd912000-03-10 22:53:23 +00006856 /* Default to Latin-1 */
6857 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006858 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006859
6860 v = _PyUnicode_New(size);
6861 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006862 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006863 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006864 return (PyObject *)v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006865 p = PyUnicode_AS_UNICODE(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006866 e = s + size;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00006867 if (PyUnicode_CheckExact(mapping)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006868 mapstring = PyUnicode_AS_UNICODE(mapping);
6869 maplen = PyUnicode_GET_SIZE(mapping);
6870 while (s < e) {
6871 unsigned char ch = *s;
6872 Py_UNICODE x = 0xfffe; /* illegal value */
Guido van Rossumd57fd912000-03-10 22:53:23 +00006873
Benjamin Peterson29060642009-01-31 22:14:21 +00006874 if (ch < maplen)
6875 x = mapstring[ch];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006876
Benjamin Peterson29060642009-01-31 22:14:21 +00006877 if (x == 0xfffe) {
6878 /* undefined mapping */
6879 outpos = p-PyUnicode_AS_UNICODE(v);
6880 startinpos = s-starts;
6881 endinpos = startinpos+1;
6882 if (unicode_decode_call_errorhandler(
6883 errors, &errorHandler,
6884 "charmap", "character maps to <undefined>",
6885 &starts, &e, &startinpos, &endinpos, &exc, &s,
6886 &v, &outpos, &p)) {
6887 goto onError;
6888 }
6889 continue;
6890 }
6891 *p++ = x;
6892 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006893 }
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00006894 }
6895 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006896 while (s < e) {
6897 unsigned char ch = *s;
6898 PyObject *w, *x;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00006899
Benjamin Peterson29060642009-01-31 22:14:21 +00006900 /* Get mapping (char ordinal -> integer, Unicode char or None) */
6901 w = PyLong_FromLong((long)ch);
6902 if (w == NULL)
6903 goto onError;
6904 x = PyObject_GetItem(mapping, w);
6905 Py_DECREF(w);
6906 if (x == NULL) {
6907 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
6908 /* No mapping found means: mapping is undefined. */
6909 PyErr_Clear();
6910 x = Py_None;
6911 Py_INCREF(x);
6912 } else
6913 goto onError;
6914 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00006915
Benjamin Peterson29060642009-01-31 22:14:21 +00006916 /* Apply mapping */
6917 if (PyLong_Check(x)) {
6918 long value = PyLong_AS_LONG(x);
6919 if (value < 0 || value > 65535) {
6920 PyErr_SetString(PyExc_TypeError,
6921 "character mapping must be in range(65536)");
6922 Py_DECREF(x);
6923 goto onError;
6924 }
6925 *p++ = (Py_UNICODE)value;
6926 }
6927 else if (x == Py_None) {
6928 /* undefined mapping */
6929 outpos = p-PyUnicode_AS_UNICODE(v);
6930 startinpos = s-starts;
6931 endinpos = startinpos+1;
6932 if (unicode_decode_call_errorhandler(
6933 errors, &errorHandler,
6934 "charmap", "character maps to <undefined>",
6935 &starts, &e, &startinpos, &endinpos, &exc, &s,
6936 &v, &outpos, &p)) {
6937 Py_DECREF(x);
6938 goto onError;
6939 }
6940 Py_DECREF(x);
6941 continue;
6942 }
6943 else if (PyUnicode_Check(x)) {
6944 Py_ssize_t targetsize = PyUnicode_GET_SIZE(x);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006945
Benjamin Peterson29060642009-01-31 22:14:21 +00006946 if (targetsize == 1)
6947 /* 1-1 mapping */
6948 *p++ = *PyUnicode_AS_UNICODE(x);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006949
Benjamin Peterson29060642009-01-31 22:14:21 +00006950 else if (targetsize > 1) {
6951 /* 1-n mapping */
6952 if (targetsize > extrachars) {
6953 /* resize first */
6954 Py_ssize_t oldpos = p - PyUnicode_AS_UNICODE(v);
6955 Py_ssize_t needed = (targetsize - extrachars) + \
6956 (targetsize << 2);
6957 extrachars += needed;
6958 /* XXX overflow detection missing */
Victor Stinnerfe226c02011-10-03 03:52:20 +02006959 if (PyUnicode_Resize((PyObject**)&v,
Benjamin Peterson29060642009-01-31 22:14:21 +00006960 PyUnicode_GET_SIZE(v) + needed) < 0) {
6961 Py_DECREF(x);
6962 goto onError;
6963 }
6964 p = PyUnicode_AS_UNICODE(v) + oldpos;
6965 }
6966 Py_UNICODE_COPY(p,
6967 PyUnicode_AS_UNICODE(x),
6968 targetsize);
6969 p += targetsize;
6970 extrachars -= targetsize;
6971 }
6972 /* 1-0 mapping: skip the character */
6973 }
6974 else {
6975 /* wrong return value */
6976 PyErr_SetString(PyExc_TypeError,
6977 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00006978 Py_DECREF(x);
6979 goto onError;
6980 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006981 Py_DECREF(x);
6982 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006983 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006984 }
6985 if (p - PyUnicode_AS_UNICODE(v) < PyUnicode_GET_SIZE(v))
Victor Stinnerfe226c02011-10-03 03:52:20 +02006986 if (PyUnicode_Resize((PyObject**)&v, p - PyUnicode_AS_UNICODE(v)) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006987 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006988 Py_XDECREF(errorHandler);
6989 Py_XDECREF(exc);
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02006990 if (_PyUnicode_READY_REPLACE(&v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006991 Py_DECREF(v);
6992 return NULL;
6993 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006994 return (PyObject *)v;
Tim Petersced69f82003-09-16 20:30:58 +00006995
Benjamin Peterson29060642009-01-31 22:14:21 +00006996 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006997 Py_XDECREF(errorHandler);
6998 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006999 Py_XDECREF(v);
7000 return NULL;
7001}
7002
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007003/* Charmap encoding: the lookup table */
7004
Alexander Belopolsky40018472011-02-26 01:02:56 +00007005struct encoding_map {
Benjamin Peterson29060642009-01-31 22:14:21 +00007006 PyObject_HEAD
7007 unsigned char level1[32];
7008 int count2, count3;
7009 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007010};
7011
7012static PyObject*
7013encoding_map_size(PyObject *obj, PyObject* args)
7014{
7015 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007016 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00007017 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007018}
7019
7020static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007021 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00007022 PyDoc_STR("Return the size (in bytes) of this object") },
7023 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007024};
7025
7026static void
7027encoding_map_dealloc(PyObject* o)
7028{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007029 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007030}
7031
7032static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007033 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007034 "EncodingMap", /*tp_name*/
7035 sizeof(struct encoding_map), /*tp_basicsize*/
7036 0, /*tp_itemsize*/
7037 /* methods */
7038 encoding_map_dealloc, /*tp_dealloc*/
7039 0, /*tp_print*/
7040 0, /*tp_getattr*/
7041 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00007042 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00007043 0, /*tp_repr*/
7044 0, /*tp_as_number*/
7045 0, /*tp_as_sequence*/
7046 0, /*tp_as_mapping*/
7047 0, /*tp_hash*/
7048 0, /*tp_call*/
7049 0, /*tp_str*/
7050 0, /*tp_getattro*/
7051 0, /*tp_setattro*/
7052 0, /*tp_as_buffer*/
7053 Py_TPFLAGS_DEFAULT, /*tp_flags*/
7054 0, /*tp_doc*/
7055 0, /*tp_traverse*/
7056 0, /*tp_clear*/
7057 0, /*tp_richcompare*/
7058 0, /*tp_weaklistoffset*/
7059 0, /*tp_iter*/
7060 0, /*tp_iternext*/
7061 encoding_map_methods, /*tp_methods*/
7062 0, /*tp_members*/
7063 0, /*tp_getset*/
7064 0, /*tp_base*/
7065 0, /*tp_dict*/
7066 0, /*tp_descr_get*/
7067 0, /*tp_descr_set*/
7068 0, /*tp_dictoffset*/
7069 0, /*tp_init*/
7070 0, /*tp_alloc*/
7071 0, /*tp_new*/
7072 0, /*tp_free*/
7073 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007074};
7075
7076PyObject*
7077PyUnicode_BuildEncodingMap(PyObject* string)
7078{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007079 PyObject *result;
7080 struct encoding_map *mresult;
7081 int i;
7082 int need_dict = 0;
7083 unsigned char level1[32];
7084 unsigned char level2[512];
7085 unsigned char *mlevel1, *mlevel2, *mlevel3;
7086 int count2 = 0, count3 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007087 int kind;
7088 void *data;
7089 Py_UCS4 ch;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007090
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007091 if (!PyUnicode_Check(string) || PyUnicode_GET_LENGTH(string) != 256) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007092 PyErr_BadArgument();
7093 return NULL;
7094 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007095 kind = PyUnicode_KIND(string);
7096 data = PyUnicode_DATA(string);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007097 memset(level1, 0xFF, sizeof level1);
7098 memset(level2, 0xFF, sizeof level2);
7099
7100 /* If there isn't a one-to-one mapping of NULL to \0,
7101 or if there are non-BMP characters, we need to use
7102 a mapping dictionary. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007103 if (PyUnicode_READ(kind, data, 0) != 0)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007104 need_dict = 1;
7105 for (i = 1; i < 256; i++) {
7106 int l1, l2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007107 ch = PyUnicode_READ(kind, data, i);
7108 if (ch == 0 || ch > 0xFFFF) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007109 need_dict = 1;
7110 break;
7111 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007112 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007113 /* unmapped character */
7114 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007115 l1 = ch >> 11;
7116 l2 = ch >> 7;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007117 if (level1[l1] == 0xFF)
7118 level1[l1] = count2++;
7119 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00007120 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007121 }
7122
7123 if (count2 >= 0xFF || count3 >= 0xFF)
7124 need_dict = 1;
7125
7126 if (need_dict) {
7127 PyObject *result = PyDict_New();
7128 PyObject *key, *value;
7129 if (!result)
7130 return NULL;
7131 for (i = 0; i < 256; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007132 key = PyLong_FromLong(PyUnicode_READ(kind, data, i));
Christian Heimes217cfd12007-12-02 14:31:20 +00007133 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007134 if (!key || !value)
7135 goto failed1;
7136 if (PyDict_SetItem(result, key, value) == -1)
7137 goto failed1;
7138 Py_DECREF(key);
7139 Py_DECREF(value);
7140 }
7141 return result;
7142 failed1:
7143 Py_XDECREF(key);
7144 Py_XDECREF(value);
7145 Py_DECREF(result);
7146 return NULL;
7147 }
7148
7149 /* Create a three-level trie */
7150 result = PyObject_MALLOC(sizeof(struct encoding_map) +
7151 16*count2 + 128*count3 - 1);
7152 if (!result)
7153 return PyErr_NoMemory();
7154 PyObject_Init(result, &EncodingMapType);
7155 mresult = (struct encoding_map*)result;
7156 mresult->count2 = count2;
7157 mresult->count3 = count3;
7158 mlevel1 = mresult->level1;
7159 mlevel2 = mresult->level23;
7160 mlevel3 = mresult->level23 + 16*count2;
7161 memcpy(mlevel1, level1, 32);
7162 memset(mlevel2, 0xFF, 16*count2);
7163 memset(mlevel3, 0, 128*count3);
7164 count3 = 0;
7165 for (i = 1; i < 256; i++) {
7166 int o1, o2, o3, i2, i3;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007167 if (PyUnicode_READ(kind, data, i) == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007168 /* unmapped character */
7169 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007170 o1 = PyUnicode_READ(kind, data, i)>>11;
7171 o2 = (PyUnicode_READ(kind, data, i)>>7) & 0xF;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007172 i2 = 16*mlevel1[o1] + o2;
7173 if (mlevel2[i2] == 0xFF)
7174 mlevel2[i2] = count3++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007175 o3 = PyUnicode_READ(kind, data, i) & 0x7F;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007176 i3 = 128*mlevel2[i2] + o3;
7177 mlevel3[i3] = i;
7178 }
7179 return result;
7180}
7181
7182static int
7183encoding_map_lookup(Py_UNICODE c, PyObject *mapping)
7184{
7185 struct encoding_map *map = (struct encoding_map*)mapping;
7186 int l1 = c>>11;
7187 int l2 = (c>>7) & 0xF;
7188 int l3 = c & 0x7F;
7189 int i;
7190
7191#ifdef Py_UNICODE_WIDE
7192 if (c > 0xFFFF) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007193 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007194 }
7195#endif
7196 if (c == 0)
7197 return 0;
7198 /* level 1*/
7199 i = map->level1[l1];
7200 if (i == 0xFF) {
7201 return -1;
7202 }
7203 /* level 2*/
7204 i = map->level23[16*i+l2];
7205 if (i == 0xFF) {
7206 return -1;
7207 }
7208 /* level 3 */
7209 i = map->level23[16*map->count2 + 128*i + l3];
7210 if (i == 0) {
7211 return -1;
7212 }
7213 return i;
7214}
7215
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007216/* Lookup the character ch in the mapping. If the character
7217 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00007218 error occurred). */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007219static PyObject *
7220charmapencode_lookup(Py_UNICODE c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007221{
Christian Heimes217cfd12007-12-02 14:31:20 +00007222 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007223 PyObject *x;
7224
7225 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007226 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007227 x = PyObject_GetItem(mapping, w);
7228 Py_DECREF(w);
7229 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007230 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7231 /* No mapping found means: mapping is undefined. */
7232 PyErr_Clear();
7233 x = Py_None;
7234 Py_INCREF(x);
7235 return x;
7236 } else
7237 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007238 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00007239 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00007240 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00007241 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007242 long value = PyLong_AS_LONG(x);
7243 if (value < 0 || value > 255) {
7244 PyErr_SetString(PyExc_TypeError,
7245 "character mapping must be in range(256)");
7246 Py_DECREF(x);
7247 return NULL;
7248 }
7249 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007250 }
Christian Heimes72b710a2008-05-26 13:28:38 +00007251 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00007252 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007253 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007254 /* wrong return value */
7255 PyErr_Format(PyExc_TypeError,
7256 "character mapping must return integer, bytes or None, not %.400s",
7257 x->ob_type->tp_name);
7258 Py_DECREF(x);
7259 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007260 }
7261}
7262
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007263static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00007264charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007265{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007266 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
7267 /* exponentially overallocate to minimize reallocations */
7268 if (requiredsize < 2*outsize)
7269 requiredsize = 2*outsize;
7270 if (_PyBytes_Resize(outobj, requiredsize))
7271 return -1;
7272 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007273}
7274
Benjamin Peterson14339b62009-01-31 16:36:08 +00007275typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00007276 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Alexander Belopolsky40018472011-02-26 01:02:56 +00007277} charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007278/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00007279 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007280 space is available. Return a new reference to the object that
7281 was put in the output buffer, or Py_None, if the mapping was undefined
7282 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00007283 reallocation error occurred. The caller must decref the result */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007284static charmapencode_result
7285charmapencode_output(Py_UNICODE c, PyObject *mapping,
7286 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007287{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007288 PyObject *rep;
7289 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00007290 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007291
Christian Heimes90aa7642007-12-19 02:45:37 +00007292 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007293 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00007294 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007295 if (res == -1)
7296 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00007297 if (outsize<requiredsize)
7298 if (charmapencode_resize(outobj, outpos, requiredsize))
7299 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00007300 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00007301 outstart[(*outpos)++] = (char)res;
7302 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007303 }
7304
7305 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007306 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007307 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007308 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007309 Py_DECREF(rep);
7310 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007311 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007312 if (PyLong_Check(rep)) {
7313 Py_ssize_t requiredsize = *outpos+1;
7314 if (outsize<requiredsize)
7315 if (charmapencode_resize(outobj, outpos, requiredsize)) {
7316 Py_DECREF(rep);
7317 return enc_EXCEPTION;
7318 }
Christian Heimes72b710a2008-05-26 13:28:38 +00007319 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00007320 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00007321 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007322 else {
7323 const char *repchars = PyBytes_AS_STRING(rep);
7324 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
7325 Py_ssize_t requiredsize = *outpos+repsize;
7326 if (outsize<requiredsize)
7327 if (charmapencode_resize(outobj, outpos, requiredsize)) {
7328 Py_DECREF(rep);
7329 return enc_EXCEPTION;
7330 }
Christian Heimes72b710a2008-05-26 13:28:38 +00007331 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00007332 memcpy(outstart + *outpos, repchars, repsize);
7333 *outpos += repsize;
7334 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007335 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007336 Py_DECREF(rep);
7337 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007338}
7339
7340/* handle an error in PyUnicode_EncodeCharmap
7341 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007342static int
7343charmap_encoding_error(
Martin v. Löwis18e16552006-02-15 17:27:45 +00007344 const Py_UNICODE *p, Py_ssize_t size, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007345 PyObject **exceptionObject,
Walter Dörwalde5402fb2003-08-14 20:25:29 +00007346 int *known_errorHandler, PyObject **errorHandler, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00007347 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007348{
7349 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis18e16552006-02-15 17:27:45 +00007350 Py_ssize_t repsize;
7351 Py_ssize_t newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007352 Py_UNICODE *uni2;
7353 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00007354 Py_ssize_t collstartpos = *inpos;
7355 Py_ssize_t collendpos = *inpos+1;
7356 Py_ssize_t collpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007357 char *encoding = "charmap";
7358 char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007359 charmapencode_result x;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007360
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007361 /* find all unencodable characters */
7362 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007363 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00007364 if (Py_TYPE(mapping) == &EncodingMapType) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007365 int res = encoding_map_lookup(p[collendpos], mapping);
7366 if (res != -1)
7367 break;
7368 ++collendpos;
7369 continue;
7370 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007371
Benjamin Peterson29060642009-01-31 22:14:21 +00007372 rep = charmapencode_lookup(p[collendpos], mapping);
7373 if (rep==NULL)
7374 return -1;
7375 else if (rep!=Py_None) {
7376 Py_DECREF(rep);
7377 break;
7378 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007379 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00007380 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007381 }
7382 /* cache callback name lookup
7383 * (if not done yet, i.e. it's the first error) */
7384 if (*known_errorHandler==-1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007385 if ((errors==NULL) || (!strcmp(errors, "strict")))
7386 *known_errorHandler = 1;
7387 else if (!strcmp(errors, "replace"))
7388 *known_errorHandler = 2;
7389 else if (!strcmp(errors, "ignore"))
7390 *known_errorHandler = 3;
7391 else if (!strcmp(errors, "xmlcharrefreplace"))
7392 *known_errorHandler = 4;
7393 else
7394 *known_errorHandler = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007395 }
7396 switch (*known_errorHandler) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007397 case 1: /* strict */
7398 raise_encode_exception(exceptionObject, encoding, p, size, collstartpos, collendpos, reason);
7399 return -1;
7400 case 2: /* replace */
7401 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007402 x = charmapencode_output('?', mapping, res, respos);
7403 if (x==enc_EXCEPTION) {
7404 return -1;
7405 }
7406 else if (x==enc_FAILED) {
7407 raise_encode_exception(exceptionObject, encoding, p, size, collstartpos, collendpos, reason);
7408 return -1;
7409 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007410 }
7411 /* fall through */
7412 case 3: /* ignore */
7413 *inpos = collendpos;
7414 break;
7415 case 4: /* xmlcharrefreplace */
7416 /* generate replacement (temporarily (mis)uses p) */
7417 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007418 char buffer[2+29+1+1];
7419 char *cp;
7420 sprintf(buffer, "&#%d;", (int)p[collpos]);
7421 for (cp = buffer; *cp; ++cp) {
7422 x = charmapencode_output(*cp, mapping, res, respos);
7423 if (x==enc_EXCEPTION)
7424 return -1;
7425 else if (x==enc_FAILED) {
7426 raise_encode_exception(exceptionObject, encoding, p, size, collstartpos, collendpos, reason);
7427 return -1;
7428 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007429 }
7430 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007431 *inpos = collendpos;
7432 break;
7433 default:
7434 repunicode = unicode_encode_call_errorhandler(errors, errorHandler,
Benjamin Peterson29060642009-01-31 22:14:21 +00007435 encoding, reason, p, size, exceptionObject,
7436 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00007437 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007438 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00007439 if (PyBytes_Check(repunicode)) {
7440 /* Directly copy bytes result to output. */
7441 Py_ssize_t outsize = PyBytes_Size(*res);
7442 Py_ssize_t requiredsize;
7443 repsize = PyBytes_Size(repunicode);
7444 requiredsize = *respos + repsize;
7445 if (requiredsize > outsize)
7446 /* Make room for all additional bytes. */
7447 if (charmapencode_resize(res, respos, requiredsize)) {
7448 Py_DECREF(repunicode);
7449 return -1;
7450 }
7451 memcpy(PyBytes_AsString(*res) + *respos,
7452 PyBytes_AsString(repunicode), repsize);
7453 *respos += repsize;
7454 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00007455 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00007456 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00007457 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007458 /* generate replacement */
7459 repsize = PyUnicode_GET_SIZE(repunicode);
7460 for (uni2 = PyUnicode_AS_UNICODE(repunicode); repsize-->0; ++uni2) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007461 x = charmapencode_output(*uni2, mapping, res, respos);
7462 if (x==enc_EXCEPTION) {
7463 return -1;
7464 }
7465 else if (x==enc_FAILED) {
7466 Py_DECREF(repunicode);
7467 raise_encode_exception(exceptionObject, encoding, p, size, collstartpos, collendpos, reason);
7468 return -1;
7469 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007470 }
7471 *inpos = newpos;
7472 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007473 }
7474 return 0;
7475}
7476
Alexander Belopolsky40018472011-02-26 01:02:56 +00007477PyObject *
7478PyUnicode_EncodeCharmap(const Py_UNICODE *p,
7479 Py_ssize_t size,
7480 PyObject *mapping,
7481 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007482{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007483 /* output object */
7484 PyObject *res = NULL;
7485 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00007486 Py_ssize_t inpos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007487 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00007488 Py_ssize_t respos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007489 PyObject *errorHandler = NULL;
7490 PyObject *exc = NULL;
7491 /* the following variable is used for caching string comparisons
7492 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
7493 * 3=ignore, 4=xmlcharrefreplace */
7494 int known_errorHandler = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007495
7496 /* Default to Latin-1 */
7497 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007498 return PyUnicode_EncodeLatin1(p, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007499
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007500 /* allocate enough for a simple encoding without
7501 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00007502 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007503 if (res == NULL)
7504 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00007505 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007506 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007507
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007508 while (inpos<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007509 /* try to encode it */
7510 charmapencode_result x = charmapencode_output(p[inpos], mapping, &res, &respos);
7511 if (x==enc_EXCEPTION) /* error */
7512 goto onError;
7513 if (x==enc_FAILED) { /* unencodable character */
7514 if (charmap_encoding_error(p, size, &inpos, mapping,
7515 &exc,
7516 &known_errorHandler, &errorHandler, errors,
7517 &res, &respos)) {
7518 goto onError;
7519 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007520 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007521 else
7522 /* done with this character => adjust input position */
7523 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007524 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00007525
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007526 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00007527 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00007528 if (_PyBytes_Resize(&res, respos) < 0)
7529 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00007530
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007531 Py_XDECREF(exc);
7532 Py_XDECREF(errorHandler);
7533 return res;
7534
Benjamin Peterson29060642009-01-31 22:14:21 +00007535 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007536 Py_XDECREF(res);
7537 Py_XDECREF(exc);
7538 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007539 return NULL;
7540}
7541
Alexander Belopolsky40018472011-02-26 01:02:56 +00007542PyObject *
7543PyUnicode_AsCharmapString(PyObject *unicode,
7544 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007545{
7546 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007547 PyErr_BadArgument();
7548 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007549 }
7550 return PyUnicode_EncodeCharmap(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00007551 PyUnicode_GET_SIZE(unicode),
7552 mapping,
7553 NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007554}
7555
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007556/* create or adjust a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007557static void
7558make_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007559 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00007560 Py_ssize_t startpos, Py_ssize_t endpos,
7561 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007562{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007563 if (*exceptionObject == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007564 *exceptionObject = _PyUnicodeTranslateError_Create(
7565 unicode, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007566 }
7567 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007568 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
7569 goto onError;
7570 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
7571 goto onError;
7572 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
7573 goto onError;
7574 return;
7575 onError:
7576 Py_DECREF(*exceptionObject);
7577 *exceptionObject = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007578 }
7579}
7580
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007581/* raises a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007582static void
7583raise_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007584 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00007585 Py_ssize_t startpos, Py_ssize_t endpos,
7586 const char *reason)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007587{
7588 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007589 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007590 if (*exceptionObject != NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007591 PyCodec_StrictErrors(*exceptionObject);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007592}
7593
7594/* error handling callback helper:
7595 build arguments, call the callback and check the arguments,
7596 put the result into newpos and return the replacement string, which
7597 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007598static PyObject *
7599unicode_translate_call_errorhandler(const char *errors,
7600 PyObject **errorHandler,
7601 const char *reason,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007602 PyObject *unicode, PyObject **exceptionObject,
Alexander Belopolsky40018472011-02-26 01:02:56 +00007603 Py_ssize_t startpos, Py_ssize_t endpos,
7604 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007605{
Benjamin Peterson142957c2008-07-04 19:55:29 +00007606 static char *argparse = "O!n;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007607
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007608 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007609 PyObject *restuple;
7610 PyObject *resunicode;
7611
7612 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007613 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007614 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007615 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007616 }
7617
7618 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007619 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007620 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007621 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007622
7623 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00007624 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007625 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007626 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007627 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00007628 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00007629 Py_DECREF(restuple);
7630 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007631 }
7632 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type,
Benjamin Peterson29060642009-01-31 22:14:21 +00007633 &resunicode, &i_newpos)) {
7634 Py_DECREF(restuple);
7635 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007636 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00007637 if (i_newpos<0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007638 *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007639 else
7640 *newpos = i_newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007641 if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007642 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
7643 Py_DECREF(restuple);
7644 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00007645 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007646 Py_INCREF(resunicode);
7647 Py_DECREF(restuple);
7648 return resunicode;
7649}
7650
7651/* Lookup the character ch in the mapping and put the result in result,
7652 which must be decrefed by the caller.
7653 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007654static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007655charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007656{
Christian Heimes217cfd12007-12-02 14:31:20 +00007657 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007658 PyObject *x;
7659
7660 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007661 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007662 x = PyObject_GetItem(mapping, w);
7663 Py_DECREF(w);
7664 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007665 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7666 /* No mapping found means: use 1:1 mapping. */
7667 PyErr_Clear();
7668 *result = NULL;
7669 return 0;
7670 } else
7671 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007672 }
7673 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007674 *result = x;
7675 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007676 }
Christian Heimes217cfd12007-12-02 14:31:20 +00007677 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007678 long value = PyLong_AS_LONG(x);
7679 long max = PyUnicode_GetMax();
7680 if (value < 0 || value > max) {
7681 PyErr_Format(PyExc_TypeError,
Guido van Rossum5a2f7e602007-10-24 21:13:09 +00007682 "character mapping must be in range(0x%x)", max+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00007683 Py_DECREF(x);
7684 return -1;
7685 }
7686 *result = x;
7687 return 0;
7688 }
7689 else if (PyUnicode_Check(x)) {
7690 *result = x;
7691 return 0;
7692 }
7693 else {
7694 /* wrong return value */
7695 PyErr_SetString(PyExc_TypeError,
7696 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00007697 Py_DECREF(x);
7698 return -1;
7699 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007700}
7701/* ensure that *outobj is at least requiredsize characters long,
Benjamin Peterson29060642009-01-31 22:14:21 +00007702 if not reallocate and adjust various state variables.
7703 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007704static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007705charmaptranslate_makespace(Py_UCS4 **outobj, Py_ssize_t *psize,
Benjamin Peterson29060642009-01-31 22:14:21 +00007706 Py_ssize_t requiredsize)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007707{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007708 Py_ssize_t oldsize = *psize;
Walter Dörwald4894c302003-10-24 14:25:28 +00007709 if (requiredsize > oldsize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007710 /* exponentially overallocate to minimize reallocations */
7711 if (requiredsize < 2 * oldsize)
7712 requiredsize = 2 * oldsize;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007713 *outobj = PyMem_Realloc(*outobj, requiredsize * sizeof(Py_UCS4));
7714 if (*outobj == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007715 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007716 *psize = requiredsize;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007717 }
7718 return 0;
7719}
7720/* lookup the character, put the result in the output string and adjust
7721 various state variables. Return a new reference to the object that
7722 was put in the output buffer in *result, or Py_None, if the mapping was
7723 undefined (in which case no character was written).
7724 The called must decref result.
7725 Return 0 on success, -1 on error. */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007726static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007727charmaptranslate_output(PyObject *input, Py_ssize_t ipos,
7728 PyObject *mapping, Py_UCS4 **output,
7729 Py_ssize_t *osize, Py_ssize_t *opos,
Alexander Belopolsky40018472011-02-26 01:02:56 +00007730 PyObject **res)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007731{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007732 Py_UCS4 curinp = PyUnicode_READ_CHAR(input, ipos);
7733 if (charmaptranslate_lookup(curinp, mapping, res))
Benjamin Peterson29060642009-01-31 22:14:21 +00007734 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007735 if (*res==NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007736 /* not found => default to 1:1 mapping */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007737 (*output)[(*opos)++] = curinp;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007738 }
7739 else if (*res==Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00007740 ;
Christian Heimes217cfd12007-12-02 14:31:20 +00007741 else if (PyLong_Check(*res)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007742 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007743 (*output)[(*opos)++] = (Py_UCS4)PyLong_AS_LONG(*res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007744 }
7745 else if (PyUnicode_Check(*res)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007746 Py_ssize_t repsize;
7747 if (PyUnicode_READY(*res) == -1)
7748 return -1;
7749 repsize = PyUnicode_GET_LENGTH(*res);
Benjamin Peterson29060642009-01-31 22:14:21 +00007750 if (repsize==1) {
7751 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007752 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +00007753 }
7754 else if (repsize!=0) {
7755 /* more than one character */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007756 Py_ssize_t requiredsize = *opos +
7757 (PyUnicode_GET_LENGTH(input) - ipos) +
Benjamin Peterson29060642009-01-31 22:14:21 +00007758 repsize - 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007759 Py_ssize_t i;
7760 if (charmaptranslate_makespace(output, osize, requiredsize))
Benjamin Peterson29060642009-01-31 22:14:21 +00007761 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007762 for(i = 0; i < repsize; i++)
7763 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00007764 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007765 }
7766 else
Benjamin Peterson29060642009-01-31 22:14:21 +00007767 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007768 return 0;
7769}
7770
Alexander Belopolsky40018472011-02-26 01:02:56 +00007771PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007772_PyUnicode_TranslateCharmap(PyObject *input,
7773 PyObject *mapping,
7774 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007775{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007776 /* input object */
7777 char *idata;
7778 Py_ssize_t size, i;
7779 int kind;
7780 /* output buffer */
7781 Py_UCS4 *output = NULL;
7782 Py_ssize_t osize;
7783 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007784 /* current output position */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007785 Py_ssize_t opos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007786 char *reason = "character maps to <undefined>";
7787 PyObject *errorHandler = NULL;
7788 PyObject *exc = NULL;
7789 /* the following variable is used for caching string comparisons
7790 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
7791 * 3=ignore, 4=xmlcharrefreplace */
7792 int known_errorHandler = -1;
7793
Guido van Rossumd57fd912000-03-10 22:53:23 +00007794 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007795 PyErr_BadArgument();
7796 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007797 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007798
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007799 if (PyUnicode_READY(input) == -1)
7800 return NULL;
7801 idata = (char*)PyUnicode_DATA(input);
7802 kind = PyUnicode_KIND(input);
7803 size = PyUnicode_GET_LENGTH(input);
7804 i = 0;
7805
7806 if (size == 0) {
7807 Py_INCREF(input);
7808 return input;
7809 }
7810
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007811 /* allocate enough for a simple 1:1 translation without
7812 replacements, if we need more, we'll resize */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007813 osize = size;
7814 output = PyMem_Malloc(osize * sizeof(Py_UCS4));
7815 opos = 0;
7816 if (output == NULL) {
7817 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00007818 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007819 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00007820
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007821 while (i<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007822 /* try to encode it */
7823 PyObject *x = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007824 if (charmaptranslate_output(input, i, mapping,
7825 &output, &osize, &opos, &x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007826 Py_XDECREF(x);
7827 goto onError;
7828 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007829 Py_XDECREF(x);
Benjamin Peterson29060642009-01-31 22:14:21 +00007830 if (x!=Py_None) /* it worked => adjust input pointer */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007831 ++i;
Benjamin Peterson29060642009-01-31 22:14:21 +00007832 else { /* untranslatable character */
7833 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
7834 Py_ssize_t repsize;
7835 Py_ssize_t newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007836 Py_ssize_t uni2;
Benjamin Peterson29060642009-01-31 22:14:21 +00007837 /* startpos for collecting untranslatable chars */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007838 Py_ssize_t collstart = i;
7839 Py_ssize_t collend = i+1;
7840 Py_ssize_t coll;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007841
Benjamin Peterson29060642009-01-31 22:14:21 +00007842 /* find all untranslatable characters */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007843 while (collend < size) {
7844 if (charmaptranslate_lookup(PyUnicode_READ(kind,idata, collend), mapping, &x))
Benjamin Peterson29060642009-01-31 22:14:21 +00007845 goto onError;
7846 Py_XDECREF(x);
7847 if (x!=Py_None)
7848 break;
7849 ++collend;
7850 }
7851 /* cache callback name lookup
7852 * (if not done yet, i.e. it's the first error) */
7853 if (known_errorHandler==-1) {
7854 if ((errors==NULL) || (!strcmp(errors, "strict")))
7855 known_errorHandler = 1;
7856 else if (!strcmp(errors, "replace"))
7857 known_errorHandler = 2;
7858 else if (!strcmp(errors, "ignore"))
7859 known_errorHandler = 3;
7860 else if (!strcmp(errors, "xmlcharrefreplace"))
7861 known_errorHandler = 4;
7862 else
7863 known_errorHandler = 0;
7864 }
7865 switch (known_errorHandler) {
7866 case 1: /* strict */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007867 raise_translate_exception(&exc, input, collstart,
7868 collend, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00007869 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00007870 case 2: /* replace */
7871 /* No need to check for space, this is a 1:1 replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007872 for (coll = collstart; coll<collend; coll++)
7873 output[opos++] = '?';
Benjamin Peterson29060642009-01-31 22:14:21 +00007874 /* fall through */
7875 case 3: /* ignore */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007876 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00007877 break;
7878 case 4: /* xmlcharrefreplace */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007879 /* generate replacement (temporarily (mis)uses i) */
7880 for (i = collstart; i < collend; ++i) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007881 char buffer[2+29+1+1];
7882 char *cp;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007883 sprintf(buffer, "&#%d;", PyUnicode_READ(kind, idata, i));
7884 if (charmaptranslate_makespace(&output, &osize,
7885 opos+strlen(buffer)+(size-collend)))
Benjamin Peterson29060642009-01-31 22:14:21 +00007886 goto onError;
7887 for (cp = buffer; *cp; ++cp)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007888 output[opos++] = *cp;
Benjamin Peterson29060642009-01-31 22:14:21 +00007889 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007890 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00007891 break;
7892 default:
7893 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007894 reason, input, &exc,
7895 collstart, collend, &newpos);
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02007896 if (repunicode == NULL || _PyUnicode_READY_REPLACE(&repunicode))
Benjamin Peterson29060642009-01-31 22:14:21 +00007897 goto onError;
7898 /* generate replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007899 repsize = PyUnicode_GET_LENGTH(repunicode);
7900 if (charmaptranslate_makespace(&output, &osize,
7901 opos+repsize+(size-collend))) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007902 Py_DECREF(repunicode);
7903 goto onError;
7904 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007905 for (uni2 = 0; repsize-->0; ++uni2)
7906 output[opos++] = PyUnicode_READ_CHAR(repunicode, uni2);
7907 i = newpos;
Benjamin Peterson29060642009-01-31 22:14:21 +00007908 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00007909 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007910 }
7911 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007912 res = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND, output, opos);
7913 if (!res)
7914 goto onError;
7915 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007916 Py_XDECREF(exc);
7917 Py_XDECREF(errorHandler);
7918 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007919
Benjamin Peterson29060642009-01-31 22:14:21 +00007920 onError:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007921 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007922 Py_XDECREF(exc);
7923 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007924 return NULL;
7925}
7926
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007927/* Deprecated. Use PyUnicode_Translate instead. */
7928PyObject *
7929PyUnicode_TranslateCharmap(const Py_UNICODE *p,
7930 Py_ssize_t size,
7931 PyObject *mapping,
7932 const char *errors)
7933{
7934 PyObject *unicode = PyUnicode_FromUnicode(p, size);
7935 if (!unicode)
7936 return NULL;
7937 return _PyUnicode_TranslateCharmap(unicode, mapping, errors);
7938}
7939
Alexander Belopolsky40018472011-02-26 01:02:56 +00007940PyObject *
7941PyUnicode_Translate(PyObject *str,
7942 PyObject *mapping,
7943 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007944{
7945 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +00007946
Guido van Rossumd57fd912000-03-10 22:53:23 +00007947 str = PyUnicode_FromObject(str);
7948 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007949 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007950 result = _PyUnicode_TranslateCharmap(str, mapping, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007951 Py_DECREF(str);
7952 return result;
Tim Petersced69f82003-09-16 20:30:58 +00007953
Benjamin Peterson29060642009-01-31 22:14:21 +00007954 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00007955 Py_XDECREF(str);
7956 return NULL;
7957}
Tim Petersced69f82003-09-16 20:30:58 +00007958
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007959static Py_UCS4
7960fix_decimal_and_space_to_ascii(PyUnicodeObject *self)
7961{
7962 /* No need to call PyUnicode_READY(self) because this function is only
7963 called as a callback from fixup() which does it already. */
7964 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
7965 const int kind = PyUnicode_KIND(self);
7966 void *data = PyUnicode_DATA(self);
7967 Py_UCS4 maxchar = 0, ch, fixed;
7968 Py_ssize_t i;
7969
7970 for (i = 0; i < len; ++i) {
7971 ch = PyUnicode_READ(kind, data, i);
7972 fixed = 0;
7973 if (ch > 127) {
7974 if (Py_UNICODE_ISSPACE(ch))
7975 fixed = ' ';
7976 else {
7977 const int decimal = Py_UNICODE_TODECIMAL(ch);
7978 if (decimal >= 0)
7979 fixed = '0' + decimal;
7980 }
7981 if (fixed != 0) {
7982 if (fixed > maxchar)
7983 maxchar = fixed;
7984 PyUnicode_WRITE(kind, data, i, fixed);
7985 }
7986 else if (ch > maxchar)
7987 maxchar = ch;
7988 }
7989 else if (ch > maxchar)
7990 maxchar = ch;
7991 }
7992
7993 return maxchar;
7994}
7995
7996PyObject *
7997_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
7998{
7999 if (!PyUnicode_Check(unicode)) {
8000 PyErr_BadInternalCall();
8001 return NULL;
8002 }
8003 if (PyUnicode_READY(unicode) == -1)
8004 return NULL;
8005 if (PyUnicode_MAX_CHAR_VALUE(unicode) <= 127) {
8006 /* If the string is already ASCII, just return the same string */
8007 Py_INCREF(unicode);
8008 return unicode;
8009 }
8010 return fixup((PyUnicodeObject *)unicode, fix_decimal_and_space_to_ascii);
8011}
8012
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008013PyObject *
8014PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
8015 Py_ssize_t length)
8016{
8017 PyObject *result;
8018 Py_UNICODE *p; /* write pointer into result */
8019 Py_ssize_t i;
8020 /* Copy to a new string */
8021 result = (PyObject *)_PyUnicode_New(length);
8022 Py_UNICODE_COPY(PyUnicode_AS_UNICODE(result), s, length);
8023 if (result == NULL)
8024 return result;
8025 p = PyUnicode_AS_UNICODE(result);
8026 /* Iterate over code points */
8027 for (i = 0; i < length; i++) {
8028 Py_UNICODE ch =s[i];
8029 if (ch > 127) {
8030 int decimal = Py_UNICODE_TODECIMAL(ch);
8031 if (decimal >= 0)
8032 p[i] = '0' + decimal;
8033 }
8034 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008035 if (PyUnicode_READY((PyUnicodeObject*)result) == -1) {
8036 Py_DECREF(result);
8037 return NULL;
8038 }
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008039 return result;
8040}
Guido van Rossum9e896b32000-04-05 20:11:21 +00008041/* --- Decimal Encoder ---------------------------------------------------- */
8042
Alexander Belopolsky40018472011-02-26 01:02:56 +00008043int
8044PyUnicode_EncodeDecimal(Py_UNICODE *s,
8045 Py_ssize_t length,
8046 char *output,
8047 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00008048{
8049 Py_UNICODE *p, *end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008050 PyObject *errorHandler = NULL;
8051 PyObject *exc = NULL;
8052 const char *encoding = "decimal";
8053 const char *reason = "invalid decimal Unicode string";
8054 /* the following variable is used for caching string comparisons
8055 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
8056 int known_errorHandler = -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008057
8058 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008059 PyErr_BadArgument();
8060 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008061 }
8062
8063 p = s;
8064 end = s + length;
8065 while (p < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008066 register Py_UNICODE ch = *p;
8067 int decimal;
8068 PyObject *repunicode;
8069 Py_ssize_t repsize;
8070 Py_ssize_t newpos;
8071 Py_UNICODE *uni2;
8072 Py_UNICODE *collstart;
8073 Py_UNICODE *collend;
Tim Petersced69f82003-09-16 20:30:58 +00008074
Benjamin Peterson29060642009-01-31 22:14:21 +00008075 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008076 *output++ = ' ';
Benjamin Peterson29060642009-01-31 22:14:21 +00008077 ++p;
8078 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008079 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008080 decimal = Py_UNICODE_TODECIMAL(ch);
8081 if (decimal >= 0) {
8082 *output++ = '0' + decimal;
8083 ++p;
8084 continue;
8085 }
8086 if (0 < ch && ch < 256) {
8087 *output++ = (char)ch;
8088 ++p;
8089 continue;
8090 }
8091 /* All other characters are considered unencodable */
8092 collstart = p;
8093 collend = p+1;
8094 while (collend < end) {
8095 if ((0 < *collend && *collend < 256) ||
8096 !Py_UNICODE_ISSPACE(*collend) ||
8097 Py_UNICODE_TODECIMAL(*collend))
8098 break;
8099 }
8100 /* cache callback name lookup
8101 * (if not done yet, i.e. it's the first error) */
8102 if (known_errorHandler==-1) {
8103 if ((errors==NULL) || (!strcmp(errors, "strict")))
8104 known_errorHandler = 1;
8105 else if (!strcmp(errors, "replace"))
8106 known_errorHandler = 2;
8107 else if (!strcmp(errors, "ignore"))
8108 known_errorHandler = 3;
8109 else if (!strcmp(errors, "xmlcharrefreplace"))
8110 known_errorHandler = 4;
8111 else
8112 known_errorHandler = 0;
8113 }
8114 switch (known_errorHandler) {
8115 case 1: /* strict */
8116 raise_encode_exception(&exc, encoding, s, length, collstart-s, collend-s, reason);
8117 goto onError;
8118 case 2: /* replace */
8119 for (p = collstart; p < collend; ++p)
8120 *output++ = '?';
8121 /* fall through */
8122 case 3: /* ignore */
8123 p = collend;
8124 break;
8125 case 4: /* xmlcharrefreplace */
8126 /* generate replacement (temporarily (mis)uses p) */
8127 for (p = collstart; p < collend; ++p)
8128 output += sprintf(output, "&#%d;", (int)*p);
8129 p = collend;
8130 break;
8131 default:
8132 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
8133 encoding, reason, s, length, &exc,
8134 collstart-s, collend-s, &newpos);
8135 if (repunicode == NULL)
8136 goto onError;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008137 if (!PyUnicode_Check(repunicode)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00008138 /* Byte results not supported, since they have no decimal property. */
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008139 PyErr_SetString(PyExc_TypeError, "error handler should return unicode");
8140 Py_DECREF(repunicode);
8141 goto onError;
8142 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008143 /* generate replacement */
8144 repsize = PyUnicode_GET_SIZE(repunicode);
8145 for (uni2 = PyUnicode_AS_UNICODE(repunicode); repsize-->0; ++uni2) {
8146 Py_UNICODE ch = *uni2;
8147 if (Py_UNICODE_ISSPACE(ch))
8148 *output++ = ' ';
8149 else {
8150 decimal = Py_UNICODE_TODECIMAL(ch);
8151 if (decimal >= 0)
8152 *output++ = '0' + decimal;
8153 else if (0 < ch && ch < 256)
8154 *output++ = (char)ch;
8155 else {
8156 Py_DECREF(repunicode);
8157 raise_encode_exception(&exc, encoding,
8158 s, length, collstart-s, collend-s, reason);
8159 goto onError;
8160 }
8161 }
8162 }
8163 p = s + newpos;
8164 Py_DECREF(repunicode);
8165 }
Guido van Rossum9e896b32000-04-05 20:11:21 +00008166 }
8167 /* 0-terminate the output string */
8168 *output++ = '\0';
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008169 Py_XDECREF(exc);
8170 Py_XDECREF(errorHandler);
Guido van Rossum9e896b32000-04-05 20:11:21 +00008171 return 0;
8172
Benjamin Peterson29060642009-01-31 22:14:21 +00008173 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008174 Py_XDECREF(exc);
8175 Py_XDECREF(errorHandler);
Guido van Rossum9e896b32000-04-05 20:11:21 +00008176 return -1;
8177}
8178
Guido van Rossumd57fd912000-03-10 22:53:23 +00008179/* --- Helpers ------------------------------------------------------------ */
8180
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008181#include "stringlib/ucs1lib.h"
8182#include "stringlib/fastsearch.h"
8183#include "stringlib/partition.h"
8184#include "stringlib/split.h"
8185#include "stringlib/count.h"
8186#include "stringlib/find.h"
8187#include "stringlib/localeutil.h"
8188#include "stringlib/undef.h"
8189
8190#include "stringlib/ucs2lib.h"
8191#include "stringlib/fastsearch.h"
8192#include "stringlib/partition.h"
8193#include "stringlib/split.h"
8194#include "stringlib/count.h"
8195#include "stringlib/find.h"
8196#include "stringlib/localeutil.h"
8197#include "stringlib/undef.h"
8198
8199#include "stringlib/ucs4lib.h"
8200#include "stringlib/fastsearch.h"
8201#include "stringlib/partition.h"
8202#include "stringlib/split.h"
8203#include "stringlib/count.h"
8204#include "stringlib/find.h"
8205#include "stringlib/localeutil.h"
8206#include "stringlib/undef.h"
8207
8208static Py_ssize_t
8209any_find_slice(Py_ssize_t Py_LOCAL_CALLBACK(ucs1)(const Py_UCS1*, Py_ssize_t,
8210 const Py_UCS1*, Py_ssize_t,
8211 Py_ssize_t, Py_ssize_t),
8212 Py_ssize_t Py_LOCAL_CALLBACK(ucs2)(const Py_UCS2*, Py_ssize_t,
8213 const Py_UCS2*, Py_ssize_t,
8214 Py_ssize_t, Py_ssize_t),
8215 Py_ssize_t Py_LOCAL_CALLBACK(ucs4)(const Py_UCS4*, Py_ssize_t,
8216 const Py_UCS4*, Py_ssize_t,
8217 Py_ssize_t, Py_ssize_t),
8218 PyObject* s1, PyObject* s2,
8219 Py_ssize_t start,
8220 Py_ssize_t end)
8221{
8222 int kind1, kind2, kind;
8223 void *buf1, *buf2;
8224 Py_ssize_t len1, len2, result;
8225
8226 kind1 = PyUnicode_KIND(s1);
8227 kind2 = PyUnicode_KIND(s2);
8228 kind = kind1 > kind2 ? kind1 : kind2;
8229 buf1 = PyUnicode_DATA(s1);
8230 buf2 = PyUnicode_DATA(s2);
8231 if (kind1 != kind)
8232 buf1 = _PyUnicode_AsKind(s1, kind);
8233 if (!buf1)
8234 return -2;
8235 if (kind2 != kind)
8236 buf2 = _PyUnicode_AsKind(s2, kind);
8237 if (!buf2) {
8238 if (kind1 != kind) PyMem_Free(buf1);
8239 return -2;
8240 }
8241 len1 = PyUnicode_GET_LENGTH(s1);
8242 len2 = PyUnicode_GET_LENGTH(s2);
8243
8244 switch(kind) {
8245 case PyUnicode_1BYTE_KIND:
8246 result = ucs1(buf1, len1, buf2, len2, start, end);
8247 break;
8248 case PyUnicode_2BYTE_KIND:
8249 result = ucs2(buf1, len1, buf2, len2, start, end);
8250 break;
8251 case PyUnicode_4BYTE_KIND:
8252 result = ucs4(buf1, len1, buf2, len2, start, end);
8253 break;
8254 default:
8255 assert(0); result = -2;
8256 }
8257
8258 if (kind1 != kind)
8259 PyMem_Free(buf1);
8260 if (kind2 != kind)
8261 PyMem_Free(buf2);
8262
8263 return result;
8264}
8265
8266Py_ssize_t
8267_PyUnicode_InsertThousandsGrouping(int kind, void *data,
8268 Py_ssize_t n_buffer,
8269 void *digits, Py_ssize_t n_digits,
8270 Py_ssize_t min_width,
8271 const char *grouping,
8272 const char *thousands_sep)
8273{
8274 switch(kind) {
8275 case PyUnicode_1BYTE_KIND:
8276 return _PyUnicode_ucs1_InsertThousandsGrouping(
8277 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
8278 min_width, grouping, thousands_sep);
8279 case PyUnicode_2BYTE_KIND:
8280 return _PyUnicode_ucs2_InsertThousandsGrouping(
8281 (Py_UCS2*)data, n_buffer, (Py_UCS2*)digits, n_digits,
8282 min_width, grouping, thousands_sep);
8283 case PyUnicode_4BYTE_KIND:
8284 return _PyUnicode_ucs4_InsertThousandsGrouping(
8285 (Py_UCS4*)data, n_buffer, (Py_UCS4*)digits, n_digits,
8286 min_width, grouping, thousands_sep);
8287 }
8288 assert(0);
8289 return -1;
8290}
8291
8292
Eric Smith8c663262007-08-25 02:26:07 +00008293#include "stringlib/unicodedefs.h"
Thomas Wouters477c8d52006-05-27 19:21:47 +00008294#include "stringlib/fastsearch.h"
Antoine Pitrouf2c54842010-01-13 08:07:53 +00008295
Thomas Wouters477c8d52006-05-27 19:21:47 +00008296#include "stringlib/count.h"
8297#include "stringlib/find.h"
Eric Smith5807c412008-05-11 21:00:57 +00008298
Thomas Wouters477c8d52006-05-27 19:21:47 +00008299/* helper macro to fixup start/end slice values */
Antoine Pitrouf2c54842010-01-13 08:07:53 +00008300#define ADJUST_INDICES(start, end, len) \
8301 if (end > len) \
8302 end = len; \
8303 else if (end < 0) { \
8304 end += len; \
8305 if (end < 0) \
8306 end = 0; \
8307 } \
8308 if (start < 0) { \
8309 start += len; \
8310 if (start < 0) \
8311 start = 0; \
8312 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00008313
Alexander Belopolsky40018472011-02-26 01:02:56 +00008314Py_ssize_t
8315PyUnicode_Count(PyObject *str,
8316 PyObject *substr,
8317 Py_ssize_t start,
8318 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008319{
Martin v. Löwis18e16552006-02-15 17:27:45 +00008320 Py_ssize_t result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00008321 PyUnicodeObject* str_obj;
8322 PyUnicodeObject* sub_obj;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008323 int kind1, kind2, kind;
8324 void *buf1 = NULL, *buf2 = NULL;
8325 Py_ssize_t len1, len2;
Tim Petersced69f82003-09-16 20:30:58 +00008326
Thomas Wouters477c8d52006-05-27 19:21:47 +00008327 str_obj = (PyUnicodeObject*) PyUnicode_FromObject(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008328 if (!str_obj || PyUnicode_READY(str_obj) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008329 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00008330 sub_obj = (PyUnicodeObject*) PyUnicode_FromObject(substr);
Victor Stinnere9a29352011-10-01 02:14:59 +02008331 if (!sub_obj || PyUnicode_READY(sub_obj) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008332 Py_DECREF(str_obj);
8333 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008334 }
Tim Petersced69f82003-09-16 20:30:58 +00008335
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008336 kind1 = PyUnicode_KIND(str_obj);
8337 kind2 = PyUnicode_KIND(sub_obj);
8338 kind = kind1 > kind2 ? kind1 : kind2;
8339 buf1 = PyUnicode_DATA(str_obj);
8340 if (kind1 != kind)
8341 buf1 = _PyUnicode_AsKind((PyObject*)str_obj, kind);
8342 if (!buf1)
8343 goto onError;
8344 buf2 = PyUnicode_DATA(sub_obj);
8345 if (kind2 != kind)
8346 buf2 = _PyUnicode_AsKind((PyObject*)sub_obj, kind);
8347 if (!buf2)
8348 goto onError;
8349 len1 = PyUnicode_GET_LENGTH(str_obj);
8350 len2 = PyUnicode_GET_LENGTH(sub_obj);
8351
8352 ADJUST_INDICES(start, end, len1);
8353 switch(kind) {
8354 case PyUnicode_1BYTE_KIND:
8355 result = ucs1lib_count(
8356 ((Py_UCS1*)buf1) + start, end - start,
8357 buf2, len2, PY_SSIZE_T_MAX
8358 );
8359 break;
8360 case PyUnicode_2BYTE_KIND:
8361 result = ucs2lib_count(
8362 ((Py_UCS2*)buf1) + start, end - start,
8363 buf2, len2, PY_SSIZE_T_MAX
8364 );
8365 break;
8366 case PyUnicode_4BYTE_KIND:
8367 result = ucs4lib_count(
8368 ((Py_UCS4*)buf1) + start, end - start,
8369 buf2, len2, PY_SSIZE_T_MAX
8370 );
8371 break;
8372 default:
8373 assert(0); result = 0;
8374 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00008375
8376 Py_DECREF(sub_obj);
8377 Py_DECREF(str_obj);
8378
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008379 if (kind1 != kind)
8380 PyMem_Free(buf1);
8381 if (kind2 != kind)
8382 PyMem_Free(buf2);
8383
Guido van Rossumd57fd912000-03-10 22:53:23 +00008384 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008385 onError:
8386 Py_DECREF(sub_obj);
8387 Py_DECREF(str_obj);
8388 if (kind1 != kind && buf1)
8389 PyMem_Free(buf1);
8390 if (kind2 != kind && buf2)
8391 PyMem_Free(buf2);
8392 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008393}
8394
Alexander Belopolsky40018472011-02-26 01:02:56 +00008395Py_ssize_t
8396PyUnicode_Find(PyObject *str,
8397 PyObject *sub,
8398 Py_ssize_t start,
8399 Py_ssize_t end,
8400 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008401{
Martin v. Löwis18e16552006-02-15 17:27:45 +00008402 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00008403
Guido van Rossumd57fd912000-03-10 22:53:23 +00008404 str = PyUnicode_FromObject(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008405 if (!str || PyUnicode_READY(str) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008406 return -2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00008407 sub = PyUnicode_FromObject(sub);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008408 if (!sub || PyUnicode_READY(sub) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008409 Py_DECREF(str);
8410 return -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008411 }
Tim Petersced69f82003-09-16 20:30:58 +00008412
Thomas Wouters477c8d52006-05-27 19:21:47 +00008413 if (direction > 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008414 result = any_find_slice(
8415 ucs1lib_find_slice, ucs2lib_find_slice, ucs4lib_find_slice,
8416 str, sub, start, end
Thomas Wouters477c8d52006-05-27 19:21:47 +00008417 );
8418 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008419 result = any_find_slice(
8420 ucs1lib_rfind_slice, ucs2lib_rfind_slice, ucs4lib_rfind_slice,
8421 str, sub, start, end
Thomas Wouters477c8d52006-05-27 19:21:47 +00008422 );
8423
Guido van Rossumd57fd912000-03-10 22:53:23 +00008424 Py_DECREF(str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00008425 Py_DECREF(sub);
8426
Guido van Rossumd57fd912000-03-10 22:53:23 +00008427 return result;
8428}
8429
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008430Py_ssize_t
8431PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
8432 Py_ssize_t start, Py_ssize_t end,
8433 int direction)
8434{
8435 char *result;
8436 int kind;
8437 if (PyUnicode_READY(str) == -1)
8438 return -2;
Victor Stinner267aa242011-10-02 01:08:37 +02008439 if (start < 0 || end < 0) {
8440 PyErr_SetString(PyExc_IndexError, "string index out of range");
8441 return -2;
8442 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008443 if (end > PyUnicode_GET_LENGTH(str))
8444 end = PyUnicode_GET_LENGTH(str);
8445 kind = PyUnicode_KIND(str);
8446 result = findchar(PyUnicode_1BYTE_DATA(str)
8447 + PyUnicode_KIND_SIZE(kind, start),
8448 kind,
8449 end-start, ch, direction);
8450 if (!result)
8451 return -1;
8452 return (result-(char*)PyUnicode_DATA(str)) >> (kind-1);
8453}
8454
Alexander Belopolsky40018472011-02-26 01:02:56 +00008455static int
8456tailmatch(PyUnicodeObject *self,
8457 PyUnicodeObject *substring,
8458 Py_ssize_t start,
8459 Py_ssize_t end,
8460 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008461{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008462 int kind_self;
8463 int kind_sub;
8464 void *data_self;
8465 void *data_sub;
8466 Py_ssize_t offset;
8467 Py_ssize_t i;
8468 Py_ssize_t end_sub;
8469
8470 if (PyUnicode_READY(self) == -1 ||
8471 PyUnicode_READY(substring) == -1)
8472 return 0;
8473
8474 if (PyUnicode_GET_LENGTH(substring) == 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008475 return 1;
8476
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008477 ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
8478 end -= PyUnicode_GET_LENGTH(substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008479 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00008480 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008481
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008482 kind_self = PyUnicode_KIND(self);
8483 data_self = PyUnicode_DATA(self);
8484 kind_sub = PyUnicode_KIND(substring);
8485 data_sub = PyUnicode_DATA(substring);
8486 end_sub = PyUnicode_GET_LENGTH(substring) - 1;
8487
8488 if (direction > 0)
8489 offset = end;
8490 else
8491 offset = start;
8492
8493 if (PyUnicode_READ(kind_self, data_self, offset) ==
8494 PyUnicode_READ(kind_sub, data_sub, 0) &&
8495 PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
8496 PyUnicode_READ(kind_sub, data_sub, end_sub)) {
8497 /* If both are of the same kind, memcmp is sufficient */
8498 if (kind_self == kind_sub) {
8499 return ! memcmp((char *)data_self +
8500 (offset * PyUnicode_CHARACTER_SIZE(substring)),
8501 data_sub,
8502 PyUnicode_GET_LENGTH(substring) *
8503 PyUnicode_CHARACTER_SIZE(substring));
8504 }
8505 /* otherwise we have to compare each character by first accesing it */
8506 else {
8507 /* We do not need to compare 0 and len(substring)-1 because
8508 the if statement above ensured already that they are equal
8509 when we end up here. */
8510 // TODO: honor direction and do a forward or backwards search
8511 for (i = 1; i < end_sub; ++i) {
8512 if (PyUnicode_READ(kind_self, data_self, offset + i) !=
8513 PyUnicode_READ(kind_sub, data_sub, i))
8514 return 0;
8515 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008516 return 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008517 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008518 }
8519
8520 return 0;
8521}
8522
Alexander Belopolsky40018472011-02-26 01:02:56 +00008523Py_ssize_t
8524PyUnicode_Tailmatch(PyObject *str,
8525 PyObject *substr,
8526 Py_ssize_t start,
8527 Py_ssize_t end,
8528 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008529{
Martin v. Löwis18e16552006-02-15 17:27:45 +00008530 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00008531
Guido van Rossumd57fd912000-03-10 22:53:23 +00008532 str = PyUnicode_FromObject(str);
8533 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008534 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008535 substr = PyUnicode_FromObject(substr);
8536 if (substr == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008537 Py_DECREF(str);
8538 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008539 }
Tim Petersced69f82003-09-16 20:30:58 +00008540
Guido van Rossumd57fd912000-03-10 22:53:23 +00008541 result = tailmatch((PyUnicodeObject *)str,
Benjamin Peterson29060642009-01-31 22:14:21 +00008542 (PyUnicodeObject *)substr,
8543 start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008544 Py_DECREF(str);
8545 Py_DECREF(substr);
8546 return result;
8547}
8548
Guido van Rossumd57fd912000-03-10 22:53:23 +00008549/* Apply fixfct filter to the Unicode object self and return a
8550 reference to the modified object */
8551
Alexander Belopolsky40018472011-02-26 01:02:56 +00008552static PyObject *
8553fixup(PyUnicodeObject *self,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008554 Py_UCS4 (*fixfct)(PyUnicodeObject *s))
Guido van Rossumd57fd912000-03-10 22:53:23 +00008555{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008556 PyObject *u;
8557 Py_UCS4 maxchar_old, maxchar_new = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008558
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008559 if (PyUnicode_READY(self) == -1)
8560 return NULL;
8561 maxchar_old = PyUnicode_MAX_CHAR_VALUE(self);
8562 u = PyUnicode_New(PyUnicode_GET_LENGTH(self),
8563 maxchar_old);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008564 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008565 return NULL;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00008566
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008567 Py_MEMCPY(PyUnicode_1BYTE_DATA(u), PyUnicode_1BYTE_DATA(self),
8568 PyUnicode_GET_LENGTH(u) * PyUnicode_CHARACTER_SIZE(u));
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00008569
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008570 /* fix functions return the new maximum character in a string,
8571 if the kind of the resulting unicode object does not change,
8572 everything is fine. Otherwise we need to change the string kind
8573 and re-run the fix function. */
8574 maxchar_new = fixfct((PyUnicodeObject*)u);
8575 if (maxchar_new == 0)
8576 /* do nothing, keep maxchar_new at 0 which means no changes. */;
8577 else if (maxchar_new <= 127)
8578 maxchar_new = 127;
8579 else if (maxchar_new <= 255)
8580 maxchar_new = 255;
8581 else if (maxchar_new <= 65535)
8582 maxchar_new = 65535;
8583 else
8584 maxchar_new = 1114111; /* 0x10ffff */
8585
8586 if (!maxchar_new && PyUnicode_CheckExact(self)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008587 /* fixfct should return TRUE if it modified the buffer. If
8588 FALSE, return a reference to the original buffer instead
8589 (to save space, not time) */
8590 Py_INCREF(self);
8591 Py_DECREF(u);
8592 return (PyObject*) self;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008593 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008594 else if (maxchar_new == maxchar_old) {
8595 return u;
8596 }
8597 else {
8598 /* In case the maximum character changed, we need to
8599 convert the string to the new category. */
Victor Stinner6c7a52a2011-09-28 21:39:17 +02008600 PyObject *v = PyUnicode_New(PyUnicode_GET_LENGTH(self), maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008601 if (v == NULL) {
8602 Py_DECREF(u);
8603 return NULL;
8604 }
8605 if (maxchar_new > maxchar_old) {
8606 /* If the maxchar increased so that the kind changed, not all
8607 characters are representable anymore and we need to fix the
8608 string again. This only happens in very few cases. */
Victor Stinner157f83f2011-09-28 21:41:31 +02008609 if (PyUnicode_CopyCharacters(v, 0,
8610 (PyObject*)self, 0,
Victor Stinner6c7a52a2011-09-28 21:39:17 +02008611 PyUnicode_GET_LENGTH(self)) < 0)
8612 {
8613 Py_DECREF(u);
8614 return NULL;
8615 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008616 maxchar_old = fixfct((PyUnicodeObject*)v);
8617 assert(maxchar_old > 0 && maxchar_old <= maxchar_new);
8618 }
Victor Stinner6c7a52a2011-09-28 21:39:17 +02008619 else {
Victor Stinner157f83f2011-09-28 21:41:31 +02008620 if (PyUnicode_CopyCharacters(v, 0,
8621 u, 0,
Victor Stinner6c7a52a2011-09-28 21:39:17 +02008622 PyUnicode_GET_LENGTH(self)) < 0)
8623 {
8624 Py_DECREF(u);
8625 return NULL;
8626 }
8627 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008628
8629 Py_DECREF(u);
8630 return v;
8631 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008632}
8633
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008634static Py_UCS4
Alexander Belopolsky40018472011-02-26 01:02:56 +00008635fixupper(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008636{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008637 /* No need to call PyUnicode_READY(self) because this function is only
8638 called as a callback from fixup() which does it already. */
8639 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
8640 const int kind = PyUnicode_KIND(self);
8641 void *data = PyUnicode_DATA(self);
8642 int touched = 0;
8643 Py_UCS4 maxchar = 0;
8644 Py_ssize_t i;
Tim Petersced69f82003-09-16 20:30:58 +00008645
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008646 for (i = 0; i < len; ++i) {
8647 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
8648 const Py_UCS4 up = Py_UNICODE_TOUPPER(ch);
8649 if (up != ch) {
8650 if (up > maxchar)
8651 maxchar = up;
8652 PyUnicode_WRITE(kind, data, i, up);
8653 touched = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00008654 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008655 else if (ch > maxchar)
8656 maxchar = ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008657 }
8658
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008659 if (touched)
8660 return maxchar;
8661 else
8662 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008663}
8664
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008665static Py_UCS4
Alexander Belopolsky40018472011-02-26 01:02:56 +00008666fixlower(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008667{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008668 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
8669 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
8670 const int kind = PyUnicode_KIND(self);
8671 void *data = PyUnicode_DATA(self);
8672 int touched = 0;
8673 Py_UCS4 maxchar = 0;
8674 Py_ssize_t i;
Tim Petersced69f82003-09-16 20:30:58 +00008675
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008676 for(i = 0; i < len; ++i) {
8677 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
8678 const Py_UCS4 lo = Py_UNICODE_TOLOWER(ch);
8679 if (lo != ch) {
8680 if (lo > maxchar)
8681 maxchar = lo;
8682 PyUnicode_WRITE(kind, data, i, lo);
8683 touched = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00008684 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008685 else if (ch > maxchar)
8686 maxchar = ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008687 }
8688
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008689 if (touched)
8690 return maxchar;
8691 else
8692 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008693}
8694
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008695static Py_UCS4
Alexander Belopolsky40018472011-02-26 01:02:56 +00008696fixswapcase(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008697{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008698 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
8699 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
8700 const int kind = PyUnicode_KIND(self);
8701 void *data = PyUnicode_DATA(self);
8702 int touched = 0;
8703 Py_UCS4 maxchar = 0;
8704 Py_ssize_t i;
Tim Petersced69f82003-09-16 20:30:58 +00008705
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008706 for(i = 0; i < len; ++i) {
8707 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
8708 Py_UCS4 nu = 0;
8709
8710 if (Py_UNICODE_ISUPPER(ch))
8711 nu = Py_UNICODE_TOLOWER(ch);
8712 else if (Py_UNICODE_ISLOWER(ch))
8713 nu = Py_UNICODE_TOUPPER(ch);
8714
8715 if (nu != 0) {
8716 if (nu > maxchar)
8717 maxchar = nu;
8718 PyUnicode_WRITE(kind, data, i, nu);
8719 touched = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008720 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008721 else if (ch > maxchar)
8722 maxchar = ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008723 }
8724
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008725 if (touched)
8726 return maxchar;
8727 else
8728 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008729}
8730
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008731static Py_UCS4
Alexander Belopolsky40018472011-02-26 01:02:56 +00008732fixcapitalize(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008733{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008734 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
8735 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
8736 const int kind = PyUnicode_KIND(self);
8737 void *data = PyUnicode_DATA(self);
8738 int touched = 0;
8739 Py_UCS4 maxchar = 0;
8740 Py_ssize_t i = 0;
8741 Py_UCS4 ch;
Tim Petersced69f82003-09-16 20:30:58 +00008742
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00008743 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008744 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008745
8746 ch = PyUnicode_READ(kind, data, i);
8747 if (!Py_UNICODE_ISUPPER(ch)) {
8748 maxchar = Py_UNICODE_TOUPPER(ch);
8749 PyUnicode_WRITE(kind, data, i, maxchar);
8750 touched = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008751 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008752 ++i;
8753 for(; i < len; ++i) {
8754 ch = PyUnicode_READ(kind, data, i);
8755 if (!Py_UNICODE_ISLOWER(ch)) {
8756 const Py_UCS4 lo = Py_UNICODE_TOLOWER(ch);
8757 if (lo > maxchar)
8758 maxchar = lo;
8759 PyUnicode_WRITE(kind, data, i, lo);
8760 touched = 1;
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00008761 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008762 else if (ch > maxchar)
8763 maxchar = ch;
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00008764 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008765
8766 if (touched)
8767 return maxchar;
8768 else
8769 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008770}
8771
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008772static Py_UCS4
Alexander Belopolsky40018472011-02-26 01:02:56 +00008773fixtitle(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008774{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008775 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
8776 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
8777 const int kind = PyUnicode_KIND(self);
8778 void *data = PyUnicode_DATA(self);
8779 Py_UCS4 maxchar = 0;
8780 Py_ssize_t i = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008781 int previous_is_cased;
8782
8783 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008784 if (len == 1) {
8785 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
8786 const Py_UCS4 ti = Py_UNICODE_TOTITLE(ch);
8787 if (ti != ch) {
8788 PyUnicode_WRITE(kind, data, i, ti);
8789 return ti;
Benjamin Peterson29060642009-01-31 22:14:21 +00008790 }
8791 else
8792 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008793 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008794 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008795 for(; i < len; ++i) {
8796 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
8797 Py_UCS4 nu;
Tim Petersced69f82003-09-16 20:30:58 +00008798
Benjamin Peterson29060642009-01-31 22:14:21 +00008799 if (previous_is_cased)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008800 nu = Py_UNICODE_TOLOWER(ch);
Benjamin Peterson29060642009-01-31 22:14:21 +00008801 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008802 nu = Py_UNICODE_TOTITLE(ch);
8803
8804 if (nu > maxchar)
8805 maxchar = nu;
8806 PyUnicode_WRITE(kind, data, i, nu);
Tim Petersced69f82003-09-16 20:30:58 +00008807
Benjamin Peterson29060642009-01-31 22:14:21 +00008808 if (Py_UNICODE_ISLOWER(ch) ||
8809 Py_UNICODE_ISUPPER(ch) ||
8810 Py_UNICODE_ISTITLE(ch))
8811 previous_is_cased = 1;
8812 else
8813 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008814 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008815 return maxchar;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008816}
8817
Tim Peters8ce9f162004-08-27 01:49:32 +00008818PyObject *
8819PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008820{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008821 PyObject *sep = NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00008822 Py_ssize_t seplen = 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008823 PyObject *res = NULL; /* the result */
Tim Peters05eba1f2004-08-27 21:32:02 +00008824 PyObject *fseq; /* PySequence_Fast(seq) */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00008825 Py_ssize_t seqlen; /* len(fseq) -- number of items in sequence */
8826 PyObject **items;
Tim Peters8ce9f162004-08-27 01:49:32 +00008827 PyObject *item;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008828 Py_ssize_t sz, i, res_offset;
8829 Py_UCS4 maxchar = 0;
8830 Py_UCS4 item_maxchar;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008831
Tim Peters05eba1f2004-08-27 21:32:02 +00008832 fseq = PySequence_Fast(seq, "");
8833 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008834 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00008835 }
8836
Antoine Pitrouaf14b792008-08-07 21:50:41 +00008837 /* NOTE: the following code can't call back into Python code,
8838 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00008839 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00008840
Tim Peters05eba1f2004-08-27 21:32:02 +00008841 seqlen = PySequence_Fast_GET_SIZE(fseq);
8842 /* If empty sequence, return u"". */
8843 if (seqlen == 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008844 res = PyUnicode_New(0, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008845 goto Done;
Tim Peters05eba1f2004-08-27 21:32:02 +00008846 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00008847 items = PySequence_Fast_ITEMS(fseq);
Tim Peters05eba1f2004-08-27 21:32:02 +00008848 /* If singleton sequence with an exact Unicode, return that. */
8849 if (seqlen == 1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008850 item = items[0];
8851 if (PyUnicode_CheckExact(item)) {
8852 Py_INCREF(item);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008853 res = item;
Benjamin Peterson29060642009-01-31 22:14:21 +00008854 goto Done;
8855 }
Tim Peters8ce9f162004-08-27 01:49:32 +00008856 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00008857 else {
8858 /* Set up sep and seplen */
8859 if (separator == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008860 /* fall back to a blank space separator */
8861 sep = PyUnicode_FromOrdinal(' ');
Victor Stinnere9a29352011-10-01 02:14:59 +02008862 if (!sep)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008863 goto onError;
Tim Peters05eba1f2004-08-27 21:32:02 +00008864 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00008865 else {
8866 if (!PyUnicode_Check(separator)) {
8867 PyErr_Format(PyExc_TypeError,
8868 "separator: expected str instance,"
8869 " %.80s found",
8870 Py_TYPE(separator)->tp_name);
8871 goto onError;
8872 }
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02008873 if (PyUnicode_READY(separator))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008874 goto onError;
8875 sep = separator;
8876 seplen = PyUnicode_GET_LENGTH(separator);
8877 maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
8878 /* inc refcount to keep this code path symetric with the
8879 above case of a blank separator */
8880 Py_INCREF(sep);
Tim Peters05eba1f2004-08-27 21:32:02 +00008881 }
8882 }
8883
Antoine Pitrouaf14b792008-08-07 21:50:41 +00008884 /* There are at least two things to join, or else we have a subclass
8885 * of str in the sequence.
8886 * Do a pre-pass to figure out the total amount of space we'll
8887 * need (sz), and see whether all argument are strings.
8888 */
8889 sz = 0;
8890 for (i = 0; i < seqlen; i++) {
8891 const Py_ssize_t old_sz = sz;
8892 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00008893 if (!PyUnicode_Check(item)) {
8894 PyErr_Format(PyExc_TypeError,
8895 "sequence item %zd: expected str instance,"
8896 " %.80s found",
8897 i, Py_TYPE(item)->tp_name);
8898 goto onError;
8899 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008900 if (PyUnicode_READY(item) == -1)
8901 goto onError;
8902 sz += PyUnicode_GET_LENGTH(item);
8903 item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
8904 if (item_maxchar > maxchar)
8905 maxchar = item_maxchar;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00008906 if (i != 0)
8907 sz += seplen;
8908 if (sz < old_sz || sz > PY_SSIZE_T_MAX) {
8909 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +00008910 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +00008911 goto onError;
8912 }
8913 }
Tim Petersced69f82003-09-16 20:30:58 +00008914
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008915 res = PyUnicode_New(sz, maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00008916 if (res == NULL)
8917 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +00008918
Antoine Pitrouaf14b792008-08-07 21:50:41 +00008919 /* Catenate everything. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008920 for (i = 0, res_offset = 0; i < seqlen; ++i) {
Victor Stinner9ce5a832011-10-03 23:36:02 +02008921 Py_ssize_t itemlen, copied;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00008922 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00008923 /* Copy item, and maybe the separator. */
Victor Stinner9ce5a832011-10-03 23:36:02 +02008924 if (i && seplen != 0) {
8925 copied = PyUnicode_CopyCharacters(res, res_offset,
8926 sep, 0, seplen);
8927 if (copied < 0)
Victor Stinner6c7a52a2011-09-28 21:39:17 +02008928 goto onError;
Victor Stinner9ce5a832011-10-03 23:36:02 +02008929#ifdef Py_DEBUG
8930 res_offset += copied;
8931#else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008932 res_offset += seplen;
Victor Stinner9ce5a832011-10-03 23:36:02 +02008933#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00008934 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02008935 itemlen = PyUnicode_GET_LENGTH(item);
8936 if (itemlen != 0) {
8937 copied = PyUnicode_CopyCharacters(res, res_offset,
8938 item, 0, itemlen);
8939 if (copied < 0)
8940 goto onError;
8941#ifdef Py_DEBUG
8942 res_offset += copied;
8943#else
8944 res_offset += itemlen;
8945#endif
8946 }
Tim Peters05eba1f2004-08-27 21:32:02 +00008947 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008948 assert(res_offset == PyUnicode_GET_LENGTH(res));
Tim Peters8ce9f162004-08-27 01:49:32 +00008949
Benjamin Peterson29060642009-01-31 22:14:21 +00008950 Done:
Tim Peters05eba1f2004-08-27 21:32:02 +00008951 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008952 Py_XDECREF(sep);
8953 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008954
Benjamin Peterson29060642009-01-31 22:14:21 +00008955 onError:
Tim Peters05eba1f2004-08-27 21:32:02 +00008956 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008957 Py_XDECREF(sep);
Tim Peters8ce9f162004-08-27 01:49:32 +00008958 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008959 return NULL;
8960}
8961
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008962#define FILL(kind, data, value, start, length) \
8963 do { \
8964 Py_ssize_t i_ = 0; \
8965 assert(kind != PyUnicode_WCHAR_KIND); \
8966 switch ((kind)) { \
8967 case PyUnicode_1BYTE_KIND: { \
8968 unsigned char * to_ = (unsigned char *)((data)) + (start); \
8969 memset(to_, (unsigned char)value, length); \
8970 break; \
8971 } \
8972 case PyUnicode_2BYTE_KIND: { \
8973 Py_UCS2 * to_ = (Py_UCS2 *)((data)) + (start); \
8974 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
8975 break; \
8976 } \
8977 default: { \
8978 Py_UCS4 * to_ = (Py_UCS4 *)((data)) + (start); \
8979 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
8980 break; \
8981 } \
8982 } \
8983 } while (0)
8984
Alexander Belopolsky40018472011-02-26 01:02:56 +00008985static PyUnicodeObject *
8986pad(PyUnicodeObject *self,
8987 Py_ssize_t left,
8988 Py_ssize_t right,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008989 Py_UCS4 fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008990{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008991 PyObject *u;
8992 Py_UCS4 maxchar;
Victor Stinner6c7a52a2011-09-28 21:39:17 +02008993 int kind;
8994 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008995
8996 if (left < 0)
8997 left = 0;
8998 if (right < 0)
8999 right = 0;
9000
Tim Peters7a29bd52001-09-12 03:03:31 +00009001 if (left == 0 && right == 0 && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00009002 Py_INCREF(self);
9003 return self;
9004 }
9005
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009006 if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
9007 right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +00009008 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
9009 return NULL;
9010 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009011 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
9012 if (fill > maxchar)
9013 maxchar = fill;
9014 u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009015 if (!u)
9016 return NULL;
9017
9018 kind = PyUnicode_KIND(u);
9019 data = PyUnicode_DATA(u);
9020 if (left)
9021 FILL(kind, data, fill, 0, left);
9022 if (right)
9023 FILL(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
Victor Stinner157f83f2011-09-28 21:41:31 +02009024 if (PyUnicode_CopyCharacters(u, left,
9025 (PyObject*)self, 0,
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009026 _PyUnicode_LENGTH(self)) < 0)
9027 {
9028 Py_DECREF(u);
9029 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009030 }
9031
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009032 return (PyUnicodeObject*)u;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009033}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009034#undef FILL
Guido van Rossumd57fd912000-03-10 22:53:23 +00009035
Alexander Belopolsky40018472011-02-26 01:02:56 +00009036PyObject *
9037PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009038{
Guido van Rossumd57fd912000-03-10 22:53:23 +00009039 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009040
9041 string = PyUnicode_FromObject(string);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009042 if (string == NULL || PyUnicode_READY(string) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00009043 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009044
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009045 switch(PyUnicode_KIND(string)) {
9046 case PyUnicode_1BYTE_KIND:
9047 list = ucs1lib_splitlines(
9048 (PyObject*) string, PyUnicode_1BYTE_DATA(string),
9049 PyUnicode_GET_LENGTH(string), keepends);
9050 break;
9051 case PyUnicode_2BYTE_KIND:
9052 list = ucs2lib_splitlines(
9053 (PyObject*) string, PyUnicode_2BYTE_DATA(string),
9054 PyUnicode_GET_LENGTH(string), keepends);
9055 break;
9056 case PyUnicode_4BYTE_KIND:
9057 list = ucs4lib_splitlines(
9058 (PyObject*) string, PyUnicode_4BYTE_DATA(string),
9059 PyUnicode_GET_LENGTH(string), keepends);
9060 break;
9061 default:
9062 assert(0);
9063 list = 0;
9064 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009065 Py_DECREF(string);
9066 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009067}
9068
Alexander Belopolsky40018472011-02-26 01:02:56 +00009069static PyObject *
9070split(PyUnicodeObject *self,
9071 PyUnicodeObject *substring,
9072 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009073{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009074 int kind1, kind2, kind;
9075 void *buf1, *buf2;
9076 Py_ssize_t len1, len2;
9077 PyObject* out;
9078
Guido van Rossumd57fd912000-03-10 22:53:23 +00009079 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00009080 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009081
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009082 if (PyUnicode_READY(self) == -1)
9083 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009084
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009085 if (substring == NULL)
9086 switch(PyUnicode_KIND(self)) {
9087 case PyUnicode_1BYTE_KIND:
9088 return ucs1lib_split_whitespace(
9089 (PyObject*) self, PyUnicode_1BYTE_DATA(self),
9090 PyUnicode_GET_LENGTH(self), maxcount
9091 );
9092 case PyUnicode_2BYTE_KIND:
9093 return ucs2lib_split_whitespace(
9094 (PyObject*) self, PyUnicode_2BYTE_DATA(self),
9095 PyUnicode_GET_LENGTH(self), maxcount
9096 );
9097 case PyUnicode_4BYTE_KIND:
9098 return ucs4lib_split_whitespace(
9099 (PyObject*) self, PyUnicode_4BYTE_DATA(self),
9100 PyUnicode_GET_LENGTH(self), maxcount
9101 );
9102 default:
9103 assert(0);
9104 return NULL;
9105 }
9106
9107 if (PyUnicode_READY(substring) == -1)
9108 return NULL;
9109
9110 kind1 = PyUnicode_KIND(self);
9111 kind2 = PyUnicode_KIND(substring);
9112 kind = kind1 > kind2 ? kind1 : kind2;
9113 buf1 = PyUnicode_DATA(self);
9114 buf2 = PyUnicode_DATA(substring);
9115 if (kind1 != kind)
9116 buf1 = _PyUnicode_AsKind((PyObject*)self, kind);
9117 if (!buf1)
9118 return NULL;
9119 if (kind2 != kind)
9120 buf2 = _PyUnicode_AsKind((PyObject*)substring, kind);
9121 if (!buf2) {
9122 if (kind1 != kind) PyMem_Free(buf1);
9123 return NULL;
9124 }
9125 len1 = PyUnicode_GET_LENGTH(self);
9126 len2 = PyUnicode_GET_LENGTH(substring);
9127
9128 switch(kind) {
9129 case PyUnicode_1BYTE_KIND:
9130 out = ucs1lib_split(
9131 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
9132 break;
9133 case PyUnicode_2BYTE_KIND:
9134 out = ucs2lib_split(
9135 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
9136 break;
9137 case PyUnicode_4BYTE_KIND:
9138 out = ucs4lib_split(
9139 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
9140 break;
9141 default:
9142 out = NULL;
9143 }
9144 if (kind1 != kind)
9145 PyMem_Free(buf1);
9146 if (kind2 != kind)
9147 PyMem_Free(buf2);
9148 return out;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009149}
9150
Alexander Belopolsky40018472011-02-26 01:02:56 +00009151static PyObject *
9152rsplit(PyUnicodeObject *self,
9153 PyUnicodeObject *substring,
9154 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009155{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009156 int kind1, kind2, kind;
9157 void *buf1, *buf2;
9158 Py_ssize_t len1, len2;
9159 PyObject* out;
9160
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009161 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00009162 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009163
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009164 if (PyUnicode_READY(self) == -1)
9165 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009166
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009167 if (substring == NULL)
9168 switch(PyUnicode_KIND(self)) {
9169 case PyUnicode_1BYTE_KIND:
9170 return ucs1lib_rsplit_whitespace(
9171 (PyObject*) self, PyUnicode_1BYTE_DATA(self),
9172 PyUnicode_GET_LENGTH(self), maxcount
9173 );
9174 case PyUnicode_2BYTE_KIND:
9175 return ucs2lib_rsplit_whitespace(
9176 (PyObject*) self, PyUnicode_2BYTE_DATA(self),
9177 PyUnicode_GET_LENGTH(self), maxcount
9178 );
9179 case PyUnicode_4BYTE_KIND:
9180 return ucs4lib_rsplit_whitespace(
9181 (PyObject*) self, PyUnicode_4BYTE_DATA(self),
9182 PyUnicode_GET_LENGTH(self), maxcount
9183 );
9184 default:
9185 assert(0);
9186 return NULL;
9187 }
9188
9189 if (PyUnicode_READY(substring) == -1)
9190 return NULL;
9191
9192 kind1 = PyUnicode_KIND(self);
9193 kind2 = PyUnicode_KIND(substring);
9194 kind = kind1 > kind2 ? kind1 : kind2;
9195 buf1 = PyUnicode_DATA(self);
9196 buf2 = PyUnicode_DATA(substring);
9197 if (kind1 != kind)
9198 buf1 = _PyUnicode_AsKind((PyObject*)self, kind);
9199 if (!buf1)
9200 return NULL;
9201 if (kind2 != kind)
9202 buf2 = _PyUnicode_AsKind((PyObject*)substring, kind);
9203 if (!buf2) {
9204 if (kind1 != kind) PyMem_Free(buf1);
9205 return NULL;
9206 }
9207 len1 = PyUnicode_GET_LENGTH(self);
9208 len2 = PyUnicode_GET_LENGTH(substring);
9209
9210 switch(kind) {
9211 case PyUnicode_1BYTE_KIND:
9212 out = ucs1lib_rsplit(
9213 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
9214 break;
9215 case PyUnicode_2BYTE_KIND:
9216 out = ucs2lib_rsplit(
9217 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
9218 break;
9219 case PyUnicode_4BYTE_KIND:
9220 out = ucs4lib_rsplit(
9221 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
9222 break;
9223 default:
9224 out = NULL;
9225 }
9226 if (kind1 != kind)
9227 PyMem_Free(buf1);
9228 if (kind2 != kind)
9229 PyMem_Free(buf2);
9230 return out;
9231}
9232
9233static Py_ssize_t
9234anylib_find(int kind, void *buf1, Py_ssize_t len1,
9235 void *buf2, Py_ssize_t len2, Py_ssize_t offset)
9236{
9237 switch(kind) {
9238 case PyUnicode_1BYTE_KIND:
9239 return ucs1lib_find(buf1, len1, buf2, len2, offset);
9240 case PyUnicode_2BYTE_KIND:
9241 return ucs2lib_find(buf1, len1, buf2, len2, offset);
9242 case PyUnicode_4BYTE_KIND:
9243 return ucs4lib_find(buf1, len1, buf2, len2, offset);
9244 }
9245 assert(0);
9246 return -1;
9247}
9248
9249static Py_ssize_t
9250anylib_count(int kind, void* sbuf, Py_ssize_t slen,
9251 void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
9252{
9253 switch(kind) {
9254 case PyUnicode_1BYTE_KIND:
9255 return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
9256 case PyUnicode_2BYTE_KIND:
9257 return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
9258 case PyUnicode_4BYTE_KIND:
9259 return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
9260 }
9261 assert(0);
9262 return 0;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009263}
9264
Alexander Belopolsky40018472011-02-26 01:02:56 +00009265static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009266replace(PyObject *self, PyObject *str1,
9267 PyObject *str2, Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009268{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009269 PyObject *u;
9270 char *sbuf = PyUnicode_DATA(self);
9271 char *buf1 = PyUnicode_DATA(str1);
9272 char *buf2 = PyUnicode_DATA(str2);
9273 int srelease = 0, release1 = 0, release2 = 0;
9274 int skind = PyUnicode_KIND(self);
9275 int kind1 = PyUnicode_KIND(str1);
9276 int kind2 = PyUnicode_KIND(str2);
9277 Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
9278 Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
9279 Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009280
9281 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009282 maxcount = PY_SSIZE_T_MAX;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009283 else if (maxcount == 0 || slen == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009284 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009285
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009286 if (skind < kind1)
9287 /* substring too wide to be present */
9288 goto nothing;
9289
9290 if (len1 == len2) {
Antoine Pitroucbfdee32010-01-13 08:58:08 +00009291 Py_ssize_t i;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009292 /* same length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009293 if (len1 == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009294 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009295 if (len1 == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00009296 /* replace characters */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009297 Py_UCS4 u1, u2, maxchar;
9298 int mayshrink, rkind;
9299 u1 = PyUnicode_READ_CHAR(str1, 0);
9300 if (!findchar(sbuf, PyUnicode_KIND(self),
9301 slen, u1, 1))
Thomas Wouters477c8d52006-05-27 19:21:47 +00009302 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009303 u2 = PyUnicode_READ_CHAR(str2, 0);
9304 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
9305 /* Replacing u1 with u2 may cause a maxchar reduction in the
9306 result string. */
9307 mayshrink = maxchar > 127;
9308 if (u2 > maxchar) {
9309 maxchar = u2;
9310 mayshrink = 0;
9311 }
9312 u = PyUnicode_New(slen, maxchar);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009313 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009314 goto error;
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009315 if (PyUnicode_CopyCharacters(u, 0,
9316 (PyObject*)self, 0, slen) < 0)
9317 {
9318 Py_DECREF(u);
9319 return NULL;
9320 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009321 rkind = PyUnicode_KIND(u);
9322 for (i = 0; i < PyUnicode_GET_LENGTH(u); i++)
9323 if (PyUnicode_READ(rkind, PyUnicode_DATA(u), i) == u1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00009324 if (--maxcount < 0)
9325 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009326 PyUnicode_WRITE(rkind, PyUnicode_DATA(u), i, u2);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009327 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009328 if (mayshrink) {
9329 PyObject *tmp = u;
9330 u = PyUnicode_FromKindAndData(rkind, PyUnicode_DATA(tmp),
9331 PyUnicode_GET_LENGTH(tmp));
9332 Py_DECREF(tmp);
9333 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009334 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009335 int rkind = skind;
9336 char *res;
9337 if (kind1 < rkind) {
9338 /* widen substring */
9339 buf1 = _PyUnicode_AsKind(str1, rkind);
9340 if (!buf1) goto error;
9341 release1 = 1;
9342 }
9343 i = anylib_find(rkind, sbuf, slen, buf1, len1, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009344 if (i < 0)
9345 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009346 if (rkind > kind2) {
9347 /* widen replacement */
9348 buf2 = _PyUnicode_AsKind(str2, rkind);
9349 if (!buf2) goto error;
9350 release2 = 1;
9351 }
9352 else if (rkind < kind2) {
9353 /* widen self and buf1 */
9354 rkind = kind2;
9355 if (release1) PyMem_Free(buf1);
9356 sbuf = _PyUnicode_AsKind(self, rkind);
9357 if (!sbuf) goto error;
9358 srelease = 1;
9359 buf1 = _PyUnicode_AsKind(str1, rkind);
9360 if (!buf1) goto error;
9361 release1 = 1;
9362 }
9363 res = PyMem_Malloc(PyUnicode_KIND_SIZE(rkind, slen));
9364 if (!res) {
9365 PyErr_NoMemory();
9366 goto error;
9367 }
9368 memcpy(res, sbuf, PyUnicode_KIND_SIZE(rkind, slen));
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009369 /* change everything in-place, starting with this one */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009370 memcpy(res + PyUnicode_KIND_SIZE(rkind, i),
9371 buf2,
9372 PyUnicode_KIND_SIZE(rkind, len2));
9373 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009374
9375 while ( --maxcount > 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009376 i = anylib_find(rkind, sbuf+PyUnicode_KIND_SIZE(rkind, i),
9377 slen-i,
9378 buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009379 if (i == -1)
9380 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009381 memcpy(res + PyUnicode_KIND_SIZE(rkind, i),
9382 buf2,
9383 PyUnicode_KIND_SIZE(rkind, len2));
9384 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009385 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009386
9387 u = PyUnicode_FromKindAndData(rkind, res, slen);
9388 PyMem_Free(res);
9389 if (!u) goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009390 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009391 } else {
Thomas Wouters477c8d52006-05-27 19:21:47 +00009392
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009393 Py_ssize_t n, i, j, ires;
9394 Py_ssize_t product, new_size;
9395 int rkind = skind;
9396 char *res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009397
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009398 if (kind1 < rkind) {
9399 buf1 = _PyUnicode_AsKind(str1, rkind);
9400 if (!buf1) goto error;
9401 release1 = 1;
9402 }
9403 n = anylib_count(rkind, sbuf, slen, buf1, len1, maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009404 if (n == 0)
9405 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009406 if (kind2 < rkind) {
9407 buf2 = _PyUnicode_AsKind(str2, rkind);
9408 if (!buf2) goto error;
9409 release2 = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009410 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009411 else if (kind2 > rkind) {
9412 rkind = kind2;
9413 sbuf = _PyUnicode_AsKind(self, rkind);
9414 if (!sbuf) goto error;
9415 srelease = 1;
9416 if (release1) PyMem_Free(buf1);
9417 buf1 = _PyUnicode_AsKind(str1, rkind);
9418 if (!buf1) goto error;
9419 release1 = 1;
9420 }
9421 /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
9422 PyUnicode_GET_LENGTH(str1))); */
9423 product = n * (len2-len1);
9424 if ((product / (len2-len1)) != n) {
9425 PyErr_SetString(PyExc_OverflowError,
9426 "replace string is too long");
9427 goto error;
9428 }
9429 new_size = slen + product;
9430 if (new_size < 0 || new_size > (PY_SSIZE_T_MAX >> (rkind-1))) {
9431 PyErr_SetString(PyExc_OverflowError,
9432 "replace string is too long");
9433 goto error;
9434 }
9435 res = PyMem_Malloc(PyUnicode_KIND_SIZE(rkind, new_size));
9436 if (!res)
9437 goto error;
9438 ires = i = 0;
9439 if (len1 > 0) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00009440 while (n-- > 0) {
9441 /* look for next match */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009442 j = anylib_find(rkind,
9443 sbuf + PyUnicode_KIND_SIZE(rkind, i),
9444 slen-i, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009445 if (j == -1)
9446 break;
9447 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00009448 /* copy unchanged part [i:j] */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009449 memcpy(res + PyUnicode_KIND_SIZE(rkind, ires),
9450 sbuf + PyUnicode_KIND_SIZE(rkind, i),
9451 PyUnicode_KIND_SIZE(rkind, j-i));
9452 ires += j - i;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009453 }
9454 /* copy substitution string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009455 if (len2 > 0) {
9456 memcpy(res + PyUnicode_KIND_SIZE(rkind, ires),
9457 buf2,
9458 PyUnicode_KIND_SIZE(rkind, len2));
9459 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009460 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009461 i = j + len1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009462 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009463 if (i < slen)
Thomas Wouters477c8d52006-05-27 19:21:47 +00009464 /* copy tail [i:] */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009465 memcpy(res + PyUnicode_KIND_SIZE(rkind, ires),
9466 sbuf + PyUnicode_KIND_SIZE(rkind, i),
9467 PyUnicode_KIND_SIZE(rkind, slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +00009468 } else {
9469 /* interleave */
9470 while (n > 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009471 memcpy(res + PyUnicode_KIND_SIZE(rkind, ires),
9472 buf2,
9473 PyUnicode_KIND_SIZE(rkind, len2));
9474 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009475 if (--n <= 0)
9476 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009477 memcpy(res + PyUnicode_KIND_SIZE(rkind, ires),
9478 sbuf + PyUnicode_KIND_SIZE(rkind, i),
9479 PyUnicode_KIND_SIZE(rkind, 1));
9480 ires++;
9481 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009482 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009483 memcpy(res + PyUnicode_KIND_SIZE(rkind, ires),
9484 sbuf + PyUnicode_KIND_SIZE(rkind, i),
9485 PyUnicode_KIND_SIZE(rkind, slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +00009486 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009487 u = PyUnicode_FromKindAndData(rkind, res, new_size);
Martin v. Löwis0b1d3482011-10-01 16:35:40 +02009488 PyMem_Free(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009489 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009490 if (srelease)
9491 PyMem_FREE(sbuf);
9492 if (release1)
9493 PyMem_FREE(buf1);
9494 if (release2)
9495 PyMem_FREE(buf2);
9496 return u;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009497
Benjamin Peterson29060642009-01-31 22:14:21 +00009498 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +00009499 /* nothing to replace; return original string (when possible) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009500 if (srelease)
9501 PyMem_FREE(sbuf);
9502 if (release1)
9503 PyMem_FREE(buf1);
9504 if (release2)
9505 PyMem_FREE(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009506 if (PyUnicode_CheckExact(self)) {
9507 Py_INCREF(self);
9508 return (PyObject *) self;
9509 }
Victor Stinner034f6cf2011-09-30 02:26:44 +02009510 return PyUnicode_Copy(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009511 error:
9512 if (srelease && sbuf)
9513 PyMem_FREE(sbuf);
9514 if (release1 && buf1)
9515 PyMem_FREE(buf1);
9516 if (release2 && buf2)
9517 PyMem_FREE(buf2);
9518 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009519}
9520
9521/* --- Unicode Object Methods --------------------------------------------- */
9522
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009523PyDoc_STRVAR(title__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00009524 "S.title() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00009525\n\
9526Return a titlecased version of S, i.e. words start with title case\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009527characters, all remaining cased characters have lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00009528
9529static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00009530unicode_title(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009531{
Guido van Rossumd57fd912000-03-10 22:53:23 +00009532 return fixup(self, fixtitle);
9533}
9534
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009535PyDoc_STRVAR(capitalize__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00009536 "S.capitalize() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00009537\n\
9538Return a capitalized version of S, i.e. make the first character\n\
Senthil Kumarane51ee8a2010-07-05 12:00:56 +00009539have upper case and the rest lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00009540
9541static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00009542unicode_capitalize(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009543{
Guido van Rossumd57fd912000-03-10 22:53:23 +00009544 return fixup(self, fixcapitalize);
9545}
9546
9547#if 0
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009548PyDoc_STRVAR(capwords__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00009549 "S.capwords() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00009550\n\
9551Apply .capitalize() to all words in S and return the result with\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009552normalized whitespace (all whitespace strings are replaced by ' ').");
Guido van Rossumd57fd912000-03-10 22:53:23 +00009553
9554static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00009555unicode_capwords(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009556{
9557 PyObject *list;
9558 PyObject *item;
Martin v. Löwis18e16552006-02-15 17:27:45 +00009559 Py_ssize_t i;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009560
Guido van Rossumd57fd912000-03-10 22:53:23 +00009561 /* Split into words */
9562 list = split(self, NULL, -1);
9563 if (!list)
9564 return NULL;
9565
9566 /* Capitalize each word */
9567 for (i = 0; i < PyList_GET_SIZE(list); i++) {
9568 item = fixup((PyUnicodeObject *)PyList_GET_ITEM(list, i),
Benjamin Peterson29060642009-01-31 22:14:21 +00009569 fixcapitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009570 if (item == NULL)
9571 goto onError;
9572 Py_DECREF(PyList_GET_ITEM(list, i));
9573 PyList_SET_ITEM(list, i, item);
9574 }
9575
9576 /* Join the words to form a new string */
9577 item = PyUnicode_Join(NULL, list);
9578
Benjamin Peterson29060642009-01-31 22:14:21 +00009579 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00009580 Py_DECREF(list);
9581 return (PyObject *)item;
9582}
9583#endif
9584
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00009585/* Argument converter. Coerces to a single unicode character */
9586
9587static int
9588convert_uc(PyObject *obj, void *addr)
9589{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009590 Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009591 PyObject *uniobj;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00009592
Benjamin Peterson14339b62009-01-31 16:36:08 +00009593 uniobj = PyUnicode_FromObject(obj);
9594 if (uniobj == NULL) {
9595 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009596 "The fill character cannot be converted to Unicode");
Benjamin Peterson14339b62009-01-31 16:36:08 +00009597 return 0;
9598 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009599 if (PyUnicode_GET_LENGTH(uniobj) != 1) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009600 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009601 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +00009602 Py_DECREF(uniobj);
9603 return 0;
9604 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009605 *fillcharloc = PyUnicode_READ_CHAR(uniobj, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +00009606 Py_DECREF(uniobj);
9607 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00009608}
9609
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009610PyDoc_STRVAR(center__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00009611 "S.center(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00009612\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +00009613Return S centered in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00009614done using the specified fill character (default is a space)");
Guido van Rossumd57fd912000-03-10 22:53:23 +00009615
9616static PyObject *
9617unicode_center(PyUnicodeObject *self, PyObject *args)
9618{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009619 Py_ssize_t marg, left;
9620 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009621 Py_UCS4 fillchar = ' ';
9622
Victor Stinnere9a29352011-10-01 02:14:59 +02009623 if (!PyArg_ParseTuple(args, "n|O&:center", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009624 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009625
Victor Stinnere9a29352011-10-01 02:14:59 +02009626 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009627 return NULL;
9628
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009629 if (_PyUnicode_LENGTH(self) >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00009630 Py_INCREF(self);
9631 return (PyObject*) self;
9632 }
9633
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009634 marg = width - _PyUnicode_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009635 left = marg / 2 + (marg & width & 1);
9636
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00009637 return (PyObject*) pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009638}
9639
Marc-André Lemburge5034372000-08-08 08:04:29 +00009640#if 0
9641
9642/* This code should go into some future Unicode collation support
9643 module. The basic comparison should compare ordinals on a naive
Georg Brandlc6c31782009-06-08 13:41:29 +00009644 basis (this is what Java does and thus Jython too). */
Marc-André Lemburge5034372000-08-08 08:04:29 +00009645
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00009646/* speedy UTF-16 code point order comparison */
9647/* gleaned from: */
9648/* http://www-4.ibm.com/software/developer/library/utf16.html?dwzone=unicode */
9649
Marc-André Lemburge12896e2000-07-07 17:51:08 +00009650static short utf16Fixup[32] =
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00009651{
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00009652 0, 0, 0, 0, 0, 0, 0, 0,
Tim Petersced69f82003-09-16 20:30:58 +00009653 0, 0, 0, 0, 0, 0, 0, 0,
9654 0, 0, 0, 0, 0, 0, 0, 0,
Marc-André Lemburge12896e2000-07-07 17:51:08 +00009655 0, 0, 0, 0x2000, -0x800, -0x800, -0x800, -0x800
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00009656};
9657
Guido van Rossumd57fd912000-03-10 22:53:23 +00009658static int
9659unicode_compare(PyUnicodeObject *str1, PyUnicodeObject *str2)
9660{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009661 Py_ssize_t len1, len2;
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00009662
Guido van Rossumd57fd912000-03-10 22:53:23 +00009663 Py_UNICODE *s1 = str1->str;
9664 Py_UNICODE *s2 = str2->str;
9665
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009666 len1 = str1->_base._base.length;
9667 len2 = str2->_base._base.length;
Tim Petersced69f82003-09-16 20:30:58 +00009668
Guido van Rossumd57fd912000-03-10 22:53:23 +00009669 while (len1 > 0 && len2 > 0) {
Tim Petersced69f82003-09-16 20:30:58 +00009670 Py_UNICODE c1, c2;
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00009671
9672 c1 = *s1++;
9673 c2 = *s2++;
Fredrik Lundh45714e92001-06-26 16:39:36 +00009674
Benjamin Peterson29060642009-01-31 22:14:21 +00009675 if (c1 > (1<<11) * 26)
9676 c1 += utf16Fixup[c1>>11];
9677 if (c2 > (1<<11) * 26)
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00009678 c2 += utf16Fixup[c2>>11];
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00009679 /* now c1 and c2 are in UTF-32-compatible order */
Fredrik Lundh45714e92001-06-26 16:39:36 +00009680
9681 if (c1 != c2)
9682 return (c1 < c2) ? -1 : 1;
Tim Petersced69f82003-09-16 20:30:58 +00009683
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00009684 len1--; len2--;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009685 }
9686
9687 return (len1 < len2) ? -1 : (len1 != len2);
9688}
9689
Marc-André Lemburge5034372000-08-08 08:04:29 +00009690#else
9691
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009692/* This function assumes that str1 and str2 are readied by the caller. */
9693
Marc-André Lemburge5034372000-08-08 08:04:29 +00009694static int
9695unicode_compare(PyUnicodeObject *str1, PyUnicodeObject *str2)
9696{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009697 int kind1, kind2;
9698 void *data1, *data2;
9699 Py_ssize_t len1, len2, i;
Marc-André Lemburge5034372000-08-08 08:04:29 +00009700
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009701 kind1 = PyUnicode_KIND(str1);
9702 kind2 = PyUnicode_KIND(str2);
9703 data1 = PyUnicode_DATA(str1);
9704 data2 = PyUnicode_DATA(str2);
9705 len1 = PyUnicode_GET_LENGTH(str1);
9706 len2 = PyUnicode_GET_LENGTH(str2);
Marc-André Lemburge5034372000-08-08 08:04:29 +00009707
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009708 for (i = 0; i < len1 && i < len2; ++i) {
9709 Py_UCS4 c1, c2;
9710 c1 = PyUnicode_READ(kind1, data1, i);
9711 c2 = PyUnicode_READ(kind2, data2, i);
Fredrik Lundh45714e92001-06-26 16:39:36 +00009712
9713 if (c1 != c2)
9714 return (c1 < c2) ? -1 : 1;
Marc-André Lemburge5034372000-08-08 08:04:29 +00009715 }
9716
9717 return (len1 < len2) ? -1 : (len1 != len2);
9718}
9719
9720#endif
9721
Alexander Belopolsky40018472011-02-26 01:02:56 +00009722int
9723PyUnicode_Compare(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009724{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009725 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
9726 if (PyUnicode_READY(left) == -1 ||
9727 PyUnicode_READY(right) == -1)
9728 return -1;
Guido van Rossum09dc34f2007-05-04 04:17:33 +00009729 return unicode_compare((PyUnicodeObject *)left,
9730 (PyUnicodeObject *)right);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009731 }
Guido van Rossum09dc34f2007-05-04 04:17:33 +00009732 PyErr_Format(PyExc_TypeError,
9733 "Can't compare %.100s and %.100s",
9734 left->ob_type->tp_name,
9735 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009736 return -1;
9737}
9738
Martin v. Löwis5b222132007-06-10 09:51:05 +00009739int
9740PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
9741{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009742 Py_ssize_t i;
9743 int kind;
9744 void *data;
9745 Py_UCS4 chr;
9746
Victor Stinner910337b2011-10-03 03:20:16 +02009747 assert(_PyUnicode_CHECK(uni));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009748 if (PyUnicode_READY(uni) == -1)
9749 return -1;
9750 kind = PyUnicode_KIND(uni);
9751 data = PyUnicode_DATA(uni);
Martin v. Löwis5b222132007-06-10 09:51:05 +00009752 /* Compare Unicode string and source character set string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009753 for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
9754 if (chr != str[i])
9755 return (chr < (unsigned char)(str[i])) ? -1 : 1;
Benjamin Peterson8667a9b2010-01-09 21:45:28 +00009756 /* This check keeps Python strings that end in '\0' from comparing equal
9757 to C strings identical up to that point. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009758 if (PyUnicode_GET_LENGTH(uni) != i || chr)
Benjamin Peterson29060642009-01-31 22:14:21 +00009759 return 1; /* uni is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +00009760 if (str[i])
Benjamin Peterson29060642009-01-31 22:14:21 +00009761 return -1; /* str is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +00009762 return 0;
9763}
9764
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00009765
Benjamin Peterson29060642009-01-31 22:14:21 +00009766#define TEST_COND(cond) \
Benjamin Peterson14339b62009-01-31 16:36:08 +00009767 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00009768
Alexander Belopolsky40018472011-02-26 01:02:56 +00009769PyObject *
9770PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00009771{
9772 int result;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009773
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00009774 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
9775 PyObject *v;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009776 if (PyUnicode_READY(left) == -1 ||
9777 PyUnicode_READY(right) == -1)
9778 return NULL;
9779 if (PyUnicode_GET_LENGTH(left) != PyUnicode_GET_LENGTH(right) ||
9780 PyUnicode_KIND(left) != PyUnicode_KIND(right)) {
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00009781 if (op == Py_EQ) {
9782 Py_INCREF(Py_False);
9783 return Py_False;
9784 }
9785 if (op == Py_NE) {
9786 Py_INCREF(Py_True);
9787 return Py_True;
9788 }
9789 }
9790 if (left == right)
9791 result = 0;
9792 else
9793 result = unicode_compare((PyUnicodeObject *)left,
9794 (PyUnicodeObject *)right);
Benjamin Peterson14339b62009-01-31 16:36:08 +00009795
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00009796 /* Convert the return value to a Boolean */
9797 switch (op) {
9798 case Py_EQ:
9799 v = TEST_COND(result == 0);
9800 break;
9801 case Py_NE:
9802 v = TEST_COND(result != 0);
9803 break;
9804 case Py_LE:
9805 v = TEST_COND(result <= 0);
9806 break;
9807 case Py_GE:
9808 v = TEST_COND(result >= 0);
9809 break;
9810 case Py_LT:
9811 v = TEST_COND(result == -1);
9812 break;
9813 case Py_GT:
9814 v = TEST_COND(result == 1);
9815 break;
9816 default:
9817 PyErr_BadArgument();
9818 return NULL;
9819 }
9820 Py_INCREF(v);
9821 return v;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00009822 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00009823
Brian Curtindfc80e32011-08-10 20:28:54 -05009824 Py_RETURN_NOTIMPLEMENTED;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00009825}
9826
Alexander Belopolsky40018472011-02-26 01:02:56 +00009827int
9828PyUnicode_Contains(PyObject *container, PyObject *element)
Guido van Rossum403d68b2000-03-13 15:55:09 +00009829{
Thomas Wouters477c8d52006-05-27 19:21:47 +00009830 PyObject *str, *sub;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009831 int kind1, kind2, kind;
9832 void *buf1, *buf2;
9833 Py_ssize_t len1, len2;
Martin v. Löwis18e16552006-02-15 17:27:45 +00009834 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +00009835
9836 /* Coerce the two arguments */
Thomas Wouters477c8d52006-05-27 19:21:47 +00009837 sub = PyUnicode_FromObject(element);
9838 if (!sub) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009839 PyErr_Format(PyExc_TypeError,
9840 "'in <string>' requires string as left operand, not %s",
9841 element->ob_type->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009842 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +00009843 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009844 if (PyUnicode_READY(sub) == -1)
9845 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +00009846
Thomas Wouters477c8d52006-05-27 19:21:47 +00009847 str = PyUnicode_FromObject(container);
Victor Stinnere9a29352011-10-01 02:14:59 +02009848 if (!str || PyUnicode_READY(str) == -1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00009849 Py_DECREF(sub);
9850 return -1;
9851 }
9852
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009853 kind1 = PyUnicode_KIND(str);
9854 kind2 = PyUnicode_KIND(sub);
9855 kind = kind1 > kind2 ? kind1 : kind2;
9856 buf1 = PyUnicode_DATA(str);
9857 buf2 = PyUnicode_DATA(sub);
9858 if (kind1 != kind)
9859 buf1 = _PyUnicode_AsKind((PyObject*)str, kind);
9860 if (!buf1) {
9861 Py_DECREF(sub);
9862 return -1;
9863 }
9864 if (kind2 != kind)
9865 buf2 = _PyUnicode_AsKind((PyObject*)sub, kind);
9866 if (!buf2) {
9867 Py_DECREF(sub);
9868 if (kind1 != kind) PyMem_Free(buf1);
9869 return -1;
9870 }
9871 len1 = PyUnicode_GET_LENGTH(str);
9872 len2 = PyUnicode_GET_LENGTH(sub);
9873
9874 switch(kind) {
9875 case PyUnicode_1BYTE_KIND:
9876 result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
9877 break;
9878 case PyUnicode_2BYTE_KIND:
9879 result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
9880 break;
9881 case PyUnicode_4BYTE_KIND:
9882 result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
9883 break;
9884 default:
9885 result = -1;
9886 assert(0);
9887 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009888
9889 Py_DECREF(str);
9890 Py_DECREF(sub);
9891
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009892 if (kind1 != kind)
9893 PyMem_Free(buf1);
9894 if (kind2 != kind)
9895 PyMem_Free(buf2);
9896
Guido van Rossum403d68b2000-03-13 15:55:09 +00009897 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +00009898}
9899
Guido van Rossumd57fd912000-03-10 22:53:23 +00009900/* Concat to string or Unicode object giving a new Unicode object. */
9901
Alexander Belopolsky40018472011-02-26 01:02:56 +00009902PyObject *
9903PyUnicode_Concat(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009904{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009905 PyObject *u = NULL, *v = NULL, *w;
9906 Py_UCS4 maxchar;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009907
9908 /* Coerce the two arguments */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009909 u = PyUnicode_FromObject(left);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009910 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009911 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009912 v = PyUnicode_FromObject(right);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009913 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009914 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009915
9916 /* Shortcuts */
Victor Stinnera464fc12011-10-02 20:39:30 +02009917 if (v == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009918 Py_DECREF(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009919 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009920 }
Victor Stinnera464fc12011-10-02 20:39:30 +02009921 if (u == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009922 Py_DECREF(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009923 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009924 }
9925
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009926 maxchar = PyUnicode_MAX_CHAR_VALUE(u);
Victor Stinnerff9e50f2011-09-28 22:17:19 +02009927 maxchar = Py_MAX(maxchar, PyUnicode_MAX_CHAR_VALUE(v));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009928
Guido van Rossumd57fd912000-03-10 22:53:23 +00009929 /* Concat the two Unicode strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009930 w = PyUnicode_New(
9931 PyUnicode_GET_LENGTH(u) + PyUnicode_GET_LENGTH(v),
9932 maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009933 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009934 goto onError;
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009935 if (PyUnicode_CopyCharacters(w, 0, u, 0, PyUnicode_GET_LENGTH(u)) < 0)
9936 goto onError;
Victor Stinner157f83f2011-09-28 21:41:31 +02009937 if (PyUnicode_CopyCharacters(w, PyUnicode_GET_LENGTH(u),
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009938 v, 0,
9939 PyUnicode_GET_LENGTH(v)) < 0)
9940 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009941 Py_DECREF(u);
9942 Py_DECREF(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009943 return w;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009944
Benjamin Peterson29060642009-01-31 22:14:21 +00009945 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00009946 Py_XDECREF(u);
9947 Py_XDECREF(v);
9948 return NULL;
9949}
9950
Walter Dörwald1ab83302007-05-18 17:15:44 +00009951void
Victor Stinner23e56682011-10-03 03:54:37 +02009952PyUnicode_Append(PyObject **p_left, PyObject *right)
Walter Dörwald1ab83302007-05-18 17:15:44 +00009953{
Victor Stinner23e56682011-10-03 03:54:37 +02009954 PyObject *left, *res;
9955
9956 if (p_left == NULL) {
9957 if (!PyErr_Occurred())
9958 PyErr_BadInternalCall();
Benjamin Peterson14339b62009-01-31 16:36:08 +00009959 return;
9960 }
Victor Stinner23e56682011-10-03 03:54:37 +02009961 left = *p_left;
9962 if (right == NULL || !PyUnicode_Check(left)) {
9963 if (!PyErr_Occurred())
9964 PyErr_BadInternalCall();
9965 goto error;
9966 }
9967
9968 if (PyUnicode_CheckExact(left) && left != unicode_empty
9969 && PyUnicode_CheckExact(right) && right != unicode_empty
9970 && unicode_resizable(left)
9971 && (_PyUnicode_KIND(right) <= _PyUnicode_KIND(left)
9972 || _PyUnicode_WSTR(left) != NULL))
9973 {
Victor Stinnerb8038952011-10-03 23:27:56 +02009974 Py_ssize_t left_len, right_len, new_len;
9975#ifdef Py_DEBUG
9976 Py_ssize_t copied;
9977#endif
Victor Stinner23e56682011-10-03 03:54:37 +02009978
Victor Stinner23e56682011-10-03 03:54:37 +02009979 if (PyUnicode_READY(left))
9980 goto error;
9981 if (PyUnicode_READY(right))
9982 goto error;
9983
9984 /* FIXME: support ascii+latin1, PyASCIIObject => PyCompactUnicodeObject */
9985 if (PyUnicode_MAX_CHAR_VALUE(right) <= PyUnicode_MAX_CHAR_VALUE(left))
9986 {
Victor Stinnerb8038952011-10-03 23:27:56 +02009987 left_len = PyUnicode_GET_LENGTH(left);
9988 right_len = PyUnicode_GET_LENGTH(right);
9989 if (left_len > PY_SSIZE_T_MAX - right_len) {
Victor Stinner23e56682011-10-03 03:54:37 +02009990 PyErr_SetString(PyExc_OverflowError,
9991 "strings are too large to concat");
9992 goto error;
9993 }
Victor Stinnerb8038952011-10-03 23:27:56 +02009994 new_len = left_len + right_len;
Victor Stinner23e56682011-10-03 03:54:37 +02009995
9996 /* Now we own the last reference to 'left', so we can resize it
9997 * in-place.
9998 */
9999 if (unicode_resize(&left, new_len) != 0) {
10000 /* XXX if _PyUnicode_Resize() fails, 'left' has been
10001 * deallocated so it cannot be put back into
10002 * 'variable'. The MemoryError is raised when there
10003 * is no value in 'variable', which might (very
10004 * remotely) be a cause of incompatibilities.
10005 */
10006 goto error;
10007 }
10008 /* copy 'right' into the newly allocated area of 'left' */
Victor Stinnerb8038952011-10-03 23:27:56 +020010009#ifdef Py_DEBUG
10010 copied = PyUnicode_CopyCharacters(left, left_len,
Victor Stinner23e56682011-10-03 03:54:37 +020010011 right, 0,
Victor Stinnerb8038952011-10-03 23:27:56 +020010012 right_len);
Victor Stinner23e56682011-10-03 03:54:37 +020010013 assert(0 <= copied);
Victor Stinnerb8038952011-10-03 23:27:56 +020010014#else
10015 PyUnicode_CopyCharacters(left, left_len, right, 0, right_len);
10016#endif
Victor Stinner23e56682011-10-03 03:54:37 +020010017 *p_left = left;
10018 return;
10019 }
10020 }
10021
10022 res = PyUnicode_Concat(left, right);
10023 if (res == NULL)
10024 goto error;
10025 Py_DECREF(left);
10026 *p_left = res;
10027 return;
10028
10029error:
10030 Py_DECREF(*p_left);
10031 *p_left = NULL;
Walter Dörwald1ab83302007-05-18 17:15:44 +000010032}
10033
10034void
10035PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
10036{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010037 PyUnicode_Append(pleft, right);
10038 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +000010039}
10040
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010041PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010042 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010043\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000010044Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010045string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010046interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010047
10048static PyObject *
10049unicode_count(PyUnicodeObject *self, PyObject *args)
10050{
10051 PyUnicodeObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010052 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010053 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010054 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010055 int kind1, kind2, kind;
10056 void *buf1, *buf2;
10057 Py_ssize_t len1, len2, iresult;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010058
Jesus Ceaac451502011-04-20 17:09:23 +020010059 if (!stringlib_parse_args_finds_unicode("count", args, &substring,
10060 &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000010061 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000010062
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010063 kind1 = PyUnicode_KIND(self);
10064 kind2 = PyUnicode_KIND(substring);
10065 kind = kind1 > kind2 ? kind1 : kind2;
10066 buf1 = PyUnicode_DATA(self);
10067 buf2 = PyUnicode_DATA(substring);
10068 if (kind1 != kind)
10069 buf1 = _PyUnicode_AsKind((PyObject*)self, kind);
10070 if (!buf1) {
10071 Py_DECREF(substring);
10072 return NULL;
10073 }
10074 if (kind2 != kind)
10075 buf2 = _PyUnicode_AsKind((PyObject*)substring, kind);
10076 if (!buf2) {
10077 Py_DECREF(substring);
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 ADJUST_INDICES(start, end, len1);
10085 switch(kind) {
10086 case PyUnicode_1BYTE_KIND:
10087 iresult = ucs1lib_count(
10088 ((Py_UCS1*)buf1) + start, end - start,
10089 buf2, len2, PY_SSIZE_T_MAX
10090 );
10091 break;
10092 case PyUnicode_2BYTE_KIND:
10093 iresult = ucs2lib_count(
10094 ((Py_UCS2*)buf1) + start, end - start,
10095 buf2, len2, PY_SSIZE_T_MAX
10096 );
10097 break;
10098 case PyUnicode_4BYTE_KIND:
10099 iresult = ucs4lib_count(
10100 ((Py_UCS4*)buf1) + start, end - start,
10101 buf2, len2, PY_SSIZE_T_MAX
10102 );
10103 break;
10104 default:
10105 assert(0); iresult = 0;
10106 }
10107
10108 result = PyLong_FromSsize_t(iresult);
10109
10110 if (kind1 != kind)
10111 PyMem_Free(buf1);
10112 if (kind2 != kind)
10113 PyMem_Free(buf2);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010114
10115 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010116
Guido van Rossumd57fd912000-03-10 22:53:23 +000010117 return result;
10118}
10119
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010120PyDoc_STRVAR(encode__doc__,
Victor Stinnerc911bbf2010-11-07 19:04:46 +000010121 "S.encode(encoding='utf-8', errors='strict') -> bytes\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010122\n\
Victor Stinnere14e2122010-11-07 18:41:46 +000010123Encode S using the codec registered for encoding. Default encoding\n\
10124is 'utf-8'. errors may be given to set a different error\n\
Fred Drakee4315f52000-05-09 19:53:39 +000010125handling scheme. Default is 'strict' meaning that encoding errors raise\n\
Walter Dörwald3aeb6322002-09-02 13:14:32 +000010126a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
10127'xmlcharrefreplace' as well as any other name registered with\n\
10128codecs.register_error that can handle UnicodeEncodeErrors.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010129
10130static PyObject *
Benjamin Peterson308d6372009-09-18 21:42:35 +000010131unicode_encode(PyUnicodeObject *self, PyObject *args, PyObject *kwargs)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010132{
Benjamin Peterson308d6372009-09-18 21:42:35 +000010133 static char *kwlist[] = {"encoding", "errors", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000010134 char *encoding = NULL;
10135 char *errors = NULL;
Guido van Rossum35d94282007-08-27 18:20:11 +000010136
Benjamin Peterson308d6372009-09-18 21:42:35 +000010137 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:encode",
10138 kwlist, &encoding, &errors))
Guido van Rossumd57fd912000-03-10 22:53:23 +000010139 return NULL;
Georg Brandl3b9406b2010-12-03 07:54:09 +000010140 return PyUnicode_AsEncodedString((PyObject *)self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +000010141}
10142
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010143PyDoc_STRVAR(expandtabs__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010144 "S.expandtabs([tabsize]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010145\n\
10146Return a copy of S where all tab characters are expanded using spaces.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010147If tabsize is not given, a tab size of 8 characters is assumed.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010148
10149static PyObject*
10150unicode_expandtabs(PyUnicodeObject *self, PyObject *args)
10151{
10152 Py_UNICODE *e;
10153 Py_UNICODE *p;
10154 Py_UNICODE *q;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010155 Py_UNICODE *qe;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010156 Py_ssize_t i, j, incr, wstr_length;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010157 PyUnicodeObject *u;
10158 int tabsize = 8;
10159
10160 if (!PyArg_ParseTuple(args, "|i:expandtabs", &tabsize))
Benjamin Peterson29060642009-01-31 22:14:21 +000010161 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010162
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010163 if (PyUnicode_AsUnicodeAndSize((PyObject *)self, &wstr_length) == NULL)
10164 return NULL;
10165
Thomas Wouters7e474022000-07-16 12:04:32 +000010166 /* First pass: determine size of output string */
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010167 i = 0; /* chars up to and including most recent \n or \r */
10168 j = 0; /* chars since most recent \n or \r (use in tab calculations) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010169 e = _PyUnicode_WSTR(self) + wstr_length; /* end of input */
10170 for (p = _PyUnicode_WSTR(self); p < e; p++)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010171 if (*p == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +000010172 if (tabsize > 0) {
10173 incr = tabsize - (j % tabsize); /* cannot overflow */
10174 if (j > PY_SSIZE_T_MAX - incr)
10175 goto overflow1;
10176 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010177 }
Benjamin Peterson29060642009-01-31 22:14:21 +000010178 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010179 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000010180 if (j > PY_SSIZE_T_MAX - 1)
10181 goto overflow1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010182 j++;
10183 if (*p == '\n' || *p == '\r') {
Benjamin Peterson29060642009-01-31 22:14:21 +000010184 if (i > PY_SSIZE_T_MAX - j)
10185 goto overflow1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010186 i += j;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010187 j = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010188 }
10189 }
10190
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010191 if (i > PY_SSIZE_T_MAX - j)
Benjamin Peterson29060642009-01-31 22:14:21 +000010192 goto overflow1;
Guido van Rossumcd16bf62007-06-13 18:07:49 +000010193
Guido van Rossumd57fd912000-03-10 22:53:23 +000010194 /* Second pass: create output string and fill it */
10195 u = _PyUnicode_New(i + j);
10196 if (!u)
10197 return NULL;
10198
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010199 j = 0; /* same as in first pass */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010200 q = _PyUnicode_WSTR(u); /* next output char */
10201 qe = _PyUnicode_WSTR(u) + PyUnicode_GET_SIZE(u); /* end of output */
Guido van Rossumd57fd912000-03-10 22:53:23 +000010202
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010203 for (p = _PyUnicode_WSTR(self); p < e; p++)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010204 if (*p == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +000010205 if (tabsize > 0) {
10206 i = tabsize - (j % tabsize);
10207 j += i;
10208 while (i--) {
10209 if (q >= qe)
10210 goto overflow2;
10211 *q++ = ' ';
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010212 }
Benjamin Peterson29060642009-01-31 22:14:21 +000010213 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000010214 }
Benjamin Peterson29060642009-01-31 22:14:21 +000010215 else {
10216 if (q >= qe)
10217 goto overflow2;
10218 *q++ = *p;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010219 j++;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010220 if (*p == '\n' || *p == '\r')
10221 j = 0;
10222 }
10223
Victor Stinner1b4f9ce2011-10-03 13:28:14 +020010224 if (_PyUnicode_READY_REPLACE(&u)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010225 Py_DECREF(u);
10226 return NULL;
10227 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010228 return (PyObject*) u;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010229
10230 overflow2:
10231 Py_DECREF(u);
10232 overflow1:
10233 PyErr_SetString(PyExc_OverflowError, "new string is too long");
10234 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010235}
10236
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010237PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010238 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010239\n\
10240Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080010241such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010242arguments start and end are interpreted as in slice notation.\n\
10243\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010244Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010245
10246static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010247unicode_find(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010248{
Jesus Ceaac451502011-04-20 17:09:23 +020010249 PyUnicodeObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000010250 Py_ssize_t start;
10251 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010252 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010253
Jesus Ceaac451502011-04-20 17:09:23 +020010254 if (!stringlib_parse_args_finds_unicode("find", args, &substring,
10255 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000010256 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010257
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010258 if (PyUnicode_READY(self) == -1)
10259 return NULL;
10260 if (PyUnicode_READY(substring) == -1)
10261 return NULL;
10262
10263 result = any_find_slice(
10264 ucs1lib_find_slice, ucs2lib_find_slice, ucs4lib_find_slice,
10265 self, (PyObject*)substring, start, end
Thomas Wouters477c8d52006-05-27 19:21:47 +000010266 );
Guido van Rossumd57fd912000-03-10 22:53:23 +000010267
10268 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010269
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010270 if (result == -2)
10271 return NULL;
10272
Christian Heimes217cfd12007-12-02 14:31:20 +000010273 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010274}
10275
10276static PyObject *
Victor Stinner2fe5ced2011-10-02 00:25:40 +020010277unicode_getitem(PyObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010278{
Victor Stinner2fe5ced2011-10-02 00:25:40 +020010279 Py_UCS4 ch = PyUnicode_ReadChar(self, index);
10280 if (ch == (Py_UCS4)-1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010281 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010282 return PyUnicode_FromOrdinal(ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010283}
10284
Guido van Rossumc2504932007-09-18 19:42:40 +000010285/* Believe it or not, this produces the same value for ASCII strings
Mark Dickinson57e683e2011-09-24 18:18:40 +010010286 as bytes_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +000010287static Py_hash_t
Neil Schemenauerf8c37d12007-09-07 20:49:04 +000010288unicode_hash(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010289{
Guido van Rossumc2504932007-09-18 19:42:40 +000010290 Py_ssize_t len;
Mark Dickinson57e683e2011-09-24 18:18:40 +010010291 Py_uhash_t x;
Guido van Rossumc2504932007-09-18 19:42:40 +000010292
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010293 if (_PyUnicode_HASH(self) != -1)
10294 return _PyUnicode_HASH(self);
10295 if (PyUnicode_READY(self) == -1)
10296 return -1;
10297 len = PyUnicode_GET_LENGTH(self);
10298
10299 /* The hash function as a macro, gets expanded three times below. */
10300#define HASH(P) \
10301 x = (Py_uhash_t)*P << 7; \
10302 while (--len >= 0) \
10303 x = (1000003*x) ^ (Py_uhash_t)*P++;
10304
10305 switch (PyUnicode_KIND(self)) {
10306 case PyUnicode_1BYTE_KIND: {
10307 const unsigned char *c = PyUnicode_1BYTE_DATA(self);
10308 HASH(c);
10309 break;
10310 }
10311 case PyUnicode_2BYTE_KIND: {
10312 const Py_UCS2 *s = PyUnicode_2BYTE_DATA(self);
10313 HASH(s);
10314 break;
10315 }
10316 default: {
10317 Py_UCS4 *l;
10318 assert(PyUnicode_KIND(self) == PyUnicode_4BYTE_KIND &&
10319 "Impossible switch case in unicode_hash");
10320 l = PyUnicode_4BYTE_DATA(self);
10321 HASH(l);
10322 break;
10323 }
10324 }
10325 x ^= (Py_uhash_t)PyUnicode_GET_LENGTH(self);
10326
Guido van Rossumc2504932007-09-18 19:42:40 +000010327 if (x == -1)
10328 x = -2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010329 _PyUnicode_HASH(self) = x;
Guido van Rossumc2504932007-09-18 19:42:40 +000010330 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010331}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010332#undef HASH
Guido van Rossumd57fd912000-03-10 22:53:23 +000010333
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010334PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010335 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010336\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010337Like S.find() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010338
10339static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010340unicode_index(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010341{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010342 Py_ssize_t result;
Jesus Ceaac451502011-04-20 17:09:23 +020010343 PyUnicodeObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000010344 Py_ssize_t start;
10345 Py_ssize_t end;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010346
Jesus Ceaac451502011-04-20 17:09:23 +020010347 if (!stringlib_parse_args_finds_unicode("index", args, &substring,
10348 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000010349 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010350
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010351 if (PyUnicode_READY(self) == -1)
10352 return NULL;
10353 if (PyUnicode_READY(substring) == -1)
10354 return NULL;
10355
10356 result = any_find_slice(
10357 ucs1lib_find_slice, ucs2lib_find_slice, ucs4lib_find_slice,
10358 self, (PyObject*)substring, start, end
Thomas Wouters477c8d52006-05-27 19:21:47 +000010359 );
Guido van Rossumd57fd912000-03-10 22:53:23 +000010360
10361 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010362
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010363 if (result == -2)
10364 return NULL;
10365
Guido van Rossumd57fd912000-03-10 22:53:23 +000010366 if (result < 0) {
10367 PyErr_SetString(PyExc_ValueError, "substring not found");
10368 return NULL;
10369 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000010370
Christian Heimes217cfd12007-12-02 14:31:20 +000010371 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010372}
10373
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010374PyDoc_STRVAR(islower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010375 "S.islower() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010376\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000010377Return True if all cased characters in S are lowercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010378at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010379
10380static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000010381unicode_islower(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010382{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010383 Py_ssize_t i, length;
10384 int kind;
10385 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010386 int cased;
10387
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010388 if (PyUnicode_READY(self) == -1)
10389 return NULL;
10390 length = PyUnicode_GET_LENGTH(self);
10391 kind = PyUnicode_KIND(self);
10392 data = PyUnicode_DATA(self);
10393
Guido van Rossumd57fd912000-03-10 22:53:23 +000010394 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010395 if (length == 1)
10396 return PyBool_FromLong(
10397 Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000010398
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000010399 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010400 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010401 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000010402
Guido van Rossumd57fd912000-03-10 22:53:23 +000010403 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010404 for (i = 0; i < length; i++) {
10405 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000010406
Benjamin Peterson29060642009-01-31 22:14:21 +000010407 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
10408 return PyBool_FromLong(0);
10409 else if (!cased && Py_UNICODE_ISLOWER(ch))
10410 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010411 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000010412 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010413}
10414
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010415PyDoc_STRVAR(isupper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010416 "S.isupper() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010417\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000010418Return True if all cased characters in S are uppercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010419at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010420
10421static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000010422unicode_isupper(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010423{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010424 Py_ssize_t i, length;
10425 int kind;
10426 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010427 int cased;
10428
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010429 if (PyUnicode_READY(self) == -1)
10430 return NULL;
10431 length = PyUnicode_GET_LENGTH(self);
10432 kind = PyUnicode_KIND(self);
10433 data = PyUnicode_DATA(self);
10434
Guido van Rossumd57fd912000-03-10 22:53:23 +000010435 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010436 if (length == 1)
10437 return PyBool_FromLong(
10438 Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010439
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000010440 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010441 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010442 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000010443
Guido van Rossumd57fd912000-03-10 22:53:23 +000010444 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010445 for (i = 0; i < length; i++) {
10446 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000010447
Benjamin Peterson29060642009-01-31 22:14:21 +000010448 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
10449 return PyBool_FromLong(0);
10450 else if (!cased && Py_UNICODE_ISUPPER(ch))
10451 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010452 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000010453 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010454}
10455
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010456PyDoc_STRVAR(istitle__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010457 "S.istitle() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010458\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000010459Return True if S is a titlecased string and there is at least one\n\
10460character in S, i.e. upper- and titlecase characters may only\n\
10461follow uncased characters and lowercase characters only cased ones.\n\
10462Return False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010463
10464static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000010465unicode_istitle(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010466{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010467 Py_ssize_t i, length;
10468 int kind;
10469 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010470 int cased, previous_is_cased;
10471
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010472 if (PyUnicode_READY(self) == -1)
10473 return NULL;
10474 length = PyUnicode_GET_LENGTH(self);
10475 kind = PyUnicode_KIND(self);
10476 data = PyUnicode_DATA(self);
10477
Guido van Rossumd57fd912000-03-10 22:53:23 +000010478 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010479 if (length == 1) {
10480 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
10481 return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
10482 (Py_UNICODE_ISUPPER(ch) != 0));
10483 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010484
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000010485 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010486 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010487 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000010488
Guido van Rossumd57fd912000-03-10 22:53:23 +000010489 cased = 0;
10490 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010491 for (i = 0; i < length; i++) {
10492 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000010493
Benjamin Peterson29060642009-01-31 22:14:21 +000010494 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
10495 if (previous_is_cased)
10496 return PyBool_FromLong(0);
10497 previous_is_cased = 1;
10498 cased = 1;
10499 }
10500 else if (Py_UNICODE_ISLOWER(ch)) {
10501 if (!previous_is_cased)
10502 return PyBool_FromLong(0);
10503 previous_is_cased = 1;
10504 cased = 1;
10505 }
10506 else
10507 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010508 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000010509 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010510}
10511
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010512PyDoc_STRVAR(isspace__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010513 "S.isspace() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010514\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000010515Return True if all characters in S are whitespace\n\
10516and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010517
10518static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000010519unicode_isspace(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010520{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010521 Py_ssize_t i, length;
10522 int kind;
10523 void *data;
10524
10525 if (PyUnicode_READY(self) == -1)
10526 return NULL;
10527 length = PyUnicode_GET_LENGTH(self);
10528 kind = PyUnicode_KIND(self);
10529 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010530
Guido van Rossumd57fd912000-03-10 22:53:23 +000010531 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010532 if (length == 1)
10533 return PyBool_FromLong(
10534 Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000010535
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000010536 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010537 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010538 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000010539
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010540 for (i = 0; i < length; i++) {
10541 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030010542 if (!Py_UNICODE_ISSPACE(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000010543 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010544 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000010545 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010546}
10547
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010548PyDoc_STRVAR(isalpha__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010549 "S.isalpha() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010550\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000010551Return True if all characters in S are alphabetic\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010552and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010553
10554static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000010555unicode_isalpha(PyUnicodeObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010556{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010557 Py_ssize_t i, length;
10558 int kind;
10559 void *data;
10560
10561 if (PyUnicode_READY(self) == -1)
10562 return NULL;
10563 length = PyUnicode_GET_LENGTH(self);
10564 kind = PyUnicode_KIND(self);
10565 data = PyUnicode_DATA(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010566
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010567 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010568 if (length == 1)
10569 return PyBool_FromLong(
10570 Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010571
10572 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010573 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010574 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010575
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010576 for (i = 0; i < length; i++) {
10577 if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000010578 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010579 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000010580 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010581}
10582
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010583PyDoc_STRVAR(isalnum__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010584 "S.isalnum() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010585\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000010586Return True if all characters in S are alphanumeric\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010587and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010588
10589static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000010590unicode_isalnum(PyUnicodeObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010591{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010592 int kind;
10593 void *data;
10594 Py_ssize_t len, i;
10595
10596 if (PyUnicode_READY(self) == -1)
10597 return NULL;
10598
10599 kind = PyUnicode_KIND(self);
10600 data = PyUnicode_DATA(self);
10601 len = PyUnicode_GET_LENGTH(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010602
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010603 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010604 if (len == 1) {
10605 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
10606 return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
10607 }
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010608
10609 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010610 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010611 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010612
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010613 for (i = 0; i < len; i++) {
10614 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030010615 if (!Py_UNICODE_ISALNUM(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000010616 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010617 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000010618 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010619}
10620
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010621PyDoc_STRVAR(isdecimal__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010622 "S.isdecimal() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010623\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000010624Return True if there are only decimal characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010625False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010626
10627static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000010628unicode_isdecimal(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010629{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010630 Py_ssize_t i, length;
10631 int kind;
10632 void *data;
10633
10634 if (PyUnicode_READY(self) == -1)
10635 return NULL;
10636 length = PyUnicode_GET_LENGTH(self);
10637 kind = PyUnicode_KIND(self);
10638 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010639
Guido van Rossumd57fd912000-03-10 22:53:23 +000010640 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010641 if (length == 1)
10642 return PyBool_FromLong(
10643 Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000010644
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000010645 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010646 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010647 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000010648
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010649 for (i = 0; i < length; i++) {
10650 if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000010651 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010652 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000010653 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010654}
10655
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010656PyDoc_STRVAR(isdigit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010657 "S.isdigit() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010658\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000010659Return True if all characters in S are digits\n\
10660and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010661
10662static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000010663unicode_isdigit(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010664{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010665 Py_ssize_t i, length;
10666 int kind;
10667 void *data;
10668
10669 if (PyUnicode_READY(self) == -1)
10670 return NULL;
10671 length = PyUnicode_GET_LENGTH(self);
10672 kind = PyUnicode_KIND(self);
10673 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010674
Guido van Rossumd57fd912000-03-10 22:53:23 +000010675 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010676 if (length == 1) {
10677 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
10678 return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
10679 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010680
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000010681 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010682 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010683 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000010684
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010685 for (i = 0; i < length; i++) {
10686 if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000010687 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010688 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000010689 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010690}
10691
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010692PyDoc_STRVAR(isnumeric__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010693 "S.isnumeric() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010694\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000010695Return True if there are only numeric characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010696False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010697
10698static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000010699unicode_isnumeric(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010700{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010701 Py_ssize_t i, length;
10702 int kind;
10703 void *data;
10704
10705 if (PyUnicode_READY(self) == -1)
10706 return NULL;
10707 length = PyUnicode_GET_LENGTH(self);
10708 kind = PyUnicode_KIND(self);
10709 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010710
Guido van Rossumd57fd912000-03-10 22:53:23 +000010711 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010712 if (length == 1)
10713 return PyBool_FromLong(
10714 Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000010715
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000010716 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010717 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010718 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000010719
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010720 for (i = 0; i < length; i++) {
10721 if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000010722 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010723 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000010724 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010725}
10726
Martin v. Löwis47383402007-08-15 07:32:56 +000010727int
10728PyUnicode_IsIdentifier(PyObject *self)
10729{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010730 int kind;
10731 void *data;
10732 Py_ssize_t i;
Ezio Melotti93e7afc2011-08-22 14:08:38 +030010733 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +000010734
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010735 if (PyUnicode_READY(self) == -1) {
10736 Py_FatalError("identifier not ready");
Benjamin Peterson29060642009-01-31 22:14:21 +000010737 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010738 }
10739
10740 /* Special case for empty strings */
10741 if (PyUnicode_GET_LENGTH(self) == 0)
10742 return 0;
10743 kind = PyUnicode_KIND(self);
10744 data = PyUnicode_DATA(self);
Martin v. Löwis47383402007-08-15 07:32:56 +000010745
10746 /* PEP 3131 says that the first character must be in
10747 XID_Start and subsequent characters in XID_Continue,
10748 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +000010749 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +000010750 letters, digits, underscore). However, given the current
10751 definition of XID_Start and XID_Continue, it is sufficient
10752 to check just for these, except that _ must be allowed
10753 as starting an identifier. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010754 first = PyUnicode_READ(kind, data, 0);
Benjamin Petersonf413b802011-08-12 22:17:18 -050010755 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +000010756 return 0;
10757
Benjamin Peterson9c6e6a02011-09-28 08:09:05 -040010758 for (i = 1; i < PyUnicode_GET_LENGTH(self); i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010759 if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000010760 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +000010761 return 1;
10762}
10763
10764PyDoc_STRVAR(isidentifier__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010765 "S.isidentifier() -> bool\n\
Martin v. Löwis47383402007-08-15 07:32:56 +000010766\n\
10767Return True if S is a valid identifier according\n\
10768to the language definition.");
10769
10770static PyObject*
10771unicode_isidentifier(PyObject *self)
10772{
10773 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
10774}
10775
Georg Brandl559e5d72008-06-11 18:37:52 +000010776PyDoc_STRVAR(isprintable__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010777 "S.isprintable() -> bool\n\
Georg Brandl559e5d72008-06-11 18:37:52 +000010778\n\
10779Return True if all characters in S are considered\n\
10780printable in repr() or S is empty, False otherwise.");
10781
10782static PyObject*
10783unicode_isprintable(PyObject *self)
10784{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010785 Py_ssize_t i, length;
10786 int kind;
10787 void *data;
10788
10789 if (PyUnicode_READY(self) == -1)
10790 return NULL;
10791 length = PyUnicode_GET_LENGTH(self);
10792 kind = PyUnicode_KIND(self);
10793 data = PyUnicode_DATA(self);
Georg Brandl559e5d72008-06-11 18:37:52 +000010794
10795 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010796 if (length == 1)
10797 return PyBool_FromLong(
10798 Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
Georg Brandl559e5d72008-06-11 18:37:52 +000010799
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010800 for (i = 0; i < length; i++) {
10801 if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
Georg Brandl559e5d72008-06-11 18:37:52 +000010802 Py_RETURN_FALSE;
10803 }
10804 }
10805 Py_RETURN_TRUE;
10806}
10807
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010808PyDoc_STRVAR(join__doc__,
Georg Brandl495f7b52009-10-27 15:28:25 +000010809 "S.join(iterable) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010810\n\
10811Return a string which is the concatenation of the strings in the\n\
Georg Brandl495f7b52009-10-27 15:28:25 +000010812iterable. The separator between elements is S.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010813
10814static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000010815unicode_join(PyObject *self, PyObject *data)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010816{
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000010817 return PyUnicode_Join(self, data);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010818}
10819
Martin v. Löwis18e16552006-02-15 17:27:45 +000010820static Py_ssize_t
Guido van Rossumd57fd912000-03-10 22:53:23 +000010821unicode_length(PyUnicodeObject *self)
10822{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010823 if (PyUnicode_READY(self) == -1)
10824 return -1;
10825 return PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010826}
10827
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010828PyDoc_STRVAR(ljust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010829 "S.ljust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010830\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000010831Return S left-justified in a Unicode string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010832done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010833
10834static PyObject *
10835unicode_ljust(PyUnicodeObject *self, PyObject *args)
10836{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010837 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010838 Py_UCS4 fillchar = ' ';
10839
10840 if (PyUnicode_READY(self) == -1)
10841 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010842
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010843 if (!PyArg_ParseTuple(args, "n|O&:ljust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +000010844 return NULL;
10845
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010846 if (_PyUnicode_LENGTH(self) >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000010847 Py_INCREF(self);
10848 return (PyObject*) self;
10849 }
10850
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010851 return (PyObject*) pad(self, 0, width - _PyUnicode_LENGTH(self), fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010852}
10853
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010854PyDoc_STRVAR(lower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010855 "S.lower() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010856\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010857Return a copy of the string S converted to lowercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010858
10859static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000010860unicode_lower(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010861{
Guido van Rossumd57fd912000-03-10 22:53:23 +000010862 return fixup(self, fixlower);
10863}
10864
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000010865#define LEFTSTRIP 0
10866#define RIGHTSTRIP 1
10867#define BOTHSTRIP 2
10868
10869/* Arrays indexed by above */
10870static const char *stripformat[] = {"|O:lstrip", "|O:rstrip", "|O:strip"};
10871
10872#define STRIPNAME(i) (stripformat[i]+3)
10873
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000010874/* externally visible for str.strip(unicode) */
10875PyObject *
10876_PyUnicode_XStrip(PyUnicodeObject *self, int striptype, PyObject *sepobj)
10877{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010878 void *data;
10879 int kind;
10880 Py_ssize_t i, j, len;
10881 BLOOM_MASK sepmask;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000010882
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010883 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
10884 return NULL;
10885
10886 kind = PyUnicode_KIND(self);
10887 data = PyUnicode_DATA(self);
10888 len = PyUnicode_GET_LENGTH(self);
10889 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
10890 PyUnicode_DATA(sepobj),
10891 PyUnicode_GET_LENGTH(sepobj));
Thomas Wouters477c8d52006-05-27 19:21:47 +000010892
Benjamin Peterson14339b62009-01-31 16:36:08 +000010893 i = 0;
10894 if (striptype != RIGHTSTRIP) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010895 while (i < len &&
10896 BLOOM_MEMBER(sepmask, PyUnicode_READ(kind, data, i), sepobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010897 i++;
10898 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000010899 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000010900
Benjamin Peterson14339b62009-01-31 16:36:08 +000010901 j = len;
10902 if (striptype != LEFTSTRIP) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010903 do {
10904 j--;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010905 } while (j >= i &&
10906 BLOOM_MEMBER(sepmask, PyUnicode_READ(kind, data, j), sepobj));
Benjamin Peterson29060642009-01-31 22:14:21 +000010907 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010908 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000010909
Victor Stinner12bab6d2011-10-01 01:53:49 +020010910 return PyUnicode_Substring((PyObject*)self, i, j);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010911}
10912
10913PyObject*
10914PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
10915{
10916 unsigned char *data;
10917 int kind;
Victor Stinner12bab6d2011-10-01 01:53:49 +020010918 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010919
Victor Stinnerde636f32011-10-01 03:55:54 +020010920 if (PyUnicode_READY(self) == -1)
10921 return NULL;
10922
10923 end = Py_MIN(end, PyUnicode_GET_LENGTH(self));
10924
Victor Stinner12bab6d2011-10-01 01:53:49 +020010925 if (start == 0 && end == PyUnicode_GET_LENGTH(self))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010926 {
Victor Stinner12bab6d2011-10-01 01:53:49 +020010927 if (PyUnicode_CheckExact(self)) {
10928 Py_INCREF(self);
10929 return self;
10930 }
10931 else
10932 return PyUnicode_Copy(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010933 }
10934
Victor Stinner12bab6d2011-10-01 01:53:49 +020010935 length = end - start;
10936 if (length == 1)
Victor Stinner2fe5ced2011-10-02 00:25:40 +020010937 return unicode_getitem(self, start);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010938
Victor Stinnerde636f32011-10-01 03:55:54 +020010939 if (start < 0 || end < 0) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020010940 PyErr_SetString(PyExc_IndexError, "string index out of range");
10941 return NULL;
10942 }
10943
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010944 kind = PyUnicode_KIND(self);
10945 data = PyUnicode_1BYTE_DATA(self);
Victor Stinner034f6cf2011-09-30 02:26:44 +020010946 return PyUnicode_FromKindAndData(kind,
10947 data + PyUnicode_KIND_SIZE(kind, start),
Victor Stinner12bab6d2011-10-01 01:53:49 +020010948 length);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010949}
Guido van Rossumd57fd912000-03-10 22:53:23 +000010950
10951static PyObject *
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000010952do_strip(PyUnicodeObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010953{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010954 int kind;
10955 void *data;
10956 Py_ssize_t len, i, j;
10957
10958 if (PyUnicode_READY(self) == -1)
10959 return NULL;
10960
10961 kind = PyUnicode_KIND(self);
10962 data = PyUnicode_DATA(self);
10963 len = PyUnicode_GET_LENGTH(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000010964
Benjamin Peterson14339b62009-01-31 16:36:08 +000010965 i = 0;
10966 if (striptype != RIGHTSTRIP) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010967 while (i < len && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, i))) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010968 i++;
10969 }
10970 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000010971
Benjamin Peterson14339b62009-01-31 16:36:08 +000010972 j = len;
10973 if (striptype != LEFTSTRIP) {
10974 do {
10975 j--;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010976 } while (j >= i && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, j)));
Benjamin Peterson14339b62009-01-31 16:36:08 +000010977 j++;
10978 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000010979
Victor Stinner12bab6d2011-10-01 01:53:49 +020010980 return PyUnicode_Substring((PyObject*)self, i, j);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010981}
10982
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000010983
10984static PyObject *
10985do_argstrip(PyUnicodeObject *self, int striptype, PyObject *args)
10986{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010987 PyObject *sep = NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000010988
Benjamin Peterson14339b62009-01-31 16:36:08 +000010989 if (!PyArg_ParseTuple(args, (char *)stripformat[striptype], &sep))
10990 return NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000010991
Benjamin Peterson14339b62009-01-31 16:36:08 +000010992 if (sep != NULL && sep != Py_None) {
10993 if (PyUnicode_Check(sep))
10994 return _PyUnicode_XStrip(self, striptype, sep);
10995 else {
10996 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010997 "%s arg must be None or str",
10998 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +000010999 return NULL;
11000 }
11001 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011002
Benjamin Peterson14339b62009-01-31 16:36:08 +000011003 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011004}
11005
11006
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011007PyDoc_STRVAR(strip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011008 "S.strip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011009\n\
11010Return a copy of the string S with leading and trailing\n\
11011whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011012If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011013
11014static PyObject *
11015unicode_strip(PyUnicodeObject *self, PyObject *args)
11016{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011017 if (PyTuple_GET_SIZE(args) == 0)
11018 return do_strip(self, BOTHSTRIP); /* Common case */
11019 else
11020 return do_argstrip(self, BOTHSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011021}
11022
11023
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011024PyDoc_STRVAR(lstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011025 "S.lstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011026\n\
11027Return a copy of the string S with leading whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011028If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011029
11030static PyObject *
11031unicode_lstrip(PyUnicodeObject *self, PyObject *args)
11032{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011033 if (PyTuple_GET_SIZE(args) == 0)
11034 return do_strip(self, LEFTSTRIP); /* Common case */
11035 else
11036 return do_argstrip(self, LEFTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011037}
11038
11039
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011040PyDoc_STRVAR(rstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011041 "S.rstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011042\n\
11043Return a copy of the string S with trailing whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011044If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011045
11046static PyObject *
11047unicode_rstrip(PyUnicodeObject *self, PyObject *args)
11048{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011049 if (PyTuple_GET_SIZE(args) == 0)
11050 return do_strip(self, RIGHTSTRIP); /* Common case */
11051 else
11052 return do_argstrip(self, RIGHTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011053}
11054
11055
Guido van Rossumd57fd912000-03-10 22:53:23 +000011056static PyObject*
Martin v. Löwis18e16552006-02-15 17:27:45 +000011057unicode_repeat(PyUnicodeObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011058{
11059 PyUnicodeObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011060 Py_ssize_t nchars, n;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011061
Georg Brandl222de0f2009-04-12 12:01:50 +000011062 if (len < 1) {
11063 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +020011064 return unicode_empty;
Georg Brandl222de0f2009-04-12 12:01:50 +000011065 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011066
Tim Peters7a29bd52001-09-12 03:03:31 +000011067 if (len == 1 && PyUnicode_CheckExact(str)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000011068 /* no repeat, return original string */
11069 Py_INCREF(str);
11070 return (PyObject*) str;
11071 }
Tim Peters8f422462000-09-09 06:13:41 +000011072
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011073 if (PyUnicode_READY(str) == -1)
11074 return NULL;
11075
Victor Stinnerc759f3e2011-10-01 03:09:58 +020011076 if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
Victor Stinner67ca64c2011-10-01 02:47:29 +020011077 PyErr_SetString(PyExc_OverflowError,
11078 "repeated string is too long");
11079 return NULL;
11080 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011081 nchars = len * PyUnicode_GET_LENGTH(str);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011082
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011083 u = (PyUnicodeObject *)PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011084 if (!u)
11085 return NULL;
Victor Stinner67ca64c2011-10-01 02:47:29 +020011086 assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011087
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011088 if (PyUnicode_GET_LENGTH(str) == 1) {
11089 const int kind = PyUnicode_KIND(str);
11090 const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
11091 void *to = PyUnicode_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011092 if (kind == PyUnicode_1BYTE_KIND)
11093 memset(to, (unsigned char)fill_char, len);
11094 else {
11095 for (n = 0; n < len; ++n)
11096 PyUnicode_WRITE(kind, to, n, fill_char);
11097 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011098 }
11099 else {
11100 /* number of characters copied this far */
11101 Py_ssize_t done = PyUnicode_GET_LENGTH(str);
11102 const Py_ssize_t char_size = PyUnicode_CHARACTER_SIZE(str);
11103 char *to = (char *) PyUnicode_DATA(u);
11104 Py_MEMCPY(to, PyUnicode_DATA(str),
11105 PyUnicode_GET_LENGTH(str) * char_size);
Benjamin Peterson29060642009-01-31 22:14:21 +000011106 while (done < nchars) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011107 n = (done <= nchars-done) ? done : nchars-done;
11108 Py_MEMCPY(to + (done * char_size), to, n * char_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011109 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +000011110 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011111 }
11112
11113 return (PyObject*) u;
11114}
11115
Alexander Belopolsky40018472011-02-26 01:02:56 +000011116PyObject *
11117PyUnicode_Replace(PyObject *obj,
11118 PyObject *subobj,
11119 PyObject *replobj,
11120 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011121{
11122 PyObject *self;
11123 PyObject *str1;
11124 PyObject *str2;
11125 PyObject *result;
11126
11127 self = PyUnicode_FromObject(obj);
Victor Stinnere9a29352011-10-01 02:14:59 +020011128 if (self == NULL || PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000011129 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011130 str1 = PyUnicode_FromObject(subobj);
Victor Stinnere9a29352011-10-01 02:14:59 +020011131 if (str1 == NULL || PyUnicode_READY(str1) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011132 Py_DECREF(self);
11133 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011134 }
11135 str2 = PyUnicode_FromObject(replobj);
Victor Stinnere9a29352011-10-01 02:14:59 +020011136 if (str2 == NULL || PyUnicode_READY(str2)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011137 Py_DECREF(self);
11138 Py_DECREF(str1);
11139 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011140 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011141 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011142 Py_DECREF(self);
11143 Py_DECREF(str1);
11144 Py_DECREF(str2);
11145 return result;
11146}
11147
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011148PyDoc_STRVAR(replace__doc__,
Ezio Melottic1897e72010-06-26 18:50:39 +000011149 "S.replace(old, new[, count]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011150\n\
11151Return a copy of S with all occurrences of substring\n\
Georg Brandlf08a9dd2008-06-10 16:57:31 +000011152old replaced by new. If the optional argument count is\n\
11153given, only the first count occurrences are replaced.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011154
11155static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011156unicode_replace(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011157{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011158 PyObject *str1;
11159 PyObject *str2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011160 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011161 PyObject *result;
11162
Martin v. Löwis18e16552006-02-15 17:27:45 +000011163 if (!PyArg_ParseTuple(args, "OO|n:replace", &str1, &str2, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011164 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011165 if (!PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000011166 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011167 str1 = PyUnicode_FromObject(str1);
11168 if (str1 == NULL || PyUnicode_READY(str1) == -1)
11169 return NULL;
11170 str2 = PyUnicode_FromObject(str2);
Victor Stinnere9a29352011-10-01 02:14:59 +020011171 if (str2 == NULL || PyUnicode_READY(str2) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011172 Py_DECREF(str1);
11173 return NULL;
Walter Dörwaldf6b56ae2003-02-09 23:42:56 +000011174 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011175
11176 result = replace(self, str1, str2, maxcount);
11177
11178 Py_DECREF(str1);
11179 Py_DECREF(str2);
11180 return result;
11181}
11182
Alexander Belopolsky40018472011-02-26 01:02:56 +000011183static PyObject *
11184unicode_repr(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011185{
Walter Dörwald79e913e2007-05-12 11:08:06 +000011186 PyObject *repr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011187 Py_ssize_t isize;
11188 Py_ssize_t osize, squote, dquote, i, o;
11189 Py_UCS4 max, quote;
11190 int ikind, okind;
11191 void *idata, *odata;
Walter Dörwald79e913e2007-05-12 11:08:06 +000011192
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011193 if (PyUnicode_READY(unicode) == -1)
Walter Dörwald79e913e2007-05-12 11:08:06 +000011194 return NULL;
11195
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011196 isize = PyUnicode_GET_LENGTH(unicode);
11197 idata = PyUnicode_DATA(unicode);
Walter Dörwald79e913e2007-05-12 11:08:06 +000011198
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011199 /* Compute length of output, quote characters, and
11200 maximum character */
11201 osize = 2; /* quotes */
11202 max = 127;
11203 squote = dquote = 0;
11204 ikind = PyUnicode_KIND(unicode);
11205 for (i = 0; i < isize; i++) {
11206 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
11207 switch (ch) {
11208 case '\'': squote++; osize++; break;
11209 case '"': dquote++; osize++; break;
11210 case '\\': case '\t': case '\r': case '\n':
11211 osize += 2; break;
11212 default:
11213 /* Fast-path ASCII */
11214 if (ch < ' ' || ch == 0x7f)
11215 osize += 4; /* \xHH */
11216 else if (ch < 0x7f)
11217 osize++;
11218 else if (Py_UNICODE_ISPRINTABLE(ch)) {
11219 osize++;
11220 max = ch > max ? ch : max;
11221 }
11222 else if (ch < 0x100)
11223 osize += 4; /* \xHH */
11224 else if (ch < 0x10000)
11225 osize += 6; /* \uHHHH */
11226 else
11227 osize += 10; /* \uHHHHHHHH */
11228 }
11229 }
11230
11231 quote = '\'';
11232 if (squote) {
11233 if (dquote)
11234 /* Both squote and dquote present. Use squote,
11235 and escape them */
11236 osize += squote;
11237 else
11238 quote = '"';
11239 }
11240
11241 repr = PyUnicode_New(osize, max);
11242 if (repr == NULL)
11243 return NULL;
11244 okind = PyUnicode_KIND(repr);
11245 odata = PyUnicode_DATA(repr);
11246
11247 PyUnicode_WRITE(okind, odata, 0, quote);
11248 PyUnicode_WRITE(okind, odata, osize-1, quote);
11249
11250 for (i = 0, o = 1; i < isize; i++) {
11251 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Walter Dörwald79e913e2007-05-12 11:08:06 +000011252
11253 /* Escape quotes and backslashes */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011254 if ((ch == quote) || (ch == '\\')) {
11255 PyUnicode_WRITE(okind, odata, o++, '\\');
11256 PyUnicode_WRITE(okind, odata, o++, ch);
Walter Dörwald79e913e2007-05-12 11:08:06 +000011257 continue;
11258 }
11259
Benjamin Peterson29060642009-01-31 22:14:21 +000011260 /* Map special whitespace to '\t', \n', '\r' */
Georg Brandl559e5d72008-06-11 18:37:52 +000011261 if (ch == '\t') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011262 PyUnicode_WRITE(okind, odata, o++, '\\');
11263 PyUnicode_WRITE(okind, odata, o++, 't');
Walter Dörwald79e913e2007-05-12 11:08:06 +000011264 }
11265 else if (ch == '\n') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011266 PyUnicode_WRITE(okind, odata, o++, '\\');
11267 PyUnicode_WRITE(okind, odata, o++, 'n');
Walter Dörwald79e913e2007-05-12 11:08:06 +000011268 }
11269 else if (ch == '\r') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011270 PyUnicode_WRITE(okind, odata, o++, '\\');
11271 PyUnicode_WRITE(okind, odata, o++, 'r');
Walter Dörwald79e913e2007-05-12 11:08:06 +000011272 }
11273
11274 /* Map non-printable US ASCII to '\xhh' */
Georg Brandl559e5d72008-06-11 18:37:52 +000011275 else if (ch < ' ' || ch == 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011276 PyUnicode_WRITE(okind, odata, o++, '\\');
11277 PyUnicode_WRITE(okind, odata, o++, 'x');
11278 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 4) & 0x000F]);
11279 PyUnicode_WRITE(okind, odata, o++, hexdigits[ch & 0x000F]);
Walter Dörwald79e913e2007-05-12 11:08:06 +000011280 }
11281
Georg Brandl559e5d72008-06-11 18:37:52 +000011282 /* Copy ASCII characters as-is */
11283 else if (ch < 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011284 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000011285 }
11286
Benjamin Peterson29060642009-01-31 22:14:21 +000011287 /* Non-ASCII characters */
Georg Brandl559e5d72008-06-11 18:37:52 +000011288 else {
Benjamin Peterson14339b62009-01-31 16:36:08 +000011289 /* Map Unicode whitespace and control characters
Georg Brandl559e5d72008-06-11 18:37:52 +000011290 (categories Z* and C* except ASCII space)
11291 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011292 if (!Py_UNICODE_ISPRINTABLE(ch)) {
Georg Brandl559e5d72008-06-11 18:37:52 +000011293 /* Map 8-bit characters to '\xhh' */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011294 if (ch <= 0xff) {
11295 PyUnicode_WRITE(okind, odata, o++, '\\');
11296 PyUnicode_WRITE(okind, odata, o++, 'x');
11297 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 4) & 0x000F]);
11298 PyUnicode_WRITE(okind, odata, o++, hexdigits[ch & 0x000F]);
Georg Brandl559e5d72008-06-11 18:37:52 +000011299 }
11300 /* Map 21-bit characters to '\U00xxxxxx' */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011301 else if (ch >= 0x10000) {
11302 PyUnicode_WRITE(okind, odata, o++, '\\');
11303 PyUnicode_WRITE(okind, odata, o++, 'U');
11304 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 28) & 0xF]);
11305 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 24) & 0xF]);
11306 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 20) & 0xF]);
11307 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 16) & 0xF]);
11308 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 12) & 0xF]);
11309 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 8) & 0xF]);
11310 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 4) & 0xF]);
11311 PyUnicode_WRITE(okind, odata, o++, hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000011312 }
11313 /* Map 16-bit characters to '\uxxxx' */
11314 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011315 PyUnicode_WRITE(okind, odata, o++, '\\');
11316 PyUnicode_WRITE(okind, odata, o++, 'u');
11317 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 12) & 0xF]);
11318 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 8) & 0xF]);
11319 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 4) & 0xF]);
11320 PyUnicode_WRITE(okind, odata, o++, hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000011321 }
11322 }
11323 /* Copy characters as-is */
11324 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011325 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000011326 }
11327 }
Walter Dörwald79e913e2007-05-12 11:08:06 +000011328 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011329 /* Closing quote already added at the beginning */
Walter Dörwald79e913e2007-05-12 11:08:06 +000011330 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011331}
11332
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011333PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011334 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011335\n\
11336Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080011337such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011338arguments start and end are interpreted as in slice notation.\n\
11339\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011340Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011341
11342static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011343unicode_rfind(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011344{
Jesus Ceaac451502011-04-20 17:09:23 +020011345 PyUnicodeObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011346 Py_ssize_t start;
11347 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011348 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011349
Jesus Ceaac451502011-04-20 17:09:23 +020011350 if (!stringlib_parse_args_finds_unicode("rfind", args, &substring,
11351 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000011352 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011353
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011354 if (PyUnicode_READY(self) == -1)
11355 return NULL;
11356 if (PyUnicode_READY(substring) == -1)
11357 return NULL;
11358
11359 result = any_find_slice(
11360 ucs1lib_rfind_slice, ucs2lib_rfind_slice, ucs4lib_rfind_slice,
11361 self, (PyObject*)substring, start, end
Thomas Wouters477c8d52006-05-27 19:21:47 +000011362 );
Guido van Rossumd57fd912000-03-10 22:53:23 +000011363
11364 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011365
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011366 if (result == -2)
11367 return NULL;
11368
Christian Heimes217cfd12007-12-02 14:31:20 +000011369 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011370}
11371
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011372PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011373 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011374\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011375Like S.rfind() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011376
11377static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011378unicode_rindex(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011379{
Jesus Ceaac451502011-04-20 17:09:23 +020011380 PyUnicodeObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011381 Py_ssize_t start;
11382 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011383 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011384
Jesus Ceaac451502011-04-20 17:09:23 +020011385 if (!stringlib_parse_args_finds_unicode("rindex", args, &substring,
11386 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000011387 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011388
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011389 if (PyUnicode_READY(self) == -1)
11390 return NULL;
11391 if (PyUnicode_READY(substring) == -1)
11392 return NULL;
11393
11394 result = any_find_slice(
11395 ucs1lib_rfind_slice, ucs2lib_rfind_slice, ucs4lib_rfind_slice,
11396 self, (PyObject*)substring, start, end
Thomas Wouters477c8d52006-05-27 19:21:47 +000011397 );
Guido van Rossumd57fd912000-03-10 22:53:23 +000011398
11399 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011400
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011401 if (result == -2)
11402 return NULL;
11403
Guido van Rossumd57fd912000-03-10 22:53:23 +000011404 if (result < 0) {
11405 PyErr_SetString(PyExc_ValueError, "substring not found");
11406 return NULL;
11407 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011408
Christian Heimes217cfd12007-12-02 14:31:20 +000011409 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011410}
11411
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011412PyDoc_STRVAR(rjust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011413 "S.rjust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011414\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000011415Return S right-justified in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011416done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011417
11418static PyObject *
11419unicode_rjust(PyUnicodeObject *self, PyObject *args)
11420{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011421 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011422 Py_UCS4 fillchar = ' ';
11423
Victor Stinnere9a29352011-10-01 02:14:59 +020011424 if (!PyArg_ParseTuple(args, "n|O&:rjust", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011425 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011426
Victor Stinnere9a29352011-10-01 02:14:59 +020011427 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011428 return NULL;
11429
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011430 if (_PyUnicode_LENGTH(self) >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000011431 Py_INCREF(self);
11432 return (PyObject*) self;
11433 }
11434
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011435 return (PyObject*) pad(self, width - _PyUnicode_LENGTH(self), 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011436}
11437
Alexander Belopolsky40018472011-02-26 01:02:56 +000011438PyObject *
11439PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011440{
11441 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +000011442
Guido van Rossumd57fd912000-03-10 22:53:23 +000011443 s = PyUnicode_FromObject(s);
11444 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000011445 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000011446 if (sep != NULL) {
11447 sep = PyUnicode_FromObject(sep);
11448 if (sep == NULL) {
11449 Py_DECREF(s);
11450 return NULL;
11451 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011452 }
11453
11454 result = split((PyUnicodeObject *)s, (PyUnicodeObject *)sep, maxsplit);
11455
11456 Py_DECREF(s);
11457 Py_XDECREF(sep);
11458 return result;
11459}
11460
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011461PyDoc_STRVAR(split__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011462 "S.split([sep[, maxsplit]]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011463\n\
11464Return a list of the words in S, using sep as the\n\
11465delimiter string. If maxsplit is given, at most maxsplit\n\
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000011466splits are done. If sep is not specified or is None, any\n\
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +000011467whitespace string is a separator and empty strings are\n\
11468removed from the result.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011469
11470static PyObject*
11471unicode_split(PyUnicodeObject *self, PyObject *args)
11472{
11473 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011474 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011475
Martin v. Löwis18e16552006-02-15 17:27:45 +000011476 if (!PyArg_ParseTuple(args, "|On:split", &substring, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011477 return NULL;
11478
11479 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000011480 return split(self, NULL, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011481 else if (PyUnicode_Check(substring))
Benjamin Peterson29060642009-01-31 22:14:21 +000011482 return split(self, (PyUnicodeObject *)substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011483 else
Benjamin Peterson29060642009-01-31 22:14:21 +000011484 return PyUnicode_Split((PyObject *)self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011485}
11486
Thomas Wouters477c8d52006-05-27 19:21:47 +000011487PyObject *
11488PyUnicode_Partition(PyObject *str_in, PyObject *sep_in)
11489{
11490 PyObject* str_obj;
11491 PyObject* sep_obj;
11492 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011493 int kind1, kind2, kind;
11494 void *buf1 = NULL, *buf2 = NULL;
11495 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011496
11497 str_obj = PyUnicode_FromObject(str_in);
Victor Stinnere9a29352011-10-01 02:14:59 +020011498 if (!str_obj || PyUnicode_READY(str_obj) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000011499 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011500 sep_obj = PyUnicode_FromObject(sep_in);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011501 if (!sep_obj || PyUnicode_READY(sep_obj) == -1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000011502 Py_DECREF(str_obj);
11503 return NULL;
11504 }
11505
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011506 kind1 = PyUnicode_KIND(str_in);
11507 kind2 = PyUnicode_KIND(sep_obj);
11508 kind = kind1 > kind2 ? kind1 : kind2;
11509 buf1 = PyUnicode_DATA(str_in);
11510 if (kind1 != kind)
11511 buf1 = _PyUnicode_AsKind(str_in, kind);
11512 if (!buf1)
11513 goto onError;
11514 buf2 = PyUnicode_DATA(sep_obj);
11515 if (kind2 != kind)
11516 buf2 = _PyUnicode_AsKind(sep_obj, kind);
11517 if (!buf2)
11518 goto onError;
11519 len1 = PyUnicode_GET_LENGTH(str_obj);
11520 len2 = PyUnicode_GET_LENGTH(sep_obj);
11521
11522 switch(PyUnicode_KIND(str_in)) {
11523 case PyUnicode_1BYTE_KIND:
11524 out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
11525 break;
11526 case PyUnicode_2BYTE_KIND:
11527 out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
11528 break;
11529 case PyUnicode_4BYTE_KIND:
11530 out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
11531 break;
11532 default:
11533 assert(0);
11534 out = 0;
11535 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011536
11537 Py_DECREF(sep_obj);
11538 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011539 if (kind1 != kind)
11540 PyMem_Free(buf1);
11541 if (kind2 != kind)
11542 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011543
11544 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011545 onError:
11546 Py_DECREF(sep_obj);
11547 Py_DECREF(str_obj);
11548 if (kind1 != kind && buf1)
11549 PyMem_Free(buf1);
11550 if (kind2 != kind && buf2)
11551 PyMem_Free(buf2);
11552 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011553}
11554
11555
11556PyObject *
11557PyUnicode_RPartition(PyObject *str_in, PyObject *sep_in)
11558{
11559 PyObject* str_obj;
11560 PyObject* sep_obj;
11561 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011562 int kind1, kind2, kind;
11563 void *buf1 = NULL, *buf2 = NULL;
11564 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011565
11566 str_obj = PyUnicode_FromObject(str_in);
11567 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000011568 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011569 sep_obj = PyUnicode_FromObject(sep_in);
11570 if (!sep_obj) {
11571 Py_DECREF(str_obj);
11572 return NULL;
11573 }
11574
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011575 kind1 = PyUnicode_KIND(str_in);
11576 kind2 = PyUnicode_KIND(sep_obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +020011577 kind = Py_MAX(kind1, kind2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011578 buf1 = PyUnicode_DATA(str_in);
11579 if (kind1 != kind)
11580 buf1 = _PyUnicode_AsKind(str_in, kind);
11581 if (!buf1)
11582 goto onError;
11583 buf2 = PyUnicode_DATA(sep_obj);
11584 if (kind2 != kind)
11585 buf2 = _PyUnicode_AsKind(sep_obj, kind);
11586 if (!buf2)
11587 goto onError;
11588 len1 = PyUnicode_GET_LENGTH(str_obj);
11589 len2 = PyUnicode_GET_LENGTH(sep_obj);
11590
11591 switch(PyUnicode_KIND(str_in)) {
11592 case PyUnicode_1BYTE_KIND:
11593 out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
11594 break;
11595 case PyUnicode_2BYTE_KIND:
11596 out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
11597 break;
11598 case PyUnicode_4BYTE_KIND:
11599 out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
11600 break;
11601 default:
11602 assert(0);
11603 out = 0;
11604 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011605
11606 Py_DECREF(sep_obj);
11607 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011608 if (kind1 != kind)
11609 PyMem_Free(buf1);
11610 if (kind2 != kind)
11611 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011612
11613 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011614 onError:
11615 Py_DECREF(sep_obj);
11616 Py_DECREF(str_obj);
11617 if (kind1 != kind && buf1)
11618 PyMem_Free(buf1);
11619 if (kind2 != kind && buf2)
11620 PyMem_Free(buf2);
11621 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011622}
11623
11624PyDoc_STRVAR(partition__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011625 "S.partition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000011626\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000011627Search for the separator sep in S, and return the part before it,\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000011628the separator itself, and the part after it. If the separator is not\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000011629found, return S and two empty strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000011630
11631static PyObject*
11632unicode_partition(PyUnicodeObject *self, PyObject *separator)
11633{
11634 return PyUnicode_Partition((PyObject *)self, separator);
11635}
11636
11637PyDoc_STRVAR(rpartition__doc__,
Ezio Melotti5b2b2422010-01-25 11:58:28 +000011638 "S.rpartition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000011639\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000011640Search for the separator sep in S, starting at the end of S, and return\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000011641the part before it, the separator itself, and the part after it. If the\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000011642separator is not found, return two empty strings and S.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000011643
11644static PyObject*
11645unicode_rpartition(PyUnicodeObject *self, PyObject *separator)
11646{
11647 return PyUnicode_RPartition((PyObject *)self, separator);
11648}
11649
Alexander Belopolsky40018472011-02-26 01:02:56 +000011650PyObject *
11651PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000011652{
11653 PyObject *result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011654
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000011655 s = PyUnicode_FromObject(s);
11656 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000011657 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000011658 if (sep != NULL) {
11659 sep = PyUnicode_FromObject(sep);
11660 if (sep == NULL) {
11661 Py_DECREF(s);
11662 return NULL;
11663 }
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000011664 }
11665
11666 result = rsplit((PyUnicodeObject *)s, (PyUnicodeObject *)sep, maxsplit);
11667
11668 Py_DECREF(s);
11669 Py_XDECREF(sep);
11670 return result;
11671}
11672
11673PyDoc_STRVAR(rsplit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011674 "S.rsplit([sep[, maxsplit]]) -> list of strings\n\
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000011675\n\
11676Return a list of the words in S, using sep as the\n\
11677delimiter string, starting at the end of the string and\n\
11678working to the front. If maxsplit is given, at most maxsplit\n\
11679splits are done. If sep is not specified, any whitespace string\n\
11680is a separator.");
11681
11682static PyObject*
11683unicode_rsplit(PyUnicodeObject *self, PyObject *args)
11684{
11685 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011686 Py_ssize_t maxcount = -1;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000011687
Martin v. Löwis18e16552006-02-15 17:27:45 +000011688 if (!PyArg_ParseTuple(args, "|On:rsplit", &substring, &maxcount))
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000011689 return NULL;
11690
11691 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000011692 return rsplit(self, NULL, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000011693 else if (PyUnicode_Check(substring))
Benjamin Peterson29060642009-01-31 22:14:21 +000011694 return rsplit(self, (PyUnicodeObject *)substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000011695 else
Benjamin Peterson29060642009-01-31 22:14:21 +000011696 return PyUnicode_RSplit((PyObject *)self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000011697}
11698
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011699PyDoc_STRVAR(splitlines__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011700 "S.splitlines([keepends]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011701\n\
11702Return a list of the lines in S, breaking at line boundaries.\n\
Guido van Rossum86662912000-04-11 15:38:46 +000011703Line breaks are not included in the resulting list unless keepends\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011704is given and true.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011705
11706static PyObject*
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010011707unicode_splitlines(PyUnicodeObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011708{
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010011709 static char *kwlist[] = {"keepends", 0};
Guido van Rossum86662912000-04-11 15:38:46 +000011710 int keepends = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011711
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010011712 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:splitlines",
11713 kwlist, &keepends))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011714 return NULL;
11715
Guido van Rossum86662912000-04-11 15:38:46 +000011716 return PyUnicode_Splitlines((PyObject *)self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011717}
11718
11719static
Guido van Rossumf15a29f2007-05-04 00:41:39 +000011720PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011721{
Walter Dörwald346737f2007-05-31 10:44:43 +000011722 if (PyUnicode_CheckExact(self)) {
11723 Py_INCREF(self);
11724 return self;
11725 } else
11726 /* Subtype -- return genuine unicode string with the same value. */
Victor Stinner034f6cf2011-09-30 02:26:44 +020011727 return PyUnicode_Copy(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011728}
11729
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011730PyDoc_STRVAR(swapcase__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011731 "S.swapcase() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011732\n\
11733Return a copy of S with uppercase characters converted to lowercase\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011734and vice versa.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011735
11736static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011737unicode_swapcase(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011738{
Guido van Rossumd57fd912000-03-10 22:53:23 +000011739 return fixup(self, fixswapcase);
11740}
11741
Georg Brandlceee0772007-11-27 23:48:05 +000011742PyDoc_STRVAR(maketrans__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011743 "str.maketrans(x[, y[, z]]) -> dict (static method)\n\
Georg Brandlceee0772007-11-27 23:48:05 +000011744\n\
11745Return a translation table usable for str.translate().\n\
11746If there is only one argument, it must be a dictionary mapping Unicode\n\
11747ordinals (integers) or characters to Unicode ordinals, strings or None.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011748Character keys will be then converted to ordinals.\n\
Georg Brandlceee0772007-11-27 23:48:05 +000011749If there are two arguments, they must be strings of equal length, and\n\
11750in the resulting dictionary, each character in x will be mapped to the\n\
11751character at the same position in y. If there is a third argument, it\n\
11752must be a string, whose characters will be mapped to None in the result.");
11753
11754static PyObject*
11755unicode_maketrans(PyUnicodeObject *null, PyObject *args)
11756{
11757 PyObject *x, *y = NULL, *z = NULL;
11758 PyObject *new = NULL, *key, *value;
11759 Py_ssize_t i = 0;
11760 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011761
Georg Brandlceee0772007-11-27 23:48:05 +000011762 if (!PyArg_ParseTuple(args, "O|UU:maketrans", &x, &y, &z))
11763 return NULL;
11764 new = PyDict_New();
11765 if (!new)
11766 return NULL;
11767 if (y != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011768 int x_kind, y_kind, z_kind;
11769 void *x_data, *y_data, *z_data;
11770
Georg Brandlceee0772007-11-27 23:48:05 +000011771 /* x must be a string too, of equal length */
Georg Brandlceee0772007-11-27 23:48:05 +000011772 if (!PyUnicode_Check(x)) {
11773 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
11774 "be a string if there is a second argument");
11775 goto err;
11776 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011777 if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
Georg Brandlceee0772007-11-27 23:48:05 +000011778 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
11779 "arguments must have equal length");
11780 goto err;
11781 }
11782 /* create entries for translating chars in x to those in y */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011783 x_kind = PyUnicode_KIND(x);
11784 y_kind = PyUnicode_KIND(y);
11785 x_data = PyUnicode_DATA(x);
11786 y_data = PyUnicode_DATA(y);
11787 for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
11788 key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
11789 value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000011790 if (!key || !value)
11791 goto err;
11792 res = PyDict_SetItem(new, key, value);
11793 Py_DECREF(key);
11794 Py_DECREF(value);
11795 if (res < 0)
11796 goto err;
11797 }
11798 /* create entries for deleting chars in z */
11799 if (z != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011800 z_kind = PyUnicode_KIND(z);
11801 z_data = PyUnicode_DATA(z);
Georg Brandlceee0772007-11-27 23:48:05 +000011802 for (i = 0; i < PyUnicode_GET_SIZE(z); i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011803 key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000011804 if (!key)
11805 goto err;
11806 res = PyDict_SetItem(new, key, Py_None);
11807 Py_DECREF(key);
11808 if (res < 0)
11809 goto err;
11810 }
11811 }
11812 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011813 int kind;
11814 void *data;
11815
Georg Brandlceee0772007-11-27 23:48:05 +000011816 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +000011817 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +000011818 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
11819 "to maketrans it must be a dict");
11820 goto err;
11821 }
11822 /* copy entries into the new dict, converting string keys to int keys */
11823 while (PyDict_Next(x, &i, &key, &value)) {
11824 if (PyUnicode_Check(key)) {
11825 /* convert string keys to integer keys */
11826 PyObject *newkey;
11827 if (PyUnicode_GET_SIZE(key) != 1) {
11828 PyErr_SetString(PyExc_ValueError, "string keys in translate "
11829 "table must be of length 1");
11830 goto err;
11831 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011832 kind = PyUnicode_KIND(key);
11833 data = PyUnicode_DATA(key);
11834 newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
Georg Brandlceee0772007-11-27 23:48:05 +000011835 if (!newkey)
11836 goto err;
11837 res = PyDict_SetItem(new, newkey, value);
11838 Py_DECREF(newkey);
11839 if (res < 0)
11840 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +000011841 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +000011842 /* just keep integer keys */
11843 if (PyDict_SetItem(new, key, value) < 0)
11844 goto err;
11845 } else {
11846 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
11847 "be strings or integers");
11848 goto err;
11849 }
11850 }
11851 }
11852 return new;
11853 err:
11854 Py_DECREF(new);
11855 return NULL;
11856}
11857
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011858PyDoc_STRVAR(translate__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011859 "S.translate(table) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011860\n\
11861Return a copy of the string S, where all characters have been mapped\n\
11862through the given translation table, which must be a mapping of\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011863Unicode ordinals to Unicode ordinals, strings, or None.\n\
Walter Dörwald5c1ee172002-09-04 20:31:32 +000011864Unmapped characters are left untouched. Characters mapped to None\n\
11865are deleted.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011866
11867static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011868unicode_translate(PyObject *self, PyObject *table)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011869{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011870 return _PyUnicode_TranslateCharmap(self, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011871}
11872
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011873PyDoc_STRVAR(upper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011874 "S.upper() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011875\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011876Return a copy of S converted to uppercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011877
11878static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011879unicode_upper(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011880{
Guido van Rossumd57fd912000-03-10 22:53:23 +000011881 return fixup(self, fixupper);
11882}
11883
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011884PyDoc_STRVAR(zfill__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011885 "S.zfill(width) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011886\n\
Benjamin Peterson9aa42992008-09-10 21:57:34 +000011887Pad a numeric string S with zeros on the left, to fill a field\n\
11888of the specified width. The string S is never truncated.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011889
11890static PyObject *
11891unicode_zfill(PyUnicodeObject *self, PyObject *args)
11892{
Martin v. Löwis18e16552006-02-15 17:27:45 +000011893 Py_ssize_t fill;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011894 PyUnicodeObject *u;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011895 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011896 int kind;
11897 void *data;
11898 Py_UCS4 chr;
11899
11900 if (PyUnicode_READY(self) == -1)
11901 return NULL;
11902
Martin v. Löwis18e16552006-02-15 17:27:45 +000011903 if (!PyArg_ParseTuple(args, "n:zfill", &width))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011904 return NULL;
11905
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011906 if (PyUnicode_GET_LENGTH(self) >= width) {
Walter Dörwald0fe940c2002-04-15 18:42:15 +000011907 if (PyUnicode_CheckExact(self)) {
11908 Py_INCREF(self);
11909 return (PyObject*) self;
11910 }
11911 else
Victor Stinner2219e0a2011-10-01 01:16:59 +020011912 return PyUnicode_Copy((PyObject*)self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011913 }
11914
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011915 fill = width - _PyUnicode_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011916
11917 u = pad(self, fill, 0, '0');
11918
Walter Dörwald068325e2002-04-15 13:36:47 +000011919 if (u == NULL)
11920 return NULL;
11921
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011922 kind = PyUnicode_KIND(u);
11923 data = PyUnicode_DATA(u);
11924 chr = PyUnicode_READ(kind, data, fill);
11925
11926 if (chr == '+' || chr == '-') {
Guido van Rossumd57fd912000-03-10 22:53:23 +000011927 /* move sign to beginning of string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011928 PyUnicode_WRITE(kind, data, 0, chr);
11929 PyUnicode_WRITE(kind, data, fill, '0');
Guido van Rossumd57fd912000-03-10 22:53:23 +000011930 }
11931
11932 return (PyObject*) u;
11933}
Guido van Rossumd57fd912000-03-10 22:53:23 +000011934
11935#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000011936static PyObject *
11937unicode__decimal2ascii(PyObject *self)
11938{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011939 return PyUnicode_TransformDecimalAndSpaceToASCII(self);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000011940}
Guido van Rossumd57fd912000-03-10 22:53:23 +000011941#endif
11942
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011943PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011944 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011945\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000011946Return True if S starts with the specified prefix, False otherwise.\n\
11947With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000011948With optional end, stop comparing S at that position.\n\
11949prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011950
11951static PyObject *
11952unicode_startswith(PyUnicodeObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000011953 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011954{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000011955 PyObject *subobj;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011956 PyUnicodeObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011957 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011958 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000011959 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011960
Jesus Ceaac451502011-04-20 17:09:23 +020011961 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000011962 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000011963 if (PyTuple_Check(subobj)) {
11964 Py_ssize_t i;
11965 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
11966 substring = (PyUnicodeObject *)PyUnicode_FromObject(
Benjamin Peterson29060642009-01-31 22:14:21 +000011967 PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000011968 if (substring == NULL)
11969 return NULL;
11970 result = tailmatch(self, substring, start, end, -1);
11971 Py_DECREF(substring);
11972 if (result) {
11973 Py_RETURN_TRUE;
11974 }
11975 }
11976 /* nothing matched */
11977 Py_RETURN_FALSE;
11978 }
11979 substring = (PyUnicodeObject *)PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030011980 if (substring == NULL) {
11981 if (PyErr_ExceptionMatches(PyExc_TypeError))
11982 PyErr_Format(PyExc_TypeError, "startswith first arg must be str or "
11983 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000011984 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030011985 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000011986 result = tailmatch(self, substring, start, end, -1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011987 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000011988 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011989}
11990
11991
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011992PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011993 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011994\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000011995Return True if S ends with the specified suffix, False otherwise.\n\
11996With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000011997With optional end, stop comparing S at that position.\n\
11998suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011999
12000static PyObject *
12001unicode_endswith(PyUnicodeObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000012002 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012003{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012004 PyObject *subobj;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012005 PyUnicodeObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012006 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012007 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012008 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012009
Jesus Ceaac451502011-04-20 17:09:23 +020012010 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000012011 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012012 if (PyTuple_Check(subobj)) {
12013 Py_ssize_t i;
12014 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
12015 substring = (PyUnicodeObject *)PyUnicode_FromObject(
Benjamin Peterson29060642009-01-31 22:14:21 +000012016 PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012017 if (substring == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000012018 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012019 result = tailmatch(self, substring, start, end, +1);
12020 Py_DECREF(substring);
12021 if (result) {
12022 Py_RETURN_TRUE;
12023 }
12024 }
12025 Py_RETURN_FALSE;
12026 }
12027 substring = (PyUnicodeObject *)PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030012028 if (substring == NULL) {
12029 if (PyErr_ExceptionMatches(PyExc_TypeError))
12030 PyErr_Format(PyExc_TypeError, "endswith first arg must be str or "
12031 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000012032 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030012033 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012034 result = tailmatch(self, substring, start, end, +1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012035 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012036 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012037}
12038
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012039#include "stringlib/unicode_format.h"
Eric Smith8c663262007-08-25 02:26:07 +000012040
12041PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012042 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000012043\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012044Return a formatted version of S, using substitutions from args and kwargs.\n\
12045The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +000012046
Eric Smith27bbca62010-11-04 17:06:58 +000012047PyDoc_STRVAR(format_map__doc__,
12048 "S.format_map(mapping) -> str\n\
12049\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012050Return a formatted version of S, using substitutions from mapping.\n\
12051The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +000012052
Eric Smith4a7d76d2008-05-30 18:10:19 +000012053static PyObject *
12054unicode__format__(PyObject* self, PyObject* args)
12055{
12056 PyObject *format_spec;
12057
12058 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
12059 return NULL;
12060
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012061 return _PyUnicode_FormatAdvanced(self, format_spec, 0,
12062 PyUnicode_GET_LENGTH(format_spec));
Eric Smith4a7d76d2008-05-30 18:10:19 +000012063}
12064
Eric Smith8c663262007-08-25 02:26:07 +000012065PyDoc_STRVAR(p_format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012066 "S.__format__(format_spec) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000012067\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012068Return a formatted version of S as described by format_spec.");
Eric Smith8c663262007-08-25 02:26:07 +000012069
12070static PyObject *
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012071unicode__sizeof__(PyUnicodeObject *v)
12072{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012073 Py_ssize_t size;
12074
12075 /* If it's a compact object, account for base structure +
12076 character data. */
12077 if (PyUnicode_IS_COMPACT_ASCII(v))
12078 size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(v) + 1;
12079 else if (PyUnicode_IS_COMPACT(v))
12080 size = sizeof(PyCompactUnicodeObject) +
12081 (PyUnicode_GET_LENGTH(v) + 1) * PyUnicode_CHARACTER_SIZE(v);
12082 else {
12083 /* If it is a two-block object, account for base object, and
12084 for character block if present. */
12085 size = sizeof(PyUnicodeObject);
Victor Stinnerc3c74152011-10-02 20:39:55 +020012086 if (_PyUnicode_DATA_ANY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012087 size += (PyUnicode_GET_LENGTH(v) + 1) *
12088 PyUnicode_CHARACTER_SIZE(v);
12089 }
12090 /* If the wstr pointer is present, account for it unless it is shared
Victor Stinnera3be6132011-10-03 02:16:37 +020012091 with the data pointer. Check if the data is not shared. */
Victor Stinner03490912011-10-03 23:45:12 +020012092 if (_PyUnicode_HAS_WSTR_MEMORY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012093 size += (PyUnicode_WSTR_LENGTH(v) + 1) * sizeof(wchar_t);
Victor Stinner829c0ad2011-10-03 01:08:02 +020012094 if (_PyUnicode_HAS_UTF8_MEMORY(v))
Victor Stinnere90fe6a2011-10-01 16:48:13 +020012095 size += PyUnicode_UTF8_LENGTH(v) + 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012096
12097 return PyLong_FromSsize_t(size);
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012098}
12099
12100PyDoc_STRVAR(sizeof__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012101 "S.__sizeof__() -> size of S in memory, in bytes");
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012102
12103static PyObject *
Victor Stinner034f6cf2011-09-30 02:26:44 +020012104unicode_getnewargs(PyObject *v)
Guido van Rossum5d9113d2003-01-29 17:58:45 +000012105{
Victor Stinner034f6cf2011-09-30 02:26:44 +020012106 PyObject *copy = PyUnicode_Copy(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012107 if (!copy)
12108 return NULL;
12109 return Py_BuildValue("(N)", copy);
Guido van Rossum5d9113d2003-01-29 17:58:45 +000012110}
12111
Guido van Rossumd57fd912000-03-10 22:53:23 +000012112static PyMethodDef unicode_methods[] = {
12113
12114 /* Order is according to common usage: often used methods should
12115 appear first, since lookup is done sequentially. */
12116
Benjamin Peterson28a4dce2010-12-12 01:33:04 +000012117 {"encode", (PyCFunction) unicode_encode, METH_VARARGS | METH_KEYWORDS, encode__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012118 {"replace", (PyCFunction) unicode_replace, METH_VARARGS, replace__doc__},
12119 {"split", (PyCFunction) unicode_split, METH_VARARGS, split__doc__},
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012120 {"rsplit", (PyCFunction) unicode_rsplit, METH_VARARGS, rsplit__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012121 {"join", (PyCFunction) unicode_join, METH_O, join__doc__},
12122 {"capitalize", (PyCFunction) unicode_capitalize, METH_NOARGS, capitalize__doc__},
12123 {"title", (PyCFunction) unicode_title, METH_NOARGS, title__doc__},
12124 {"center", (PyCFunction) unicode_center, METH_VARARGS, center__doc__},
12125 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
12126 {"expandtabs", (PyCFunction) unicode_expandtabs, METH_VARARGS, expandtabs__doc__},
12127 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000012128 {"partition", (PyCFunction) unicode_partition, METH_O, partition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012129 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
12130 {"ljust", (PyCFunction) unicode_ljust, METH_VARARGS, ljust__doc__},
12131 {"lower", (PyCFunction) unicode_lower, METH_NOARGS, lower__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012132 {"lstrip", (PyCFunction) unicode_lstrip, METH_VARARGS, lstrip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012133 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
12134 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
12135 {"rjust", (PyCFunction) unicode_rjust, METH_VARARGS, rjust__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012136 {"rstrip", (PyCFunction) unicode_rstrip, METH_VARARGS, rstrip__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000012137 {"rpartition", (PyCFunction) unicode_rpartition, METH_O, rpartition__doc__},
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012138 {"splitlines", (PyCFunction) unicode_splitlines, METH_VARARGS | METH_KEYWORDS, splitlines__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012139 {"strip", (PyCFunction) unicode_strip, METH_VARARGS, strip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012140 {"swapcase", (PyCFunction) unicode_swapcase, METH_NOARGS, swapcase__doc__},
12141 {"translate", (PyCFunction) unicode_translate, METH_O, translate__doc__},
12142 {"upper", (PyCFunction) unicode_upper, METH_NOARGS, upper__doc__},
12143 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
12144 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
12145 {"islower", (PyCFunction) unicode_islower, METH_NOARGS, islower__doc__},
12146 {"isupper", (PyCFunction) unicode_isupper, METH_NOARGS, isupper__doc__},
12147 {"istitle", (PyCFunction) unicode_istitle, METH_NOARGS, istitle__doc__},
12148 {"isspace", (PyCFunction) unicode_isspace, METH_NOARGS, isspace__doc__},
12149 {"isdecimal", (PyCFunction) unicode_isdecimal, METH_NOARGS, isdecimal__doc__},
12150 {"isdigit", (PyCFunction) unicode_isdigit, METH_NOARGS, isdigit__doc__},
12151 {"isnumeric", (PyCFunction) unicode_isnumeric, METH_NOARGS, isnumeric__doc__},
12152 {"isalpha", (PyCFunction) unicode_isalpha, METH_NOARGS, isalpha__doc__},
12153 {"isalnum", (PyCFunction) unicode_isalnum, METH_NOARGS, isalnum__doc__},
Martin v. Löwis47383402007-08-15 07:32:56 +000012154 {"isidentifier", (PyCFunction) unicode_isidentifier, METH_NOARGS, isidentifier__doc__},
Georg Brandl559e5d72008-06-11 18:37:52 +000012155 {"isprintable", (PyCFunction) unicode_isprintable, METH_NOARGS, isprintable__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012156 {"zfill", (PyCFunction) unicode_zfill, METH_VARARGS, zfill__doc__},
Eric Smith9cd1e092007-08-31 18:39:38 +000012157 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +000012158 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
Eric Smith4a7d76d2008-05-30 18:10:19 +000012159 {"__format__", (PyCFunction) unicode__format__, METH_VARARGS, p_format__doc__},
Georg Brandlceee0772007-11-27 23:48:05 +000012160 {"maketrans", (PyCFunction) unicode_maketrans,
12161 METH_VARARGS | METH_STATIC, maketrans__doc__},
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012162 {"__sizeof__", (PyCFunction) unicode__sizeof__, METH_NOARGS, sizeof__doc__},
Walter Dörwald068325e2002-04-15 13:36:47 +000012163#if 0
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012164 {"capwords", (PyCFunction) unicode_capwords, METH_NOARGS, capwords__doc__},
Guido van Rossumd57fd912000-03-10 22:53:23 +000012165#endif
12166
12167#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012168 /* These methods are just used for debugging the implementation. */
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012169 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000012170#endif
12171
Benjamin Peterson14339b62009-01-31 16:36:08 +000012172 {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000012173 {NULL, NULL}
12174};
12175
Neil Schemenauerce30bc92002-11-18 16:10:18 +000012176static PyObject *
12177unicode_mod(PyObject *v, PyObject *w)
12178{
Brian Curtindfc80e32011-08-10 20:28:54 -050012179 if (!PyUnicode_Check(v))
12180 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson29060642009-01-31 22:14:21 +000012181 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +000012182}
12183
12184static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012185 0, /*nb_add*/
12186 0, /*nb_subtract*/
12187 0, /*nb_multiply*/
12188 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +000012189};
12190
Guido van Rossumd57fd912000-03-10 22:53:23 +000012191static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012192 (lenfunc) unicode_length, /* sq_length */
12193 PyUnicode_Concat, /* sq_concat */
12194 (ssizeargfunc) unicode_repeat, /* sq_repeat */
12195 (ssizeargfunc) unicode_getitem, /* sq_item */
12196 0, /* sq_slice */
12197 0, /* sq_ass_item */
12198 0, /* sq_ass_slice */
12199 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +000012200};
12201
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012202static PyObject*
12203unicode_subscript(PyUnicodeObject* self, PyObject* item)
12204{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012205 if (PyUnicode_READY(self) == -1)
12206 return NULL;
12207
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000012208 if (PyIndex_Check(item)) {
12209 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012210 if (i == -1 && PyErr_Occurred())
12211 return NULL;
12212 if (i < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012213 i += PyUnicode_GET_LENGTH(self);
Victor Stinner2fe5ced2011-10-02 00:25:40 +020012214 return unicode_getitem((PyObject*)self, i);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012215 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000012216 Py_ssize_t start, stop, step, slicelength, cur, i;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012217 const Py_UNICODE* source_buf;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012218 Py_UNICODE* result_buf;
12219 PyObject* result;
12220
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012221 if (PySlice_GetIndicesEx(item, PyUnicode_GET_LENGTH(self),
Benjamin Peterson29060642009-01-31 22:14:21 +000012222 &start, &stop, &step, &slicelength) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012223 return NULL;
12224 }
12225
12226 if (slicelength <= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012227 return PyUnicode_New(0, 0);
12228 } else if (start == 0 && step == 1 &&
12229 slicelength == PyUnicode_GET_LENGTH(self) &&
Thomas Woutersed03b412007-08-28 21:37:11 +000012230 PyUnicode_CheckExact(self)) {
12231 Py_INCREF(self);
12232 return (PyObject *)self;
12233 } else if (step == 1) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020012234 return PyUnicode_Substring((PyObject*)self,
12235 start, start + slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012236 } else {
12237 source_buf = PyUnicode_AS_UNICODE((PyObject*)self);
Christian Heimesb186d002008-03-18 15:15:01 +000012238 result_buf = (Py_UNICODE *)PyObject_MALLOC(slicelength*
12239 sizeof(Py_UNICODE));
Benjamin Peterson14339b62009-01-31 16:36:08 +000012240
Benjamin Peterson29060642009-01-31 22:14:21 +000012241 if (result_buf == NULL)
12242 return PyErr_NoMemory();
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012243
12244 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
12245 result_buf[i] = source_buf[cur];
12246 }
Tim Petersced69f82003-09-16 20:30:58 +000012247
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012248 result = PyUnicode_FromUnicode(result_buf, slicelength);
Christian Heimesb186d002008-03-18 15:15:01 +000012249 PyObject_FREE(result_buf);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012250 return result;
12251 }
12252 } else {
12253 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
12254 return NULL;
12255 }
12256}
12257
12258static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012259 (lenfunc)unicode_length, /* mp_length */
12260 (binaryfunc)unicode_subscript, /* mp_subscript */
12261 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012262};
12263
Guido van Rossumd57fd912000-03-10 22:53:23 +000012264
Guido van Rossumd57fd912000-03-10 22:53:23 +000012265/* Helpers for PyUnicode_Format() */
12266
12267static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +000012268getnextarg(PyObject *args, Py_ssize_t arglen, Py_ssize_t *p_argidx)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012269{
Martin v. Löwis18e16552006-02-15 17:27:45 +000012270 Py_ssize_t argidx = *p_argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012271 if (argidx < arglen) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012272 (*p_argidx)++;
12273 if (arglen < 0)
12274 return args;
12275 else
12276 return PyTuple_GetItem(args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012277 }
12278 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000012279 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012280 return NULL;
12281}
12282
Mark Dickinsonf489caf2009-05-01 11:42:00 +000012283/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +000012284
Mark Dickinsonf489caf2009-05-01 11:42:00 +000012285static PyObject *
12286formatfloat(PyObject *v, int flags, int prec, int type)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012287{
Mark Dickinsonf489caf2009-05-01 11:42:00 +000012288 char *p;
12289 PyObject *result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012290 double x;
Tim Petersced69f82003-09-16 20:30:58 +000012291
Guido van Rossumd57fd912000-03-10 22:53:23 +000012292 x = PyFloat_AsDouble(v);
12293 if (x == -1.0 && PyErr_Occurred())
Mark Dickinsonf489caf2009-05-01 11:42:00 +000012294 return NULL;
12295
Guido van Rossumd57fd912000-03-10 22:53:23 +000012296 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012297 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +000012298
Eric Smith0923d1d2009-04-16 20:16:10 +000012299 p = PyOS_double_to_string(x, type, prec,
12300 (flags & F_ALT) ? Py_DTSF_ALT : 0, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +000012301 if (p == NULL)
12302 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012303 result = PyUnicode_DecodeASCII(p, strlen(p), NULL);
Eric Smith0923d1d2009-04-16 20:16:10 +000012304 PyMem_Free(p);
12305 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012306}
12307
Tim Peters38fd5b62000-09-21 05:43:11 +000012308static PyObject*
12309formatlong(PyObject *val, int flags, int prec, int type)
12310{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012311 char *buf;
12312 int len;
12313 PyObject *str; /* temporary string object. */
12314 PyObject *result;
Tim Peters38fd5b62000-09-21 05:43:11 +000012315
Benjamin Peterson14339b62009-01-31 16:36:08 +000012316 str = _PyBytes_FormatLong(val, flags, prec, type, &buf, &len);
12317 if (!str)
12318 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012319 result = PyUnicode_DecodeASCII(buf, len, NULL);
Benjamin Peterson14339b62009-01-31 16:36:08 +000012320 Py_DECREF(str);
12321 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +000012322}
12323
Guido van Rossumd57fd912000-03-10 22:53:23 +000012324static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012325formatchar(Py_UCS4 *buf,
Marc-André Lemburgf28dd832000-06-30 10:29:57 +000012326 size_t buflen,
12327 PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012328{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000012329 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000012330 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012331 if (PyUnicode_GET_LENGTH(v) == 1) {
12332 buf[0] = PyUnicode_READ_CHAR(v, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +000012333 buf[1] = '\0';
12334 return 1;
12335 }
Benjamin Peterson29060642009-01-31 22:14:21 +000012336 goto onError;
12337 }
12338 else {
12339 /* Integer input truncated to a character */
12340 long x;
12341 x = PyLong_AsLong(v);
12342 if (x == -1 && PyErr_Occurred())
12343 goto onError;
12344
12345 if (x < 0 || x > 0x10ffff) {
12346 PyErr_SetString(PyExc_OverflowError,
12347 "%c arg not in range(0x110000)");
12348 return -1;
12349 }
12350
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012351 buf[0] = (Py_UCS4) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012352 buf[1] = '\0';
12353 return 1;
12354 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000012355
Benjamin Peterson29060642009-01-31 22:14:21 +000012356 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000012357 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000012358 "%c requires int or char");
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000012359 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012360}
12361
Marc-André Lemburgf28dd832000-06-30 10:29:57 +000012362/* fmt%(v1,v2,...) is roughly equivalent to sprintf(fmt, v1, v2, ...)
Mark Dickinsonf489caf2009-05-01 11:42:00 +000012363 FORMATBUFLEN is the length of the buffer in which chars are formatted.
Marc-André Lemburgf28dd832000-06-30 10:29:57 +000012364*/
Mark Dickinsonf489caf2009-05-01 11:42:00 +000012365#define FORMATBUFLEN (size_t)10
Marc-André Lemburgf28dd832000-06-30 10:29:57 +000012366
Alexander Belopolsky40018472011-02-26 01:02:56 +000012367PyObject *
12368PyUnicode_Format(PyObject *format, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012369{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012370 void *fmt;
12371 int fmtkind;
12372 PyObject *result;
12373 Py_UCS4 *res, *res0;
12374 Py_UCS4 max;
12375 int kind;
12376 Py_ssize_t fmtcnt, fmtpos, rescnt, reslen, arglen, argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012377 int args_owned = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012378 PyObject *dict = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012379 PyUnicodeObject *uformat;
Tim Petersced69f82003-09-16 20:30:58 +000012380
Guido van Rossumd57fd912000-03-10 22:53:23 +000012381 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012382 PyErr_BadInternalCall();
12383 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012384 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012385 uformat = (PyUnicodeObject*)PyUnicode_FromObject(format);
12386 if (uformat == NULL || PyUnicode_READY(uformat) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000012387 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012388 fmt = PyUnicode_DATA(uformat);
12389 fmtkind = PyUnicode_KIND(uformat);
12390 fmtcnt = PyUnicode_GET_LENGTH(uformat);
12391 fmtpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012392
12393 reslen = rescnt = fmtcnt + 100;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012394 res = res0 = PyMem_Malloc(reslen * sizeof(Py_UCS4));
12395 if (res0 == NULL) {
12396 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +000012397 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012398 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012399
12400 if (PyTuple_Check(args)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012401 arglen = PyTuple_Size(args);
12402 argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012403 }
12404 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000012405 arglen = -1;
12406 argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012407 }
Christian Heimes90aa7642007-12-19 02:45:37 +000012408 if (Py_TYPE(args)->tp_as_mapping && !PyTuple_Check(args) &&
Christian Heimesf3863112007-11-22 07:46:41 +000012409 !PyUnicode_Check(args))
Benjamin Peterson29060642009-01-31 22:14:21 +000012410 dict = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012411
12412 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012413 if (PyUnicode_READ(fmtkind, fmt, fmtpos) != '%') {
Benjamin Peterson29060642009-01-31 22:14:21 +000012414 if (--rescnt < 0) {
12415 rescnt = fmtcnt + 100;
12416 reslen += rescnt;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012417 res0 = PyMem_Realloc(res0, reslen*sizeof(Py_UCS4));
12418 if (res0 == NULL){
12419 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +000012420 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012421 }
12422 res = res0 + reslen - rescnt;
Benjamin Peterson29060642009-01-31 22:14:21 +000012423 --rescnt;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012424 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012425 *res++ = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson14339b62009-01-31 16:36:08 +000012426 }
12427 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000012428 /* Got a format specifier */
12429 int flags = 0;
12430 Py_ssize_t width = -1;
12431 int prec = -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012432 Py_UCS4 c = '\0';
12433 Py_UCS4 fill;
Benjamin Peterson29060642009-01-31 22:14:21 +000012434 int isnumok;
12435 PyObject *v = NULL;
12436 PyObject *temp = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012437 void *pbuf;
12438 Py_ssize_t pindex;
Benjamin Peterson29060642009-01-31 22:14:21 +000012439 Py_UNICODE sign;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012440 Py_ssize_t len, len1;
12441 Py_UCS4 formatbuf[FORMATBUFLEN]; /* For formatchar() */
Guido van Rossumd57fd912000-03-10 22:53:23 +000012442
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012443 fmtpos++;
12444 if (PyUnicode_READ(fmtkind, fmt, fmtpos) == '(') {
12445 Py_ssize_t keystart;
Benjamin Peterson29060642009-01-31 22:14:21 +000012446 Py_ssize_t keylen;
12447 PyObject *key;
12448 int pcount = 1;
Christian Heimesa612dc02008-02-24 13:08:18 +000012449
Benjamin Peterson29060642009-01-31 22:14:21 +000012450 if (dict == NULL) {
12451 PyErr_SetString(PyExc_TypeError,
12452 "format requires a mapping");
12453 goto onError;
12454 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012455 ++fmtpos;
Benjamin Peterson29060642009-01-31 22:14:21 +000012456 --fmtcnt;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012457 keystart = fmtpos;
Benjamin Peterson29060642009-01-31 22:14:21 +000012458 /* Skip over balanced parentheses */
12459 while (pcount > 0 && --fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012460 if (PyUnicode_READ(fmtkind, fmt, fmtpos) == ')')
Benjamin Peterson29060642009-01-31 22:14:21 +000012461 --pcount;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012462 else if (PyUnicode_READ(fmtkind, fmt, fmtpos) == '(')
Benjamin Peterson29060642009-01-31 22:14:21 +000012463 ++pcount;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012464 fmtpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +000012465 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012466 keylen = fmtpos - keystart - 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000012467 if (fmtcnt < 0 || pcount > 0) {
12468 PyErr_SetString(PyExc_ValueError,
12469 "incomplete format key");
12470 goto onError;
12471 }
Victor Stinner12bab6d2011-10-01 01:53:49 +020012472 key = PyUnicode_Substring((PyObject*)uformat,
12473 keystart, keystart + keylen);
Benjamin Peterson29060642009-01-31 22:14:21 +000012474 if (key == NULL)
12475 goto onError;
12476 if (args_owned) {
12477 Py_DECREF(args);
12478 args_owned = 0;
12479 }
12480 args = PyObject_GetItem(dict, key);
12481 Py_DECREF(key);
12482 if (args == NULL) {
12483 goto onError;
12484 }
12485 args_owned = 1;
12486 arglen = -1;
12487 argidx = -2;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012488 }
Benjamin Peterson29060642009-01-31 22:14:21 +000012489 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012490 switch (c = PyUnicode_READ(fmtkind, fmt, fmtpos++)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012491 case '-': flags |= F_LJUST; continue;
12492 case '+': flags |= F_SIGN; continue;
12493 case ' ': flags |= F_BLANK; continue;
12494 case '#': flags |= F_ALT; continue;
12495 case '0': flags |= F_ZERO; continue;
12496 }
12497 break;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012498 }
Benjamin Peterson29060642009-01-31 22:14:21 +000012499 if (c == '*') {
12500 v = getnextarg(args, arglen, &argidx);
12501 if (v == NULL)
12502 goto onError;
12503 if (!PyLong_Check(v)) {
12504 PyErr_SetString(PyExc_TypeError,
12505 "* wants int");
12506 goto onError;
12507 }
12508 width = PyLong_AsLong(v);
12509 if (width == -1 && PyErr_Occurred())
12510 goto onError;
12511 if (width < 0) {
12512 flags |= F_LJUST;
12513 width = -width;
12514 }
12515 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012516 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000012517 }
12518 else if (c >= '0' && c <= '9') {
12519 width = c - '0';
12520 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012521 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000012522 if (c < '0' || c > '9')
12523 break;
12524 if ((width*10) / 10 != width) {
12525 PyErr_SetString(PyExc_ValueError,
12526 "width too big");
Benjamin Peterson14339b62009-01-31 16:36:08 +000012527 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +000012528 }
12529 width = width*10 + (c - '0');
12530 }
12531 }
12532 if (c == '.') {
12533 prec = 0;
12534 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012535 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000012536 if (c == '*') {
12537 v = getnextarg(args, arglen, &argidx);
12538 if (v == NULL)
12539 goto onError;
12540 if (!PyLong_Check(v)) {
12541 PyErr_SetString(PyExc_TypeError,
12542 "* wants int");
12543 goto onError;
12544 }
12545 prec = PyLong_AsLong(v);
12546 if (prec == -1 && PyErr_Occurred())
12547 goto onError;
12548 if (prec < 0)
12549 prec = 0;
12550 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012551 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000012552 }
12553 else if (c >= '0' && c <= '9') {
12554 prec = c - '0';
12555 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012556 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000012557 if (c < '0' || c > '9')
12558 break;
12559 if ((prec*10) / 10 != prec) {
12560 PyErr_SetString(PyExc_ValueError,
12561 "prec too big");
12562 goto onError;
12563 }
12564 prec = prec*10 + (c - '0');
12565 }
12566 }
12567 } /* prec */
12568 if (fmtcnt >= 0) {
12569 if (c == 'h' || c == 'l' || c == 'L') {
12570 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012571 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000012572 }
12573 }
12574 if (fmtcnt < 0) {
12575 PyErr_SetString(PyExc_ValueError,
12576 "incomplete format");
12577 goto onError;
12578 }
12579 if (c != '%') {
12580 v = getnextarg(args, arglen, &argidx);
12581 if (v == NULL)
12582 goto onError;
12583 }
12584 sign = 0;
12585 fill = ' ';
12586 switch (c) {
12587
12588 case '%':
12589 pbuf = formatbuf;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012590 kind = PyUnicode_4BYTE_KIND;
Benjamin Peterson29060642009-01-31 22:14:21 +000012591 /* presume that buffer length is at least 1 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012592 PyUnicode_WRITE(kind, pbuf, 0, '%');
Benjamin Peterson29060642009-01-31 22:14:21 +000012593 len = 1;
12594 break;
12595
12596 case 's':
12597 case 'r':
12598 case 'a':
Victor Stinner808fc0a2010-03-22 12:50:40 +000012599 if (PyUnicode_CheckExact(v) && c == 's') {
Benjamin Peterson29060642009-01-31 22:14:21 +000012600 temp = v;
12601 Py_INCREF(temp);
Benjamin Peterson14339b62009-01-31 16:36:08 +000012602 }
12603 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000012604 if (c == 's')
12605 temp = PyObject_Str(v);
12606 else if (c == 'r')
12607 temp = PyObject_Repr(v);
12608 else
12609 temp = PyObject_ASCII(v);
12610 if (temp == NULL)
12611 goto onError;
12612 if (PyUnicode_Check(temp))
12613 /* nothing to do */;
12614 else {
12615 Py_DECREF(temp);
12616 PyErr_SetString(PyExc_TypeError,
12617 "%s argument has non-string str()");
12618 goto onError;
12619 }
12620 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012621 if (PyUnicode_READY(temp) == -1) {
12622 Py_CLEAR(temp);
12623 goto onError;
12624 }
12625 pbuf = PyUnicode_DATA(temp);
12626 kind = PyUnicode_KIND(temp);
12627 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000012628 if (prec >= 0 && len > prec)
12629 len = prec;
12630 break;
12631
12632 case 'i':
12633 case 'd':
12634 case 'u':
12635 case 'o':
12636 case 'x':
12637 case 'X':
Benjamin Peterson29060642009-01-31 22:14:21 +000012638 isnumok = 0;
12639 if (PyNumber_Check(v)) {
12640 PyObject *iobj=NULL;
12641
12642 if (PyLong_Check(v)) {
12643 iobj = v;
12644 Py_INCREF(iobj);
12645 }
12646 else {
12647 iobj = PyNumber_Long(v);
12648 }
12649 if (iobj!=NULL) {
12650 if (PyLong_Check(iobj)) {
12651 isnumok = 1;
Senthil Kumaran9ebe08d2011-07-03 21:03:16 -070012652 temp = formatlong(iobj, flags, prec, (c == 'i'? 'd': c));
Benjamin Peterson29060642009-01-31 22:14:21 +000012653 Py_DECREF(iobj);
12654 if (!temp)
12655 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012656 if (PyUnicode_READY(temp) == -1) {
12657 Py_CLEAR(temp);
12658 goto onError;
12659 }
12660 pbuf = PyUnicode_DATA(temp);
12661 kind = PyUnicode_KIND(temp);
12662 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000012663 sign = 1;
12664 }
12665 else {
12666 Py_DECREF(iobj);
12667 }
12668 }
12669 }
12670 if (!isnumok) {
12671 PyErr_Format(PyExc_TypeError,
12672 "%%%c format: a number is required, "
12673 "not %.200s", (char)c, Py_TYPE(v)->tp_name);
12674 goto onError;
12675 }
12676 if (flags & F_ZERO)
12677 fill = '0';
12678 break;
12679
12680 case 'e':
12681 case 'E':
12682 case 'f':
12683 case 'F':
12684 case 'g':
12685 case 'G':
Mark Dickinsonf489caf2009-05-01 11:42:00 +000012686 temp = formatfloat(v, flags, prec, c);
12687 if (!temp)
Benjamin Peterson29060642009-01-31 22:14:21 +000012688 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012689 if (PyUnicode_READY(temp) == -1) {
12690 Py_CLEAR(temp);
12691 goto onError;
12692 }
12693 pbuf = PyUnicode_DATA(temp);
12694 kind = PyUnicode_KIND(temp);
12695 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000012696 sign = 1;
12697 if (flags & F_ZERO)
12698 fill = '0';
12699 break;
12700
12701 case 'c':
12702 pbuf = formatbuf;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012703 kind = PyUnicode_4BYTE_KIND;
Victor Stinnerb9dcffb2011-09-29 00:39:24 +020012704 len = formatchar(pbuf, Py_ARRAY_LENGTH(formatbuf), v);
Benjamin Peterson29060642009-01-31 22:14:21 +000012705 if (len < 0)
12706 goto onError;
12707 break;
12708
12709 default:
12710 PyErr_Format(PyExc_ValueError,
12711 "unsupported format character '%c' (0x%x) "
12712 "at index %zd",
12713 (31<=c && c<=126) ? (char)c : '?',
12714 (int)c,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012715 fmtpos - 1);
Benjamin Peterson29060642009-01-31 22:14:21 +000012716 goto onError;
12717 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012718 /* pbuf is initialized here. */
12719 pindex = 0;
Benjamin Peterson29060642009-01-31 22:14:21 +000012720 if (sign) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012721 if (PyUnicode_READ(kind, pbuf, pindex) == '-' ||
12722 PyUnicode_READ(kind, pbuf, pindex) == '+') {
12723 sign = PyUnicode_READ(kind, pbuf, pindex++);
Benjamin Peterson29060642009-01-31 22:14:21 +000012724 len--;
12725 }
12726 else if (flags & F_SIGN)
12727 sign = '+';
12728 else if (flags & F_BLANK)
12729 sign = ' ';
12730 else
12731 sign = 0;
12732 }
12733 if (width < len)
12734 width = len;
12735 if (rescnt - (sign != 0) < width) {
12736 reslen -= rescnt;
12737 rescnt = width + fmtcnt + 100;
12738 reslen += rescnt;
12739 if (reslen < 0) {
12740 Py_XDECREF(temp);
12741 PyErr_NoMemory();
12742 goto onError;
12743 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012744 res0 = PyMem_Realloc(res0, reslen*sizeof(Py_UCS4));
12745 if (res0 == 0) {
12746 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +000012747 Py_XDECREF(temp);
12748 goto onError;
12749 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012750 res = res0 + reslen - rescnt;
Benjamin Peterson29060642009-01-31 22:14:21 +000012751 }
12752 if (sign) {
12753 if (fill != ' ')
12754 *res++ = sign;
12755 rescnt--;
12756 if (width > len)
12757 width--;
12758 }
12759 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012760 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
12761 assert(PyUnicode_READ(kind, pbuf, pindex+1) == c);
Benjamin Peterson29060642009-01-31 22:14:21 +000012762 if (fill != ' ') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012763 *res++ = PyUnicode_READ(kind, pbuf, pindex++);
12764 *res++ = PyUnicode_READ(kind, pbuf, pindex++);
Benjamin Peterson29060642009-01-31 22:14:21 +000012765 }
12766 rescnt -= 2;
12767 width -= 2;
12768 if (width < 0)
12769 width = 0;
12770 len -= 2;
12771 }
12772 if (width > len && !(flags & F_LJUST)) {
12773 do {
12774 --rescnt;
12775 *res++ = fill;
12776 } while (--width > len);
12777 }
12778 if (fill == ' ') {
12779 if (sign)
12780 *res++ = sign;
12781 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012782 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
12783 assert(PyUnicode_READ(kind, pbuf, pindex+1) == c);
12784 *res++ = PyUnicode_READ(kind, pbuf, pindex++);
12785 *res++ = PyUnicode_READ(kind, pbuf, pindex++);
Benjamin Peterson14339b62009-01-31 16:36:08 +000012786 }
12787 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012788 /* Copy all characters, preserving len */
12789 len1 = len;
12790 while (len1--) {
12791 *res++ = PyUnicode_READ(kind, pbuf, pindex++);
12792 rescnt--;
12793 }
Benjamin Peterson29060642009-01-31 22:14:21 +000012794 while (--width >= len) {
12795 --rescnt;
12796 *res++ = ' ';
12797 }
12798 if (dict && (argidx < arglen) && c != '%') {
12799 PyErr_SetString(PyExc_TypeError,
12800 "not all arguments converted during string formatting");
Thomas Woutersa96affe2006-03-12 00:29:36 +000012801 Py_XDECREF(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000012802 goto onError;
12803 }
12804 Py_XDECREF(temp);
12805 } /* '%' */
Guido van Rossumd57fd912000-03-10 22:53:23 +000012806 } /* until end */
12807 if (argidx < arglen && !dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012808 PyErr_SetString(PyExc_TypeError,
12809 "not all arguments converted during string formatting");
12810 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012811 }
12812
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012813
12814 for (max=0, res = res0; res < res0+reslen-rescnt; res++)
12815 if (*res > max)
12816 max = *res;
12817 result = PyUnicode_New(reslen - rescnt, max);
12818 if (!result)
Benjamin Peterson29060642009-01-31 22:14:21 +000012819 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012820 kind = PyUnicode_KIND(result);
12821 for (res = res0; res < res0+reslen-rescnt; res++)
12822 PyUnicode_WRITE(kind, PyUnicode_DATA(result), res-res0, *res);
12823 PyMem_Free(res0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012824 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012825 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012826 }
12827 Py_DECREF(uformat);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012828 return (PyObject *)result;
12829
Benjamin Peterson29060642009-01-31 22:14:21 +000012830 onError:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012831 PyMem_Free(res0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012832 Py_DECREF(uformat);
12833 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012834 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012835 }
12836 return NULL;
12837}
12838
Jeremy Hylton938ace62002-07-17 16:30:39 +000012839static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +000012840unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
12841
Tim Peters6d6c1a32001-08-02 04:15:00 +000012842static PyObject *
12843unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
12844{
Benjamin Peterson29060642009-01-31 22:14:21 +000012845 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012846 static char *kwlist[] = {"object", "encoding", "errors", 0};
12847 char *encoding = NULL;
12848 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000012849
Benjamin Peterson14339b62009-01-31 16:36:08 +000012850 if (type != &PyUnicode_Type)
12851 return unicode_subtype_new(type, args, kwds);
12852 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +000012853 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012854 return NULL;
12855 if (x == NULL)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012856 return (PyObject *)PyUnicode_New(0, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000012857 if (encoding == NULL && errors == NULL)
12858 return PyObject_Str(x);
12859 else
Benjamin Peterson29060642009-01-31 22:14:21 +000012860 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +000012861}
12862
Guido van Rossume023fe02001-08-30 03:12:59 +000012863static PyObject *
12864unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
12865{
Victor Stinner07ac3eb2011-10-01 16:16:43 +020012866 PyUnicodeObject *unicode, *self;
12867 Py_ssize_t length, char_size;
12868 int share_wstr, share_utf8;
12869 unsigned int kind;
12870 void *data;
Guido van Rossume023fe02001-08-30 03:12:59 +000012871
Benjamin Peterson14339b62009-01-31 16:36:08 +000012872 assert(PyType_IsSubtype(type, &PyUnicode_Type));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020012873
12874 unicode = (PyUnicodeObject *)unicode_new(&PyUnicode_Type, args, kwds);
12875 if (unicode == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012876 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020012877 assert(_PyUnicode_CHECK(unicode));
Victor Stinner1b4f9ce2011-10-03 13:28:14 +020012878 if (_PyUnicode_READY_REPLACE(&unicode))
Victor Stinner07ac3eb2011-10-01 16:16:43 +020012879 return NULL;
12880
12881 self = (PyUnicodeObject *) type->tp_alloc(type, 0);
12882 if (self == NULL) {
12883 Py_DECREF(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +000012884 return NULL;
12885 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020012886 kind = PyUnicode_KIND(unicode);
12887 length = PyUnicode_GET_LENGTH(unicode);
12888
12889 _PyUnicode_LENGTH(self) = length;
12890 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
12891 _PyUnicode_STATE(self).interned = 0;
12892 _PyUnicode_STATE(self).kind = kind;
12893 _PyUnicode_STATE(self).compact = 0;
Victor Stinner3cf46372011-10-03 14:42:15 +020012894 _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020012895 _PyUnicode_STATE(self).ready = 1;
12896 _PyUnicode_WSTR(self) = NULL;
12897 _PyUnicode_UTF8_LENGTH(self) = 0;
12898 _PyUnicode_UTF8(self) = NULL;
12899 _PyUnicode_WSTR_LENGTH(self) = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +020012900 _PyUnicode_DATA_ANY(self) = NULL;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020012901
12902 share_utf8 = 0;
12903 share_wstr = 0;
12904 if (kind == PyUnicode_1BYTE_KIND) {
12905 char_size = 1;
12906 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
12907 share_utf8 = 1;
12908 }
12909 else if (kind == PyUnicode_2BYTE_KIND) {
12910 char_size = 2;
12911 if (sizeof(wchar_t) == 2)
12912 share_wstr = 1;
12913 }
12914 else {
12915 assert(kind == PyUnicode_4BYTE_KIND);
12916 char_size = 4;
12917 if (sizeof(wchar_t) == 4)
12918 share_wstr = 1;
12919 }
12920
12921 /* Ensure we won't overflow the length. */
12922 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
12923 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012924 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012925 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020012926 data = PyObject_MALLOC((length + 1) * char_size);
12927 if (data == NULL) {
12928 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012929 goto onError;
12930 }
12931
Victor Stinnerc3c74152011-10-02 20:39:55 +020012932 _PyUnicode_DATA_ANY(self) = data;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020012933 if (share_utf8) {
12934 _PyUnicode_UTF8_LENGTH(self) = length;
12935 _PyUnicode_UTF8(self) = data;
12936 }
12937 if (share_wstr) {
12938 _PyUnicode_WSTR_LENGTH(self) = length;
12939 _PyUnicode_WSTR(self) = (wchar_t *)data;
12940 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012941
Victor Stinner07ac3eb2011-10-01 16:16:43 +020012942 Py_MEMCPY(data, PyUnicode_DATA(unicode),
12943 PyUnicode_KIND_SIZE(kind, length + 1));
12944 Py_DECREF(unicode);
12945 return (PyObject *)self;
12946
12947onError:
12948 Py_DECREF(unicode);
12949 Py_DECREF(self);
12950 return NULL;
Guido van Rossume023fe02001-08-30 03:12:59 +000012951}
12952
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012953PyDoc_STRVAR(unicode_doc,
Benjamin Peterson29060642009-01-31 22:14:21 +000012954 "str(string[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +000012955\n\
Collin Winterd474ce82007-08-07 19:42:11 +000012956Create a new string object from the given encoded string.\n\
Skip Montanaro35b37a52002-07-26 16:22:46 +000012957encoding defaults to the current default string encoding.\n\
12958errors can be 'strict', 'replace' or 'ignore' and defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +000012959
Guido van Rossum50e9fb92006-08-17 05:42:55 +000012960static PyObject *unicode_iter(PyObject *seq);
12961
Guido van Rossumd57fd912000-03-10 22:53:23 +000012962PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000012963 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012964 "str", /* tp_name */
12965 sizeof(PyUnicodeObject), /* tp_size */
12966 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +000012967 /* Slots */
Benjamin Peterson14339b62009-01-31 16:36:08 +000012968 (destructor)unicode_dealloc, /* tp_dealloc */
12969 0, /* tp_print */
12970 0, /* tp_getattr */
12971 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000012972 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000012973 unicode_repr, /* tp_repr */
12974 &unicode_as_number, /* tp_as_number */
12975 &unicode_as_sequence, /* tp_as_sequence */
12976 &unicode_as_mapping, /* tp_as_mapping */
12977 (hashfunc) unicode_hash, /* tp_hash*/
12978 0, /* tp_call*/
12979 (reprfunc) unicode_str, /* tp_str */
12980 PyObject_GenericGetAttr, /* tp_getattro */
12981 0, /* tp_setattro */
12982 0, /* tp_as_buffer */
12983 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Benjamin Peterson29060642009-01-31 22:14:21 +000012984 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
Benjamin Peterson14339b62009-01-31 16:36:08 +000012985 unicode_doc, /* tp_doc */
12986 0, /* tp_traverse */
12987 0, /* tp_clear */
12988 PyUnicode_RichCompare, /* tp_richcompare */
12989 0, /* tp_weaklistoffset */
12990 unicode_iter, /* tp_iter */
12991 0, /* tp_iternext */
12992 unicode_methods, /* tp_methods */
12993 0, /* tp_members */
12994 0, /* tp_getset */
12995 &PyBaseObject_Type, /* tp_base */
12996 0, /* tp_dict */
12997 0, /* tp_descr_get */
12998 0, /* tp_descr_set */
12999 0, /* tp_dictoffset */
13000 0, /* tp_init */
13001 0, /* tp_alloc */
13002 unicode_new, /* tp_new */
13003 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013004};
13005
13006/* Initialize the Unicode implementation */
13007
Thomas Wouters78890102000-07-22 19:25:51 +000013008void _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013009{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013010 int i;
13011
Thomas Wouters477c8d52006-05-27 19:21:47 +000013012 /* XXX - move this array to unicodectype.c ? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013013 Py_UCS2 linebreak[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +000013014 0x000A, /* LINE FEED */
13015 0x000D, /* CARRIAGE RETURN */
13016 0x001C, /* FILE SEPARATOR */
13017 0x001D, /* GROUP SEPARATOR */
13018 0x001E, /* RECORD SEPARATOR */
13019 0x0085, /* NEXT LINE */
13020 0x2028, /* LINE SEPARATOR */
13021 0x2029, /* PARAGRAPH SEPARATOR */
13022 };
13023
Fred Drakee4315f52000-05-09 19:53:39 +000013024 /* Init the implementation */
Victor Stinnera464fc12011-10-02 20:39:30 +020013025 unicode_empty = PyUnicode_New(0, 0);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013026 if (!unicode_empty)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013027 Py_FatalError("Can't create empty string");
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013028
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013029 for (i = 0; i < 256; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +000013030 unicode_latin1[i] = NULL;
Guido van Rossumcacfc072002-05-24 19:01:59 +000013031 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000013032 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +000013033
13034 /* initialize the linebreak bloom filter */
13035 bloom_linebreak = make_bloom_mask(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013036 PyUnicode_2BYTE_KIND, linebreak,
Victor Stinner63941882011-09-29 00:42:28 +020013037 Py_ARRAY_LENGTH(linebreak));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013038
13039 PyType_Ready(&EncodingMapType);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013040}
13041
13042/* Finalize the Unicode implementation */
13043
Christian Heimesa156e092008-02-16 07:38:31 +000013044int
13045PyUnicode_ClearFreeList(void)
13046{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013047 return 0;
Christian Heimesa156e092008-02-16 07:38:31 +000013048}
13049
Guido van Rossumd57fd912000-03-10 22:53:23 +000013050void
Thomas Wouters78890102000-07-22 19:25:51 +000013051_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013052{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013053 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013054
Guido van Rossum4ae8ef82000-10-03 18:09:04 +000013055 Py_XDECREF(unicode_empty);
13056 unicode_empty = NULL;
Barry Warsaw5b4c2282000-10-03 20:45:26 +000013057
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013058 for (i = 0; i < 256; i++) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013059 if (unicode_latin1[i]) {
13060 Py_DECREF(unicode_latin1[i]);
13061 unicode_latin1[i] = NULL;
13062 }
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013063 }
Christian Heimesa156e092008-02-16 07:38:31 +000013064 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +000013065}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000013066
Walter Dörwald16807132007-05-25 13:52:07 +000013067void
13068PyUnicode_InternInPlace(PyObject **p)
13069{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013070 register PyUnicodeObject *s = (PyUnicodeObject *)(*p);
13071 PyObject *t;
Victor Stinner4fae54c2011-10-03 02:01:52 +020013072#ifdef Py_DEBUG
13073 assert(s != NULL);
13074 assert(_PyUnicode_CHECK(s));
13075#else
Benjamin Peterson14339b62009-01-31 16:36:08 +000013076 if (s == NULL || !PyUnicode_Check(s))
Victor Stinner4fae54c2011-10-03 02:01:52 +020013077 return;
13078#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000013079 /* If it's a subclass, we don't really know what putting
13080 it in the interned dict might do. */
13081 if (!PyUnicode_CheckExact(s))
13082 return;
13083 if (PyUnicode_CHECK_INTERNED(s))
13084 return;
Victor Stinner1b4f9ce2011-10-03 13:28:14 +020013085 if (_PyUnicode_READY_REPLACE(p)) {
Victor Stinner4fae54c2011-10-03 02:01:52 +020013086 assert(0 && "PyUnicode_READY fail in PyUnicode_InternInPlace");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013087 return;
13088 }
Victor Stinner1b4f9ce2011-10-03 13:28:14 +020013089 s = (PyUnicodeObject *)(*p);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013090 if (interned == NULL) {
13091 interned = PyDict_New();
13092 if (interned == NULL) {
13093 PyErr_Clear(); /* Don't leave an exception */
13094 return;
13095 }
13096 }
13097 /* It might be that the GetItem call fails even
13098 though the key is present in the dictionary,
13099 namely when this happens during a stack overflow. */
13100 Py_ALLOW_RECURSION
Benjamin Peterson29060642009-01-31 22:14:21 +000013101 t = PyDict_GetItem(interned, (PyObject *)s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013102 Py_END_ALLOW_RECURSION
Martin v. Löwis5b222132007-06-10 09:51:05 +000013103
Benjamin Peterson29060642009-01-31 22:14:21 +000013104 if (t) {
13105 Py_INCREF(t);
13106 Py_DECREF(*p);
13107 *p = t;
13108 return;
13109 }
Walter Dörwald16807132007-05-25 13:52:07 +000013110
Benjamin Peterson14339b62009-01-31 16:36:08 +000013111 PyThreadState_GET()->recursion_critical = 1;
13112 if (PyDict_SetItem(interned, (PyObject *)s, (PyObject *)s) < 0) {
13113 PyErr_Clear();
13114 PyThreadState_GET()->recursion_critical = 0;
13115 return;
13116 }
13117 PyThreadState_GET()->recursion_critical = 0;
13118 /* The two references in interned are not counted by refcnt.
13119 The deallocator will take care of this */
13120 Py_REFCNT(s) -= 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013121 _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000013122}
13123
13124void
13125PyUnicode_InternImmortal(PyObject **p)
13126{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013127 PyUnicodeObject *u = (PyUnicodeObject *)*p;
13128
Benjamin Peterson14339b62009-01-31 16:36:08 +000013129 PyUnicode_InternInPlace(p);
13130 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013131 _PyUnicode_STATE(u).interned = SSTATE_INTERNED_IMMORTAL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013132 Py_INCREF(*p);
13133 }
Walter Dörwald16807132007-05-25 13:52:07 +000013134}
13135
13136PyObject *
13137PyUnicode_InternFromString(const char *cp)
13138{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013139 PyObject *s = PyUnicode_FromString(cp);
13140 if (s == NULL)
13141 return NULL;
13142 PyUnicode_InternInPlace(&s);
13143 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000013144}
13145
Alexander Belopolsky40018472011-02-26 01:02:56 +000013146void
13147_Py_ReleaseInternedUnicodeStrings(void)
Walter Dörwald16807132007-05-25 13:52:07 +000013148{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013149 PyObject *keys;
13150 PyUnicodeObject *s;
13151 Py_ssize_t i, n;
13152 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000013153
Benjamin Peterson14339b62009-01-31 16:36:08 +000013154 if (interned == NULL || !PyDict_Check(interned))
13155 return;
13156 keys = PyDict_Keys(interned);
13157 if (keys == NULL || !PyList_Check(keys)) {
13158 PyErr_Clear();
13159 return;
13160 }
Walter Dörwald16807132007-05-25 13:52:07 +000013161
Benjamin Peterson14339b62009-01-31 16:36:08 +000013162 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
13163 detector, interned unicode strings are not forcibly deallocated;
13164 rather, we give them their stolen references back, and then clear
13165 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000013166
Benjamin Peterson14339b62009-01-31 16:36:08 +000013167 n = PyList_GET_SIZE(keys);
13168 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000013169 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013170 for (i = 0; i < n; i++) {
13171 s = (PyUnicodeObject *) PyList_GET_ITEM(keys, i);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013172 if (PyUnicode_READY(s) == -1)
13173 fprintf(stderr, "could not ready string\n");
13174 switch (PyUnicode_CHECK_INTERNED(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013175 case SSTATE_NOT_INTERNED:
13176 /* XXX Shouldn't happen */
13177 break;
13178 case SSTATE_INTERNED_IMMORTAL:
13179 Py_REFCNT(s) += 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013180 immortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013181 break;
13182 case SSTATE_INTERNED_MORTAL:
13183 Py_REFCNT(s) += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013184 mortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013185 break;
13186 default:
13187 Py_FatalError("Inconsistent interned string state.");
13188 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013189 _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013190 }
13191 fprintf(stderr, "total size of all interned strings: "
13192 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
13193 "mortal/immortal\n", mortal_size, immortal_size);
13194 Py_DECREF(keys);
13195 PyDict_Clear(interned);
13196 Py_DECREF(interned);
13197 interned = NULL;
Walter Dörwald16807132007-05-25 13:52:07 +000013198}
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013199
13200
13201/********************* Unicode Iterator **************************/
13202
13203typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013204 PyObject_HEAD
13205 Py_ssize_t it_index;
13206 PyUnicodeObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013207} unicodeiterobject;
13208
13209static void
13210unicodeiter_dealloc(unicodeiterobject *it)
13211{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013212 _PyObject_GC_UNTRACK(it);
13213 Py_XDECREF(it->it_seq);
13214 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013215}
13216
13217static int
13218unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
13219{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013220 Py_VISIT(it->it_seq);
13221 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013222}
13223
13224static PyObject *
13225unicodeiter_next(unicodeiterobject *it)
13226{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013227 PyUnicodeObject *seq;
13228 PyObject *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013229
Benjamin Peterson14339b62009-01-31 16:36:08 +000013230 assert(it != NULL);
13231 seq = it->it_seq;
13232 if (seq == NULL)
13233 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020013234 assert(_PyUnicode_CHECK(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013235
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013236 if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
13237 int kind = PyUnicode_KIND(seq);
13238 void *data = PyUnicode_DATA(seq);
13239 Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
13240 item = PyUnicode_FromOrdinal(chr);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013241 if (item != NULL)
13242 ++it->it_index;
13243 return item;
13244 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013245
Benjamin Peterson14339b62009-01-31 16:36:08 +000013246 Py_DECREF(seq);
13247 it->it_seq = NULL;
13248 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013249}
13250
13251static PyObject *
13252unicodeiter_len(unicodeiterobject *it)
13253{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013254 Py_ssize_t len = 0;
13255 if (it->it_seq)
13256 len = PyUnicode_GET_SIZE(it->it_seq) - it->it_index;
13257 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013258}
13259
13260PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
13261
13262static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013263 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000013264 length_hint_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000013265 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013266};
13267
13268PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013269 PyVarObject_HEAD_INIT(&PyType_Type, 0)
13270 "str_iterator", /* tp_name */
13271 sizeof(unicodeiterobject), /* tp_basicsize */
13272 0, /* tp_itemsize */
13273 /* methods */
13274 (destructor)unicodeiter_dealloc, /* tp_dealloc */
13275 0, /* tp_print */
13276 0, /* tp_getattr */
13277 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000013278 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000013279 0, /* tp_repr */
13280 0, /* tp_as_number */
13281 0, /* tp_as_sequence */
13282 0, /* tp_as_mapping */
13283 0, /* tp_hash */
13284 0, /* tp_call */
13285 0, /* tp_str */
13286 PyObject_GenericGetAttr, /* tp_getattro */
13287 0, /* tp_setattro */
13288 0, /* tp_as_buffer */
13289 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
13290 0, /* tp_doc */
13291 (traverseproc)unicodeiter_traverse, /* tp_traverse */
13292 0, /* tp_clear */
13293 0, /* tp_richcompare */
13294 0, /* tp_weaklistoffset */
13295 PyObject_SelfIter, /* tp_iter */
13296 (iternextfunc)unicodeiter_next, /* tp_iternext */
13297 unicodeiter_methods, /* tp_methods */
13298 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013299};
13300
13301static PyObject *
13302unicode_iter(PyObject *seq)
13303{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013304 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013305
Benjamin Peterson14339b62009-01-31 16:36:08 +000013306 if (!PyUnicode_Check(seq)) {
13307 PyErr_BadInternalCall();
13308 return NULL;
13309 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013310 if (PyUnicode_READY(seq) == -1)
13311 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013312 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
13313 if (it == NULL)
13314 return NULL;
13315 it->it_index = 0;
13316 Py_INCREF(seq);
13317 it->it_seq = (PyUnicodeObject *)seq;
13318 _PyObject_GC_TRACK(it);
13319 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013320}
13321
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013322#define UNIOP(x) Py_UNICODE_##x
13323#define UNIOP_t Py_UNICODE
13324#include "uniops.h"
13325#undef UNIOP
13326#undef UNIOP_t
13327#define UNIOP(x) Py_UCS4_##x
13328#define UNIOP_t Py_UCS4
13329#include "uniops.h"
13330#undef UNIOP
13331#undef UNIOP_t
Victor Stinner331ea922010-08-10 16:37:20 +000013332
Victor Stinner71133ff2010-09-01 23:43:53 +000013333Py_UNICODE*
Victor Stinner46408602010-09-03 16:18:00 +000013334PyUnicode_AsUnicodeCopy(PyObject *object)
Victor Stinner71133ff2010-09-01 23:43:53 +000013335{
13336 PyUnicodeObject *unicode = (PyUnicodeObject *)object;
13337 Py_UNICODE *copy;
13338 Py_ssize_t size;
13339
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013340 if (!PyUnicode_Check(unicode)) {
13341 PyErr_BadArgument();
13342 return NULL;
13343 }
Victor Stinner71133ff2010-09-01 23:43:53 +000013344 /* Ensure we won't overflow the size. */
13345 if (PyUnicode_GET_SIZE(unicode) > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
13346 PyErr_NoMemory();
13347 return NULL;
13348 }
13349 size = PyUnicode_GET_SIZE(unicode) + 1; /* copy the nul character */
13350 size *= sizeof(Py_UNICODE);
13351 copy = PyMem_Malloc(size);
13352 if (copy == NULL) {
13353 PyErr_NoMemory();
13354 return NULL;
13355 }
13356 memcpy(copy, PyUnicode_AS_UNICODE(unicode), size);
13357 return copy;
13358}
Martin v. Löwis5b222132007-06-10 09:51:05 +000013359
Georg Brandl66c221e2010-10-14 07:04:07 +000013360/* A _string module, to export formatter_parser and formatter_field_name_split
13361 to the string.Formatter class implemented in Python. */
13362
13363static PyMethodDef _string_methods[] = {
13364 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
13365 METH_O, PyDoc_STR("split the argument as a field name")},
13366 {"formatter_parser", (PyCFunction) formatter_parser,
13367 METH_O, PyDoc_STR("parse the argument as a format string")},
13368 {NULL, NULL}
13369};
13370
13371static struct PyModuleDef _string_module = {
13372 PyModuleDef_HEAD_INIT,
13373 "_string",
13374 PyDoc_STR("string helper module"),
13375 0,
13376 _string_methods,
13377 NULL,
13378 NULL,
13379 NULL,
13380 NULL
13381};
13382
13383PyMODINIT_FUNC
13384PyInit__string(void)
13385{
13386 return PyModule_Create(&_string_module);
13387}
13388
13389
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013390#ifdef __cplusplus
13391}
13392#endif