blob: b0b9528be57de14a56ab3bdda3ce58a1d8841823 [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
Victor Stinnerce5faf62011-10-05 00:42:43 +020049#ifdef Py_DEBUG
50# define DONT_MAKE_RESULT_READY
51#endif
52
Guido van Rossumd57fd912000-03-10 22:53:23 +000053/* Endianness switches; defaults to little endian */
54
55#ifdef WORDS_BIGENDIAN
56# define BYTEORDER_IS_BIG_ENDIAN
57#else
58# define BYTEORDER_IS_LITTLE_ENDIAN
59#endif
60
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000061/* --- Globals ------------------------------------------------------------
62
63 The globals are initialized by the _PyUnicode_Init() API and should
64 not be used before calling that API.
65
66*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000067
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000068
69#ifdef __cplusplus
70extern "C" {
71#endif
72
Victor Stinner910337b2011-10-03 03:20:16 +020073#ifdef Py_DEBUG
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020074# define _PyUnicode_CHECK(op) _PyUnicode_CheckConsistency(op, 0)
Victor Stinner910337b2011-10-03 03:20:16 +020075#else
76# define _PyUnicode_CHECK(op) PyUnicode_Check(op)
77#endif
Victor Stinnerfb5f5f22011-09-28 21:39:49 +020078
Victor Stinnere90fe6a2011-10-01 16:48:13 +020079#define _PyUnicode_UTF8(op) \
80 (((PyCompactUnicodeObject*)(op))->utf8)
81#define PyUnicode_UTF8(op) \
Victor Stinner910337b2011-10-03 03:20:16 +020082 (assert(_PyUnicode_CHECK(op)), \
Victor Stinnere90fe6a2011-10-01 16:48:13 +020083 assert(PyUnicode_IS_READY(op)), \
84 PyUnicode_IS_COMPACT_ASCII(op) ? \
85 ((char*)((PyASCIIObject*)(op) + 1)) : \
86 _PyUnicode_UTF8(op))
Victor Stinnerbc8b81b2011-09-29 19:31:34 +020087#define _PyUnicode_UTF8_LENGTH(op) \
Victor Stinnere90fe6a2011-10-01 16:48:13 +020088 (((PyCompactUnicodeObject*)(op))->utf8_length)
89#define PyUnicode_UTF8_LENGTH(op) \
Victor Stinner910337b2011-10-03 03:20:16 +020090 (assert(_PyUnicode_CHECK(op)), \
Victor Stinnere90fe6a2011-10-01 16:48:13 +020091 assert(PyUnicode_IS_READY(op)), \
92 PyUnicode_IS_COMPACT_ASCII(op) ? \
93 ((PyASCIIObject*)(op))->length : \
94 _PyUnicode_UTF8_LENGTH(op))
Victor Stinnera5f91632011-10-04 01:07:11 +020095#define _PyUnicode_WSTR(op) \
96 (((PyASCIIObject*)(op))->wstr)
97#define _PyUnicode_WSTR_LENGTH(op) \
98 (((PyCompactUnicodeObject*)(op))->wstr_length)
99#define _PyUnicode_LENGTH(op) \
100 (((PyASCIIObject *)(op))->length)
101#define _PyUnicode_STATE(op) \
102 (((PyASCIIObject *)(op))->state)
103#define _PyUnicode_HASH(op) \
104 (((PyASCIIObject *)(op))->hash)
Victor Stinner910337b2011-10-03 03:20:16 +0200105#define _PyUnicode_KIND(op) \
106 (assert(_PyUnicode_CHECK(op)), \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200107 ((PyASCIIObject *)(op))->state.kind)
Victor Stinner910337b2011-10-03 03:20:16 +0200108#define _PyUnicode_GET_LENGTH(op) \
109 (assert(_PyUnicode_CHECK(op)), \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200110 ((PyASCIIObject *)(op))->length)
Victor Stinnera5f91632011-10-04 01:07:11 +0200111#define _PyUnicode_DATA_ANY(op) \
112 (((PyUnicodeObject*)(op))->data.any)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200113
Victor Stinner910337b2011-10-03 03:20:16 +0200114#undef PyUnicode_READY
115#define PyUnicode_READY(op) \
116 (assert(_PyUnicode_CHECK(op)), \
117 (PyUnicode_IS_READY(op) ? \
Victor Stinnera5f91632011-10-04 01:07:11 +0200118 0 : \
Victor Stinner7931d9a2011-11-04 00:22:48 +0100119 _PyUnicode_Ready(op)))
Victor Stinner910337b2011-10-03 03:20:16 +0200120
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200121#define _PyUnicode_READY_REPLACE(p_obj) \
122 (assert(_PyUnicode_CHECK(*p_obj)), \
123 (PyUnicode_IS_READY(*p_obj) ? \
124 0 : _PyUnicode_ReadyReplace((PyObject **)(p_obj))))
125
Victor Stinnerc379ead2011-10-03 12:52:27 +0200126#define _PyUnicode_SHARE_UTF8(op) \
127 (assert(_PyUnicode_CHECK(op)), \
128 assert(!PyUnicode_IS_COMPACT_ASCII(op)), \
129 (_PyUnicode_UTF8(op) == PyUnicode_DATA(op)))
130#define _PyUnicode_SHARE_WSTR(op) \
131 (assert(_PyUnicode_CHECK(op)), \
132 (_PyUnicode_WSTR(unicode) == PyUnicode_DATA(op)))
133
Victor Stinner829c0ad2011-10-03 01:08:02 +0200134/* true if the Unicode object has an allocated UTF-8 memory block
135 (not shared with other data) */
Victor Stinner910337b2011-10-03 03:20:16 +0200136#define _PyUnicode_HAS_UTF8_MEMORY(op) \
137 (assert(_PyUnicode_CHECK(op)), \
138 (!PyUnicode_IS_COMPACT_ASCII(op) \
139 && _PyUnicode_UTF8(op) \
Victor Stinner829c0ad2011-10-03 01:08:02 +0200140 && _PyUnicode_UTF8(op) != PyUnicode_DATA(op)))
141
Victor Stinner03490912011-10-03 23:45:12 +0200142/* true if the Unicode object has an allocated wstr memory block
143 (not shared with other data) */
144#define _PyUnicode_HAS_WSTR_MEMORY(op) \
145 (assert(_PyUnicode_CHECK(op)), \
146 (_PyUnicode_WSTR(op) && \
147 (!PyUnicode_IS_READY(op) || \
148 _PyUnicode_WSTR(op) != PyUnicode_DATA(op))))
149
Victor Stinner910337b2011-10-03 03:20:16 +0200150/* Generic helper macro to convert characters of different types.
151 from_type and to_type have to be valid type names, begin and end
152 are pointers to the source characters which should be of type
153 "from_type *". to is a pointer of type "to_type *" and points to the
154 buffer where the result characters are written to. */
155#define _PyUnicode_CONVERT_BYTES(from_type, to_type, begin, end, to) \
156 do { \
Antoine Pitroue459a082011-10-11 20:58:41 +0200157 to_type *_to = (to_type *) to; \
158 const from_type *_iter = (begin); \
159 const from_type *_end = (end); \
160 Py_ssize_t n = (_end) - (_iter); \
161 const from_type *_unrolled_end = \
162 _iter + (n & ~ (Py_ssize_t) 3); \
163 while (_iter < (_unrolled_end)) { \
164 _to[0] = (to_type) _iter[0]; \
165 _to[1] = (to_type) _iter[1]; \
166 _to[2] = (to_type) _iter[2]; \
167 _to[3] = (to_type) _iter[3]; \
168 _iter += 4; _to += 4; \
Victor Stinner910337b2011-10-03 03:20:16 +0200169 } \
Antoine Pitroue459a082011-10-11 20:58:41 +0200170 while (_iter < (_end)) \
171 *_to++ = (to_type) *_iter++; \
Victor Stinner910337b2011-10-03 03:20:16 +0200172 } while (0)
Victor Stinner829c0ad2011-10-03 01:08:02 +0200173
Victor Stinnerb15d4d82011-09-28 23:59:20 +0200174/* The Unicode string has been modified: reset the hash */
175#define _PyUnicode_DIRTY(op) do { _PyUnicode_HASH(op) = -1; } while (0)
176
Walter Dörwald16807132007-05-25 13:52:07 +0000177/* This dictionary holds all interned unicode strings. Note that references
178 to strings in this dictionary are *not* counted in the string's ob_refcnt.
179 When the interned string reaches a refcnt of 0 the string deallocation
180 function will delete the reference from this dictionary.
181
182 Another way to look at this is that to say that the actual reference
Guido van Rossum98297ee2007-11-06 21:34:58 +0000183 count of a string is: s->ob_refcnt + (s->state ? 2 : 0)
Walter Dörwald16807132007-05-25 13:52:07 +0000184*/
185static PyObject *interned;
186
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000187/* The empty Unicode object is shared to improve performance. */
Victor Stinnera464fc12011-10-02 20:39:30 +0200188static PyObject *unicode_empty;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000189
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200190/* List of static strings. */
191static _Py_Identifier *static_strings;
192
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000193/* 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 Stinnerfb9ea8c2011-10-06 01:45:57 +0200231static void copy_characters(
232 PyObject *to, Py_ssize_t to_start,
233 PyObject *from, Py_ssize_t from_start,
234 Py_ssize_t how_many);
Victor Stinnerc729b8e2011-10-06 02:36:59 +0200235#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200236static int unicode_is_singleton(PyObject *unicode);
Victor Stinnerc729b8e2011-10-06 02:36:59 +0200237#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +0200238
Alexander Belopolsky40018472011-02-26 01:02:56 +0000239static PyObject *
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200240unicode_fromascii(const unsigned char *s, Py_ssize_t size);
241static PyObject *
242_PyUnicode_FromUCS1(const unsigned char *s, Py_ssize_t size);
243static PyObject *
244_PyUnicode_FromUCS2(const Py_UCS2 *s, Py_ssize_t size);
245static PyObject *
246_PyUnicode_FromUCS4(const Py_UCS4 *s, Py_ssize_t size);
247
248static PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +0000249unicode_encode_call_errorhandler(const char *errors,
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000250 PyObject **errorHandler,const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +0100251 PyObject *unicode, PyObject **exceptionObject,
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000252 Py_ssize_t startpos, Py_ssize_t endpos, Py_ssize_t *newpos);
253
Alexander Belopolsky40018472011-02-26 01:02:56 +0000254static void
255raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +0300256 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +0100257 PyObject *unicode,
258 Py_ssize_t startpos, Py_ssize_t endpos,
259 const char *reason);
Victor Stinner31be90b2010-04-22 19:38:16 +0000260
Christian Heimes190d79e2008-01-30 11:58:22 +0000261/* Same for linebreaks */
262static unsigned char ascii_linebreak[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000263 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000264/* 0x000A, * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000265/* 0x000B, * LINE TABULATION */
266/* 0x000C, * FORM FEED */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000267/* 0x000D, * CARRIAGE RETURN */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000268 0, 0, 1, 1, 1, 1, 0, 0,
Benjamin Peterson14339b62009-01-31 16:36:08 +0000269 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000270/* 0x001C, * FILE SEPARATOR */
271/* 0x001D, * GROUP SEPARATOR */
272/* 0x001E, * RECORD SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000273 0, 0, 0, 0, 1, 1, 1, 0,
274 0, 0, 0, 0, 0, 0, 0, 0,
275 0, 0, 0, 0, 0, 0, 0, 0,
276 0, 0, 0, 0, 0, 0, 0, 0,
277 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes190d79e2008-01-30 11:58:22 +0000278
Benjamin Peterson14339b62009-01-31 16:36:08 +0000279 0, 0, 0, 0, 0, 0, 0, 0,
280 0, 0, 0, 0, 0, 0, 0, 0,
281 0, 0, 0, 0, 0, 0, 0, 0,
282 0, 0, 0, 0, 0, 0, 0, 0,
283 0, 0, 0, 0, 0, 0, 0, 0,
284 0, 0, 0, 0, 0, 0, 0, 0,
285 0, 0, 0, 0, 0, 0, 0, 0,
286 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000287};
288
Ezio Melotti48a2f8f2011-09-29 00:18:19 +0300289/* The max unicode value is always 0x10FFFF while using the PEP-393 API.
290 This function is kept for backward compatibility with the old API. */
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000291Py_UNICODE
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +0000292PyUnicode_GetMax(void)
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000293{
Fredrik Lundh8f455852001-06-27 18:59:43 +0000294#ifdef Py_UNICODE_WIDE
Benjamin Peterson14339b62009-01-31 16:36:08 +0000295 return 0x10FFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000296#else
Benjamin Peterson14339b62009-01-31 16:36:08 +0000297 /* This is actually an illegal character, so it should
298 not be passed to unichr. */
299 return 0xFFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000300#endif
301}
302
Victor Stinner910337b2011-10-03 03:20:16 +0200303#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200304int
Victor Stinner7931d9a2011-11-04 00:22:48 +0100305_PyUnicode_CheckConsistency(PyObject *op, int check_content)
Victor Stinner910337b2011-10-03 03:20:16 +0200306{
307 PyASCIIObject *ascii;
308 unsigned int kind;
309
310 assert(PyUnicode_Check(op));
311
312 ascii = (PyASCIIObject *)op;
313 kind = ascii->state.kind;
314
Victor Stinnera3b334d2011-10-03 13:53:37 +0200315 if (ascii->state.ascii == 1 && ascii->state.compact == 1) {
Victor Stinner910337b2011-10-03 03:20:16 +0200316 assert(kind == PyUnicode_1BYTE_KIND);
Victor Stinner910337b2011-10-03 03:20:16 +0200317 assert(ascii->state.ready == 1);
318 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200319 else {
Victor Stinner85041a52011-10-03 14:42:39 +0200320 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
Victor Stinner7f11ad42011-10-04 00:00:20 +0200321 void *data;
Victor Stinner910337b2011-10-03 03:20:16 +0200322
Victor Stinnera41463c2011-10-04 01:05:08 +0200323 if (ascii->state.compact == 1) {
324 data = compact + 1;
Victor Stinner910337b2011-10-03 03:20:16 +0200325 assert(kind == PyUnicode_1BYTE_KIND
326 || kind == PyUnicode_2BYTE_KIND
327 || kind == PyUnicode_4BYTE_KIND);
Victor Stinnera41463c2011-10-04 01:05:08 +0200328 assert(ascii->state.ascii == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200329 assert(ascii->state.ready == 1);
Victor Stinnera41463c2011-10-04 01:05:08 +0200330 assert (compact->utf8 != data);
Victor Stinnere30c0a12011-11-04 20:54:05 +0100331 }
332 else {
Victor Stinnera41463c2011-10-04 01:05:08 +0200333 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
334
335 data = unicode->data.any;
336 if (kind == PyUnicode_WCHAR_KIND) {
Victor Stinnere30c0a12011-11-04 20:54:05 +0100337 assert(ascii->length == 0);
338 assert(ascii->hash == -1);
Victor Stinnera41463c2011-10-04 01:05:08 +0200339 assert(ascii->state.compact == 0);
340 assert(ascii->state.ascii == 0);
341 assert(ascii->state.ready == 0);
Victor Stinnere30c0a12011-11-04 20:54:05 +0100342 assert(ascii->state.interned == SSTATE_NOT_INTERNED);
Victor Stinnera41463c2011-10-04 01:05:08 +0200343 assert(ascii->wstr != NULL);
344 assert(data == NULL);
345 assert(compact->utf8 == NULL);
Victor Stinnera41463c2011-10-04 01:05:08 +0200346 }
347 else {
348 assert(kind == PyUnicode_1BYTE_KIND
349 || kind == PyUnicode_2BYTE_KIND
350 || kind == PyUnicode_4BYTE_KIND);
351 assert(ascii->state.compact == 0);
352 assert(ascii->state.ready == 1);
353 assert(data != NULL);
354 if (ascii->state.ascii) {
355 assert (compact->utf8 == data);
356 assert (compact->utf8_length == ascii->length);
357 }
358 else
359 assert (compact->utf8 != data);
360 }
361 }
362 if (kind != PyUnicode_WCHAR_KIND) {
Victor Stinner7f11ad42011-10-04 00:00:20 +0200363 if (
364#if SIZEOF_WCHAR_T == 2
365 kind == PyUnicode_2BYTE_KIND
366#else
367 kind == PyUnicode_4BYTE_KIND
368#endif
369 )
Victor Stinnera41463c2011-10-04 01:05:08 +0200370 {
371 assert(ascii->wstr == data);
372 assert(compact->wstr_length == ascii->length);
373 } else
374 assert(ascii->wstr != data);
Victor Stinner910337b2011-10-03 03:20:16 +0200375 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200376
377 if (compact->utf8 == NULL)
378 assert(compact->utf8_length == 0);
379 if (ascii->wstr == NULL)
380 assert(compact->wstr_length == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200381 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200382 /* check that the best kind is used */
383 if (check_content && kind != PyUnicode_WCHAR_KIND)
384 {
385 Py_ssize_t i;
386 Py_UCS4 maxchar = 0;
387 void *data = PyUnicode_DATA(ascii);
388 for (i=0; i < ascii->length; i++)
389 {
390 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
391 if (ch > maxchar)
392 maxchar = ch;
393 }
394 if (kind == PyUnicode_1BYTE_KIND) {
395 if (ascii->state.ascii == 0)
396 assert(maxchar >= 128);
397 else
398 assert(maxchar < 128);
399 }
400 else if (kind == PyUnicode_2BYTE_KIND)
401 assert(maxchar >= 0x100);
402 else
403 assert(maxchar >= 0x10000);
404 }
Victor Stinner7931d9a2011-11-04 00:22:48 +0100405 if (check_content && !unicode_is_singleton(op))
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200406 assert(ascii->hash == -1);
Benjamin Petersonccc51c12011-10-03 19:34:12 -0400407 return 1;
408}
Victor Stinner910337b2011-10-03 03:20:16 +0200409#endif
410
Victor Stinner3a50e702011-10-18 21:21:00 +0200411#ifdef HAVE_MBCS
412static OSVERSIONINFOEX winver;
413#endif
414
Thomas Wouters477c8d52006-05-27 19:21:47 +0000415/* --- Bloom Filters ----------------------------------------------------- */
416
417/* stuff to implement simple "bloom filters" for Unicode characters.
418 to keep things simple, we use a single bitmask, using the least 5
419 bits from each unicode characters as the bit index. */
420
421/* the linebreak mask is set up by Unicode_Init below */
422
Antoine Pitrouf068f942010-01-13 14:19:12 +0000423#if LONG_BIT >= 128
424#define BLOOM_WIDTH 128
425#elif LONG_BIT >= 64
426#define BLOOM_WIDTH 64
427#elif LONG_BIT >= 32
428#define BLOOM_WIDTH 32
429#else
430#error "LONG_BIT is smaller than 32"
431#endif
432
Thomas Wouters477c8d52006-05-27 19:21:47 +0000433#define BLOOM_MASK unsigned long
434
435static BLOOM_MASK bloom_linebreak;
436
Antoine Pitrouf068f942010-01-13 14:19:12 +0000437#define BLOOM_ADD(mask, ch) ((mask |= (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
438#define BLOOM(mask, ch) ((mask & (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000439
Benjamin Peterson29060642009-01-31 22:14:21 +0000440#define BLOOM_LINEBREAK(ch) \
441 ((ch) < 128U ? ascii_linebreak[(ch)] : \
442 (BLOOM(bloom_linebreak, (ch)) && Py_UNICODE_ISLINEBREAK(ch)))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000443
Alexander Belopolsky40018472011-02-26 01:02:56 +0000444Py_LOCAL_INLINE(BLOOM_MASK)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200445make_bloom_mask(int kind, void* ptr, Py_ssize_t len)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000446{
447 /* calculate simple bloom-style bitmask for a given unicode string */
448
Antoine Pitrouf068f942010-01-13 14:19:12 +0000449 BLOOM_MASK mask;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000450 Py_ssize_t i;
451
452 mask = 0;
453 for (i = 0; i < len; i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200454 BLOOM_ADD(mask, PyUnicode_READ(kind, ptr, i));
Thomas Wouters477c8d52006-05-27 19:21:47 +0000455
456 return mask;
457}
458
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200459#define BLOOM_MEMBER(mask, chr, str) \
460 (BLOOM(mask, chr) \
461 && (PyUnicode_FindChar(str, chr, 0, PyUnicode_GET_LENGTH(str), 1) >= 0))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000462
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200463/* Compilation of templated routines */
464
465#include "stringlib/asciilib.h"
466#include "stringlib/fastsearch.h"
467#include "stringlib/partition.h"
468#include "stringlib/split.h"
469#include "stringlib/count.h"
470#include "stringlib/find.h"
471#include "stringlib/find_max_char.h"
472#include "stringlib/localeutil.h"
473#include "stringlib/undef.h"
474
475#include "stringlib/ucs1lib.h"
476#include "stringlib/fastsearch.h"
477#include "stringlib/partition.h"
478#include "stringlib/split.h"
479#include "stringlib/count.h"
480#include "stringlib/find.h"
481#include "stringlib/find_max_char.h"
482#include "stringlib/localeutil.h"
483#include "stringlib/undef.h"
484
485#include "stringlib/ucs2lib.h"
486#include "stringlib/fastsearch.h"
487#include "stringlib/partition.h"
488#include "stringlib/split.h"
489#include "stringlib/count.h"
490#include "stringlib/find.h"
491#include "stringlib/find_max_char.h"
492#include "stringlib/localeutil.h"
493#include "stringlib/undef.h"
494
495#include "stringlib/ucs4lib.h"
496#include "stringlib/fastsearch.h"
497#include "stringlib/partition.h"
498#include "stringlib/split.h"
499#include "stringlib/count.h"
500#include "stringlib/find.h"
501#include "stringlib/find_max_char.h"
502#include "stringlib/localeutil.h"
503#include "stringlib/undef.h"
504
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200505#include "stringlib/unicodedefs.h"
506#include "stringlib/fastsearch.h"
507#include "stringlib/count.h"
508#include "stringlib/find.h"
509
Guido van Rossumd57fd912000-03-10 22:53:23 +0000510/* --- Unicode Object ----------------------------------------------------- */
511
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200512static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +0200513fixup(PyObject *self, Py_UCS4 (*fixfct)(PyObject *s));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200514
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200515Py_LOCAL_INLINE(Py_ssize_t) findchar(void *s, int kind,
516 Py_ssize_t size, Py_UCS4 ch,
517 int direction)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200518{
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200519 int mode = (direction == 1) ? FAST_SEARCH : FAST_RSEARCH;
520
521 switch (kind) {
522 case PyUnicode_1BYTE_KIND:
523 {
524 Py_UCS1 ch1 = (Py_UCS1) ch;
525 if (ch1 == ch)
526 return ucs1lib_fastsearch((Py_UCS1 *) s, size, &ch1, 1, 0, mode);
527 else
528 return -1;
529 }
530 case PyUnicode_2BYTE_KIND:
531 {
532 Py_UCS2 ch2 = (Py_UCS2) ch;
533 if (ch2 == ch)
534 return ucs2lib_fastsearch((Py_UCS2 *) s, size, &ch2, 1, 0, mode);
535 else
536 return -1;
537 }
538 case PyUnicode_4BYTE_KIND:
539 return ucs4lib_fastsearch((Py_UCS4 *) s, size, &ch, 1, 0, mode);
540 default:
541 assert(0);
542 return -1;
Victor Stinner9e7a1bc2011-10-13 00:18:12 +0200543 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200544}
545
Victor Stinnerfe226c02011-10-03 03:52:20 +0200546static PyObject*
547resize_compact(PyObject *unicode, Py_ssize_t length)
548{
549 Py_ssize_t char_size;
550 Py_ssize_t struct_size;
551 Py_ssize_t new_size;
552 int share_wstr;
553
554 assert(PyUnicode_IS_READY(unicode));
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200555 char_size = PyUnicode_KIND(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200556 if (PyUnicode_IS_COMPACT_ASCII(unicode))
557 struct_size = sizeof(PyASCIIObject);
558 else
559 struct_size = sizeof(PyCompactUnicodeObject);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200560 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200561
562 _Py_DEC_REFTOTAL;
563 _Py_ForgetReference(unicode);
564
565 if (length > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1)) {
566 PyErr_NoMemory();
567 return NULL;
568 }
569 new_size = (struct_size + (length + 1) * char_size);
570
571 unicode = (PyObject *)PyObject_REALLOC((char *)unicode, new_size);
572 if (unicode == NULL) {
573 PyObject_Del(unicode);
574 PyErr_NoMemory();
575 return NULL;
576 }
577 _Py_NewReference(unicode);
578 _PyUnicode_LENGTH(unicode) = length;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200579 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200580 _PyUnicode_WSTR(unicode) = PyUnicode_DATA(unicode);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200581 if (!PyUnicode_IS_COMPACT_ASCII(unicode))
582 _PyUnicode_WSTR_LENGTH(unicode) = length;
583 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200584 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
585 length, 0);
586 return unicode;
587}
588
Alexander Belopolsky40018472011-02-26 01:02:56 +0000589static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200590resize_inplace(PyObject *unicode, Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000591{
Victor Stinner95663112011-10-04 01:03:50 +0200592 wchar_t *wstr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200593 assert(!PyUnicode_IS_COMPACT(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200594 assert(Py_REFCNT(unicode) == 1);
Tim Petersced69f82003-09-16 20:30:58 +0000595
Victor Stinner95663112011-10-04 01:03:50 +0200596 _PyUnicode_DIRTY(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200597
598 if (PyUnicode_IS_READY(unicode)) {
599 Py_ssize_t char_size;
600 Py_ssize_t new_size;
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200601 int share_wstr, share_utf8;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200602 void *data;
603
604 data = _PyUnicode_DATA_ANY(unicode);
605 assert(data != NULL);
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200606 char_size = PyUnicode_KIND(unicode);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200607 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
608 share_utf8 = _PyUnicode_SHARE_UTF8(unicode);
Victor Stinner95663112011-10-04 01:03:50 +0200609 if (!share_utf8 && _PyUnicode_HAS_UTF8_MEMORY(unicode))
610 {
611 PyObject_DEL(_PyUnicode_UTF8(unicode));
612 _PyUnicode_UTF8(unicode) = NULL;
613 _PyUnicode_UTF8_LENGTH(unicode) = 0;
614 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200615
616 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
617 PyErr_NoMemory();
618 return -1;
619 }
620 new_size = (length + 1) * char_size;
621
622 data = (PyObject *)PyObject_REALLOC(data, new_size);
623 if (data == NULL) {
624 PyErr_NoMemory();
625 return -1;
626 }
627 _PyUnicode_DATA_ANY(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200628 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200629 _PyUnicode_WSTR(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200630 _PyUnicode_WSTR_LENGTH(unicode) = length;
631 }
632 if (share_utf8) {
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200633 _PyUnicode_UTF8(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200634 _PyUnicode_UTF8_LENGTH(unicode) = length;
635 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200636 _PyUnicode_LENGTH(unicode) = length;
637 PyUnicode_WRITE(PyUnicode_KIND(unicode), data, length, 0);
Victor Stinner95663112011-10-04 01:03:50 +0200638 if (share_wstr || _PyUnicode_WSTR(unicode) == NULL) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200639 assert(_PyUnicode_CheckConsistency(unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200640 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200641 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200642 }
Victor Stinner95663112011-10-04 01:03:50 +0200643 assert(_PyUnicode_WSTR(unicode) != NULL);
644
645 /* check for integer overflow */
646 if (length > PY_SSIZE_T_MAX / sizeof(wchar_t) - 1) {
647 PyErr_NoMemory();
648 return -1;
649 }
650 wstr = _PyUnicode_WSTR(unicode);
651 wstr = PyObject_REALLOC(wstr, sizeof(wchar_t) * (length + 1));
652 if (!wstr) {
653 PyErr_NoMemory();
654 return -1;
655 }
656 _PyUnicode_WSTR(unicode) = wstr;
657 _PyUnicode_WSTR(unicode)[length] = 0;
658 _PyUnicode_WSTR_LENGTH(unicode) = length;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200659 assert(_PyUnicode_CheckConsistency(unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +0000660 return 0;
661}
662
Victor Stinnerfe226c02011-10-03 03:52:20 +0200663static PyObject*
664resize_copy(PyObject *unicode, Py_ssize_t length)
665{
666 Py_ssize_t copy_length;
667 if (PyUnicode_IS_COMPACT(unicode)) {
668 PyObject *copy;
669 assert(PyUnicode_IS_READY(unicode));
670
671 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
672 if (copy == NULL)
673 return NULL;
674
675 copy_length = Py_MIN(length, PyUnicode_GET_LENGTH(unicode));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200676 copy_characters(copy, 0, unicode, 0, copy_length);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200677 return copy;
Victor Stinner8cfcbed2011-10-03 23:19:21 +0200678 }
679 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200680 PyObject *w;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200681 assert(_PyUnicode_WSTR(unicode) != NULL);
682 assert(_PyUnicode_DATA_ANY(unicode) == NULL);
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200683 w = (PyObject*)_PyUnicode_New(length);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200684 if (w == NULL)
685 return NULL;
686 copy_length = _PyUnicode_WSTR_LENGTH(unicode);
687 copy_length = Py_MIN(copy_length, length);
688 Py_UNICODE_COPY(_PyUnicode_WSTR(w), _PyUnicode_WSTR(unicode),
689 copy_length);
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200690 return w;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200691 }
692}
693
Guido van Rossumd57fd912000-03-10 22:53:23 +0000694/* We allocate one more byte to make sure the string is
Martin v. Löwis47383402007-08-15 07:32:56 +0000695 Ux0000 terminated; some code (e.g. new_identifier)
696 relies on that.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000697
698 XXX This allocator could further be enhanced by assuring that the
Benjamin Peterson29060642009-01-31 22:14:21 +0000699 free list never reduces its size below 1.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000700
701*/
702
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200703#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +0200704static int unicode_old_new_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200705#endif
706
Alexander Belopolsky40018472011-02-26 01:02:56 +0000707static PyUnicodeObject *
708_PyUnicode_New(Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000709{
710 register PyUnicodeObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200711 size_t new_size;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000712
Thomas Wouters477c8d52006-05-27 19:21:47 +0000713 /* Optimization for empty strings */
Guido van Rossumd57fd912000-03-10 22:53:23 +0000714 if (length == 0 && unicode_empty != NULL) {
715 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +0200716 return (PyUnicodeObject*)unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000717 }
718
Neal Norwitz3ce5d922008-08-24 07:08:55 +0000719 /* Ensure we won't overflow the size. */
720 if (length > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
721 return (PyUnicodeObject *)PyErr_NoMemory();
722 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200723 if (length < 0) {
724 PyErr_SetString(PyExc_SystemError,
725 "Negative size passed to _PyUnicode_New");
726 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000727 }
728
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200729#ifdef Py_DEBUG
730 ++unicode_old_new_calls;
731#endif
732
733 unicode = PyObject_New(PyUnicodeObject, &PyUnicode_Type);
734 if (unicode == NULL)
735 return NULL;
736 new_size = sizeof(Py_UNICODE) * ((size_t)length + 1);
737 _PyUnicode_WSTR(unicode) = (Py_UNICODE*) PyObject_MALLOC(new_size);
738 if (!_PyUnicode_WSTR(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +0000739 PyErr_NoMemory();
740 goto onError;
Guido van Rossum3c1bb802000-04-27 20:13:50 +0000741 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200742
Jeremy Hyltond8082792003-09-16 19:41:39 +0000743 /* Initialize the first element to guard against cases where
Tim Petersced69f82003-09-16 20:30:58 +0000744 * the caller fails before initializing str -- unicode_resize()
745 * reads str[0], and the Keep-Alive optimization can keep memory
746 * allocated for str alive across a call to unicode_dealloc(unicode).
747 * We don't want unicode_resize to read uninitialized memory in
748 * that case.
749 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200750 _PyUnicode_WSTR(unicode)[0] = 0;
751 _PyUnicode_WSTR(unicode)[length] = 0;
752 _PyUnicode_WSTR_LENGTH(unicode) = length;
753 _PyUnicode_HASH(unicode) = -1;
754 _PyUnicode_STATE(unicode).interned = 0;
755 _PyUnicode_STATE(unicode).kind = 0;
756 _PyUnicode_STATE(unicode).compact = 0;
757 _PyUnicode_STATE(unicode).ready = 0;
758 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +0200759 _PyUnicode_DATA_ANY(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200760 _PyUnicode_LENGTH(unicode) = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200761 _PyUnicode_UTF8(unicode) = NULL;
762 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner7931d9a2011-11-04 00:22:48 +0100763 assert(_PyUnicode_CheckConsistency((PyObject *)unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +0000764 return unicode;
Barry Warsaw51ac5802000-03-20 16:36:48 +0000765
Benjamin Peterson29060642009-01-31 22:14:21 +0000766 onError:
Amaury Forgeot d'Arc7888d082008-08-01 01:06:32 +0000767 /* XXX UNREF/NEWREF interface should be more symmetrical */
768 _Py_DEC_REFTOTAL;
Barry Warsaw51ac5802000-03-20 16:36:48 +0000769 _Py_ForgetReference((PyObject *)unicode);
Neil Schemenauer58aa8612002-04-12 03:07:20 +0000770 PyObject_Del(unicode);
Barry Warsaw51ac5802000-03-20 16:36:48 +0000771 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000772}
773
Victor Stinnerf42dc442011-10-02 23:33:16 +0200774static const char*
775unicode_kind_name(PyObject *unicode)
776{
Victor Stinner42dfd712011-10-03 14:41:45 +0200777 /* don't check consistency: unicode_kind_name() is called from
778 _PyUnicode_Dump() */
Victor Stinnerf42dc442011-10-02 23:33:16 +0200779 if (!PyUnicode_IS_COMPACT(unicode))
780 {
781 if (!PyUnicode_IS_READY(unicode))
782 return "wstr";
783 switch(PyUnicode_KIND(unicode))
784 {
785 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200786 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200787 return "legacy ascii";
788 else
789 return "legacy latin1";
790 case PyUnicode_2BYTE_KIND:
791 return "legacy UCS2";
792 case PyUnicode_4BYTE_KIND:
793 return "legacy UCS4";
794 default:
795 return "<legacy invalid kind>";
796 }
797 }
798 assert(PyUnicode_IS_READY(unicode));
799 switch(PyUnicode_KIND(unicode))
800 {
801 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200802 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200803 return "ascii";
804 else
Victor Stinnera3b334d2011-10-03 13:53:37 +0200805 return "latin1";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200806 case PyUnicode_2BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200807 return "UCS2";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200808 case PyUnicode_4BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200809 return "UCS4";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200810 default:
811 return "<invalid compact kind>";
812 }
813}
814
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200815#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +0200816static int unicode_new_new_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200817
818/* Functions wrapping macros for use in debugger */
819char *_PyUnicode_utf8(void *unicode){
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200820 return PyUnicode_UTF8(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200821}
822
823void *_PyUnicode_compact_data(void *unicode) {
824 return _PyUnicode_COMPACT_DATA(unicode);
825}
826void *_PyUnicode_data(void *unicode){
827 printf("obj %p\n", unicode);
828 printf("compact %d\n", PyUnicode_IS_COMPACT(unicode));
829 printf("compact ascii %d\n", PyUnicode_IS_COMPACT_ASCII(unicode));
830 printf("ascii op %p\n", ((void*)((PyASCIIObject*)(unicode) + 1)));
831 printf("compact op %p\n", ((void*)((PyCompactUnicodeObject*)(unicode) + 1)));
832 printf("compact data %p\n", _PyUnicode_COMPACT_DATA(unicode));
833 return PyUnicode_DATA(unicode);
834}
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200835
836void
837_PyUnicode_Dump(PyObject *op)
838{
839 PyASCIIObject *ascii = (PyASCIIObject *)op;
Victor Stinnera849a4b2011-10-03 12:12:11 +0200840 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
841 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
842 void *data;
Victor Stinner0d60e872011-10-23 19:47:19 +0200843
Victor Stinnera849a4b2011-10-03 12:12:11 +0200844 if (ascii->state.compact)
Victor Stinner0d60e872011-10-23 19:47:19 +0200845 {
846 if (ascii->state.ascii)
847 data = (ascii + 1);
848 else
849 data = (compact + 1);
850 }
Victor Stinnera849a4b2011-10-03 12:12:11 +0200851 else
852 data = unicode->data.any;
Victor Stinner0d60e872011-10-23 19:47:19 +0200853 printf("%s: len=%zu, ",unicode_kind_name(op), ascii->length);
854
Victor Stinnera849a4b2011-10-03 12:12:11 +0200855 if (ascii->wstr == data)
856 printf("shared ");
857 printf("wstr=%p", ascii->wstr);
Victor Stinner0d60e872011-10-23 19:47:19 +0200858
Victor Stinnera3b334d2011-10-03 13:53:37 +0200859 if (!(ascii->state.ascii == 1 && ascii->state.compact == 1)) {
Victor Stinnera849a4b2011-10-03 12:12:11 +0200860 printf(" (%zu), ", compact->wstr_length);
861 if (!ascii->state.compact && compact->utf8 == unicode->data.any)
862 printf("shared ");
863 printf("utf8=%p (%zu)", compact->utf8, compact->utf8_length);
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200864 }
Victor Stinnera849a4b2011-10-03 12:12:11 +0200865 printf(", data=%p\n", data);
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200866}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200867#endif
868
869PyObject *
870PyUnicode_New(Py_ssize_t size, Py_UCS4 maxchar)
871{
872 PyObject *obj;
873 PyCompactUnicodeObject *unicode;
874 void *data;
875 int kind_state;
Victor Stinner9e9d6892011-10-04 01:02:02 +0200876 int is_sharing, is_ascii;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200877 Py_ssize_t char_size;
878 Py_ssize_t struct_size;
879
880 /* Optimization for empty strings */
881 if (size == 0 && unicode_empty != NULL) {
882 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +0200883 return unicode_empty;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200884 }
885
886#ifdef Py_DEBUG
887 ++unicode_new_new_calls;
888#endif
889
Victor Stinner9e9d6892011-10-04 01:02:02 +0200890 is_ascii = 0;
891 is_sharing = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200892 struct_size = sizeof(PyCompactUnicodeObject);
893 if (maxchar < 128) {
894 kind_state = PyUnicode_1BYTE_KIND;
895 char_size = 1;
896 is_ascii = 1;
897 struct_size = sizeof(PyASCIIObject);
898 }
899 else if (maxchar < 256) {
900 kind_state = PyUnicode_1BYTE_KIND;
901 char_size = 1;
902 }
903 else if (maxchar < 65536) {
904 kind_state = PyUnicode_2BYTE_KIND;
905 char_size = 2;
906 if (sizeof(wchar_t) == 2)
907 is_sharing = 1;
908 }
909 else {
910 kind_state = PyUnicode_4BYTE_KIND;
911 char_size = 4;
912 if (sizeof(wchar_t) == 4)
913 is_sharing = 1;
914 }
915
916 /* Ensure we won't overflow the size. */
917 if (size < 0) {
918 PyErr_SetString(PyExc_SystemError,
919 "Negative size passed to PyUnicode_New");
920 return NULL;
921 }
922 if (size > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1))
923 return PyErr_NoMemory();
924
925 /* Duplicated allocation code from _PyObject_New() instead of a call to
926 * PyObject_New() so we are able to allocate space for the object and
927 * it's data buffer.
928 */
929 obj = (PyObject *) PyObject_MALLOC(struct_size + (size + 1) * char_size);
930 if (obj == NULL)
931 return PyErr_NoMemory();
932 obj = PyObject_INIT(obj, &PyUnicode_Type);
933 if (obj == NULL)
934 return NULL;
935
936 unicode = (PyCompactUnicodeObject *)obj;
937 if (is_ascii)
938 data = ((PyASCIIObject*)obj) + 1;
939 else
940 data = unicode + 1;
941 _PyUnicode_LENGTH(unicode) = size;
942 _PyUnicode_HASH(unicode) = -1;
943 _PyUnicode_STATE(unicode).interned = 0;
944 _PyUnicode_STATE(unicode).kind = kind_state;
945 _PyUnicode_STATE(unicode).compact = 1;
946 _PyUnicode_STATE(unicode).ready = 1;
947 _PyUnicode_STATE(unicode).ascii = is_ascii;
948 if (is_ascii) {
949 ((char*)data)[size] = 0;
950 _PyUnicode_WSTR(unicode) = NULL;
951 }
952 else if (kind_state == PyUnicode_1BYTE_KIND) {
953 ((char*)data)[size] = 0;
954 _PyUnicode_WSTR(unicode) = NULL;
955 _PyUnicode_WSTR_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200956 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +0200957 unicode->utf8_length = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200958 }
959 else {
960 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +0200961 unicode->utf8_length = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200962 if (kind_state == PyUnicode_2BYTE_KIND)
963 ((Py_UCS2*)data)[size] = 0;
964 else /* kind_state == PyUnicode_4BYTE_KIND */
965 ((Py_UCS4*)data)[size] = 0;
966 if (is_sharing) {
967 _PyUnicode_WSTR_LENGTH(unicode) = size;
968 _PyUnicode_WSTR(unicode) = (wchar_t *)data;
969 }
970 else {
971 _PyUnicode_WSTR_LENGTH(unicode) = 0;
972 _PyUnicode_WSTR(unicode) = NULL;
973 }
974 }
Victor Stinner7931d9a2011-11-04 00:22:48 +0100975 assert(_PyUnicode_CheckConsistency((PyObject*)unicode, 0));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200976 return obj;
977}
978
979#if SIZEOF_WCHAR_T == 2
980/* Helper function to convert a 16-bits wchar_t representation to UCS4, this
981 will decode surrogate pairs, the other conversions are implemented as macros
Georg Brandl7597add2011-10-05 16:36:47 +0200982 for efficiency.
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200983
984 This function assumes that unicode can hold one more code point than wstr
985 characters for a terminating null character. */
Victor Stinnerc53be962011-10-02 21:33:54 +0200986static void
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200987unicode_convert_wchar_to_ucs4(const wchar_t *begin, const wchar_t *end,
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200988 PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200989{
990 const wchar_t *iter;
991 Py_UCS4 *ucs4_out;
992
Victor Stinner910337b2011-10-03 03:20:16 +0200993 assert(unicode != NULL);
994 assert(_PyUnicode_CHECK(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200995 assert(_PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
996 ucs4_out = PyUnicode_4BYTE_DATA(unicode);
997
998 for (iter = begin; iter < end; ) {
999 assert(ucs4_out < (PyUnicode_4BYTE_DATA(unicode) +
1000 _PyUnicode_GET_LENGTH(unicode)));
1001 if (*iter >= 0xD800 && *iter <= 0xDBFF
1002 && (iter+1) < end && iter[1] >= 0xDC00 && iter[1] <= 0xDFFF)
1003 {
1004 *ucs4_out++ = (((iter[0] & 0x3FF)<<10) | (iter[1] & 0x3FF)) + 0x10000;
1005 iter += 2;
1006 }
1007 else {
1008 *ucs4_out++ = *iter;
1009 iter++;
1010 }
1011 }
1012 assert(ucs4_out == (PyUnicode_4BYTE_DATA(unicode) +
1013 _PyUnicode_GET_LENGTH(unicode)));
1014
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001015}
1016#endif
1017
Victor Stinnercd9950f2011-10-02 00:34:53 +02001018static int
1019_PyUnicode_Dirty(PyObject *unicode)
1020{
Victor Stinner910337b2011-10-03 03:20:16 +02001021 assert(_PyUnicode_CHECK(unicode));
Victor Stinnercd9950f2011-10-02 00:34:53 +02001022 if (Py_REFCNT(unicode) != 1) {
Victor Stinner01698042011-10-04 00:04:26 +02001023 PyErr_SetString(PyExc_SystemError,
Victor Stinnercd9950f2011-10-02 00:34:53 +02001024 "Cannot modify a string having more than 1 reference");
1025 return -1;
1026 }
1027 _PyUnicode_DIRTY(unicode);
1028 return 0;
1029}
1030
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001031static int
1032_copy_characters(PyObject *to, Py_ssize_t to_start,
1033 PyObject *from, Py_ssize_t from_start,
1034 Py_ssize_t how_many, int check_maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001035{
Victor Stinnera0702ab2011-09-29 14:14:38 +02001036 unsigned int from_kind, to_kind;
1037 void *from_data, *to_data;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001038 int fast;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001039
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001040 assert(PyUnicode_Check(from));
1041 assert(PyUnicode_Check(to));
1042 assert(PyUnicode_IS_READY(from));
1043 assert(PyUnicode_IS_READY(to));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001044
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001045 assert(PyUnicode_GET_LENGTH(from) >= how_many);
1046 assert(to_start + how_many <= PyUnicode_GET_LENGTH(to));
1047 assert(0 <= how_many);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001048
Victor Stinnerf5ca1a22011-09-28 23:54:59 +02001049 if (how_many == 0)
1050 return 0;
1051
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001052 from_kind = PyUnicode_KIND(from);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001053 from_data = PyUnicode_DATA(from);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001054 to_kind = PyUnicode_KIND(to);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001055 to_data = PyUnicode_DATA(to);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001056
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001057#ifdef Py_DEBUG
1058 if (!check_maxchar
1059 && (from_kind > to_kind
1060 || (!PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to))))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001061 {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001062 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
1063 Py_UCS4 ch;
1064 Py_ssize_t i;
1065 for (i=0; i < how_many; i++) {
1066 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1067 assert(ch <= to_maxchar);
1068 }
1069 }
1070#endif
1071 fast = (from_kind == to_kind);
1072 if (check_maxchar
1073 && (!PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to)))
1074 {
1075 /* deny latin1 => ascii */
1076 fast = 0;
1077 }
1078
1079 if (fast) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +02001080 Py_MEMCPY((char*)to_data + to_kind * to_start,
1081 (char*)from_data + from_kind * from_start,
1082 to_kind * how_many);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001083 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001084 else if (from_kind == PyUnicode_1BYTE_KIND
1085 && to_kind == PyUnicode_2BYTE_KIND)
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001086 {
1087 _PyUnicode_CONVERT_BYTES(
1088 Py_UCS1, Py_UCS2,
1089 PyUnicode_1BYTE_DATA(from) + from_start,
1090 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1091 PyUnicode_2BYTE_DATA(to) + to_start
1092 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001093 }
Victor Stinner157f83f2011-09-28 21:41:31 +02001094 else if (from_kind == PyUnicode_1BYTE_KIND
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001095 && to_kind == PyUnicode_4BYTE_KIND)
1096 {
1097 _PyUnicode_CONVERT_BYTES(
1098 Py_UCS1, Py_UCS4,
1099 PyUnicode_1BYTE_DATA(from) + from_start,
1100 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1101 PyUnicode_4BYTE_DATA(to) + to_start
1102 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001103 }
1104 else if (from_kind == PyUnicode_2BYTE_KIND
1105 && to_kind == PyUnicode_4BYTE_KIND)
1106 {
1107 _PyUnicode_CONVERT_BYTES(
1108 Py_UCS2, Py_UCS4,
1109 PyUnicode_2BYTE_DATA(from) + from_start,
1110 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1111 PyUnicode_4BYTE_DATA(to) + to_start
1112 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001113 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001114 else {
Victor Stinnerf42dc442011-10-02 23:33:16 +02001115 /* check if max_char(from substring) <= max_char(to) */
1116 if (from_kind > to_kind
1117 /* latin1 => ascii */
Victor Stinnerb9275c12011-10-05 14:01:42 +02001118 || (!PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to)))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001119 {
Victor Stinnera0702ab2011-09-29 14:14:38 +02001120 /* slow path to check for character overflow */
1121 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001122 Py_UCS4 ch;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001123 Py_ssize_t i;
1124
Victor Stinner56c161a2011-10-06 02:47:11 +02001125#ifdef Py_DEBUG
Victor Stinnera0702ab2011-09-29 14:14:38 +02001126 for (i=0; i < how_many; i++) {
1127 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
Victor Stinner56c161a2011-10-06 02:47:11 +02001128 assert(ch <= to_maxchar);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001129 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1130 }
Victor Stinner56c161a2011-10-06 02:47:11 +02001131#else
1132 if (!check_maxchar) {
1133 for (i=0; i < how_many; i++) {
1134 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1135 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1136 }
1137 }
1138 else {
1139 for (i=0; i < how_many; i++) {
1140 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1141 if (ch > to_maxchar)
1142 return 1;
1143 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1144 }
1145 }
1146#endif
Victor Stinnera0702ab2011-09-29 14:14:38 +02001147 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001148 else {
Victor Stinner56c161a2011-10-06 02:47:11 +02001149 assert(0 && "inconsistent state");
1150 return 1;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001151 }
1152 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001153 return 0;
1154}
1155
1156static void
1157copy_characters(PyObject *to, Py_ssize_t to_start,
1158 PyObject *from, Py_ssize_t from_start,
1159 Py_ssize_t how_many)
1160{
1161 (void)_copy_characters(to, to_start, from, from_start, how_many, 0);
1162}
1163
1164Py_ssize_t
1165PyUnicode_CopyCharacters(PyObject *to, Py_ssize_t to_start,
1166 PyObject *from, Py_ssize_t from_start,
1167 Py_ssize_t how_many)
1168{
1169 int err;
1170
1171 if (!PyUnicode_Check(from) || !PyUnicode_Check(to)) {
1172 PyErr_BadInternalCall();
1173 return -1;
1174 }
1175
1176 if (PyUnicode_READY(from))
1177 return -1;
1178 if (PyUnicode_READY(to))
1179 return -1;
1180
1181 how_many = Py_MIN(PyUnicode_GET_LENGTH(from), how_many);
1182 if (to_start + how_many > PyUnicode_GET_LENGTH(to)) {
1183 PyErr_Format(PyExc_SystemError,
1184 "Cannot write %zi characters at %zi "
1185 "in a string of %zi characters",
1186 how_many, to_start, PyUnicode_GET_LENGTH(to));
1187 return -1;
1188 }
1189
1190 if (how_many == 0)
1191 return 0;
1192
1193 if (_PyUnicode_Dirty(to))
1194 return -1;
1195
1196 err = _copy_characters(to, to_start, from, from_start, how_many, 1);
1197 if (err) {
1198 PyErr_Format(PyExc_SystemError,
1199 "Cannot copy %s characters "
1200 "into a string of %s characters",
1201 unicode_kind_name(from),
1202 unicode_kind_name(to));
1203 return -1;
1204 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001205 return how_many;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001206}
1207
Victor Stinner17222162011-09-28 22:15:37 +02001208/* Find the maximum code point and count the number of surrogate pairs so a
1209 correct string length can be computed before converting a string to UCS4.
1210 This function counts single surrogates as a character and not as a pair.
1211
1212 Return 0 on success, or -1 on error. */
1213static int
1214find_maxchar_surrogates(const wchar_t *begin, const wchar_t *end,
1215 Py_UCS4 *maxchar, Py_ssize_t *num_surrogates)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001216{
1217 const wchar_t *iter;
1218
Victor Stinnerc53be962011-10-02 21:33:54 +02001219 assert(num_surrogates != NULL && maxchar != NULL);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001220 *num_surrogates = 0;
1221 *maxchar = 0;
1222
1223 for (iter = begin; iter < end; ) {
Victor Stinnerae864852011-10-05 14:02:44 +02001224 if (*iter > *maxchar) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001225 *maxchar = *iter;
Victor Stinnerae864852011-10-05 14:02:44 +02001226#if SIZEOF_WCHAR_T != 2
1227 if (*maxchar >= 0x10000)
1228 return 0;
1229#endif
1230 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001231#if SIZEOF_WCHAR_T == 2
1232 if (*iter >= 0xD800 && *iter <= 0xDBFF
1233 && (iter+1) < end && iter[1] >= 0xDC00 && iter[1] <= 0xDFFF)
1234 {
1235 Py_UCS4 surrogate_val;
1236 surrogate_val = (((iter[0] & 0x3FF)<<10)
1237 | (iter[1] & 0x3FF)) + 0x10000;
1238 ++(*num_surrogates);
1239 if (surrogate_val > *maxchar)
1240 *maxchar = surrogate_val;
1241 iter += 2;
1242 }
1243 else
1244 iter++;
1245#else
1246 iter++;
1247#endif
1248 }
1249 return 0;
1250}
1251
1252#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +02001253static int unicode_ready_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001254#endif
1255
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02001256static int
1257unicode_ready(PyObject **p_obj, int replace)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001258{
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001259 PyObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001260 wchar_t *end;
1261 Py_UCS4 maxchar = 0;
1262 Py_ssize_t num_surrogates;
1263#if SIZEOF_WCHAR_T == 2
1264 Py_ssize_t length_wo_surrogates;
1265#endif
1266
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02001267 assert(p_obj != NULL);
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001268 unicode = *p_obj;
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02001269
Georg Brandl7597add2011-10-05 16:36:47 +02001270 /* _PyUnicode_Ready() is only intended for old-style API usage where
Victor Stinnerd8f65102011-09-29 19:43:17 +02001271 strings were created using _PyObject_New() and where no canonical
1272 representation (the str field) has been set yet aka strings
1273 which are not yet ready. */
Victor Stinner910337b2011-10-03 03:20:16 +02001274 assert(_PyUnicode_CHECK(unicode));
1275 assert(_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001276 assert(_PyUnicode_WSTR(unicode) != NULL);
Victor Stinnerc3c74152011-10-02 20:39:55 +02001277 assert(_PyUnicode_DATA_ANY(unicode) == NULL);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001278 assert(_PyUnicode_UTF8(unicode) == NULL);
Victor Stinnerd8f65102011-09-29 19:43:17 +02001279 /* Actually, it should neither be interned nor be anything else: */
1280 assert(_PyUnicode_STATE(unicode).interned == SSTATE_NOT_INTERNED);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001281
1282#ifdef Py_DEBUG
1283 ++unicode_ready_calls;
1284#endif
1285
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02001286#ifdef Py_DEBUG
1287 assert(!replace || Py_REFCNT(unicode) == 1);
1288#else
1289 if (replace && Py_REFCNT(unicode) != 1)
1290 replace = 0;
1291#endif
1292 if (replace) {
1293 Py_ssize_t len = _PyUnicode_WSTR_LENGTH(unicode);
1294 wchar_t *wstr = _PyUnicode_WSTR(unicode);
1295 /* Optimization for empty strings */
1296 if (len == 0) {
1297 Py_INCREF(unicode_empty);
1298 Py_DECREF(*p_obj);
1299 *p_obj = unicode_empty;
1300 return 0;
1301 }
1302 if (len == 1 && wstr[0] < 256) {
1303 PyObject *latin1_char = get_latin1_char((unsigned char)wstr[0]);
1304 if (latin1_char == NULL)
1305 return -1;
1306 Py_DECREF(*p_obj);
1307 *p_obj = latin1_char;
1308 return 0;
1309 }
1310 }
1311
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001312 end = _PyUnicode_WSTR(unicode) + _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinner17222162011-09-28 22:15:37 +02001313 if (find_maxchar_surrogates(_PyUnicode_WSTR(unicode), end,
Victor Stinnerd8f65102011-09-29 19:43:17 +02001314 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001315 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001316
1317 if (maxchar < 256) {
Victor Stinnerc3c74152011-10-02 20:39:55 +02001318 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(_PyUnicode_WSTR_LENGTH(unicode) + 1);
1319 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001320 PyErr_NoMemory();
1321 return -1;
1322 }
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001323 _PyUnicode_CONVERT_BYTES(wchar_t, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001324 _PyUnicode_WSTR(unicode), end,
1325 PyUnicode_1BYTE_DATA(unicode));
1326 PyUnicode_1BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1327 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1328 _PyUnicode_STATE(unicode).kind = PyUnicode_1BYTE_KIND;
1329 if (maxchar < 128) {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001330 _PyUnicode_STATE(unicode).ascii = 1;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001331 _PyUnicode_UTF8(unicode) = _PyUnicode_DATA_ANY(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001332 _PyUnicode_UTF8_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001333 }
1334 else {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001335 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001336 _PyUnicode_UTF8(unicode) = NULL;
1337 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001338 }
1339 PyObject_FREE(_PyUnicode_WSTR(unicode));
1340 _PyUnicode_WSTR(unicode) = NULL;
1341 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1342 }
1343 /* In this case we might have to convert down from 4-byte native
1344 wchar_t to 2-byte unicode. */
1345 else if (maxchar < 65536) {
1346 assert(num_surrogates == 0 &&
1347 "FindMaxCharAndNumSurrogatePairs() messed up");
1348
Victor Stinner506f5922011-09-28 22:34:18 +02001349#if SIZEOF_WCHAR_T == 2
1350 /* We can share representations and are done. */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001351 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Victor Stinner506f5922011-09-28 22:34:18 +02001352 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1353 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1354 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001355 _PyUnicode_UTF8(unicode) = NULL;
1356 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001357#else
1358 /* sizeof(wchar_t) == 4 */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001359 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(
Victor Stinner506f5922011-09-28 22:34:18 +02001360 2 * (_PyUnicode_WSTR_LENGTH(unicode) + 1));
Victor Stinnerc3c74152011-10-02 20:39:55 +02001361 if (!_PyUnicode_DATA_ANY(unicode)) {
Victor Stinner506f5922011-09-28 22:34:18 +02001362 PyErr_NoMemory();
1363 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001364 }
Victor Stinner506f5922011-09-28 22:34:18 +02001365 _PyUnicode_CONVERT_BYTES(wchar_t, Py_UCS2,
1366 _PyUnicode_WSTR(unicode), end,
1367 PyUnicode_2BYTE_DATA(unicode));
1368 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1369 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1370 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001371 _PyUnicode_UTF8(unicode) = NULL;
1372 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001373 PyObject_FREE(_PyUnicode_WSTR(unicode));
1374 _PyUnicode_WSTR(unicode) = NULL;
1375 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1376#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001377 }
1378 /* maxchar exeeds 16 bit, wee need 4 bytes for unicode characters */
1379 else {
1380#if SIZEOF_WCHAR_T == 2
1381 /* in case the native representation is 2-bytes, we need to allocate a
1382 new normalized 4-byte version. */
1383 length_wo_surrogates = _PyUnicode_WSTR_LENGTH(unicode) - num_surrogates;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001384 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(4 * (length_wo_surrogates + 1));
1385 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001386 PyErr_NoMemory();
1387 return -1;
1388 }
1389 _PyUnicode_LENGTH(unicode) = length_wo_surrogates;
1390 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001391 _PyUnicode_UTF8(unicode) = NULL;
1392 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner126c5592011-10-03 04:17:10 +02001393 /* unicode_convert_wchar_to_ucs4() requires a ready string */
1394 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerc53be962011-10-02 21:33:54 +02001395 unicode_convert_wchar_to_ucs4(_PyUnicode_WSTR(unicode), end, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001396 PyObject_FREE(_PyUnicode_WSTR(unicode));
1397 _PyUnicode_WSTR(unicode) = NULL;
1398 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1399#else
1400 assert(num_surrogates == 0);
1401
Victor Stinnerc3c74152011-10-02 20:39:55 +02001402 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001403 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001404 _PyUnicode_UTF8(unicode) = NULL;
1405 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001406 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
1407#endif
1408 PyUnicode_4BYTE_DATA(unicode)[_PyUnicode_LENGTH(unicode)] = '\0';
1409 }
1410 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001411 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001412 return 0;
1413}
1414
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02001415int
1416_PyUnicode_ReadyReplace(PyObject **op)
1417{
1418 return unicode_ready(op, 1);
1419}
1420
1421int
1422_PyUnicode_Ready(PyObject *op)
1423{
1424 return unicode_ready(&op, 0);
1425}
1426
Alexander Belopolsky40018472011-02-26 01:02:56 +00001427static void
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001428unicode_dealloc(register PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001429{
Walter Dörwald16807132007-05-25 13:52:07 +00001430 switch (PyUnicode_CHECK_INTERNED(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001431 case SSTATE_NOT_INTERNED:
1432 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001433
Benjamin Peterson29060642009-01-31 22:14:21 +00001434 case SSTATE_INTERNED_MORTAL:
1435 /* revive dead object temporarily for DelItem */
1436 Py_REFCNT(unicode) = 3;
Victor Stinner7931d9a2011-11-04 00:22:48 +01001437 if (PyDict_DelItem(interned, unicode) != 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00001438 Py_FatalError(
1439 "deletion of interned string failed");
1440 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001441
Benjamin Peterson29060642009-01-31 22:14:21 +00001442 case SSTATE_INTERNED_IMMORTAL:
1443 Py_FatalError("Immortal interned string died.");
Walter Dörwald16807132007-05-25 13:52:07 +00001444
Benjamin Peterson29060642009-01-31 22:14:21 +00001445 default:
1446 Py_FatalError("Inconsistent interned string state.");
Walter Dörwald16807132007-05-25 13:52:07 +00001447 }
1448
Victor Stinner03490912011-10-03 23:45:12 +02001449 if (_PyUnicode_HAS_WSTR_MEMORY(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001450 PyObject_DEL(_PyUnicode_WSTR(unicode));
Victor Stinner829c0ad2011-10-03 01:08:02 +02001451 if (_PyUnicode_HAS_UTF8_MEMORY(unicode))
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001452 PyObject_DEL(_PyUnicode_UTF8(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001453
1454 if (PyUnicode_IS_COMPACT(unicode)) {
Victor Stinner7931d9a2011-11-04 00:22:48 +01001455 Py_TYPE(unicode)->tp_free(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001456 }
1457 else {
Victor Stinnerc3c74152011-10-02 20:39:55 +02001458 if (_PyUnicode_DATA_ANY(unicode))
1459 PyObject_DEL(_PyUnicode_DATA_ANY(unicode));
Victor Stinner7931d9a2011-11-04 00:22:48 +01001460 Py_TYPE(unicode)->tp_free(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001461 }
1462}
1463
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001464#ifdef Py_DEBUG
1465static int
1466unicode_is_singleton(PyObject *unicode)
1467{
1468 PyASCIIObject *ascii = (PyASCIIObject *)unicode;
1469 if (unicode == unicode_empty)
1470 return 1;
1471 if (ascii->state.kind != PyUnicode_WCHAR_KIND && ascii->length == 1)
1472 {
1473 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, 0);
1474 if (ch < 256 && unicode_latin1[ch] == unicode)
1475 return 1;
1476 }
1477 return 0;
1478}
1479#endif
1480
Alexander Belopolsky40018472011-02-26 01:02:56 +00001481static int
Victor Stinnerfe226c02011-10-03 03:52:20 +02001482unicode_resizable(PyObject *unicode)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001483{
Victor Stinnerfe226c02011-10-03 03:52:20 +02001484 if (Py_REFCNT(unicode) != 1)
1485 return 0;
1486 if (PyUnicode_CHECK_INTERNED(unicode))
1487 return 0;
Victor Stinner77bb47b2011-10-03 20:06:05 +02001488#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001489 /* singleton refcount is greater than 1 */
1490 assert(!unicode_is_singleton(unicode));
Victor Stinner77bb47b2011-10-03 20:06:05 +02001491#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +02001492 return 1;
1493}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001494
Victor Stinnerfe226c02011-10-03 03:52:20 +02001495static int
1496unicode_resize(PyObject **p_unicode, Py_ssize_t length)
1497{
1498 PyObject *unicode;
1499 Py_ssize_t old_length;
1500
1501 assert(p_unicode != NULL);
1502 unicode = *p_unicode;
1503
1504 assert(unicode != NULL);
1505 assert(PyUnicode_Check(unicode));
1506 assert(0 <= length);
1507
Victor Stinner910337b2011-10-03 03:20:16 +02001508 if (_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001509 old_length = PyUnicode_WSTR_LENGTH(unicode);
1510 else
1511 old_length = PyUnicode_GET_LENGTH(unicode);
1512 if (old_length == length)
1513 return 0;
1514
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001515 if (length == 0) {
1516 Py_DECREF(*p_unicode);
1517 *p_unicode = unicode_empty;
1518 Py_INCREF(*p_unicode);
1519 return 0;
1520 }
1521
Victor Stinnerfe226c02011-10-03 03:52:20 +02001522 if (!unicode_resizable(unicode)) {
1523 PyObject *copy = resize_copy(unicode, length);
1524 if (copy == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001525 return -1;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001526 Py_DECREF(*p_unicode);
1527 *p_unicode = copy;
Benjamin Peterson29060642009-01-31 22:14:21 +00001528 return 0;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001529 }
1530
Victor Stinnerfe226c02011-10-03 03:52:20 +02001531 if (PyUnicode_IS_COMPACT(unicode)) {
1532 *p_unicode = resize_compact(unicode, length);
1533 if (*p_unicode == NULL)
1534 return -1;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001535 assert(_PyUnicode_CheckConsistency(*p_unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001536 return 0;
Benjamin Peterson4bfce8f2011-10-03 19:35:07 -04001537 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001538 return resize_inplace(unicode, length);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001539}
1540
Alexander Belopolsky40018472011-02-26 01:02:56 +00001541int
Victor Stinnerfe226c02011-10-03 03:52:20 +02001542PyUnicode_Resize(PyObject **p_unicode, Py_ssize_t length)
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001543{
Victor Stinnerfe226c02011-10-03 03:52:20 +02001544 PyObject *unicode;
1545 if (p_unicode == NULL) {
1546 PyErr_BadInternalCall();
1547 return -1;
1548 }
1549 unicode = *p_unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001550 if (unicode == NULL || !PyUnicode_Check(unicode) || length < 0)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001551 {
1552 PyErr_BadInternalCall();
1553 return -1;
1554 }
1555 return unicode_resize(p_unicode, length);
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001556}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001557
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001558static int
Victor Stinner0a045ef2011-11-09 00:02:42 +01001559unicode_widen(PyObject **p_unicode, unsigned int maxchar)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001560{
1561 PyObject *result;
1562 assert(PyUnicode_IS_READY(*p_unicode));
1563 if (maxchar <= PyUnicode_MAX_CHAR_VALUE(*p_unicode))
1564 return 0;
1565 result = PyUnicode_New(PyUnicode_GET_LENGTH(*p_unicode),
1566 maxchar);
1567 if (result == NULL)
1568 return -1;
1569 PyUnicode_CopyCharacters(result, 0, *p_unicode, 0,
1570 PyUnicode_GET_LENGTH(*p_unicode));
1571 Py_DECREF(*p_unicode);
1572 *p_unicode = result;
1573 return 0;
1574}
1575
1576static int
1577unicode_putchar(PyObject **p_unicode, Py_ssize_t *pos,
1578 Py_UCS4 ch)
1579{
1580 if (unicode_widen(p_unicode, ch) < 0)
1581 return -1;
1582 PyUnicode_WRITE(PyUnicode_KIND(*p_unicode),
1583 PyUnicode_DATA(*p_unicode),
1584 (*pos)++, ch);
1585 return 0;
1586}
1587
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001588static PyObject*
1589get_latin1_char(unsigned char ch)
1590{
Victor Stinnera464fc12011-10-02 20:39:30 +02001591 PyObject *unicode = unicode_latin1[ch];
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001592 if (!unicode) {
Victor Stinnera464fc12011-10-02 20:39:30 +02001593 unicode = PyUnicode_New(1, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001594 if (!unicode)
1595 return NULL;
1596 PyUnicode_1BYTE_DATA(unicode)[0] = ch;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001597 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001598 unicode_latin1[ch] = unicode;
1599 }
1600 Py_INCREF(unicode);
Victor Stinnera464fc12011-10-02 20:39:30 +02001601 return unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001602}
1603
Alexander Belopolsky40018472011-02-26 01:02:56 +00001604PyObject *
1605PyUnicode_FromUnicode(const Py_UNICODE *u, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001606{
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001607 PyObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001608 Py_UCS4 maxchar = 0;
1609 Py_ssize_t num_surrogates;
1610
1611 if (u == NULL)
1612 return (PyObject*)_PyUnicode_New(size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001613
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001614 /* If the Unicode data is known at construction time, we can apply
1615 some optimizations which share commonly used objects. */
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001616
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001617 /* Optimization for empty strings */
1618 if (size == 0 && unicode_empty != NULL) {
1619 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001620 return unicode_empty;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001621 }
Tim Petersced69f82003-09-16 20:30:58 +00001622
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001623 /* Single character Unicode objects in the Latin-1 range are
1624 shared when using this constructor */
1625 if (size == 1 && *u < 256)
1626 return get_latin1_char((unsigned char)*u);
1627
1628 /* If not empty and not single character, copy the Unicode data
1629 into the new object */
Victor Stinnerd8f65102011-09-29 19:43:17 +02001630 if (find_maxchar_surrogates(u, u + size,
1631 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001632 return NULL;
1633
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001634 unicode = PyUnicode_New(size - num_surrogates,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001635 maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001636 if (!unicode)
1637 return NULL;
1638
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001639 switch (PyUnicode_KIND(unicode)) {
1640 case PyUnicode_1BYTE_KIND:
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001641 _PyUnicode_CONVERT_BYTES(Py_UNICODE, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001642 u, u + size, PyUnicode_1BYTE_DATA(unicode));
1643 break;
1644 case PyUnicode_2BYTE_KIND:
1645#if Py_UNICODE_SIZE == 2
1646 Py_MEMCPY(PyUnicode_2BYTE_DATA(unicode), u, size * 2);
1647#else
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001648 _PyUnicode_CONVERT_BYTES(Py_UNICODE, Py_UCS2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001649 u, u + size, PyUnicode_2BYTE_DATA(unicode));
1650#endif
1651 break;
1652 case PyUnicode_4BYTE_KIND:
1653#if SIZEOF_WCHAR_T == 2
1654 /* This is the only case which has to process surrogates, thus
1655 a simple copy loop is not enough and we need a function. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001656 unicode_convert_wchar_to_ucs4(u, u + size, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001657#else
1658 assert(num_surrogates == 0);
1659 Py_MEMCPY(PyUnicode_4BYTE_DATA(unicode), u, size * 4);
1660#endif
1661 break;
1662 default:
1663 assert(0 && "Impossible state");
1664 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00001665
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001666 assert(_PyUnicode_CheckConsistency(unicode, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001667 return unicode;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001668}
1669
Alexander Belopolsky40018472011-02-26 01:02:56 +00001670PyObject *
1671PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size)
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001672{
Benjamin Peterson14339b62009-01-31 16:36:08 +00001673 if (size < 0) {
1674 PyErr_SetString(PyExc_SystemError,
Benjamin Peterson29060642009-01-31 22:14:21 +00001675 "Negative size passed to PyUnicode_FromStringAndSize");
Benjamin Peterson14339b62009-01-31 16:36:08 +00001676 return NULL;
1677 }
Christian Heimes33fe8092008-04-13 13:53:33 +00001678
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001679 /* If the Unicode data is known at construction time, we can apply
Martin v. Löwis9c121062007-08-05 20:26:11 +00001680 some optimizations which share commonly used objects.
1681 Also, this means the input must be UTF-8, so fall back to the
1682 UTF-8 decoder at the end. */
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001683 if (u != NULL) {
1684
Benjamin Peterson29060642009-01-31 22:14:21 +00001685 /* Optimization for empty strings */
1686 if (size == 0 && unicode_empty != NULL) {
1687 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001688 return unicode_empty;
Benjamin Peterson14339b62009-01-31 16:36:08 +00001689 }
Benjamin Peterson29060642009-01-31 22:14:21 +00001690
1691 /* Single characters are shared when using this constructor.
1692 Restrict to ASCII, since the input must be UTF-8. */
Victor Stinner9faa3842011-10-23 20:06:00 +02001693 if (size == 1 && (unsigned char)*u < 128)
1694 return get_latin1_char((unsigned char)*u);
Martin v. Löwis9c121062007-08-05 20:26:11 +00001695
1696 return PyUnicode_DecodeUTF8(u, size, NULL);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001697 }
1698
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001699 return (PyObject *)_PyUnicode_New(size);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001700}
1701
Alexander Belopolsky40018472011-02-26 01:02:56 +00001702PyObject *
1703PyUnicode_FromString(const char *u)
Walter Dörwaldd2034312007-05-18 16:29:38 +00001704{
1705 size_t size = strlen(u);
1706 if (size > PY_SSIZE_T_MAX) {
1707 PyErr_SetString(PyExc_OverflowError, "input too long");
1708 return NULL;
1709 }
1710
1711 return PyUnicode_FromStringAndSize(u, size);
1712}
1713
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001714PyObject *
1715_PyUnicode_FromId(_Py_Identifier *id)
1716{
1717 if (!id->object) {
1718 id->object = PyUnicode_FromString(id->string);
1719 if (!id->object)
1720 return NULL;
1721 PyUnicode_InternInPlace(&id->object);
1722 assert(!id->next);
1723 id->next = static_strings;
1724 static_strings = id;
1725 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001726 return id->object;
1727}
1728
1729void
1730_PyUnicode_ClearStaticStrings()
1731{
1732 _Py_Identifier *i;
1733 for (i = static_strings; i; i = i->next) {
1734 Py_DECREF(i->object);
1735 i->object = NULL;
1736 i->next = NULL;
1737 }
1738}
1739
Victor Stinnere57b1c02011-09-28 22:20:48 +02001740static PyObject*
Victor Stinner0617b6e2011-10-05 23:26:01 +02001741unicode_fromascii(const unsigned char* s, Py_ssize_t size)
Victor Stinner702c7342011-10-05 13:50:52 +02001742{
Victor Stinner0617b6e2011-10-05 23:26:01 +02001743 PyObject *res;
1744#ifdef Py_DEBUG
1745 const unsigned char *p;
1746 const unsigned char *end = s + size;
1747 for (p=s; p < end; p++) {
1748 assert(*p < 128);
1749 }
1750#endif
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001751 if (size == 1)
1752 return get_latin1_char(s[0]);
Victor Stinner0617b6e2011-10-05 23:26:01 +02001753 res = PyUnicode_New(size, 127);
Victor Stinner702c7342011-10-05 13:50:52 +02001754 if (!res)
1755 return NULL;
Victor Stinner0617b6e2011-10-05 23:26:01 +02001756 memcpy(PyUnicode_1BYTE_DATA(res), s, size);
Victor Stinner702c7342011-10-05 13:50:52 +02001757 return res;
1758}
1759
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001760static Py_UCS4
1761kind_maxchar_limit(unsigned int kind)
1762{
1763 switch(kind) {
1764 case PyUnicode_1BYTE_KIND:
1765 return 0x80;
1766 case PyUnicode_2BYTE_KIND:
1767 return 0x100;
1768 case PyUnicode_4BYTE_KIND:
1769 return 0x10000;
1770 default:
1771 assert(0 && "invalid kind");
1772 return 0x10ffff;
1773 }
1774}
1775
Victor Stinner702c7342011-10-05 13:50:52 +02001776static PyObject*
Victor Stinnere57b1c02011-09-28 22:20:48 +02001777_PyUnicode_FromUCS1(const unsigned char* u, Py_ssize_t size)
Mark Dickinson081dfee2009-03-18 14:47:41 +00001778{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001779 PyObject *res;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001780 unsigned char max_char = 127;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001781
1782 assert(size >= 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001783 if (size == 1)
1784 return get_latin1_char(u[0]);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001785 max_char = ucs1lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001786 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001787 if (!res)
1788 return NULL;
1789 memcpy(PyUnicode_1BYTE_DATA(res), u, size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001790 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001791 return res;
Mark Dickinson081dfee2009-03-18 14:47:41 +00001792}
1793
Victor Stinnere57b1c02011-09-28 22:20:48 +02001794static PyObject*
1795_PyUnicode_FromUCS2(const Py_UCS2 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001796{
1797 PyObject *res;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001798 Py_UCS2 max_char = 0;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001799
1800 assert(size >= 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001801 if (size == 1 && u[0] < 256)
Victor Stinner4e101002011-10-11 23:27:52 +02001802 return get_latin1_char((unsigned char)u[0]);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001803 max_char = ucs2lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001804 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001805 if (!res)
1806 return NULL;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001807 if (max_char >= 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001808 memcpy(PyUnicode_2BYTE_DATA(res), u, sizeof(Py_UCS2)*size);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001809 else {
1810 _PyUnicode_CONVERT_BYTES(
1811 Py_UCS2, Py_UCS1, u, u + size, PyUnicode_1BYTE_DATA(res));
1812 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001813 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001814 return res;
1815}
1816
Victor Stinnere57b1c02011-09-28 22:20:48 +02001817static PyObject*
1818_PyUnicode_FromUCS4(const Py_UCS4 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001819{
1820 PyObject *res;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001821 Py_UCS4 max_char = 0;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001822
1823 assert(size >= 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001824 if (size == 1 && u[0] < 256)
1825 return get_latin1_char(u[0]);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001826 max_char = ucs4lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001827 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001828 if (!res)
1829 return NULL;
Antoine Pitrou950468e2011-10-11 22:45:48 +02001830 if (max_char < 256)
1831 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, u, u + size,
1832 PyUnicode_1BYTE_DATA(res));
1833 else if (max_char < 0x10000)
1834 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, u, u + size,
1835 PyUnicode_2BYTE_DATA(res));
1836 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001837 memcpy(PyUnicode_4BYTE_DATA(res), u, sizeof(Py_UCS4)*size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001838 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001839 return res;
1840}
1841
1842PyObject*
1843PyUnicode_FromKindAndData(int kind, const void *buffer, Py_ssize_t size)
1844{
1845 switch(kind) {
1846 case PyUnicode_1BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02001847 return _PyUnicode_FromUCS1(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001848 case PyUnicode_2BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02001849 return _PyUnicode_FromUCS2(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001850 case PyUnicode_4BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02001851 return _PyUnicode_FromUCS4(buffer, size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001852 default:
1853 assert(0 && "invalid kind");
1854 PyErr_SetString(PyExc_SystemError, "invalid kind");
1855 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001856 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001857}
1858
Victor Stinner25a4b292011-10-06 12:31:55 +02001859/* Ensure that a string uses the most efficient storage, if it is not the
1860 case: create a new string with of the right kind. Write NULL into *p_unicode
1861 on error. */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02001862static void
Victor Stinner25a4b292011-10-06 12:31:55 +02001863unicode_adjust_maxchar(PyObject **p_unicode)
1864{
1865 PyObject *unicode, *copy;
1866 Py_UCS4 max_char;
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001867 Py_ssize_t len;
Victor Stinner25a4b292011-10-06 12:31:55 +02001868 unsigned int kind;
1869
1870 assert(p_unicode != NULL);
1871 unicode = *p_unicode;
1872 assert(PyUnicode_IS_READY(unicode));
1873 if (PyUnicode_IS_ASCII(unicode))
1874 return;
1875
1876 len = PyUnicode_GET_LENGTH(unicode);
1877 kind = PyUnicode_KIND(unicode);
1878 if (kind == PyUnicode_1BYTE_KIND) {
1879 const Py_UCS1 *u = PyUnicode_1BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001880 max_char = ucs1lib_find_max_char(u, u + len);
1881 if (max_char >= 128)
1882 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02001883 }
1884 else if (kind == PyUnicode_2BYTE_KIND) {
1885 const Py_UCS2 *u = PyUnicode_2BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001886 max_char = ucs2lib_find_max_char(u, u + len);
1887 if (max_char >= 256)
1888 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02001889 }
1890 else {
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001891 const Py_UCS4 *u = PyUnicode_4BYTE_DATA(unicode);
Victor Stinner25a4b292011-10-06 12:31:55 +02001892 assert(kind == PyUnicode_4BYTE_KIND);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001893 max_char = ucs4lib_find_max_char(u, u + len);
1894 if (max_char >= 0x10000)
1895 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02001896 }
Victor Stinner25a4b292011-10-06 12:31:55 +02001897 copy = PyUnicode_New(len, max_char);
1898 copy_characters(copy, 0, unicode, 0, len);
1899 Py_DECREF(unicode);
1900 *p_unicode = copy;
1901}
1902
Victor Stinner034f6cf2011-09-30 02:26:44 +02001903PyObject*
1904PyUnicode_Copy(PyObject *unicode)
1905{
Victor Stinnerc841e7d2011-10-01 01:34:32 +02001906 Py_ssize_t size;
1907 PyObject *copy;
1908 void *data;
1909
Victor Stinner034f6cf2011-09-30 02:26:44 +02001910 if (!PyUnicode_Check(unicode)) {
1911 PyErr_BadInternalCall();
1912 return NULL;
1913 }
1914 if (PyUnicode_READY(unicode))
1915 return NULL;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02001916
1917 size = PyUnicode_GET_LENGTH(unicode);
1918 copy = PyUnicode_New(size, PyUnicode_MAX_CHAR_VALUE(unicode));
1919 if (!copy)
1920 return NULL;
1921 assert(PyUnicode_KIND(copy) == PyUnicode_KIND(unicode));
1922
1923 data = PyUnicode_DATA(unicode);
1924 switch (PyUnicode_KIND(unicode))
1925 {
1926 case PyUnicode_1BYTE_KIND:
1927 memcpy(PyUnicode_1BYTE_DATA(copy), data, size);
1928 break;
1929 case PyUnicode_2BYTE_KIND:
1930 memcpy(PyUnicode_2BYTE_DATA(copy), data, sizeof(Py_UCS2) * size);
1931 break;
1932 case PyUnicode_4BYTE_KIND:
1933 memcpy(PyUnicode_4BYTE_DATA(copy), data, sizeof(Py_UCS4) * size);
1934 break;
1935 default:
1936 assert(0);
1937 break;
1938 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001939 assert(_PyUnicode_CheckConsistency(copy, 1));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02001940 return copy;
Victor Stinner034f6cf2011-09-30 02:26:44 +02001941}
1942
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001943
Victor Stinnerbc603d12011-10-02 01:00:40 +02001944/* Widen Unicode objects to larger buffers. Don't write terminating null
1945 character. Return NULL on error. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001946
1947void*
1948_PyUnicode_AsKind(PyObject *s, unsigned int kind)
1949{
Victor Stinnerbc603d12011-10-02 01:00:40 +02001950 Py_ssize_t len;
1951 void *result;
1952 unsigned int skind;
1953
1954 if (PyUnicode_READY(s))
1955 return NULL;
1956
1957 len = PyUnicode_GET_LENGTH(s);
1958 skind = PyUnicode_KIND(s);
1959 if (skind >= kind) {
Victor Stinner01698042011-10-04 00:04:26 +02001960 PyErr_SetString(PyExc_SystemError, "invalid widening attempt");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001961 return NULL;
1962 }
1963 switch(kind) {
Victor Stinnerbc603d12011-10-02 01:00:40 +02001964 case PyUnicode_2BYTE_KIND:
1965 result = PyMem_Malloc(len * sizeof(Py_UCS2));
1966 if (!result)
1967 return PyErr_NoMemory();
1968 assert(skind == PyUnicode_1BYTE_KIND);
1969 _PyUnicode_CONVERT_BYTES(
1970 Py_UCS1, Py_UCS2,
1971 PyUnicode_1BYTE_DATA(s),
1972 PyUnicode_1BYTE_DATA(s) + len,
1973 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001974 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02001975 case PyUnicode_4BYTE_KIND:
1976 result = PyMem_Malloc(len * sizeof(Py_UCS4));
1977 if (!result)
1978 return PyErr_NoMemory();
1979 if (skind == PyUnicode_2BYTE_KIND) {
1980 _PyUnicode_CONVERT_BYTES(
1981 Py_UCS2, Py_UCS4,
1982 PyUnicode_2BYTE_DATA(s),
1983 PyUnicode_2BYTE_DATA(s) + len,
1984 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001985 }
Victor Stinnerbc603d12011-10-02 01:00:40 +02001986 else {
1987 assert(skind == PyUnicode_1BYTE_KIND);
1988 _PyUnicode_CONVERT_BYTES(
1989 Py_UCS1, Py_UCS4,
1990 PyUnicode_1BYTE_DATA(s),
1991 PyUnicode_1BYTE_DATA(s) + len,
1992 result);
1993 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001994 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02001995 default:
1996 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001997 }
Victor Stinner01698042011-10-04 00:04:26 +02001998 PyErr_SetString(PyExc_SystemError, "invalid kind");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001999 return NULL;
2000}
2001
2002static Py_UCS4*
2003as_ucs4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2004 int copy_null)
2005{
2006 int kind;
2007 void *data;
2008 Py_ssize_t len, targetlen;
2009 if (PyUnicode_READY(string) == -1)
2010 return NULL;
2011 kind = PyUnicode_KIND(string);
2012 data = PyUnicode_DATA(string);
2013 len = PyUnicode_GET_LENGTH(string);
2014 targetlen = len;
2015 if (copy_null)
2016 targetlen++;
2017 if (!target) {
2018 if (PY_SSIZE_T_MAX / sizeof(Py_UCS4) < targetlen) {
2019 PyErr_NoMemory();
2020 return NULL;
2021 }
2022 target = PyMem_Malloc(targetlen * sizeof(Py_UCS4));
2023 if (!target) {
2024 PyErr_NoMemory();
2025 return NULL;
2026 }
2027 }
2028 else {
2029 if (targetsize < targetlen) {
2030 PyErr_Format(PyExc_SystemError,
2031 "string is longer than the buffer");
2032 if (copy_null && 0 < targetsize)
2033 target[0] = 0;
2034 return NULL;
2035 }
2036 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002037 if (kind == PyUnicode_1BYTE_KIND) {
2038 Py_UCS1 *start = (Py_UCS1 *) data;
2039 _PyUnicode_CONVERT_BYTES(Py_UCS1, Py_UCS4, start, start + len, target);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002040 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002041 else if (kind == PyUnicode_2BYTE_KIND) {
2042 Py_UCS2 *start = (Py_UCS2 *) data;
2043 _PyUnicode_CONVERT_BYTES(Py_UCS2, Py_UCS4, start, start + len, target);
2044 }
2045 else {
2046 assert(kind == PyUnicode_4BYTE_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002047 Py_MEMCPY(target, data, len * sizeof(Py_UCS4));
Antoine Pitrou950468e2011-10-11 22:45:48 +02002048 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002049 if (copy_null)
2050 target[len] = 0;
2051 return target;
2052}
2053
2054Py_UCS4*
2055PyUnicode_AsUCS4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2056 int copy_null)
2057{
Antoine Pitroude20b0b2011-11-10 21:47:38 +01002058 if (target == NULL || targetsize < 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002059 PyErr_BadInternalCall();
2060 return NULL;
2061 }
2062 return as_ucs4(string, target, targetsize, copy_null);
2063}
2064
2065Py_UCS4*
2066PyUnicode_AsUCS4Copy(PyObject *string)
2067{
2068 return as_ucs4(string, NULL, 0, 1);
2069}
2070
2071#ifdef HAVE_WCHAR_H
Mark Dickinson081dfee2009-03-18 14:47:41 +00002072
Alexander Belopolsky40018472011-02-26 01:02:56 +00002073PyObject *
2074PyUnicode_FromWideChar(register const wchar_t *w, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002075{
Guido van Rossumd57fd912000-03-10 22:53:23 +00002076 if (w == NULL) {
Martin v. Löwis790465f2008-04-05 20:41:37 +00002077 if (size == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002078 return PyUnicode_New(0, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +00002079 PyErr_BadInternalCall();
2080 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002081 }
2082
Martin v. Löwis790465f2008-04-05 20:41:37 +00002083 if (size == -1) {
2084 size = wcslen(w);
2085 }
2086
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002087 return PyUnicode_FromUnicode(w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002088}
2089
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002090#endif /* HAVE_WCHAR_H */
Mark Dickinson081dfee2009-03-18 14:47:41 +00002091
Walter Dörwald346737f2007-05-31 10:44:43 +00002092static void
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002093makefmt(char *fmt, int longflag, int longlongflag, int size_tflag,
2094 int zeropad, int width, int precision, char c)
Walter Dörwald346737f2007-05-31 10:44:43 +00002095{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002096 *fmt++ = '%';
2097 if (width) {
2098 if (zeropad)
2099 *fmt++ = '0';
2100 fmt += sprintf(fmt, "%d", width);
2101 }
2102 if (precision)
2103 fmt += sprintf(fmt, ".%d", precision);
2104 if (longflag)
2105 *fmt++ = 'l';
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002106 else if (longlongflag) {
2107 /* longlongflag should only ever be nonzero on machines with
2108 HAVE_LONG_LONG defined */
2109#ifdef HAVE_LONG_LONG
2110 char *f = PY_FORMAT_LONG_LONG;
2111 while (*f)
2112 *fmt++ = *f++;
2113#else
2114 /* we shouldn't ever get here */
2115 assert(0);
2116 *fmt++ = 'l';
2117#endif
2118 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002119 else if (size_tflag) {
2120 char *f = PY_FORMAT_SIZE_T;
2121 while (*f)
2122 *fmt++ = *f++;
2123 }
2124 *fmt++ = c;
2125 *fmt = '\0';
Walter Dörwald346737f2007-05-31 10:44:43 +00002126}
2127
Victor Stinner96865452011-03-01 23:44:09 +00002128/* helper for PyUnicode_FromFormatV() */
2129
2130static const char*
2131parse_format_flags(const char *f,
2132 int *p_width, int *p_precision,
2133 int *p_longflag, int *p_longlongflag, int *p_size_tflag)
2134{
2135 int width, precision, longflag, longlongflag, size_tflag;
2136
2137 /* parse the width.precision part, e.g. "%2.5s" => width=2, precision=5 */
2138 f++;
2139 width = 0;
2140 while (Py_ISDIGIT((unsigned)*f))
2141 width = (width*10) + *f++ - '0';
2142 precision = 0;
2143 if (*f == '.') {
2144 f++;
2145 while (Py_ISDIGIT((unsigned)*f))
2146 precision = (precision*10) + *f++ - '0';
2147 if (*f == '%') {
2148 /* "%.3%s" => f points to "3" */
2149 f--;
2150 }
2151 }
2152 if (*f == '\0') {
2153 /* bogus format "%.1" => go backward, f points to "1" */
2154 f--;
2155 }
2156 if (p_width != NULL)
2157 *p_width = width;
2158 if (p_precision != NULL)
2159 *p_precision = precision;
2160
2161 /* Handle %ld, %lu, %lld and %llu. */
2162 longflag = 0;
2163 longlongflag = 0;
Victor Stinnere7faec12011-03-02 00:01:53 +00002164 size_tflag = 0;
Victor Stinner96865452011-03-01 23:44:09 +00002165
2166 if (*f == 'l') {
Victor Stinner6d970f42011-03-02 00:04:25 +00002167 if (f[1] == 'd' || f[1] == 'u' || f[1] == 'i') {
Victor Stinner96865452011-03-01 23:44:09 +00002168 longflag = 1;
2169 ++f;
2170 }
2171#ifdef HAVE_LONG_LONG
2172 else if (f[1] == 'l' &&
Victor Stinner6d970f42011-03-02 00:04:25 +00002173 (f[2] == 'd' || f[2] == 'u' || f[2] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002174 longlongflag = 1;
2175 f += 2;
2176 }
2177#endif
2178 }
2179 /* handle the size_t flag. */
Victor Stinner6d970f42011-03-02 00:04:25 +00002180 else if (*f == 'z' && (f[1] == 'd' || f[1] == 'u' || f[1] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002181 size_tflag = 1;
2182 ++f;
2183 }
2184 if (p_longflag != NULL)
2185 *p_longflag = longflag;
2186 if (p_longlongflag != NULL)
2187 *p_longlongflag = longlongflag;
2188 if (p_size_tflag != NULL)
2189 *p_size_tflag = size_tflag;
2190 return f;
2191}
2192
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002193/* maximum number of characters required for output of %ld. 21 characters
2194 allows for 64-bit integers (in decimal) and an optional sign. */
2195#define MAX_LONG_CHARS 21
2196/* maximum number of characters required for output of %lld.
2197 We need at most ceil(log10(256)*SIZEOF_LONG_LONG) digits,
2198 plus 1 for the sign. 53/22 is an upper bound for log10(256). */
2199#define MAX_LONG_LONG_CHARS (2 + (SIZEOF_LONG_LONG*53-1) / 22)
2200
Walter Dörwaldd2034312007-05-18 16:29:38 +00002201PyObject *
2202PyUnicode_FromFormatV(const char *format, va_list vargs)
2203{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002204 va_list count;
2205 Py_ssize_t callcount = 0;
2206 PyObject **callresults = NULL;
2207 PyObject **callresult = NULL;
2208 Py_ssize_t n = 0;
2209 int width = 0;
2210 int precision = 0;
2211 int zeropad;
2212 const char* f;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002213 PyObject *string;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002214 /* used by sprintf */
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002215 char fmt[61]; /* should be enough for %0width.precisionlld */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002216 Py_UCS4 maxchar = 127; /* result is ASCII by default */
2217 Py_UCS4 argmaxchar;
2218 Py_ssize_t numbersize = 0;
2219 char *numberresults = NULL;
2220 char *numberresult = NULL;
2221 Py_ssize_t i;
2222 int kind;
2223 void *data;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002224
Victor Stinner4a2b7a12010-08-13 14:03:48 +00002225 Py_VA_COPY(count, vargs);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002226 /* step 1: count the number of %S/%R/%A/%s format specifications
2227 * (we call PyObject_Str()/PyObject_Repr()/PyObject_ASCII()/
2228 * PyUnicode_DecodeUTF8() for these objects once during step 3 and put the
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002229 * result in an array)
Georg Brandl7597add2011-10-05 16:36:47 +02002230 * also estimate a upper bound for all the number formats in the string,
2231 * numbers will be formatted in step 3 and be kept in a '\0'-separated
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002232 * buffer before putting everything together. */
Benjamin Peterson14339b62009-01-31 16:36:08 +00002233 for (f = format; *f; f++) {
2234 if (*f == '%') {
Victor Stinner96865452011-03-01 23:44:09 +00002235 int longlongflag;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002236 /* skip width or width.precision (eg. "1.2" of "%1.2f") */
2237 f = parse_format_flags(f, &width, NULL, NULL, &longlongflag, NULL);
2238 if (*f == 's' || *f=='S' || *f=='R' || *f=='A' || *f=='V')
2239 ++callcount;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002240
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002241 else if (*f == 'd' || *f=='u' || *f=='i' || *f=='x' || *f=='p') {
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002242#ifdef HAVE_LONG_LONG
2243 if (longlongflag) {
2244 if (width < MAX_LONG_LONG_CHARS)
2245 width = MAX_LONG_LONG_CHARS;
2246 }
2247 else
2248#endif
2249 /* MAX_LONG_CHARS is enough to hold a 64-bit integer,
2250 including sign. Decimal takes the most space. This
2251 isn't enough for octal. If a width is specified we
2252 need more (which we allocate later). */
2253 if (width < MAX_LONG_CHARS)
2254 width = MAX_LONG_CHARS;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002255
2256 /* account for the size + '\0' to separate numbers
2257 inside of the numberresults buffer */
2258 numbersize += (width + 1);
2259 }
2260 }
2261 else if ((unsigned char)*f > 127) {
2262 PyErr_Format(PyExc_ValueError,
2263 "PyUnicode_FromFormatV() expects an ASCII-encoded format "
2264 "string, got a non-ASCII byte: 0x%02x",
2265 (unsigned char)*f);
2266 return NULL;
2267 }
2268 }
2269 /* step 2: allocate memory for the results of
2270 * PyObject_Str()/PyObject_Repr()/PyUnicode_DecodeUTF8() calls */
2271 if (callcount) {
2272 callresults = PyObject_Malloc(sizeof(PyObject *) * callcount);
2273 if (!callresults) {
2274 PyErr_NoMemory();
2275 return NULL;
2276 }
2277 callresult = callresults;
2278 }
2279 /* step 2.5: allocate memory for the results of formating numbers */
2280 if (numbersize) {
2281 numberresults = PyObject_Malloc(numbersize);
2282 if (!numberresults) {
2283 PyErr_NoMemory();
2284 goto fail;
2285 }
2286 numberresult = numberresults;
2287 }
2288
2289 /* step 3: format numbers and figure out how large a buffer we need */
2290 for (f = format; *f; f++) {
2291 if (*f == '%') {
2292 const char* p;
2293 int longflag;
2294 int longlongflag;
2295 int size_tflag;
2296 int numprinted;
2297
2298 p = f;
2299 zeropad = (f[1] == '0');
2300 f = parse_format_flags(f, &width, &precision,
2301 &longflag, &longlongflag, &size_tflag);
2302 switch (*f) {
2303 case 'c':
2304 {
2305 Py_UCS4 ordinal = va_arg(count, int);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002306 maxchar = Py_MAX(maxchar, ordinal);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002307 n++;
2308 break;
2309 }
2310 case '%':
2311 n++;
2312 break;
2313 case 'i':
2314 case 'd':
2315 makefmt(fmt, longflag, longlongflag, size_tflag, zeropad,
2316 width, precision, *f);
2317 if (longflag)
2318 numprinted = sprintf(numberresult, fmt,
2319 va_arg(count, long));
2320#ifdef HAVE_LONG_LONG
2321 else if (longlongflag)
2322 numprinted = sprintf(numberresult, fmt,
2323 va_arg(count, PY_LONG_LONG));
2324#endif
2325 else if (size_tflag)
2326 numprinted = sprintf(numberresult, fmt,
2327 va_arg(count, Py_ssize_t));
2328 else
2329 numprinted = sprintf(numberresult, fmt,
2330 va_arg(count, int));
2331 n += numprinted;
2332 /* advance by +1 to skip over the '\0' */
2333 numberresult += (numprinted + 1);
2334 assert(*(numberresult - 1) == '\0');
2335 assert(*(numberresult - 2) != '\0');
2336 assert(numprinted >= 0);
2337 assert(numberresult <= numberresults + numbersize);
2338 break;
2339 case 'u':
2340 makefmt(fmt, longflag, longlongflag, size_tflag, zeropad,
2341 width, precision, 'u');
2342 if (longflag)
2343 numprinted = sprintf(numberresult, fmt,
2344 va_arg(count, unsigned long));
2345#ifdef HAVE_LONG_LONG
2346 else if (longlongflag)
2347 numprinted = sprintf(numberresult, fmt,
2348 va_arg(count, unsigned PY_LONG_LONG));
2349#endif
2350 else if (size_tflag)
2351 numprinted = sprintf(numberresult, fmt,
2352 va_arg(count, size_t));
2353 else
2354 numprinted = sprintf(numberresult, fmt,
2355 va_arg(count, unsigned int));
2356 n += numprinted;
2357 numberresult += (numprinted + 1);
2358 assert(*(numberresult - 1) == '\0');
2359 assert(*(numberresult - 2) != '\0');
2360 assert(numprinted >= 0);
2361 assert(numberresult <= numberresults + numbersize);
2362 break;
2363 case 'x':
2364 makefmt(fmt, 0, 0, 0, zeropad, width, precision, 'x');
2365 numprinted = sprintf(numberresult, fmt, va_arg(count, int));
2366 n += numprinted;
2367 numberresult += (numprinted + 1);
2368 assert(*(numberresult - 1) == '\0');
2369 assert(*(numberresult - 2) != '\0');
2370 assert(numprinted >= 0);
2371 assert(numberresult <= numberresults + numbersize);
2372 break;
2373 case 'p':
2374 numprinted = sprintf(numberresult, "%p", va_arg(count, void*));
2375 /* %p is ill-defined: ensure leading 0x. */
2376 if (numberresult[1] == 'X')
2377 numberresult[1] = 'x';
2378 else if (numberresult[1] != 'x') {
2379 memmove(numberresult + 2, numberresult,
2380 strlen(numberresult) + 1);
2381 numberresult[0] = '0';
2382 numberresult[1] = 'x';
2383 numprinted += 2;
2384 }
2385 n += numprinted;
2386 numberresult += (numprinted + 1);
2387 assert(*(numberresult - 1) == '\0');
2388 assert(*(numberresult - 2) != '\0');
2389 assert(numprinted >= 0);
2390 assert(numberresult <= numberresults + numbersize);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002391 break;
2392 case 's':
2393 {
2394 /* UTF-8 */
Georg Brandl780b2a62009-05-05 09:19:59 +00002395 const char *s = va_arg(count, const char*);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002396 PyObject *str = PyUnicode_DecodeUTF8(s, strlen(s), "replace");
2397 if (!str)
2398 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002399 /* since PyUnicode_DecodeUTF8 returns already flexible
2400 unicode objects, there is no need to call ready on them */
2401 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002402 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002403 n += PyUnicode_GET_LENGTH(str);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002404 /* Remember the str and switch to the next slot */
2405 *callresult++ = str;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002406 break;
2407 }
2408 case 'U':
2409 {
2410 PyObject *obj = va_arg(count, PyObject *);
Victor Stinner910337b2011-10-03 03:20:16 +02002411 assert(obj && _PyUnicode_CHECK(obj));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002412 if (PyUnicode_READY(obj) == -1)
2413 goto fail;
2414 argmaxchar = PyUnicode_MAX_CHAR_VALUE(obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002415 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002416 n += PyUnicode_GET_LENGTH(obj);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002417 break;
2418 }
2419 case 'V':
2420 {
2421 PyObject *obj = va_arg(count, PyObject *);
2422 const char *str = va_arg(count, const char *);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002423 PyObject *str_obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002424 assert(obj || str);
Victor Stinner910337b2011-10-03 03:20:16 +02002425 assert(!obj || _PyUnicode_CHECK(obj));
Victor Stinner2512a8b2011-03-01 22:46:52 +00002426 if (obj) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002427 if (PyUnicode_READY(obj) == -1)
2428 goto fail;
2429 argmaxchar = PyUnicode_MAX_CHAR_VALUE(obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002430 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002431 n += PyUnicode_GET_LENGTH(obj);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002432 *callresult++ = NULL;
2433 }
2434 else {
2435 str_obj = PyUnicode_DecodeUTF8(str, strlen(str), "replace");
2436 if (!str_obj)
2437 goto fail;
Victor Stinnere1335c72011-10-04 20:53:03 +02002438 if (PyUnicode_READY(str_obj)) {
2439 Py_DECREF(str_obj);
2440 goto fail;
2441 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002442 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str_obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002443 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002444 n += PyUnicode_GET_LENGTH(str_obj);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002445 *callresult++ = str_obj;
2446 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002447 break;
2448 }
2449 case 'S':
2450 {
2451 PyObject *obj = va_arg(count, PyObject *);
2452 PyObject *str;
2453 assert(obj);
2454 str = PyObject_Str(obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002455 if (!str || PyUnicode_READY(str) == -1)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002456 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002457 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002458 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002459 n += PyUnicode_GET_LENGTH(str);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002460 /* Remember the str and switch to the next slot */
2461 *callresult++ = str;
2462 break;
2463 }
2464 case 'R':
2465 {
2466 PyObject *obj = va_arg(count, PyObject *);
2467 PyObject *repr;
2468 assert(obj);
2469 repr = PyObject_Repr(obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002470 if (!repr || PyUnicode_READY(repr) == -1)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002471 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002472 argmaxchar = PyUnicode_MAX_CHAR_VALUE(repr);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002473 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002474 n += PyUnicode_GET_LENGTH(repr);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002475 /* Remember the repr and switch to the next slot */
2476 *callresult++ = repr;
2477 break;
2478 }
2479 case 'A':
2480 {
2481 PyObject *obj = va_arg(count, PyObject *);
2482 PyObject *ascii;
2483 assert(obj);
2484 ascii = PyObject_ASCII(obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002485 if (!ascii || PyUnicode_READY(ascii) == -1)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002486 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002487 argmaxchar = PyUnicode_MAX_CHAR_VALUE(ascii);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002488 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002489 n += PyUnicode_GET_LENGTH(ascii);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002490 /* Remember the repr and switch to the next slot */
2491 *callresult++ = ascii;
2492 break;
2493 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002494 default:
2495 /* if we stumble upon an unknown
2496 formatting code, copy the rest of
2497 the format string to the output
2498 string. (we cannot just skip the
2499 code, since there's no way to know
2500 what's in the argument list) */
2501 n += strlen(p);
2502 goto expand;
2503 }
2504 } else
2505 n++;
2506 }
Benjamin Peterson29060642009-01-31 22:14:21 +00002507 expand:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002508 /* step 4: fill the buffer */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002509 /* Since we've analyzed how much space we need,
Benjamin Peterson14339b62009-01-31 16:36:08 +00002510 we don't have to resize the string.
2511 There can be no errors beyond this point. */
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002512 string = PyUnicode_New(n, maxchar);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002513 if (!string)
2514 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002515 kind = PyUnicode_KIND(string);
2516 data = PyUnicode_DATA(string);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002517 callresult = callresults;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002518 numberresult = numberresults;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002519
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002520 for (i = 0, f = format; *f; f++) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00002521 if (*f == '%') {
Victor Stinner96865452011-03-01 23:44:09 +00002522 const char* p;
Victor Stinner96865452011-03-01 23:44:09 +00002523
2524 p = f;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002525 f = parse_format_flags(f, NULL, NULL, NULL, NULL, NULL);
2526 /* checking for == because the last argument could be a empty
2527 string, which causes i to point to end, the assert at the end of
2528 the loop */
2529 assert(i <= PyUnicode_GET_LENGTH(string));
Walter Dörwaldd2034312007-05-18 16:29:38 +00002530
Benjamin Peterson14339b62009-01-31 16:36:08 +00002531 switch (*f) {
2532 case 'c':
Victor Stinner5ed8b2c2011-02-21 21:13:44 +00002533 {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002534 const int ordinal = va_arg(vargs, int);
2535 PyUnicode_WRITE(kind, data, i++, ordinal);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002536 break;
Victor Stinner5ed8b2c2011-02-21 21:13:44 +00002537 }
Victor Stinner6d970f42011-03-02 00:04:25 +00002538 case 'i':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002539 case 'd':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002540 case 'u':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002541 case 'x':
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002542 case 'p':
2543 /* unused, since we already have the result */
2544 if (*f == 'p')
2545 (void) va_arg(vargs, void *);
2546 else
2547 (void) va_arg(vargs, int);
2548 /* extract the result from numberresults and append. */
2549 for (; *numberresult; ++i, ++numberresult)
2550 PyUnicode_WRITE(kind, data, i, *numberresult);
2551 /* skip over the separating '\0' */
2552 assert(*numberresult == '\0');
2553 numberresult++;
2554 assert(numberresult <= numberresults + numbersize);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002555 break;
2556 case 's':
2557 {
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002558 /* unused, since we already have the result */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002559 Py_ssize_t size;
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002560 (void) va_arg(vargs, char *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002561 size = PyUnicode_GET_LENGTH(*callresult);
2562 assert(PyUnicode_KIND(*callresult) <= PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002563 copy_characters(string, i, *callresult, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002564 i += size;
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002565 /* We're done with the unicode()/repr() => forget it */
2566 Py_DECREF(*callresult);
2567 /* switch to next unicode()/repr() result */
2568 ++callresult;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002569 break;
2570 }
2571 case 'U':
2572 {
2573 PyObject *obj = va_arg(vargs, PyObject *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002574 Py_ssize_t size;
2575 assert(PyUnicode_KIND(obj) <= PyUnicode_KIND(string));
2576 size = PyUnicode_GET_LENGTH(obj);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002577 copy_characters(string, i, obj, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002578 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002579 break;
2580 }
2581 case 'V':
2582 {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002583 Py_ssize_t size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002584 PyObject *obj = va_arg(vargs, PyObject *);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002585 va_arg(vargs, const char *);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002586 if (obj) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002587 size = PyUnicode_GET_LENGTH(obj);
2588 assert(PyUnicode_KIND(obj) <= PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002589 copy_characters(string, i, obj, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002590 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002591 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002592 size = PyUnicode_GET_LENGTH(*callresult);
2593 assert(PyUnicode_KIND(*callresult) <=
2594 PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002595 copy_characters(string, i, *callresult, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002596 i += size;
Victor Stinner2512a8b2011-03-01 22:46:52 +00002597 Py_DECREF(*callresult);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002598 }
Victor Stinner2512a8b2011-03-01 22:46:52 +00002599 ++callresult;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002600 break;
2601 }
2602 case 'S':
2603 case 'R':
Victor Stinner9a909002010-10-18 20:59:24 +00002604 case 'A':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002605 {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002606 Py_ssize_t size = PyUnicode_GET_LENGTH(*callresult);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002607 /* unused, since we already have the result */
2608 (void) va_arg(vargs, PyObject *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002609 assert(PyUnicode_KIND(*callresult) <= PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002610 copy_characters(string, i, *callresult, 0, size);
2611 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002612 /* We're done with the unicode()/repr() => forget it */
2613 Py_DECREF(*callresult);
2614 /* switch to next unicode()/repr() result */
2615 ++callresult;
2616 break;
2617 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002618 case '%':
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002619 PyUnicode_WRITE(kind, data, i++, '%');
Benjamin Peterson14339b62009-01-31 16:36:08 +00002620 break;
2621 default:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002622 for (; *p; ++p, ++i)
2623 PyUnicode_WRITE(kind, data, i, *p);
2624 assert(i == PyUnicode_GET_LENGTH(string));
Benjamin Peterson14339b62009-01-31 16:36:08 +00002625 goto end;
2626 }
Victor Stinner1205f272010-09-11 00:54:47 +00002627 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002628 else {
2629 assert(i < PyUnicode_GET_LENGTH(string));
2630 PyUnicode_WRITE(kind, data, i++, *f);
2631 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002632 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002633 assert(i == PyUnicode_GET_LENGTH(string));
Walter Dörwaldd2034312007-05-18 16:29:38 +00002634
Benjamin Peterson29060642009-01-31 22:14:21 +00002635 end:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002636 if (callresults)
2637 PyObject_Free(callresults);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002638 if (numberresults)
2639 PyObject_Free(numberresults);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002640 assert(_PyUnicode_CheckConsistency(string, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01002641 return string;
Benjamin Peterson29060642009-01-31 22:14:21 +00002642 fail:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002643 if (callresults) {
2644 PyObject **callresult2 = callresults;
2645 while (callresult2 < callresult) {
Victor Stinner2512a8b2011-03-01 22:46:52 +00002646 Py_XDECREF(*callresult2);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002647 ++callresult2;
2648 }
2649 PyObject_Free(callresults);
2650 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002651 if (numberresults)
2652 PyObject_Free(numberresults);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002653 return NULL;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002654}
2655
Walter Dörwaldd2034312007-05-18 16:29:38 +00002656PyObject *
2657PyUnicode_FromFormat(const char *format, ...)
2658{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002659 PyObject* ret;
2660 va_list vargs;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002661
2662#ifdef HAVE_STDARG_PROTOTYPES
Benjamin Peterson14339b62009-01-31 16:36:08 +00002663 va_start(vargs, format);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002664#else
Benjamin Peterson14339b62009-01-31 16:36:08 +00002665 va_start(vargs);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002666#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00002667 ret = PyUnicode_FromFormatV(format, vargs);
2668 va_end(vargs);
2669 return ret;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002670}
2671
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002672#ifdef HAVE_WCHAR_H
2673
Victor Stinner5593d8a2010-10-02 11:11:27 +00002674/* Helper function for PyUnicode_AsWideChar() and PyUnicode_AsWideCharString():
2675 convert a Unicode object to a wide character string.
2676
Victor Stinnerd88d9832011-09-06 02:00:05 +02002677 - If w is NULL: return the number of wide characters (including the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002678 character) required to convert the unicode object. Ignore size argument.
2679
Victor Stinnerd88d9832011-09-06 02:00:05 +02002680 - Otherwise: return the number of wide characters (excluding the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002681 character) written into w. Write at most size wide characters (including
Victor Stinnerd88d9832011-09-06 02:00:05 +02002682 the null character). */
Victor Stinner5593d8a2010-10-02 11:11:27 +00002683static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002684unicode_aswidechar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002685 wchar_t *w,
2686 Py_ssize_t size)
2687{
Victor Stinner5593d8a2010-10-02 11:11:27 +00002688 Py_ssize_t res;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002689 const wchar_t *wstr;
2690
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002691 wstr = PyUnicode_AsUnicodeAndSize(unicode, &res);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002692 if (wstr == NULL)
2693 return -1;
2694
Victor Stinner5593d8a2010-10-02 11:11:27 +00002695 if (w != NULL) {
Victor Stinner5593d8a2010-10-02 11:11:27 +00002696 if (size > res)
2697 size = res + 1;
2698 else
2699 res = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002700 Py_MEMCPY(w, wstr, size * sizeof(wchar_t));
Victor Stinner5593d8a2010-10-02 11:11:27 +00002701 return res;
2702 }
2703 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002704 return res + 1;
Victor Stinner137c34c2010-09-29 10:25:54 +00002705}
2706
2707Py_ssize_t
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002708PyUnicode_AsWideChar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002709 wchar_t *w,
2710 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002711{
2712 if (unicode == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002713 PyErr_BadInternalCall();
2714 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002715 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002716 return unicode_aswidechar(unicode, w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002717}
2718
Victor Stinner137c34c2010-09-29 10:25:54 +00002719wchar_t*
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00002720PyUnicode_AsWideCharString(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002721 Py_ssize_t *size)
2722{
2723 wchar_t* buffer;
2724 Py_ssize_t buflen;
2725
2726 if (unicode == NULL) {
2727 PyErr_BadInternalCall();
2728 return NULL;
2729 }
2730
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002731 buflen = unicode_aswidechar(unicode, NULL, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002732 if (buflen == -1)
2733 return NULL;
Victor Stinner5593d8a2010-10-02 11:11:27 +00002734 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < buflen) {
Victor Stinner137c34c2010-09-29 10:25:54 +00002735 PyErr_NoMemory();
2736 return NULL;
2737 }
2738
Victor Stinner137c34c2010-09-29 10:25:54 +00002739 buffer = PyMem_MALLOC(buflen * sizeof(wchar_t));
2740 if (buffer == NULL) {
2741 PyErr_NoMemory();
2742 return NULL;
2743 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002744 buflen = unicode_aswidechar(unicode, buffer, buflen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002745 if (buflen == -1)
2746 return NULL;
Victor Stinner5593d8a2010-10-02 11:11:27 +00002747 if (size != NULL)
2748 *size = buflen;
Victor Stinner137c34c2010-09-29 10:25:54 +00002749 return buffer;
2750}
2751
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002752#endif /* HAVE_WCHAR_H */
Guido van Rossumd57fd912000-03-10 22:53:23 +00002753
Alexander Belopolsky40018472011-02-26 01:02:56 +00002754PyObject *
2755PyUnicode_FromOrdinal(int ordinal)
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002756{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002757 PyObject *v;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002758 if (ordinal < 0 || ordinal > 0x10ffff) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002759 PyErr_SetString(PyExc_ValueError,
2760 "chr() arg not in range(0x110000)");
2761 return NULL;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002762 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00002763
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002764 if (ordinal < 256)
2765 return get_latin1_char(ordinal);
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002766
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002767 v = PyUnicode_New(1, ordinal);
2768 if (v == NULL)
2769 return NULL;
2770 PyUnicode_WRITE(PyUnicode_KIND(v), PyUnicode_DATA(v), 0, ordinal);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002771 assert(_PyUnicode_CheckConsistency(v, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002772 return v;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002773}
2774
Alexander Belopolsky40018472011-02-26 01:02:56 +00002775PyObject *
2776PyUnicode_FromObject(register PyObject *obj)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002777{
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002778 /* XXX Perhaps we should make this API an alias of
Benjamin Peterson29060642009-01-31 22:14:21 +00002779 PyObject_Str() instead ?! */
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002780 if (PyUnicode_CheckExact(obj)) {
Victor Stinnerd3a83d52011-10-01 03:09:33 +02002781 if (PyUnicode_READY(obj))
2782 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +00002783 Py_INCREF(obj);
2784 return obj;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002785 }
2786 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002787 /* For a Unicode subtype that's not a Unicode object,
2788 return a true Unicode object with the same data. */
Victor Stinner2219e0a2011-10-01 01:16:59 +02002789 return PyUnicode_Copy(obj);
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002790 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00002791 PyErr_Format(PyExc_TypeError,
2792 "Can't convert '%.100s' object to str implicitly",
Christian Heimes90aa7642007-12-19 02:45:37 +00002793 Py_TYPE(obj)->tp_name);
Guido van Rossum98297ee2007-11-06 21:34:58 +00002794 return NULL;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002795}
2796
Alexander Belopolsky40018472011-02-26 01:02:56 +00002797PyObject *
2798PyUnicode_FromEncodedObject(register PyObject *obj,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002799 const char *encoding,
2800 const char *errors)
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002801{
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002802 Py_buffer buffer;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002803 PyObject *v;
Tim Petersced69f82003-09-16 20:30:58 +00002804
Guido van Rossumd57fd912000-03-10 22:53:23 +00002805 if (obj == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002806 PyErr_BadInternalCall();
2807 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002808 }
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002809
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002810 /* Decoding bytes objects is the most common case and should be fast */
2811 if (PyBytes_Check(obj)) {
2812 if (PyBytes_GET_SIZE(obj) == 0) {
2813 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02002814 v = unicode_empty;
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002815 }
2816 else {
2817 v = PyUnicode_Decode(
2818 PyBytes_AS_STRING(obj), PyBytes_GET_SIZE(obj),
2819 encoding, errors);
2820 }
2821 return v;
2822 }
2823
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002824 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002825 PyErr_SetString(PyExc_TypeError,
2826 "decoding str is not supported");
2827 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002828 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002829
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002830 /* Retrieve a bytes buffer view through the PEP 3118 buffer interface */
2831 if (PyObject_GetBuffer(obj, &buffer, PyBUF_SIMPLE) < 0) {
2832 PyErr_Format(PyExc_TypeError,
2833 "coercing to str: need bytes, bytearray "
2834 "or buffer-like object, %.80s found",
2835 Py_TYPE(obj)->tp_name);
2836 return NULL;
Marc-André Lemburg6871f6a2001-09-20 12:53:16 +00002837 }
Tim Petersced69f82003-09-16 20:30:58 +00002838
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002839 if (buffer.len == 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002840 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02002841 v = unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002842 }
Tim Petersced69f82003-09-16 20:30:58 +00002843 else
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002844 v = PyUnicode_Decode((char*) buffer.buf, buffer.len, encoding, errors);
Marc-André Lemburgad7c98e2001-01-17 17:09:53 +00002845
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002846 PyBuffer_Release(&buffer);
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002847 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002848}
2849
Victor Stinner600d3be2010-06-10 12:00:55 +00002850/* Convert encoding to lower case and replace '_' with '-' in order to
Victor Stinner37296e82010-06-10 13:36:23 +00002851 catch e.g. UTF_8. Return 0 on error (encoding is longer than lower_len-1),
2852 1 on success. */
2853static int
2854normalize_encoding(const char *encoding,
2855 char *lower,
2856 size_t lower_len)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002857{
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002858 const char *e;
Victor Stinner600d3be2010-06-10 12:00:55 +00002859 char *l;
2860 char *l_end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002861
Benjamin Peterson7a6debe2011-10-15 09:25:28 -04002862 if (encoding == NULL) {
2863 strcpy(lower, "utf-8");
2864 return 1;
2865 }
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002866 e = encoding;
2867 l = lower;
Victor Stinner600d3be2010-06-10 12:00:55 +00002868 l_end = &lower[lower_len - 1];
Victor Stinner37296e82010-06-10 13:36:23 +00002869 while (*e) {
2870 if (l == l_end)
2871 return 0;
David Malcolm96960882010-11-05 17:23:41 +00002872 if (Py_ISUPPER(*e)) {
2873 *l++ = Py_TOLOWER(*e++);
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002874 }
2875 else if (*e == '_') {
2876 *l++ = '-';
2877 e++;
2878 }
2879 else {
2880 *l++ = *e++;
2881 }
2882 }
2883 *l = '\0';
Victor Stinner37296e82010-06-10 13:36:23 +00002884 return 1;
Victor Stinner600d3be2010-06-10 12:00:55 +00002885}
2886
Alexander Belopolsky40018472011-02-26 01:02:56 +00002887PyObject *
2888PyUnicode_Decode(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002889 Py_ssize_t size,
2890 const char *encoding,
2891 const char *errors)
Victor Stinner600d3be2010-06-10 12:00:55 +00002892{
2893 PyObject *buffer = NULL, *unicode;
2894 Py_buffer info;
2895 char lower[11]; /* Enough for any encoding shortcut */
2896
Fred Drakee4315f52000-05-09 19:53:39 +00002897 /* Shortcuts for common default encodings */
Victor Stinner37296e82010-06-10 13:36:23 +00002898 if (normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00002899 if ((strcmp(lower, "utf-8") == 0) ||
2900 (strcmp(lower, "utf8") == 0))
Victor Stinner37296e82010-06-10 13:36:23 +00002901 return PyUnicode_DecodeUTF8(s, size, errors);
2902 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00002903 (strcmp(lower, "latin1") == 0) ||
Victor Stinner37296e82010-06-10 13:36:23 +00002904 (strcmp(lower, "iso-8859-1") == 0))
2905 return PyUnicode_DecodeLatin1(s, size, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02002906#ifdef HAVE_MBCS
Victor Stinner37296e82010-06-10 13:36:23 +00002907 else if (strcmp(lower, "mbcs") == 0)
2908 return PyUnicode_DecodeMBCS(s, size, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00002909#endif
Victor Stinner37296e82010-06-10 13:36:23 +00002910 else if (strcmp(lower, "ascii") == 0)
2911 return PyUnicode_DecodeASCII(s, size, errors);
2912 else if (strcmp(lower, "utf-16") == 0)
2913 return PyUnicode_DecodeUTF16(s, size, errors, 0);
2914 else if (strcmp(lower, "utf-32") == 0)
2915 return PyUnicode_DecodeUTF32(s, size, errors, 0);
2916 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002917
2918 /* Decode via the codec registry */
Guido van Rossumbe801ac2007-10-08 03:32:34 +00002919 buffer = NULL;
Antoine Pitrouc3b39242009-01-03 16:59:18 +00002920 if (PyBuffer_FillInfo(&info, NULL, (void *)s, size, 1, PyBUF_FULL_RO) < 0)
Guido van Rossumbe801ac2007-10-08 03:32:34 +00002921 goto onError;
Antoine Pitrouee58fa42008-08-19 18:22:14 +00002922 buffer = PyMemoryView_FromBuffer(&info);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002923 if (buffer == NULL)
2924 goto onError;
2925 unicode = PyCodec_Decode(buffer, encoding, errors);
2926 if (unicode == NULL)
2927 goto onError;
2928 if (!PyUnicode_Check(unicode)) {
2929 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00002930 "decoder did not return a str object (type=%.400s)",
Christian Heimes90aa7642007-12-19 02:45:37 +00002931 Py_TYPE(unicode)->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002932 Py_DECREF(unicode);
2933 goto onError;
2934 }
2935 Py_DECREF(buffer);
Victor Stinner17efeed2011-10-04 20:05:46 +02002936#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02002937 if (_PyUnicode_READY_REPLACE(&unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002938 Py_DECREF(unicode);
2939 return NULL;
2940 }
Victor Stinner17efeed2011-10-04 20:05:46 +02002941#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002942 assert(_PyUnicode_CheckConsistency(unicode, 1));
Guido van Rossumd57fd912000-03-10 22:53:23 +00002943 return unicode;
Tim Petersced69f82003-09-16 20:30:58 +00002944
Benjamin Peterson29060642009-01-31 22:14:21 +00002945 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00002946 Py_XDECREF(buffer);
2947 return NULL;
2948}
2949
Alexander Belopolsky40018472011-02-26 01:02:56 +00002950PyObject *
2951PyUnicode_AsDecodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002952 const char *encoding,
2953 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002954{
2955 PyObject *v;
2956
2957 if (!PyUnicode_Check(unicode)) {
2958 PyErr_BadArgument();
2959 goto onError;
2960 }
2961
2962 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00002963 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002964
2965 /* Decode via the codec registry */
2966 v = PyCodec_Decode(unicode, encoding, errors);
2967 if (v == NULL)
2968 goto onError;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002969 assert(_PyUnicode_CheckConsistency(v, 1));
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002970 return v;
2971
Benjamin Peterson29060642009-01-31 22:14:21 +00002972 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002973 return NULL;
2974}
2975
Alexander Belopolsky40018472011-02-26 01:02:56 +00002976PyObject *
2977PyUnicode_AsDecodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002978 const char *encoding,
2979 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002980{
2981 PyObject *v;
2982
2983 if (!PyUnicode_Check(unicode)) {
2984 PyErr_BadArgument();
2985 goto onError;
2986 }
2987
2988 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00002989 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002990
2991 /* Decode via the codec registry */
2992 v = PyCodec_Decode(unicode, encoding, errors);
2993 if (v == NULL)
2994 goto onError;
2995 if (!PyUnicode_Check(v)) {
2996 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00002997 "decoder did not return a str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002998 Py_TYPE(v)->tp_name);
2999 Py_DECREF(v);
3000 goto onError;
3001 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02003002 assert(_PyUnicode_CheckConsistency(v, 1));
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003003 return v;
3004
Benjamin Peterson29060642009-01-31 22:14:21 +00003005 onError:
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003006 return NULL;
3007}
3008
Alexander Belopolsky40018472011-02-26 01:02:56 +00003009PyObject *
3010PyUnicode_Encode(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003011 Py_ssize_t size,
3012 const char *encoding,
3013 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003014{
3015 PyObject *v, *unicode;
Tim Petersced69f82003-09-16 20:30:58 +00003016
Guido van Rossumd57fd912000-03-10 22:53:23 +00003017 unicode = PyUnicode_FromUnicode(s, size);
3018 if (unicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003019 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003020 v = PyUnicode_AsEncodedString(unicode, encoding, errors);
3021 Py_DECREF(unicode);
3022 return v;
3023}
3024
Alexander Belopolsky40018472011-02-26 01:02:56 +00003025PyObject *
3026PyUnicode_AsEncodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003027 const char *encoding,
3028 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003029{
3030 PyObject *v;
3031
3032 if (!PyUnicode_Check(unicode)) {
3033 PyErr_BadArgument();
3034 goto onError;
3035 }
3036
3037 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003038 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003039
3040 /* Encode via the codec registry */
3041 v = PyCodec_Encode(unicode, encoding, errors);
3042 if (v == NULL)
3043 goto onError;
3044 return v;
3045
Benjamin Peterson29060642009-01-31 22:14:21 +00003046 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003047 return NULL;
3048}
3049
Victor Stinnerad158722010-10-27 00:25:46 +00003050PyObject *
3051PyUnicode_EncodeFSDefault(PyObject *unicode)
Victor Stinnerae6265f2010-05-15 16:27:27 +00003052{
Victor Stinner99b95382011-07-04 14:23:54 +02003053#ifdef HAVE_MBCS
Victor Stinner1f795172011-11-17 00:45:54 +01003054 const Py_UNICODE *wstr;
3055 Py_ssize_t wlen;
3056
3057 wstr = PyUnicode_AsUnicodeAndSize(unicode, &wlen);
3058 if (wstr == NULL)
3059 return NULL;
3060 return PyUnicode_EncodeMBCS(wstr, wlen, NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003061#elif defined(__APPLE__)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003062 return _PyUnicode_AsUTF8String(unicode, "surrogateescape");
Victor Stinnerad158722010-10-27 00:25:46 +00003063#else
Victor Stinner793b5312011-04-27 00:24:21 +02003064 PyInterpreterState *interp = PyThreadState_GET()->interp;
3065 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3066 cannot use it to encode and decode filenames before it is loaded. Load
3067 the Python codec requires to encode at least its own filename. Use the C
3068 version of the locale codec until the codec registry is initialized and
3069 the Python codec is loaded.
3070
3071 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3072 cannot only rely on it: check also interp->fscodec_initialized for
3073 subinterpreters. */
3074 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Victor Stinnerae6265f2010-05-15 16:27:27 +00003075 return PyUnicode_AsEncodedString(unicode,
3076 Py_FileSystemDefaultEncoding,
3077 "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00003078 }
3079 else {
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003080 /* locale encoding with surrogateescape */
3081 wchar_t *wchar;
3082 char *bytes;
3083 PyObject *bytes_obj;
Victor Stinner2f02a512010-11-08 22:43:46 +00003084 size_t error_pos;
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003085
3086 wchar = PyUnicode_AsWideCharString(unicode, NULL);
3087 if (wchar == NULL)
3088 return NULL;
Victor Stinner2f02a512010-11-08 22:43:46 +00003089 bytes = _Py_wchar2char(wchar, &error_pos);
3090 if (bytes == NULL) {
3091 if (error_pos != (size_t)-1) {
3092 char *errmsg = strerror(errno);
3093 PyObject *exc = NULL;
3094 if (errmsg == NULL)
3095 errmsg = "Py_wchar2char() failed";
3096 raise_encode_exception(&exc,
Martin v. Löwis12be46c2011-11-04 19:04:15 +01003097 "filesystemencoding", unicode,
Victor Stinner2f02a512010-11-08 22:43:46 +00003098 error_pos, error_pos+1,
3099 errmsg);
3100 Py_XDECREF(exc);
3101 }
3102 else
3103 PyErr_NoMemory();
3104 PyMem_Free(wchar);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003105 return NULL;
Victor Stinner2f02a512010-11-08 22:43:46 +00003106 }
3107 PyMem_Free(wchar);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003108
3109 bytes_obj = PyBytes_FromString(bytes);
3110 PyMem_Free(bytes);
3111 return bytes_obj;
Victor Stinnerc39211f2010-09-29 16:35:47 +00003112 }
Victor Stinnerad158722010-10-27 00:25:46 +00003113#endif
Victor Stinnerae6265f2010-05-15 16:27:27 +00003114}
3115
Alexander Belopolsky40018472011-02-26 01:02:56 +00003116PyObject *
3117PyUnicode_AsEncodedString(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003118 const char *encoding,
3119 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003120{
3121 PyObject *v;
Victor Stinner600d3be2010-06-10 12:00:55 +00003122 char lower[11]; /* Enough for any encoding shortcut */
Tim Petersced69f82003-09-16 20:30:58 +00003123
Guido van Rossumd57fd912000-03-10 22:53:23 +00003124 if (!PyUnicode_Check(unicode)) {
3125 PyErr_BadArgument();
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003126 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003127 }
Fred Drakee4315f52000-05-09 19:53:39 +00003128
Fred Drakee4315f52000-05-09 19:53:39 +00003129 /* Shortcuts for common default encodings */
Victor Stinner37296e82010-06-10 13:36:23 +00003130 if (normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003131 if ((strcmp(lower, "utf-8") == 0) ||
3132 (strcmp(lower, "utf8") == 0))
Victor Stinnera5c68c32011-03-02 01:03:14 +00003133 {
Victor Stinner2f283c22011-03-02 01:21:46 +00003134 if (errors == NULL || strcmp(errors, "strict") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003135 return _PyUnicode_AsUTF8String(unicode, NULL);
Victor Stinner2f283c22011-03-02 01:21:46 +00003136 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003137 return _PyUnicode_AsUTF8String(unicode, errors);
Victor Stinnera5c68c32011-03-02 01:03:14 +00003138 }
Victor Stinner37296e82010-06-10 13:36:23 +00003139 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003140 (strcmp(lower, "latin1") == 0) ||
Victor Stinner37296e82010-06-10 13:36:23 +00003141 (strcmp(lower, "iso-8859-1") == 0))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003142 return _PyUnicode_AsLatin1String(unicode, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02003143#ifdef HAVE_MBCS
Victor Stinner1f795172011-11-17 00:45:54 +01003144 else if (strcmp(lower, "mbcs") == 0) {
3145 const Py_UNICODE *wstr;
3146 Py_ssize_t wlen;
3147
3148 wstr = PyUnicode_AsUnicodeAndSize(unicode, &wlen);
3149 if (wstr == NULL)
3150 return NULL;
3151 return PyUnicode_EncodeMBCS(wstr, wlen, errors);
3152 }
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003153#endif
Victor Stinner37296e82010-06-10 13:36:23 +00003154 else if (strcmp(lower, "ascii") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003155 return _PyUnicode_AsASCIIString(unicode, errors);
Victor Stinner37296e82010-06-10 13:36:23 +00003156 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003157
3158 /* Encode via the codec registry */
3159 v = PyCodec_Encode(unicode, encoding, errors);
3160 if (v == NULL)
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003161 return NULL;
3162
3163 /* The normal path */
3164 if (PyBytes_Check(v))
3165 return v;
3166
3167 /* If the codec returns a buffer, raise a warning and convert to bytes */
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003168 if (PyByteArray_Check(v)) {
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003169 int error;
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003170 PyObject *b;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003171
3172 error = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
3173 "encoder %s returned bytearray instead of bytes",
3174 encoding);
3175 if (error) {
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003176 Py_DECREF(v);
3177 return NULL;
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003178 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003179
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003180 b = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(v), Py_SIZE(v));
3181 Py_DECREF(v);
3182 return b;
3183 }
3184
3185 PyErr_Format(PyExc_TypeError,
3186 "encoder did not return a bytes object (type=%.400s)",
3187 Py_TYPE(v)->tp_name);
3188 Py_DECREF(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003189 return NULL;
3190}
3191
Alexander Belopolsky40018472011-02-26 01:02:56 +00003192PyObject *
3193PyUnicode_AsEncodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003194 const char *encoding,
3195 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003196{
3197 PyObject *v;
3198
3199 if (!PyUnicode_Check(unicode)) {
3200 PyErr_BadArgument();
3201 goto onError;
3202 }
3203
3204 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003205 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003206
3207 /* Encode via the codec registry */
3208 v = PyCodec_Encode(unicode, encoding, errors);
3209 if (v == NULL)
3210 goto onError;
3211 if (!PyUnicode_Check(v)) {
3212 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00003213 "encoder did not return an str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003214 Py_TYPE(v)->tp_name);
3215 Py_DECREF(v);
3216 goto onError;
3217 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003218 return v;
Tim Petersced69f82003-09-16 20:30:58 +00003219
Benjamin Peterson29060642009-01-31 22:14:21 +00003220 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003221 return NULL;
3222}
3223
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003224PyObject*
Christian Heimes5894ba72007-11-04 11:43:14 +00003225PyUnicode_DecodeFSDefault(const char *s) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003226 Py_ssize_t size = (Py_ssize_t)strlen(s);
Christian Heimes5894ba72007-11-04 11:43:14 +00003227 return PyUnicode_DecodeFSDefaultAndSize(s, size);
3228}
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003229
Christian Heimes5894ba72007-11-04 11:43:14 +00003230PyObject*
3231PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
3232{
Victor Stinner99b95382011-07-04 14:23:54 +02003233#ifdef HAVE_MBCS
Victor Stinnerad158722010-10-27 00:25:46 +00003234 return PyUnicode_DecodeMBCS(s, size, NULL);
3235#elif defined(__APPLE__)
3236 return PyUnicode_DecodeUTF8(s, size, "surrogateescape");
3237#else
Victor Stinner793b5312011-04-27 00:24:21 +02003238 PyInterpreterState *interp = PyThreadState_GET()->interp;
3239 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3240 cannot use it to encode and decode filenames before it is loaded. Load
3241 the Python codec requires to encode at least its own filename. Use the C
3242 version of the locale codec until the codec registry is initialized and
3243 the Python codec is loaded.
3244
3245 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3246 cannot only rely on it: check also interp->fscodec_initialized for
3247 subinterpreters. */
3248 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003249 return PyUnicode_Decode(s, size,
3250 Py_FileSystemDefaultEncoding,
Victor Stinnerb9a20ad2010-04-30 16:37:52 +00003251 "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003252 }
3253 else {
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003254 /* locale encoding with surrogateescape */
3255 wchar_t *wchar;
3256 PyObject *unicode;
Victor Stinner168e1172010-10-16 23:16:16 +00003257 size_t len;
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003258
3259 if (s[size] != '\0' || size != strlen(s)) {
3260 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
3261 return NULL;
3262 }
3263
Victor Stinner168e1172010-10-16 23:16:16 +00003264 wchar = _Py_char2wchar(s, &len);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003265 if (wchar == NULL)
Victor Stinnerd5af0a52010-11-08 23:34:29 +00003266 return PyErr_NoMemory();
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003267
Victor Stinner168e1172010-10-16 23:16:16 +00003268 unicode = PyUnicode_FromWideChar(wchar, len);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003269 PyMem_Free(wchar);
3270 return unicode;
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003271 }
Victor Stinnerad158722010-10-27 00:25:46 +00003272#endif
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003273}
3274
Martin v. Löwis011e8422009-05-05 04:43:17 +00003275
3276int
3277PyUnicode_FSConverter(PyObject* arg, void* addr)
3278{
3279 PyObject *output = NULL;
3280 Py_ssize_t size;
3281 void *data;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003282 if (arg == NULL) {
3283 Py_DECREF(*(PyObject**)addr);
3284 return 1;
3285 }
Victor Stinnerdcb24032010-04-22 12:08:36 +00003286 if (PyBytes_Check(arg)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00003287 output = arg;
3288 Py_INCREF(output);
3289 }
3290 else {
3291 arg = PyUnicode_FromObject(arg);
3292 if (!arg)
3293 return 0;
Victor Stinnerae6265f2010-05-15 16:27:27 +00003294 output = PyUnicode_EncodeFSDefault(arg);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003295 Py_DECREF(arg);
3296 if (!output)
3297 return 0;
3298 if (!PyBytes_Check(output)) {
3299 Py_DECREF(output);
3300 PyErr_SetString(PyExc_TypeError, "encoder failed to return bytes");
3301 return 0;
3302 }
3303 }
Victor Stinner0ea2a462010-04-30 00:22:08 +00003304 size = PyBytes_GET_SIZE(output);
3305 data = PyBytes_AS_STRING(output);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003306 if (size != strlen(data)) {
Benjamin Peterson7a6b44a2011-08-18 13:51:47 -05003307 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
Martin v. Löwis011e8422009-05-05 04:43:17 +00003308 Py_DECREF(output);
3309 return 0;
3310 }
3311 *(PyObject**)addr = output;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003312 return Py_CLEANUP_SUPPORTED;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003313}
3314
3315
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003316int
3317PyUnicode_FSDecoder(PyObject* arg, void* addr)
3318{
3319 PyObject *output = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003320 if (arg == NULL) {
3321 Py_DECREF(*(PyObject**)addr);
3322 return 1;
3323 }
3324 if (PyUnicode_Check(arg)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003325 if (PyUnicode_READY(arg))
3326 return 0;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003327 output = arg;
3328 Py_INCREF(output);
3329 }
3330 else {
3331 arg = PyBytes_FromObject(arg);
3332 if (!arg)
3333 return 0;
3334 output = PyUnicode_DecodeFSDefaultAndSize(PyBytes_AS_STRING(arg),
3335 PyBytes_GET_SIZE(arg));
3336 Py_DECREF(arg);
3337 if (!output)
3338 return 0;
3339 if (!PyUnicode_Check(output)) {
3340 Py_DECREF(output);
3341 PyErr_SetString(PyExc_TypeError, "decoder failed to return unicode");
3342 return 0;
3343 }
3344 }
Victor Stinner065836e2011-10-27 01:56:33 +02003345 if (PyUnicode_READY(output) < 0) {
3346 Py_DECREF(output);
3347 return 0;
3348 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003349 if (findchar(PyUnicode_DATA(output), PyUnicode_KIND(output),
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02003350 PyUnicode_GET_LENGTH(output), 0, 1) >= 0) {
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003351 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
3352 Py_DECREF(output);
3353 return 0;
3354 }
3355 *(PyObject**)addr = output;
3356 return Py_CLEANUP_SUPPORTED;
3357}
3358
3359
Martin v. Löwis5b222132007-06-10 09:51:05 +00003360char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003361PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *psize)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003362{
Christian Heimesf3863112007-11-22 07:46:41 +00003363 PyObject *bytes;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003364
Neal Norwitze0a0a6e2007-08-25 01:04:21 +00003365 if (!PyUnicode_Check(unicode)) {
3366 PyErr_BadArgument();
3367 return NULL;
3368 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003369 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003370 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003371
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003372 if (PyUnicode_UTF8(unicode) == NULL) {
3373 assert(!PyUnicode_IS_COMPACT_ASCII(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003374 bytes = _PyUnicode_AsUTF8String(unicode, "strict");
3375 if (bytes == NULL)
3376 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003377 _PyUnicode_UTF8(unicode) = PyObject_MALLOC(PyBytes_GET_SIZE(bytes) + 1);
3378 if (_PyUnicode_UTF8(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003379 Py_DECREF(bytes);
3380 return NULL;
3381 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003382 _PyUnicode_UTF8_LENGTH(unicode) = PyBytes_GET_SIZE(bytes);
3383 Py_MEMCPY(_PyUnicode_UTF8(unicode),
3384 PyBytes_AS_STRING(bytes),
3385 _PyUnicode_UTF8_LENGTH(unicode) + 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003386 Py_DECREF(bytes);
3387 }
3388
3389 if (psize)
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003390 *psize = PyUnicode_UTF8_LENGTH(unicode);
3391 return PyUnicode_UTF8(unicode);
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003392}
3393
3394char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003395PyUnicode_AsUTF8(PyObject *unicode)
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003396{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003397 return PyUnicode_AsUTF8AndSize(unicode, NULL);
3398}
3399
3400#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +02003401static int unicode_as_unicode_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003402#endif
3403
3404
3405Py_UNICODE *
3406PyUnicode_AsUnicodeAndSize(PyObject *unicode, Py_ssize_t *size)
3407{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003408 const unsigned char *one_byte;
3409#if SIZEOF_WCHAR_T == 4
3410 const Py_UCS2 *two_bytes;
3411#else
3412 const Py_UCS4 *four_bytes;
3413 const Py_UCS4 *ucs4_end;
3414 Py_ssize_t num_surrogates;
3415#endif
3416 wchar_t *w;
3417 wchar_t *wchar_end;
3418
3419 if (!PyUnicode_Check(unicode)) {
3420 PyErr_BadArgument();
3421 return NULL;
3422 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003423 if (_PyUnicode_WSTR(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003424 /* Non-ASCII compact unicode object */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003425 assert(_PyUnicode_KIND(unicode) != 0);
3426 assert(PyUnicode_IS_READY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003427
3428#ifdef Py_DEBUG
3429 ++unicode_as_unicode_calls;
3430#endif
3431
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003432 if (PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003433#if SIZEOF_WCHAR_T == 2
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003434 four_bytes = PyUnicode_4BYTE_DATA(unicode);
3435 ucs4_end = four_bytes + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003436 num_surrogates = 0;
3437
3438 for (; four_bytes < ucs4_end; ++four_bytes) {
3439 if (*four_bytes > 0xFFFF)
3440 ++num_surrogates;
3441 }
3442
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003443 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(
3444 sizeof(wchar_t) * (_PyUnicode_LENGTH(unicode) + 1 + num_surrogates));
3445 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003446 PyErr_NoMemory();
3447 return NULL;
3448 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003449 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode) + num_surrogates;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003450
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003451 w = _PyUnicode_WSTR(unicode);
3452 wchar_end = w + _PyUnicode_WSTR_LENGTH(unicode);
3453 four_bytes = PyUnicode_4BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003454 for (; four_bytes < ucs4_end; ++four_bytes, ++w) {
3455 if (*four_bytes > 0xFFFF) {
3456 /* encode surrogate pair in this case */
3457 *w++ = 0xD800 | ((*four_bytes - 0x10000) >> 10);
3458 *w = 0xDC00 | ((*four_bytes - 0x10000) & 0x3FF);
3459 }
3460 else
3461 *w = *four_bytes;
3462
3463 if (w > wchar_end) {
3464 assert(0 && "Miscalculated string end");
3465 }
3466 }
3467 *w = 0;
3468#else
3469 /* sizeof(wchar_t) == 4 */
3470 Py_FatalError("Impossible unicode object state, wstr and str "
3471 "should share memory already.");
3472 return NULL;
3473#endif
3474 }
3475 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003476 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(sizeof(wchar_t) *
3477 (_PyUnicode_LENGTH(unicode) + 1));
3478 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003479 PyErr_NoMemory();
3480 return NULL;
3481 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003482 if (!PyUnicode_IS_COMPACT_ASCII(unicode))
3483 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode);
3484 w = _PyUnicode_WSTR(unicode);
3485 wchar_end = w + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003486
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003487 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND) {
3488 one_byte = PyUnicode_1BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003489 for (; w < wchar_end; ++one_byte, ++w)
3490 *w = *one_byte;
3491 /* null-terminate the wstr */
3492 *w = 0;
3493 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003494 else if (PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003495#if SIZEOF_WCHAR_T == 4
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003496 two_bytes = PyUnicode_2BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003497 for (; w < wchar_end; ++two_bytes, ++w)
3498 *w = *two_bytes;
3499 /* null-terminate the wstr */
3500 *w = 0;
3501#else
3502 /* sizeof(wchar_t) == 2 */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003503 PyObject_FREE(_PyUnicode_WSTR(unicode));
3504 _PyUnicode_WSTR(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003505 Py_FatalError("Impossible unicode object state, wstr "
3506 "and str should share memory already.");
3507 return NULL;
3508#endif
3509 }
3510 else {
3511 assert(0 && "This should never happen.");
3512 }
3513 }
3514 }
3515 if (size != NULL)
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003516 *size = PyUnicode_WSTR_LENGTH(unicode);
3517 return _PyUnicode_WSTR(unicode);
Martin v. Löwis5b222132007-06-10 09:51:05 +00003518}
3519
Alexander Belopolsky40018472011-02-26 01:02:56 +00003520Py_UNICODE *
3521PyUnicode_AsUnicode(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003522{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003523 return PyUnicode_AsUnicodeAndSize(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003524}
3525
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003526
Alexander Belopolsky40018472011-02-26 01:02:56 +00003527Py_ssize_t
3528PyUnicode_GetSize(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003529{
3530 if (!PyUnicode_Check(unicode)) {
3531 PyErr_BadArgument();
3532 goto onError;
3533 }
3534 return PyUnicode_GET_SIZE(unicode);
3535
Benjamin Peterson29060642009-01-31 22:14:21 +00003536 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003537 return -1;
3538}
3539
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003540Py_ssize_t
3541PyUnicode_GetLength(PyObject *unicode)
3542{
Victor Stinner5a706cf2011-10-02 00:36:53 +02003543 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003544 PyErr_BadArgument();
3545 return -1;
3546 }
3547
3548 return PyUnicode_GET_LENGTH(unicode);
3549}
3550
3551Py_UCS4
3552PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
3553{
Victor Stinner2fe5ced2011-10-02 00:25:40 +02003554 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
3555 PyErr_BadArgument();
3556 return (Py_UCS4)-1;
3557 }
3558 if (index < 0 || index >= _PyUnicode_LENGTH(unicode)) {
3559 PyErr_SetString(PyExc_IndexError, "string index out of range");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003560 return (Py_UCS4)-1;
3561 }
3562 return PyUnicode_READ_CHAR(unicode, index);
3563}
3564
3565int
3566PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 ch)
3567{
3568 if (!PyUnicode_Check(unicode) || !PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02003569 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003570 return -1;
3571 }
Victor Stinnercd9950f2011-10-02 00:34:53 +02003572 if (index < 0 || index >= _PyUnicode_LENGTH(unicode)) {
3573 PyErr_SetString(PyExc_IndexError, "string index out of range");
3574 return -1;
3575 }
3576 if (_PyUnicode_Dirty(unicode))
3577 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003578 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
3579 index, ch);
3580 return 0;
3581}
3582
Alexander Belopolsky40018472011-02-26 01:02:56 +00003583const char *
3584PyUnicode_GetDefaultEncoding(void)
Fred Drakee4315f52000-05-09 19:53:39 +00003585{
Victor Stinner42cb4622010-09-01 19:39:01 +00003586 return "utf-8";
Fred Drakee4315f52000-05-09 19:53:39 +00003587}
3588
Victor Stinner554f3f02010-06-16 23:33:54 +00003589/* create or adjust a UnicodeDecodeError */
3590static void
3591make_decode_exception(PyObject **exceptionObject,
3592 const char *encoding,
3593 const char *input, Py_ssize_t length,
3594 Py_ssize_t startpos, Py_ssize_t endpos,
3595 const char *reason)
3596{
3597 if (*exceptionObject == NULL) {
3598 *exceptionObject = PyUnicodeDecodeError_Create(
3599 encoding, input, length, startpos, endpos, reason);
3600 }
3601 else {
3602 if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
3603 goto onError;
3604 if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
3605 goto onError;
3606 if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
3607 goto onError;
3608 }
3609 return;
3610
3611onError:
3612 Py_DECREF(*exceptionObject);
3613 *exceptionObject = NULL;
3614}
3615
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003616/* error handling callback helper:
3617 build arguments, call the callback and check the arguments,
Fred Drakedb390c12005-10-28 14:39:47 +00003618 if no exception occurred, copy the replacement to the output
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003619 and adjust various state variables.
3620 return 0 on success, -1 on error
3621*/
3622
Alexander Belopolsky40018472011-02-26 01:02:56 +00003623static int
3624unicode_decode_call_errorhandler(const char *errors, PyObject **errorHandler,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003625 const char *encoding, const char *reason,
3626 const char **input, const char **inend, Py_ssize_t *startinpos,
3627 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003628 PyObject **output, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003629{
Benjamin Peterson142957c2008-07-04 19:55:29 +00003630 static char *argparse = "O!n;decoding error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003631
3632 PyObject *restuple = NULL;
3633 PyObject *repunicode = NULL;
Victor Stinner596a6c42011-11-09 00:02:18 +01003634 Py_ssize_t outsize;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003635 Py_ssize_t insize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003636 Py_ssize_t requiredsize;
3637 Py_ssize_t newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003638 PyObject *inputobj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003639 int res = -1;
3640
Victor Stinner596a6c42011-11-09 00:02:18 +01003641 if (_PyUnicode_KIND(*output) != PyUnicode_WCHAR_KIND)
3642 outsize = PyUnicode_GET_LENGTH(*output);
3643 else
3644 outsize = _PyUnicode_WSTR_LENGTH(*output);
3645
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003646 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003647 *errorHandler = PyCodec_LookupError(errors);
3648 if (*errorHandler == NULL)
3649 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003650 }
3651
Victor Stinner554f3f02010-06-16 23:33:54 +00003652 make_decode_exception(exceptionObject,
3653 encoding,
3654 *input, *inend - *input,
3655 *startinpos, *endinpos,
3656 reason);
3657 if (*exceptionObject == NULL)
3658 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003659
3660 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
3661 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003662 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003663 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00003664 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00003665 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003666 }
3667 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00003668 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003669 if (PyUnicode_READY(repunicode) < 0)
3670 goto onError;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003671
3672 /* Copy back the bytes variables, which might have been modified by the
3673 callback */
3674 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
3675 if (!inputobj)
3676 goto onError;
Christian Heimes72b710a2008-05-26 13:28:38 +00003677 if (!PyBytes_Check(inputobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003678 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
Walter Dörwalde78178e2007-07-30 13:31:40 +00003679 }
Christian Heimes72b710a2008-05-26 13:28:38 +00003680 *input = PyBytes_AS_STRING(inputobj);
3681 insize = PyBytes_GET_SIZE(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00003682 *inend = *input + insize;
Walter Dörwald36f938f2007-08-10 10:11:43 +00003683 /* we can DECREF safely, as the exception has another reference,
3684 so the object won't go away. */
3685 Py_DECREF(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00003686
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003687 if (newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00003688 newpos = insize+newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00003689 if (newpos<0 || newpos>insize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003690 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
3691 goto onError;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00003692 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003693
Victor Stinner596a6c42011-11-09 00:02:18 +01003694 if (_PyUnicode_KIND(*output) != PyUnicode_WCHAR_KIND) {
3695 /* need more space? (at least enough for what we
3696 have+the replacement+the rest of the string (starting
3697 at the new input position), so we won't have to check space
3698 when there are no errors in the rest of the string) */
3699 Py_ssize_t replen = PyUnicode_GET_LENGTH(repunicode);
3700 requiredsize = *outpos + replen + insize-newpos;
3701 if (requiredsize > outsize) {
3702 if (requiredsize<2*outsize)
3703 requiredsize = 2*outsize;
3704 if (unicode_resize(output, requiredsize) < 0)
3705 goto onError;
3706 }
3707 if (unicode_widen(output, PyUnicode_MAX_CHAR_VALUE(repunicode)) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00003708 goto onError;
Victor Stinner596a6c42011-11-09 00:02:18 +01003709 copy_characters(*output, *outpos, repunicode, 0, replen);
3710 *outpos += replen;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003711 }
Victor Stinner596a6c42011-11-09 00:02:18 +01003712 else {
3713 wchar_t *repwstr;
3714 Py_ssize_t repwlen;
3715 repwstr = PyUnicode_AsUnicodeAndSize(repunicode, &repwlen);
3716 if (repwstr == NULL)
3717 goto onError;
3718 /* need more space? (at least enough for what we
3719 have+the replacement+the rest of the string (starting
3720 at the new input position), so we won't have to check space
3721 when there are no errors in the rest of the string) */
3722 requiredsize = *outpos + repwlen + insize-newpos;
3723 if (requiredsize > outsize) {
3724 if (requiredsize < 2*outsize)
3725 requiredsize = 2*outsize;
3726 if (unicode_resize(output, requiredsize) < 0)
3727 goto onError;
3728 }
3729 wcsncpy(_PyUnicode_WSTR(*output) + *outpos, repwstr, repwlen);
3730 *outpos += repwlen;
3731 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003732 *endinpos = newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003733 *inptr = *input + newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003734
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003735 /* we made it! */
3736 res = 0;
3737
Benjamin Peterson29060642009-01-31 22:14:21 +00003738 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003739 Py_XDECREF(restuple);
3740 return res;
3741}
3742
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003743/* --- UTF-7 Codec -------------------------------------------------------- */
3744
Antoine Pitrou244651a2009-05-04 18:56:13 +00003745/* See RFC2152 for details. We encode conservatively and decode liberally. */
3746
3747/* Three simple macros defining base-64. */
3748
3749/* Is c a base-64 character? */
3750
3751#define IS_BASE64(c) \
3752 (((c) >= 'A' && (c) <= 'Z') || \
3753 ((c) >= 'a' && (c) <= 'z') || \
3754 ((c) >= '0' && (c) <= '9') || \
3755 (c) == '+' || (c) == '/')
3756
3757/* given that c is a base-64 character, what is its base-64 value? */
3758
3759#define FROM_BASE64(c) \
3760 (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' : \
3761 ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 : \
3762 ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 : \
3763 (c) == '+' ? 62 : 63)
3764
3765/* What is the base-64 character of the bottom 6 bits of n? */
3766
3767#define TO_BASE64(n) \
3768 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
3769
3770/* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
3771 * decoded as itself. We are permissive on decoding; the only ASCII
3772 * byte not decoding to itself is the + which begins a base64
3773 * string. */
3774
3775#define DECODE_DIRECT(c) \
3776 ((c) <= 127 && (c) != '+')
3777
3778/* The UTF-7 encoder treats ASCII characters differently according to
3779 * whether they are Set D, Set O, Whitespace, or special (i.e. none of
3780 * the above). See RFC2152. This array identifies these different
3781 * sets:
3782 * 0 : "Set D"
3783 * alphanumeric and '(),-./:?
3784 * 1 : "Set O"
3785 * !"#$%&*;<=>@[]^_`{|}
3786 * 2 : "whitespace"
3787 * ht nl cr sp
3788 * 3 : special (must be base64 encoded)
3789 * everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
3790 */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003791
Tim Petersced69f82003-09-16 20:30:58 +00003792static
Antoine Pitrou244651a2009-05-04 18:56:13 +00003793char utf7_category[128] = {
3794/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
3795 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
3796/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
3797 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
3798/* sp ! " # $ % & ' ( ) * + , - . / */
3799 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
3800/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
3801 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
3802/* @ A B C D E F G H I J K L M N O */
3803 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
3804/* P Q R S T U V W X Y Z [ \ ] ^ _ */
3805 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
3806/* ` a b c d e f g h i j k l m n o */
3807 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
3808/* p q r s t u v w x y z { | } ~ del */
3809 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003810};
3811
Antoine Pitrou244651a2009-05-04 18:56:13 +00003812/* ENCODE_DIRECT: this character should be encoded as itself. The
3813 * answer depends on whether we are encoding set O as itself, and also
3814 * on whether we are encoding whitespace as itself. RFC2152 makes it
3815 * clear that the answers to these questions vary between
3816 * applications, so this code needs to be flexible. */
Marc-André Lemburge115ec82005-10-19 22:33:31 +00003817
Antoine Pitrou244651a2009-05-04 18:56:13 +00003818#define ENCODE_DIRECT(c, directO, directWS) \
3819 ((c) < 128 && (c) > 0 && \
3820 ((utf7_category[(c)] == 0) || \
3821 (directWS && (utf7_category[(c)] == 2)) || \
3822 (directO && (utf7_category[(c)] == 1))))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003823
Alexander Belopolsky40018472011-02-26 01:02:56 +00003824PyObject *
3825PyUnicode_DecodeUTF7(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003826 Py_ssize_t size,
3827 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003828{
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003829 return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
3830}
3831
Antoine Pitrou244651a2009-05-04 18:56:13 +00003832/* The decoder. The only state we preserve is our read position,
3833 * i.e. how many characters we have consumed. So if we end in the
3834 * middle of a shift sequence we have to back off the read position
3835 * and the output to the beginning of the sequence, otherwise we lose
3836 * all the shift state (seen bits, number of bits seen, high
3837 * surrogate). */
3838
Alexander Belopolsky40018472011-02-26 01:02:56 +00003839PyObject *
3840PyUnicode_DecodeUTF7Stateful(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003841 Py_ssize_t size,
3842 const char *errors,
3843 Py_ssize_t *consumed)
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003844{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003845 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003846 Py_ssize_t startinpos;
3847 Py_ssize_t endinpos;
3848 Py_ssize_t outpos;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003849 const char *e;
Victor Stinner7931d9a2011-11-04 00:22:48 +01003850 PyObject *unicode;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003851 const char *errmsg = "";
3852 int inShift = 0;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003853 Py_ssize_t shiftOutStart;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003854 unsigned int base64bits = 0;
3855 unsigned long base64buffer = 0;
Victor Stinner24729f32011-11-10 20:31:37 +01003856 Py_UCS4 surrogate = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003857 PyObject *errorHandler = NULL;
3858 PyObject *exc = NULL;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003859
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003860 /* Start off assuming it's all ASCII. Widen later as necessary. */
3861 unicode = PyUnicode_New(size, 127);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003862 if (!unicode)
3863 return NULL;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003864 if (size == 0) {
3865 if (consumed)
3866 *consumed = 0;
Victor Stinner7931d9a2011-11-04 00:22:48 +01003867 return unicode;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003868 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003869
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003870 shiftOutStart = outpos = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003871 e = s + size;
3872
3873 while (s < e) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003874 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00003875 restart:
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00003876 ch = (unsigned char) *s;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003877
Antoine Pitrou244651a2009-05-04 18:56:13 +00003878 if (inShift) { /* in a base-64 section */
3879 if (IS_BASE64(ch)) { /* consume a base-64 character */
3880 base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
3881 base64bits += 6;
3882 s++;
3883 if (base64bits >= 16) {
3884 /* we have enough bits for a UTF-16 value */
Victor Stinner24729f32011-11-10 20:31:37 +01003885 Py_UCS4 outCh = (Py_UCS4)(base64buffer >> (base64bits-16));
Antoine Pitrou244651a2009-05-04 18:56:13 +00003886 base64bits -= 16;
3887 base64buffer &= (1 << base64bits) - 1; /* clear high bits */
3888 if (surrogate) {
3889 /* expecting a second surrogate */
3890 if (outCh >= 0xDC00 && outCh <= 0xDFFF) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003891 Py_UCS4 ch2 = (((surrogate & 0x3FF)<<10)
3892 | (outCh & 0x3FF)) + 0x10000;
3893 if (unicode_putchar(&unicode, &outpos, ch2) < 0)
3894 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003895 surrogate = 0;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01003896 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003897 }
3898 else {
Antoine Pitrou78edf752011-11-15 01:44:16 +01003899 if (unicode_putchar(&unicode, &outpos, surrogate) < 0)
3900 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003901 surrogate = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003902 }
3903 }
Antoine Pitrou5418ee02011-11-15 01:42:21 +01003904 if (outCh >= 0xD800 && outCh <= 0xDBFF) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00003905 /* first surrogate */
3906 surrogate = outCh;
3907 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003908 else {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003909 if (unicode_putchar(&unicode, &outpos, outCh) < 0)
3910 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003911 }
3912 }
3913 }
3914 else { /* now leaving a base-64 section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003915 inShift = 0;
3916 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003917 if (surrogate) {
Antoine Pitrou78edf752011-11-15 01:44:16 +01003918 if (unicode_putchar(&unicode, &outpos, surrogate) < 0)
3919 goto onError;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01003920 surrogate = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003921 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003922 if (base64bits > 0) { /* left-over bits */
3923 if (base64bits >= 6) {
3924 /* We've seen at least one base-64 character */
3925 errmsg = "partial character in shift sequence";
3926 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003927 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003928 else {
3929 /* Some bits remain; they should be zero */
3930 if (base64buffer != 0) {
3931 errmsg = "non-zero padding bits in shift sequence";
3932 goto utf7Error;
3933 }
3934 }
3935 }
3936 if (ch != '-') {
3937 /* '-' is absorbed; other terminating
3938 characters are preserved */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003939 if (unicode_putchar(&unicode, &outpos, ch) < 0)
3940 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003941 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003942 }
3943 }
3944 else if ( ch == '+' ) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003945 startinpos = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003946 s++; /* consume '+' */
3947 if (s < e && *s == '-') { /* '+-' encodes '+' */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003948 s++;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003949 if (unicode_putchar(&unicode, &outpos, '+') < 0)
3950 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003951 }
3952 else { /* begin base64-encoded section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003953 inShift = 1;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003954 shiftOutStart = outpos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003955 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003956 }
3957 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003958 else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003959 if (unicode_putchar(&unicode, &outpos, ch) < 0)
3960 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003961 s++;
3962 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003963 else {
3964 startinpos = s-starts;
3965 s++;
3966 errmsg = "unexpected special character";
3967 goto utf7Error;
3968 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003969 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003970utf7Error:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003971 endinpos = s-starts;
3972 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00003973 errors, &errorHandler,
3974 "utf7", errmsg,
3975 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003976 &unicode, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00003977 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003978 }
3979
Antoine Pitrou244651a2009-05-04 18:56:13 +00003980 /* end of string */
3981
3982 if (inShift && !consumed) { /* in shift sequence, no more to follow */
3983 /* if we're in an inconsistent state, that's an error */
3984 if (surrogate ||
3985 (base64bits >= 6) ||
3986 (base64bits > 0 && base64buffer != 0)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00003987 endinpos = size;
3988 if (unicode_decode_call_errorhandler(
3989 errors, &errorHandler,
3990 "utf7", "unterminated shift sequence",
3991 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003992 &unicode, &outpos))
Antoine Pitrou244651a2009-05-04 18:56:13 +00003993 goto onError;
3994 if (s < e)
3995 goto restart;
3996 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003997 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003998
3999 /* return state */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004000 if (consumed) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004001 if (inShift) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004002 outpos = shiftOutStart; /* back off output */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004003 *consumed = startinpos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004004 }
4005 else {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004006 *consumed = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004007 }
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004008 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004009
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004010 if (unicode_resize(&unicode, outpos) < 0)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004011 goto onError;
4012
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004013 Py_XDECREF(errorHandler);
4014 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02004015#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02004016 if (_PyUnicode_READY_REPLACE(&unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004017 Py_DECREF(unicode);
4018 return NULL;
4019 }
Victor Stinner17efeed2011-10-04 20:05:46 +02004020#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02004021 assert(_PyUnicode_CheckConsistency(unicode, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01004022 return unicode;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004023
Benjamin Peterson29060642009-01-31 22:14:21 +00004024 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004025 Py_XDECREF(errorHandler);
4026 Py_XDECREF(exc);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004027 Py_DECREF(unicode);
4028 return NULL;
4029}
4030
4031
Alexander Belopolsky40018472011-02-26 01:02:56 +00004032PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004033_PyUnicode_EncodeUTF7(PyObject *str,
4034 int base64SetO,
4035 int base64WhiteSpace,
4036 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004037{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004038 int kind;
4039 void *data;
4040 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004041 PyObject *v;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004042 Py_ssize_t allocated;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004043 int inShift = 0;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004044 Py_ssize_t i;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004045 unsigned int base64bits = 0;
4046 unsigned long base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004047 char * out;
4048 char * start;
4049
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004050 if (PyUnicode_READY(str) < 0)
4051 return NULL;
4052 kind = PyUnicode_KIND(str);
4053 data = PyUnicode_DATA(str);
4054 len = PyUnicode_GET_LENGTH(str);
4055
4056 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004057 return PyBytes_FromStringAndSize(NULL, 0);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004058
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004059 /* It might be possible to tighten this worst case */
4060 allocated = 8 * len;
4061 if (allocated / 8 != len)
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004062 return PyErr_NoMemory();
4063
Antoine Pitrou244651a2009-05-04 18:56:13 +00004064 v = PyBytes_FromStringAndSize(NULL, allocated);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004065 if (v == NULL)
4066 return NULL;
4067
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004068 start = out = PyBytes_AS_STRING(v);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004069 for (i = 0; i < len; ++i) {
Victor Stinner0e368262011-11-10 20:12:49 +01004070 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004071
Antoine Pitrou244651a2009-05-04 18:56:13 +00004072 if (inShift) {
4073 if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4074 /* shifting out */
4075 if (base64bits) { /* output remaining bits */
4076 *out++ = TO_BASE64(base64buffer << (6-base64bits));
4077 base64buffer = 0;
4078 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004079 }
4080 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004081 /* Characters not in the BASE64 set implicitly unshift the sequence
4082 so no '-' is required, except if the character is itself a '-' */
4083 if (IS_BASE64(ch) || ch == '-') {
4084 *out++ = '-';
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004085 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004086 *out++ = (char) ch;
4087 }
4088 else {
4089 goto encode_char;
Tim Petersced69f82003-09-16 20:30:58 +00004090 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004091 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004092 else { /* not in a shift sequence */
4093 if (ch == '+') {
4094 *out++ = '+';
4095 *out++ = '-';
4096 }
4097 else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4098 *out++ = (char) ch;
4099 }
4100 else {
4101 *out++ = '+';
4102 inShift = 1;
4103 goto encode_char;
4104 }
4105 }
4106 continue;
4107encode_char:
Antoine Pitrou244651a2009-05-04 18:56:13 +00004108 if (ch >= 0x10000) {
4109 /* code first surrogate */
4110 base64bits += 16;
4111 base64buffer = (base64buffer << 16) | 0xd800 | ((ch-0x10000) >> 10);
4112 while (base64bits >= 6) {
4113 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4114 base64bits -= 6;
4115 }
4116 /* prepare second surrogate */
4117 ch = 0xDC00 | ((ch-0x10000) & 0x3FF);
4118 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004119 base64bits += 16;
4120 base64buffer = (base64buffer << 16) | ch;
4121 while (base64bits >= 6) {
4122 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4123 base64bits -= 6;
4124 }
Hye-Shik Chang1bc09b72004-01-03 19:35:43 +00004125 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004126 if (base64bits)
4127 *out++= TO_BASE64(base64buffer << (6-base64bits) );
4128 if (inShift)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004129 *out++ = '-';
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004130 if (_PyBytes_Resize(&v, out - start) < 0)
4131 return NULL;
4132 return v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004133}
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004134PyObject *
4135PyUnicode_EncodeUTF7(const Py_UNICODE *s,
4136 Py_ssize_t size,
4137 int base64SetO,
4138 int base64WhiteSpace,
4139 const char *errors)
4140{
4141 PyObject *result;
4142 PyObject *tmp = PyUnicode_FromUnicode(s, size);
4143 if (tmp == NULL)
4144 return NULL;
Victor Stinner0e368262011-11-10 20:12:49 +01004145 result = _PyUnicode_EncodeUTF7(tmp, base64SetO,
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004146 base64WhiteSpace, errors);
4147 Py_DECREF(tmp);
4148 return result;
4149}
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004150
Antoine Pitrou244651a2009-05-04 18:56:13 +00004151#undef IS_BASE64
4152#undef FROM_BASE64
4153#undef TO_BASE64
4154#undef DECODE_DIRECT
4155#undef ENCODE_DIRECT
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004156
Guido van Rossumd57fd912000-03-10 22:53:23 +00004157/* --- UTF-8 Codec -------------------------------------------------------- */
4158
Tim Petersced69f82003-09-16 20:30:58 +00004159static
Guido van Rossumd57fd912000-03-10 22:53:23 +00004160char utf8_code_length[256] = {
Ezio Melotti57221d02010-07-01 07:32:02 +00004161 /* Map UTF-8 encoded prefix byte to sequence length. Zero means
4162 illegal prefix. See RFC 3629 for details */
4163 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 00-0F */
4164 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Victor Stinner4a2b7a12010-08-13 14:03:48 +00004165 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Guido van Rossumd57fd912000-03-10 22:53:23 +00004166 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
4167 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
4168 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
4169 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Ezio Melotti57221d02010-07-01 07:32:02 +00004170 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 70-7F */
4171 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 +00004172 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4173 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
Ezio Melotti57221d02010-07-01 07:32:02 +00004174 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* B0-BF */
4175 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* C0-C1 + C2-CF */
4176 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* D0-DF */
4177 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, /* E0-EF */
4178 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 +00004179};
4180
Alexander Belopolsky40018472011-02-26 01:02:56 +00004181PyObject *
4182PyUnicode_DecodeUTF8(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004183 Py_ssize_t size,
4184 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004185{
Walter Dörwald69652032004-09-07 20:24:22 +00004186 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
4187}
4188
Antoine Pitrouab868312009-01-10 15:40:25 +00004189/* Mask to check or force alignment of a pointer to C 'long' boundaries */
4190#define LONG_PTR_MASK (size_t) (SIZEOF_LONG - 1)
4191
4192/* Mask to quickly check whether a C 'long' contains a
4193 non-ASCII, UTF8-encoded char. */
4194#if (SIZEOF_LONG == 8)
4195# define ASCII_CHAR_MASK 0x8080808080808080L
4196#elif (SIZEOF_LONG == 4)
4197# define ASCII_CHAR_MASK 0x80808080L
4198#else
4199# error C 'long' size should be either 4 or 8!
4200#endif
4201
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004202/* Scans a UTF-8 string and returns the maximum character to be expected,
4203 the size of the decoded unicode string and if any major errors were
4204 encountered.
4205
4206 This function does check basic UTF-8 sanity, it does however NOT CHECK
4207 if the string contains surrogates, and if all continuation bytes are
4208 within the correct ranges, these checks are performed in
4209 PyUnicode_DecodeUTF8Stateful.
4210
4211 If it sets has_errors to 1, it means the value of unicode_size and max_char
4212 will be bogus and you should not rely on useful information in them.
4213 */
4214static Py_UCS4
4215utf8_max_char_size_and_has_errors(const char *s, Py_ssize_t string_size,
4216 Py_ssize_t *unicode_size, Py_ssize_t* consumed,
4217 int *has_errors)
4218{
4219 Py_ssize_t n;
4220 Py_ssize_t char_count = 0;
4221 Py_UCS4 max_char = 127, new_max;
4222 Py_UCS4 upper_bound;
4223 const unsigned char *p = (const unsigned char *)s;
4224 const unsigned char *end = p + string_size;
4225 const unsigned char *aligned_end = (const unsigned char *) ((size_t) end & ~LONG_PTR_MASK);
4226 int err = 0;
4227
4228 for (; p < end && !err; ++p, ++char_count) {
4229 /* Only check value if it's not a ASCII char... */
4230 if (*p < 0x80) {
4231 /* Fast path, see below in PyUnicode_DecodeUTF8Stateful for
4232 an explanation. */
4233 if (!((size_t) p & LONG_PTR_MASK)) {
4234 /* Help register allocation */
4235 register const unsigned char *_p = p;
4236 while (_p < aligned_end) {
4237 unsigned long value = *(unsigned long *) _p;
4238 if (value & ASCII_CHAR_MASK)
4239 break;
4240 _p += SIZEOF_LONG;
4241 char_count += SIZEOF_LONG;
4242 }
4243 p = _p;
4244 if (p == end)
4245 break;
4246 }
4247 }
4248 if (*p >= 0x80) {
4249 n = utf8_code_length[*p];
4250 new_max = max_char;
4251 switch (n) {
4252 /* invalid start byte */
4253 case 0:
4254 err = 1;
4255 break;
4256 case 2:
4257 /* Code points between 0x00FF and 0x07FF inclusive.
4258 Approximate the upper bound of the code point,
4259 if this flips over 255 we can be sure it will be more
4260 than 255 and the string will need 2 bytes per code coint,
4261 if it stays under or equal to 255, we can be sure 1 byte
4262 is enough.
4263 ((*p & 0b00011111) << 6) | 0b00111111 */
4264 upper_bound = ((*p & 0x1F) << 6) | 0x3F;
4265 if (max_char < upper_bound)
4266 new_max = upper_bound;
4267 /* Ensure we track at least that we left ASCII space. */
4268 if (new_max < 128)
4269 new_max = 128;
4270 break;
4271 case 3:
4272 /* Between 0x0FFF and 0xFFFF inclusive, so values are
4273 always > 255 and <= 65535 and will always need 2 bytes. */
4274 if (max_char < 65535)
4275 new_max = 65535;
4276 break;
4277 case 4:
4278 /* Code point will be above 0xFFFF for sure in this case. */
4279 new_max = 65537;
4280 break;
4281 /* Internal error, this should be caught by the first if */
4282 case 1:
4283 default:
4284 assert(0 && "Impossible case in utf8_max_char_and_size");
4285 err = 1;
4286 }
4287 /* Instead of number of overall bytes for this code point,
Georg Brandl7597add2011-10-05 16:36:47 +02004288 n contains the number of following bytes: */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004289 --n;
4290 /* Check if the follow up chars are all valid continuation bytes */
4291 if (n >= 1) {
4292 const unsigned char *cont;
4293 if ((p + n) >= end) {
4294 if (consumed == 0)
4295 /* incomplete data, non-incremental decoding */
4296 err = 1;
4297 break;
4298 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004299 for (cont = p + 1; cont <= (p + n); ++cont) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004300 if ((*cont & 0xc0) != 0x80) {
4301 err = 1;
4302 break;
4303 }
4304 }
4305 p += n;
4306 }
4307 else
4308 err = 1;
4309 max_char = new_max;
4310 }
4311 }
4312
4313 if (unicode_size)
4314 *unicode_size = char_count;
4315 if (has_errors)
4316 *has_errors = err;
4317 return max_char;
4318}
4319
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004320/* Similar to PyUnicode_WRITE but may attempt to widen and resize the string
4321 in case of errors. Implicit parameters: unicode, kind, data, has_errors,
4322 onError. Potential resizing overallocates, so the result needs to shrink
4323 at the end.
4324*/
4325#define WRITE_MAYBE_FAIL(index, value) \
4326 do { \
4327 if (has_errors) { \
4328 Py_ssize_t pos = index; \
4329 if (pos > PyUnicode_GET_LENGTH(unicode) && \
4330 unicode_resize(&unicode, pos + pos/8) < 0) \
4331 goto onError; \
4332 if (unicode_putchar(&unicode, &pos, value) < 0) \
4333 goto onError; \
4334 } \
4335 else \
4336 PyUnicode_WRITE(kind, data, index, value); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004337 } while (0)
4338
Alexander Belopolsky40018472011-02-26 01:02:56 +00004339PyObject *
4340PyUnicode_DecodeUTF8Stateful(const char *s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004341 Py_ssize_t size,
4342 const char *errors,
4343 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00004344{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004345 const char *starts = s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004346 int n;
Ezio Melotti57221d02010-07-01 07:32:02 +00004347 int k;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004348 Py_ssize_t startinpos;
4349 Py_ssize_t endinpos;
Antoine Pitrouab868312009-01-10 15:40:25 +00004350 const char *e, *aligned_end;
Victor Stinner7931d9a2011-11-04 00:22:48 +01004351 PyObject *unicode;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004352 const char *errmsg = "";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004353 PyObject *errorHandler = NULL;
4354 PyObject *exc = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004355 Py_UCS4 maxchar = 0;
4356 Py_ssize_t unicode_size;
4357 Py_ssize_t i;
4358 int kind;
4359 void *data;
4360 int has_errors;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004361
Walter Dörwald69652032004-09-07 20:24:22 +00004362 if (size == 0) {
4363 if (consumed)
4364 *consumed = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004365 return (PyObject *)PyUnicode_New(0, 0);
Walter Dörwald69652032004-09-07 20:24:22 +00004366 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004367 maxchar = utf8_max_char_size_and_has_errors(s, size, &unicode_size,
4368 consumed, &has_errors);
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004369 if (has_errors)
Victor Stinner62aa4d02011-11-09 00:03:45 +01004370 /* maxchar and size computation might be incorrect;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004371 code below widens and resizes as necessary. */
4372 unicode = PyUnicode_New(size, 127);
4373 else
Victor Stinner7931d9a2011-11-04 00:22:48 +01004374 unicode = PyUnicode_New(unicode_size, maxchar);
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004375 if (!unicode)
4376 return NULL;
4377 /* When the string is ASCII only, just use memcpy and return.
4378 unicode_size may be != size if there is an incomplete UTF-8
4379 sequence at the end of the ASCII block. */
4380 if (!has_errors && maxchar < 128 && size == unicode_size) {
4381 Py_MEMCPY(PyUnicode_1BYTE_DATA(unicode), s, unicode_size);
4382 return unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004383 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004384 kind = PyUnicode_KIND(unicode);
4385 data = PyUnicode_DATA(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004386 /* Unpack UTF-8 encoded data */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004387 i = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004388 e = s + size;
Antoine Pitrouab868312009-01-10 15:40:25 +00004389 aligned_end = (const char *) ((size_t) e & ~LONG_PTR_MASK);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004390
4391 while (s < e) {
Marc-André Lemburge12896e2000-07-07 17:51:08 +00004392 Py_UCS4 ch = (unsigned char)*s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004393
4394 if (ch < 0x80) {
Antoine Pitrouab868312009-01-10 15:40:25 +00004395 /* Fast path for runs of ASCII characters. Given that common UTF-8
4396 input will consist of an overwhelming majority of ASCII
4397 characters, we try to optimize for this case by checking
4398 as many characters as a C 'long' can contain.
4399 First, check if we can do an aligned read, as most CPUs have
4400 a penalty for unaligned reads.
4401 */
4402 if (!((size_t) s & LONG_PTR_MASK)) {
4403 /* Help register allocation */
4404 register const char *_s = s;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004405 register Py_ssize_t _i = i;
Antoine Pitrouab868312009-01-10 15:40:25 +00004406 while (_s < aligned_end) {
4407 /* Read a whole long at a time (either 4 or 8 bytes),
4408 and do a fast unrolled copy if it only contains ASCII
4409 characters. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004410 unsigned long value = *(unsigned long *) _s;
4411 if (value & ASCII_CHAR_MASK)
Antoine Pitrouab868312009-01-10 15:40:25 +00004412 break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004413 WRITE_MAYBE_FAIL(_i+0, _s[0]);
4414 WRITE_MAYBE_FAIL(_i+1, _s[1]);
4415 WRITE_MAYBE_FAIL(_i+2, _s[2]);
4416 WRITE_MAYBE_FAIL(_i+3, _s[3]);
Antoine Pitrouab868312009-01-10 15:40:25 +00004417#if (SIZEOF_LONG == 8)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004418 WRITE_MAYBE_FAIL(_i+4, _s[4]);
4419 WRITE_MAYBE_FAIL(_i+5, _s[5]);
4420 WRITE_MAYBE_FAIL(_i+6, _s[6]);
4421 WRITE_MAYBE_FAIL(_i+7, _s[7]);
Antoine Pitrouab868312009-01-10 15:40:25 +00004422#endif
4423 _s += SIZEOF_LONG;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004424 _i += SIZEOF_LONG;
Antoine Pitrouab868312009-01-10 15:40:25 +00004425 }
4426 s = _s;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004427 i = _i;
Antoine Pitrouab868312009-01-10 15:40:25 +00004428 if (s == e)
4429 break;
4430 ch = (unsigned char)*s;
4431 }
4432 }
4433
4434 if (ch < 0x80) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004435 WRITE_MAYBE_FAIL(i++, ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004436 s++;
4437 continue;
4438 }
4439
4440 n = utf8_code_length[ch];
4441
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004442 if (s + n > e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004443 if (consumed)
4444 break;
4445 else {
4446 errmsg = "unexpected end of data";
4447 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004448 endinpos = startinpos+1;
4449 for (k=1; (k < size-startinpos) && ((s[k]&0xC0) == 0x80); k++)
4450 endinpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00004451 goto utf8Error;
4452 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00004453 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004454
4455 switch (n) {
4456
4457 case 0:
Ezio Melotti57221d02010-07-01 07:32:02 +00004458 errmsg = "invalid start byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004459 startinpos = s-starts;
4460 endinpos = startinpos+1;
4461 goto utf8Error;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004462
4463 case 1:
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004464 errmsg = "internal error";
Benjamin Peterson29060642009-01-31 22:14:21 +00004465 startinpos = s-starts;
4466 endinpos = startinpos+1;
4467 goto utf8Error;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004468
4469 case 2:
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004470 if ((s[1] & 0xc0) != 0x80) {
Ezio Melotti57221d02010-07-01 07:32:02 +00004471 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004472 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004473 endinpos = startinpos + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00004474 goto utf8Error;
4475 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004476 ch = ((s[0] & 0x1f) << 6) + (s[1] & 0x3f);
Ezio Melotti57221d02010-07-01 07:32:02 +00004477 assert ((ch > 0x007F) && (ch <= 0x07FF));
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004478 WRITE_MAYBE_FAIL(i++, ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004479 break;
4480
4481 case 3:
Ezio Melotti9bf2b3a2010-07-03 04:52:19 +00004482 /* Decoding UTF-8 sequences in range \xed\xa0\x80-\xed\xbf\xbf
4483 will result in surrogates in range d800-dfff. Surrogates are
4484 not valid UTF-8 so they are rejected.
4485 See http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf
4486 (table 3-7) and http://www.rfc-editor.org/rfc/rfc3629.txt */
Tim Petersced69f82003-09-16 20:30:58 +00004487 if ((s[1] & 0xc0) != 0x80 ||
Ezio Melotti57221d02010-07-01 07:32:02 +00004488 (s[2] & 0xc0) != 0x80 ||
4489 ((unsigned char)s[0] == 0xE0 &&
4490 (unsigned char)s[1] < 0xA0) ||
4491 ((unsigned char)s[0] == 0xED &&
4492 (unsigned char)s[1] > 0x9F)) {
4493 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004494 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004495 endinpos = startinpos + 1;
4496
4497 /* if s[1] first two bits are 1 and 0, then the invalid
4498 continuation byte is s[2], so increment endinpos by 1,
4499 if not, s[1] is invalid and endinpos doesn't need to
4500 be incremented. */
4501 if ((s[1] & 0xC0) == 0x80)
4502 endinpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00004503 goto utf8Error;
4504 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004505 ch = ((s[0] & 0x0f) << 12) + ((s[1] & 0x3f) << 6) + (s[2] & 0x3f);
Ezio Melotti57221d02010-07-01 07:32:02 +00004506 assert ((ch > 0x07FF) && (ch <= 0xFFFF));
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004507 WRITE_MAYBE_FAIL(i++, ch);
Marc-André Lemburge12896e2000-07-07 17:51:08 +00004508 break;
4509
4510 case 4:
4511 if ((s[1] & 0xc0) != 0x80 ||
4512 (s[2] & 0xc0) != 0x80 ||
Ezio Melotti57221d02010-07-01 07:32:02 +00004513 (s[3] & 0xc0) != 0x80 ||
4514 ((unsigned char)s[0] == 0xF0 &&
4515 (unsigned char)s[1] < 0x90) ||
4516 ((unsigned char)s[0] == 0xF4 &&
4517 (unsigned char)s[1] > 0x8F)) {
4518 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004519 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004520 endinpos = startinpos + 1;
4521 if ((s[1] & 0xC0) == 0x80) {
4522 endinpos++;
4523 if ((s[2] & 0xC0) == 0x80)
4524 endinpos++;
4525 }
Benjamin Peterson29060642009-01-31 22:14:21 +00004526 goto utf8Error;
4527 }
Marc-André Lemburge12896e2000-07-07 17:51:08 +00004528 ch = ((s[0] & 0x7) << 18) + ((s[1] & 0x3f) << 12) +
Ezio Melotti57221d02010-07-01 07:32:02 +00004529 ((s[2] & 0x3f) << 6) + (s[3] & 0x3f);
4530 assert ((ch > 0xFFFF) && (ch <= 0x10ffff));
4531
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004532 WRITE_MAYBE_FAIL(i++, ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004533 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004534 }
4535 s += n;
Benjamin Peterson29060642009-01-31 22:14:21 +00004536 continue;
Tim Petersced69f82003-09-16 20:30:58 +00004537
Benjamin Peterson29060642009-01-31 22:14:21 +00004538 utf8Error:
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004539 if (!has_errors) {
4540 PyObject *tmp;
4541 Py_ssize_t k;
4542 /* We encountered some error that wasn't detected in the original scan,
4543 e.g. an encoded surrogate character. The original maxchar computation may
4544 have been incorrect, so redo it now. */
4545 for (k = 0, maxchar = 0; k < i; k++)
4546 maxchar = Py_MAX(maxchar, PyUnicode_READ(kind, data, k));
4547 tmp = PyUnicode_New(PyUnicode_GET_LENGTH(unicode), maxchar);
4548 if (tmp == NULL)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004549 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004550 PyUnicode_CopyCharacters(tmp, 0, unicode, 0, i);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004551 Py_DECREF(unicode);
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004552 unicode = tmp;
4553 has_errors = 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004554 }
Benjamin Peterson29060642009-01-31 22:14:21 +00004555 if (unicode_decode_call_errorhandler(
4556 errors, &errorHandler,
4557 "utf8", errmsg,
4558 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004559 &unicode, &i))
Benjamin Peterson29060642009-01-31 22:14:21 +00004560 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004561 /* Update data because unicode_decode_call_errorhandler might have
4562 re-created or resized the unicode object. */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004563 data = PyUnicode_DATA(unicode);
4564 kind = PyUnicode_KIND(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00004565 aligned_end = (const char *) ((size_t) e & ~LONG_PTR_MASK);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004566 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004567 /* Ensure the unicode_size calculation above was correct: */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004568 assert(has_errors || i == unicode_size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004569
Walter Dörwald69652032004-09-07 20:24:22 +00004570 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00004571 *consumed = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004572
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004573 /* Adjust length and ready string when it contained errors and
4574 is of the old resizable kind. */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004575 if (has_errors) {
Victor Stinner7931d9a2011-11-04 00:22:48 +01004576 if (PyUnicode_Resize(&unicode, i) < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004577 goto onError;
4578 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004579
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004580 Py_XDECREF(errorHandler);
4581 Py_XDECREF(exc);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02004582 assert(_PyUnicode_CheckConsistency(unicode, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01004583 return unicode;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004584
Benjamin Peterson29060642009-01-31 22:14:21 +00004585 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004586 Py_XDECREF(errorHandler);
4587 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004588 Py_DECREF(unicode);
4589 return NULL;
4590}
4591
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004592#undef WRITE_MAYBE_FAIL
Antoine Pitrouab868312009-01-10 15:40:25 +00004593
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004594#ifdef __APPLE__
4595
4596/* Simplified UTF-8 decoder using surrogateescape error handler,
4597 used to decode the command line arguments on Mac OS X. */
4598
4599wchar_t*
4600_Py_DecodeUTF8_surrogateescape(const char *s, Py_ssize_t size)
4601{
4602 int n;
4603 const char *e;
4604 wchar_t *unicode, *p;
4605
4606 /* Note: size will always be longer than the resulting Unicode
4607 character count */
4608 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < (size + 1)) {
4609 PyErr_NoMemory();
4610 return NULL;
4611 }
4612 unicode = PyMem_Malloc((size + 1) * sizeof(wchar_t));
4613 if (!unicode)
4614 return NULL;
4615
4616 /* Unpack UTF-8 encoded data */
4617 p = unicode;
4618 e = s + size;
4619 while (s < e) {
4620 Py_UCS4 ch = (unsigned char)*s;
4621
4622 if (ch < 0x80) {
4623 *p++ = (wchar_t)ch;
4624 s++;
4625 continue;
4626 }
4627
4628 n = utf8_code_length[ch];
4629 if (s + n > e) {
4630 goto surrogateescape;
4631 }
4632
4633 switch (n) {
4634 case 0:
4635 case 1:
4636 goto surrogateescape;
4637
4638 case 2:
4639 if ((s[1] & 0xc0) != 0x80)
4640 goto surrogateescape;
4641 ch = ((s[0] & 0x1f) << 6) + (s[1] & 0x3f);
4642 assert ((ch > 0x007F) && (ch <= 0x07FF));
4643 *p++ = (wchar_t)ch;
4644 break;
4645
4646 case 3:
4647 /* Decoding UTF-8 sequences in range \xed\xa0\x80-\xed\xbf\xbf
4648 will result in surrogates in range d800-dfff. Surrogates are
4649 not valid UTF-8 so they are rejected.
4650 See http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf
4651 (table 3-7) and http://www.rfc-editor.org/rfc/rfc3629.txt */
4652 if ((s[1] & 0xc0) != 0x80 ||
4653 (s[2] & 0xc0) != 0x80 ||
4654 ((unsigned char)s[0] == 0xE0 &&
4655 (unsigned char)s[1] < 0xA0) ||
4656 ((unsigned char)s[0] == 0xED &&
4657 (unsigned char)s[1] > 0x9F)) {
4658
4659 goto surrogateescape;
4660 }
4661 ch = ((s[0] & 0x0f) << 12) + ((s[1] & 0x3f) << 6) + (s[2] & 0x3f);
4662 assert ((ch > 0x07FF) && (ch <= 0xFFFF));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004663 *p++ = (wchar_t)ch;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004664 break;
4665
4666 case 4:
4667 if ((s[1] & 0xc0) != 0x80 ||
4668 (s[2] & 0xc0) != 0x80 ||
4669 (s[3] & 0xc0) != 0x80 ||
4670 ((unsigned char)s[0] == 0xF0 &&
4671 (unsigned char)s[1] < 0x90) ||
4672 ((unsigned char)s[0] == 0xF4 &&
4673 (unsigned char)s[1] > 0x8F)) {
4674 goto surrogateescape;
4675 }
4676 ch = ((s[0] & 0x7) << 18) + ((s[1] & 0x3f) << 12) +
4677 ((s[2] & 0x3f) << 6) + (s[3] & 0x3f);
4678 assert ((ch > 0xFFFF) && (ch <= 0x10ffff));
4679
4680#if SIZEOF_WCHAR_T == 4
4681 *p++ = (wchar_t)ch;
4682#else
4683 /* compute and append the two surrogates: */
4684
4685 /* translate from 10000..10FFFF to 0..FFFF */
4686 ch -= 0x10000;
4687
4688 /* high surrogate = top 10 bits added to D800 */
4689 *p++ = (wchar_t)(0xD800 + (ch >> 10));
4690
4691 /* low surrogate = bottom 10 bits added to DC00 */
4692 *p++ = (wchar_t)(0xDC00 + (ch & 0x03FF));
4693#endif
4694 break;
4695 }
4696 s += n;
4697 continue;
4698
4699 surrogateescape:
4700 *p++ = 0xDC00 + ch;
4701 s++;
4702 }
4703 *p = L'\0';
4704 return unicode;
4705}
4706
4707#endif /* __APPLE__ */
Antoine Pitrouab868312009-01-10 15:40:25 +00004708
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004709/* Primary internal function which creates utf8 encoded bytes objects.
4710
4711 Allocation strategy: if the string is short, convert into a stack buffer
Tim Peters602f7402002-04-27 18:03:26 +00004712 and allocate exactly as much space needed at the end. Else allocate the
4713 maximum possible needed (4 result bytes per Unicode character), and return
4714 the excess memory at the end.
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004715*/
Tim Peters7e3d9612002-04-21 03:26:37 +00004716PyObject *
Victor Stinner7931d9a2011-11-04 00:22:48 +01004717_PyUnicode_AsUTF8String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004718{
Tim Peters602f7402002-04-27 18:03:26 +00004719#define MAX_SHORT_UNICHARS 300 /* largest size we'll do on the stack */
Tim Peters0eca65c2002-04-21 17:28:06 +00004720
Guido van Rossum98297ee2007-11-06 21:34:58 +00004721 Py_ssize_t i; /* index into s of next input byte */
4722 PyObject *result; /* result string object */
4723 char *p; /* next free byte in output buffer */
4724 Py_ssize_t nallocated; /* number of result bytes allocated */
4725 Py_ssize_t nneeded; /* number of result bytes needed */
Tim Peters602f7402002-04-27 18:03:26 +00004726 char stackbuf[MAX_SHORT_UNICHARS * 4];
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004727 PyObject *errorHandler = NULL;
4728 PyObject *exc = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004729 int kind;
4730 void *data;
4731 Py_ssize_t size;
Antoine Pitrou31b92a52011-11-12 18:35:19 +01004732 PyObject *rep = NULL;
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00004733
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004734 if (!PyUnicode_Check(unicode)) {
4735 PyErr_BadArgument();
4736 return NULL;
4737 }
4738
4739 if (PyUnicode_READY(unicode) == -1)
4740 return NULL;
4741
Victor Stinnere90fe6a2011-10-01 16:48:13 +02004742 if (PyUnicode_UTF8(unicode))
4743 return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode),
4744 PyUnicode_UTF8_LENGTH(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004745
4746 kind = PyUnicode_KIND(unicode);
4747 data = PyUnicode_DATA(unicode);
4748 size = PyUnicode_GET_LENGTH(unicode);
4749
Tim Peters602f7402002-04-27 18:03:26 +00004750 assert(size >= 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004751
Tim Peters602f7402002-04-27 18:03:26 +00004752 if (size <= MAX_SHORT_UNICHARS) {
4753 /* Write into the stack buffer; nallocated can't overflow.
4754 * At the end, we'll allocate exactly as much heap space as it
4755 * turns out we need.
4756 */
4757 nallocated = Py_SAFE_DOWNCAST(sizeof(stackbuf), size_t, int);
Guido van Rossum98297ee2007-11-06 21:34:58 +00004758 result = NULL; /* will allocate after we're done */
Tim Peters602f7402002-04-27 18:03:26 +00004759 p = stackbuf;
4760 }
4761 else {
4762 /* Overallocate on the heap, and give the excess back at the end. */
4763 nallocated = size * 4;
4764 if (nallocated / 4 != size) /* overflow! */
4765 return PyErr_NoMemory();
Christian Heimes72b710a2008-05-26 13:28:38 +00004766 result = PyBytes_FromStringAndSize(NULL, nallocated);
Guido van Rossum98297ee2007-11-06 21:34:58 +00004767 if (result == NULL)
Tim Peters602f7402002-04-27 18:03:26 +00004768 return NULL;
Christian Heimes72b710a2008-05-26 13:28:38 +00004769 p = PyBytes_AS_STRING(result);
Tim Peters602f7402002-04-27 18:03:26 +00004770 }
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004771
Tim Peters602f7402002-04-27 18:03:26 +00004772 for (i = 0; i < size;) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004773 Py_UCS4 ch = PyUnicode_READ(kind, data, i++);
Marc-André Lemburg3688a882002-02-06 18:09:02 +00004774
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004775 if (ch < 0x80)
Tim Peters602f7402002-04-27 18:03:26 +00004776 /* Encode ASCII */
Guido van Rossumd57fd912000-03-10 22:53:23 +00004777 *p++ = (char) ch;
Marc-André Lemburg3688a882002-02-06 18:09:02 +00004778
Guido van Rossumd57fd912000-03-10 22:53:23 +00004779 else if (ch < 0x0800) {
Tim Peters602f7402002-04-27 18:03:26 +00004780 /* Encode Latin-1 */
Marc-André Lemburgdc724d62002-02-06 18:20:19 +00004781 *p++ = (char)(0xc0 | (ch >> 6));
4782 *p++ = (char)(0x80 | (ch & 0x3f));
Victor Stinner31be90b2010-04-22 19:38:16 +00004783 } else if (0xD800 <= ch && ch <= 0xDFFF) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004784 Py_ssize_t newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004785 Py_ssize_t repsize, k, startpos;
4786 startpos = i-1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004787 rep = unicode_encode_call_errorhandler(
4788 errors, &errorHandler, "utf-8", "surrogates not allowed",
Victor Stinner7931d9a2011-11-04 00:22:48 +01004789 unicode, &exc, startpos, startpos+1, &newpos);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004790 if (!rep)
4791 goto error;
Victor Stinner31be90b2010-04-22 19:38:16 +00004792
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004793 if (PyBytes_Check(rep))
4794 repsize = PyBytes_GET_SIZE(rep);
4795 else
4796 repsize = PyUnicode_GET_SIZE(rep);
4797
4798 if (repsize > 4) {
4799 Py_ssize_t offset;
4800
4801 if (result == NULL)
4802 offset = p - stackbuf;
Victor Stinner31be90b2010-04-22 19:38:16 +00004803 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004804 offset = p - PyBytes_AS_STRING(result);
Victor Stinner31be90b2010-04-22 19:38:16 +00004805
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004806 if (nallocated > PY_SSIZE_T_MAX - repsize + 4) {
4807 /* integer overflow */
4808 PyErr_NoMemory();
4809 goto error;
4810 }
4811 nallocated += repsize - 4;
4812 if (result != NULL) {
4813 if (_PyBytes_Resize(&result, nallocated) < 0)
4814 goto error;
4815 } else {
4816 result = PyBytes_FromStringAndSize(NULL, nallocated);
Victor Stinner31be90b2010-04-22 19:38:16 +00004817 if (result == NULL)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004818 goto error;
4819 Py_MEMCPY(PyBytes_AS_STRING(result), stackbuf, offset);
4820 }
4821 p = PyBytes_AS_STRING(result) + offset;
4822 }
Victor Stinner31be90b2010-04-22 19:38:16 +00004823
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004824 if (PyBytes_Check(rep)) {
4825 char *prep = PyBytes_AS_STRING(rep);
4826 for(k = repsize; k > 0; k--)
4827 *p++ = *prep++;
4828 } else /* rep is unicode */ {
Victor Stinnera98b28c2011-11-10 20:21:49 +01004829 enum PyUnicode_Kind repkind;
4830 void *repdata;
4831
Antoine Pitrou31b92a52011-11-12 18:35:19 +01004832 if (PyUnicode_READY(rep) < 0)
Victor Stinnera98b28c2011-11-10 20:21:49 +01004833 goto error;
Victor Stinnera98b28c2011-11-10 20:21:49 +01004834 repkind = PyUnicode_KIND(rep);
4835 repdata = PyUnicode_DATA(rep);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004836
4837 for(k=0; k<repsize; k++) {
Victor Stinnera98b28c2011-11-10 20:21:49 +01004838 Py_UCS4 c = PyUnicode_READ(repkind, repdata, k);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004839 if (0x80 <= c) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01004840 raise_encode_exception(&exc, "utf-8",
Victor Stinner7931d9a2011-11-04 00:22:48 +01004841 unicode,
Martin v. Löwis9e816682011-11-02 12:45:42 +01004842 i-1, i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004843 "surrogates not allowed");
Victor Stinner31be90b2010-04-22 19:38:16 +00004844 goto error;
4845 }
Victor Stinnera98b28c2011-11-10 20:21:49 +01004846 *p++ = (char)c;
Victor Stinner31be90b2010-04-22 19:38:16 +00004847 }
Victor Stinner31be90b2010-04-22 19:38:16 +00004848 }
Antoine Pitrou31b92a52011-11-12 18:35:19 +01004849 Py_CLEAR(rep);
Victor Stinner31be90b2010-04-22 19:38:16 +00004850 } else if (ch < 0x10000) {
4851 *p++ = (char)(0xe0 | (ch >> 12));
4852 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
4853 *p++ = (char)(0x80 | (ch & 0x3f));
4854 } else /* ch >= 0x10000 */ {
Tim Peters602f7402002-04-27 18:03:26 +00004855 /* Encode UCS4 Unicode ordinals */
4856 *p++ = (char)(0xf0 | (ch >> 18));
4857 *p++ = (char)(0x80 | ((ch >> 12) & 0x3f));
4858 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
4859 *p++ = (char)(0x80 | (ch & 0x3f));
4860 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004861 }
Tim Peters0eca65c2002-04-21 17:28:06 +00004862
Guido van Rossum98297ee2007-11-06 21:34:58 +00004863 if (result == NULL) {
Tim Peters602f7402002-04-27 18:03:26 +00004864 /* This was stack allocated. */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004865 nneeded = p - stackbuf;
Tim Peters602f7402002-04-27 18:03:26 +00004866 assert(nneeded <= nallocated);
Christian Heimes72b710a2008-05-26 13:28:38 +00004867 result = PyBytes_FromStringAndSize(stackbuf, nneeded);
Tim Peters602f7402002-04-27 18:03:26 +00004868 }
4869 else {
Christian Heimesf3863112007-11-22 07:46:41 +00004870 /* Cut back to size actually needed. */
Christian Heimes72b710a2008-05-26 13:28:38 +00004871 nneeded = p - PyBytes_AS_STRING(result);
Tim Peters602f7402002-04-27 18:03:26 +00004872 assert(nneeded <= nallocated);
Christian Heimes72b710a2008-05-26 13:28:38 +00004873 _PyBytes_Resize(&result, nneeded);
Tim Peters602f7402002-04-27 18:03:26 +00004874 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004875
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004876 Py_XDECREF(errorHandler);
4877 Py_XDECREF(exc);
Guido van Rossum98297ee2007-11-06 21:34:58 +00004878 return result;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004879 error:
Antoine Pitrou31b92a52011-11-12 18:35:19 +01004880 Py_XDECREF(rep);
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004881 Py_XDECREF(errorHandler);
4882 Py_XDECREF(exc);
4883 Py_XDECREF(result);
4884 return NULL;
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004885
Tim Peters602f7402002-04-27 18:03:26 +00004886#undef MAX_SHORT_UNICHARS
Guido van Rossumd57fd912000-03-10 22:53:23 +00004887}
4888
Alexander Belopolsky40018472011-02-26 01:02:56 +00004889PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004890PyUnicode_EncodeUTF8(const Py_UNICODE *s,
4891 Py_ssize_t size,
4892 const char *errors)
4893{
4894 PyObject *v, *unicode;
4895
4896 unicode = PyUnicode_FromUnicode(s, size);
4897 if (unicode == NULL)
4898 return NULL;
4899 v = _PyUnicode_AsUTF8String(unicode, errors);
4900 Py_DECREF(unicode);
4901 return v;
4902}
4903
4904PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00004905PyUnicode_AsUTF8String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004906{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004907 return _PyUnicode_AsUTF8String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004908}
4909
Walter Dörwald41980ca2007-08-16 21:55:45 +00004910/* --- UTF-32 Codec ------------------------------------------------------- */
4911
4912PyObject *
4913PyUnicode_DecodeUTF32(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004914 Py_ssize_t size,
4915 const char *errors,
4916 int *byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004917{
4918 return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
4919}
4920
4921PyObject *
4922PyUnicode_DecodeUTF32Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004923 Py_ssize_t size,
4924 const char *errors,
4925 int *byteorder,
4926 Py_ssize_t *consumed)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004927{
4928 const char *starts = s;
4929 Py_ssize_t startinpos;
4930 Py_ssize_t endinpos;
4931 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01004932 PyObject *unicode;
Mark Dickinson7db923c2010-06-12 09:10:14 +00004933 const unsigned char *q, *e;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004934 int bo = 0; /* assume native ordering by default */
4935 const char *errmsg = "";
Walter Dörwald41980ca2007-08-16 21:55:45 +00004936 /* Offsets from q for retrieving bytes in the right order. */
4937#ifdef BYTEORDER_IS_LITTLE_ENDIAN
4938 int iorder[] = {0, 1, 2, 3};
4939#else
4940 int iorder[] = {3, 2, 1, 0};
4941#endif
4942 PyObject *errorHandler = NULL;
4943 PyObject *exc = NULL;
Victor Stinner313a1202010-06-11 23:56:51 +00004944
Walter Dörwald41980ca2007-08-16 21:55:45 +00004945 q = (unsigned char *)s;
4946 e = q + size;
4947
4948 if (byteorder)
4949 bo = *byteorder;
4950
4951 /* Check for BOM marks (U+FEFF) in the input and adjust current
4952 byte order setting accordingly. In native mode, the leading BOM
4953 mark is skipped, in all other modes, it is copied to the output
4954 stream as-is (giving a ZWNBSP character). */
4955 if (bo == 0) {
4956 if (size >= 4) {
4957 const Py_UCS4 bom = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
Benjamin Peterson29060642009-01-31 22:14:21 +00004958 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00004959#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Benjamin Peterson29060642009-01-31 22:14:21 +00004960 if (bom == 0x0000FEFF) {
4961 q += 4;
4962 bo = -1;
4963 }
4964 else if (bom == 0xFFFE0000) {
4965 q += 4;
4966 bo = 1;
4967 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004968#else
Benjamin Peterson29060642009-01-31 22:14:21 +00004969 if (bom == 0x0000FEFF) {
4970 q += 4;
4971 bo = 1;
4972 }
4973 else if (bom == 0xFFFE0000) {
4974 q += 4;
4975 bo = -1;
4976 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004977#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00004978 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004979 }
4980
4981 if (bo == -1) {
4982 /* force LE */
4983 iorder[0] = 0;
4984 iorder[1] = 1;
4985 iorder[2] = 2;
4986 iorder[3] = 3;
4987 }
4988 else if (bo == 1) {
4989 /* force BE */
4990 iorder[0] = 3;
4991 iorder[1] = 2;
4992 iorder[2] = 1;
4993 iorder[3] = 0;
4994 }
4995
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00004996 /* This might be one to much, because of a BOM */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004997 unicode = PyUnicode_New((size+3)/4, 127);
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00004998 if (!unicode)
4999 return NULL;
5000 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01005001 return unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005002 outpos = 0;
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005003
Walter Dörwald41980ca2007-08-16 21:55:45 +00005004 while (q < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005005 Py_UCS4 ch;
5006 /* remaining bytes at the end? (size should be divisible by 4) */
5007 if (e-q<4) {
5008 if (consumed)
5009 break;
5010 errmsg = "truncated data";
5011 startinpos = ((const char *)q)-starts;
5012 endinpos = ((const char *)e)-starts;
5013 goto utf32Error;
5014 /* The remaining input chars are ignored if the callback
5015 chooses to skip the input */
5016 }
5017 ch = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
5018 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00005019
Benjamin Peterson29060642009-01-31 22:14:21 +00005020 if (ch >= 0x110000)
5021 {
5022 errmsg = "codepoint not in range(0x110000)";
5023 startinpos = ((const char *)q)-starts;
5024 endinpos = startinpos+4;
5025 goto utf32Error;
5026 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005027 if (unicode_putchar(&unicode, &outpos, ch) < 0)
5028 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005029 q += 4;
5030 continue;
5031 utf32Error:
Benjamin Peterson29060642009-01-31 22:14:21 +00005032 if (unicode_decode_call_errorhandler(
5033 errors, &errorHandler,
5034 "utf32", errmsg,
5035 &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005036 &unicode, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00005037 goto onError;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005038 }
5039
5040 if (byteorder)
5041 *byteorder = bo;
5042
5043 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005044 *consumed = (const char *)q-starts;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005045
5046 /* Adjust length */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005047 if (PyUnicode_Resize(&unicode, outpos) < 0)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005048 goto onError;
5049
5050 Py_XDECREF(errorHandler);
5051 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02005052#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02005053 if (_PyUnicode_READY_REPLACE(&unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005054 Py_DECREF(unicode);
5055 return NULL;
5056 }
Victor Stinner17efeed2011-10-04 20:05:46 +02005057#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02005058 assert(_PyUnicode_CheckConsistency(unicode, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01005059 return unicode;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005060
Benjamin Peterson29060642009-01-31 22:14:21 +00005061 onError:
Walter Dörwald41980ca2007-08-16 21:55:45 +00005062 Py_DECREF(unicode);
5063 Py_XDECREF(errorHandler);
5064 Py_XDECREF(exc);
5065 return NULL;
5066}
5067
5068PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005069_PyUnicode_EncodeUTF32(PyObject *str,
5070 const char *errors,
5071 int byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005072{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005073 int kind;
5074 void *data;
5075 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005076 PyObject *v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005077 unsigned char *p;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005078 Py_ssize_t nsize, bytesize, i;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005079 /* Offsets from p for storing byte pairs in the right order. */
5080#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5081 int iorder[] = {0, 1, 2, 3};
5082#else
5083 int iorder[] = {3, 2, 1, 0};
5084#endif
5085
Benjamin Peterson29060642009-01-31 22:14:21 +00005086#define STORECHAR(CH) \
5087 do { \
5088 p[iorder[3]] = ((CH) >> 24) & 0xff; \
5089 p[iorder[2]] = ((CH) >> 16) & 0xff; \
5090 p[iorder[1]] = ((CH) >> 8) & 0xff; \
5091 p[iorder[0]] = (CH) & 0xff; \
5092 p += 4; \
Walter Dörwald41980ca2007-08-16 21:55:45 +00005093 } while(0)
5094
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005095 if (!PyUnicode_Check(str)) {
5096 PyErr_BadArgument();
5097 return NULL;
5098 }
5099 if (PyUnicode_READY(str) < 0)
5100 return NULL;
5101 kind = PyUnicode_KIND(str);
5102 data = PyUnicode_DATA(str);
5103 len = PyUnicode_GET_LENGTH(str);
5104
5105 nsize = len + (byteorder == 0);
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005106 bytesize = nsize * 4;
5107 if (bytesize / 4 != nsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005108 return PyErr_NoMemory();
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005109 v = PyBytes_FromStringAndSize(NULL, bytesize);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005110 if (v == NULL)
5111 return NULL;
5112
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005113 p = (unsigned char *)PyBytes_AS_STRING(v);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005114 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005115 STORECHAR(0xFEFF);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005116 if (len == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005117 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005118
5119 if (byteorder == -1) {
5120 /* force LE */
5121 iorder[0] = 0;
5122 iorder[1] = 1;
5123 iorder[2] = 2;
5124 iorder[3] = 3;
5125 }
5126 else if (byteorder == 1) {
5127 /* force BE */
5128 iorder[0] = 3;
5129 iorder[1] = 2;
5130 iorder[2] = 1;
5131 iorder[3] = 0;
5132 }
5133
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005134 for (i = 0; i < len; i++)
5135 STORECHAR(PyUnicode_READ(kind, data, i));
Guido van Rossum98297ee2007-11-06 21:34:58 +00005136
5137 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005138 return v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005139#undef STORECHAR
5140}
5141
Alexander Belopolsky40018472011-02-26 01:02:56 +00005142PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005143PyUnicode_EncodeUTF32(const Py_UNICODE *s,
5144 Py_ssize_t size,
5145 const char *errors,
5146 int byteorder)
5147{
5148 PyObject *result;
5149 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5150 if (tmp == NULL)
5151 return NULL;
5152 result = _PyUnicode_EncodeUTF32(tmp, errors, byteorder);
5153 Py_DECREF(tmp);
5154 return result;
5155}
5156
5157PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005158PyUnicode_AsUTF32String(PyObject *unicode)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005159{
Victor Stinner1f795172011-11-17 00:45:54 +01005160 const Py_UNICODE *wstr;
5161 Py_ssize_t wlen;
5162 wstr = PyUnicode_AsUnicodeAndSize(unicode, &wlen);
5163 if (wstr == NULL)
5164 return NULL;
5165 return PyUnicode_EncodeUTF32(wstr, wlen, NULL, 0);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005166}
5167
Guido van Rossumd57fd912000-03-10 22:53:23 +00005168/* --- UTF-16 Codec ------------------------------------------------------- */
5169
Tim Peters772747b2001-08-09 22:21:55 +00005170PyObject *
5171PyUnicode_DecodeUTF16(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005172 Py_ssize_t size,
5173 const char *errors,
5174 int *byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005175{
Walter Dörwald69652032004-09-07 20:24:22 +00005176 return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
5177}
5178
Antoine Pitrouab868312009-01-10 15:40:25 +00005179/* Two masks for fast checking of whether a C 'long' may contain
5180 UTF16-encoded surrogate characters. This is an efficient heuristic,
5181 assuming that non-surrogate characters with a code point >= 0x8000 are
5182 rare in most input.
5183 FAST_CHAR_MASK is used when the input is in native byte ordering,
5184 SWAPPED_FAST_CHAR_MASK when the input is in byteswapped ordering.
Benjamin Peterson29060642009-01-31 22:14:21 +00005185*/
Antoine Pitrouab868312009-01-10 15:40:25 +00005186#if (SIZEOF_LONG == 8)
5187# define FAST_CHAR_MASK 0x8000800080008000L
5188# define SWAPPED_FAST_CHAR_MASK 0x0080008000800080L
5189#elif (SIZEOF_LONG == 4)
5190# define FAST_CHAR_MASK 0x80008000L
5191# define SWAPPED_FAST_CHAR_MASK 0x00800080L
5192#else
5193# error C 'long' size should be either 4 or 8!
5194#endif
5195
Walter Dörwald69652032004-09-07 20:24:22 +00005196PyObject *
5197PyUnicode_DecodeUTF16Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005198 Py_ssize_t size,
5199 const char *errors,
5200 int *byteorder,
5201 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00005202{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005203 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005204 Py_ssize_t startinpos;
5205 Py_ssize_t endinpos;
5206 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01005207 PyObject *unicode;
Antoine Pitrouab868312009-01-10 15:40:25 +00005208 const unsigned char *q, *e, *aligned_end;
Tim Peters772747b2001-08-09 22:21:55 +00005209 int bo = 0; /* assume native ordering by default */
Antoine Pitrouab868312009-01-10 15:40:25 +00005210 int native_ordering = 0;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00005211 const char *errmsg = "";
Tim Peters772747b2001-08-09 22:21:55 +00005212 /* Offsets from q for retrieving byte pairs in the right order. */
5213#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5214 int ihi = 1, ilo = 0;
5215#else
5216 int ihi = 0, ilo = 1;
5217#endif
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005218 PyObject *errorHandler = NULL;
5219 PyObject *exc = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005220
5221 /* Note: size will always be longer than the resulting Unicode
5222 character count */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005223 unicode = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005224 if (!unicode)
5225 return NULL;
5226 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01005227 return unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005228 outpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005229
Tim Peters772747b2001-08-09 22:21:55 +00005230 q = (unsigned char *)s;
Antoine Pitrouab868312009-01-10 15:40:25 +00005231 e = q + size - 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005232
5233 if (byteorder)
Tim Peters772747b2001-08-09 22:21:55 +00005234 bo = *byteorder;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005235
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005236 /* Check for BOM marks (U+FEFF) in the input and adjust current
5237 byte order setting accordingly. In native mode, the leading BOM
5238 mark is skipped, in all other modes, it is copied to the output
5239 stream as-is (giving a ZWNBSP character). */
5240 if (bo == 0) {
Walter Dörwald69652032004-09-07 20:24:22 +00005241 if (size >= 2) {
Victor Stinner24729f32011-11-10 20:31:37 +01005242 const Py_UCS4 bom = (q[ihi] << 8) | q[ilo];
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005243#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Benjamin Peterson29060642009-01-31 22:14:21 +00005244 if (bom == 0xFEFF) {
5245 q += 2;
5246 bo = -1;
5247 }
5248 else if (bom == 0xFFFE) {
5249 q += 2;
5250 bo = 1;
5251 }
Tim Petersced69f82003-09-16 20:30:58 +00005252#else
Benjamin Peterson29060642009-01-31 22:14:21 +00005253 if (bom == 0xFEFF) {
5254 q += 2;
5255 bo = 1;
5256 }
5257 else if (bom == 0xFFFE) {
5258 q += 2;
5259 bo = -1;
5260 }
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005261#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00005262 }
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005263 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005264
Tim Peters772747b2001-08-09 22:21:55 +00005265 if (bo == -1) {
5266 /* force LE */
5267 ihi = 1;
5268 ilo = 0;
5269 }
5270 else if (bo == 1) {
5271 /* force BE */
5272 ihi = 0;
5273 ilo = 1;
5274 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005275#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5276 native_ordering = ilo < ihi;
5277#else
5278 native_ordering = ilo > ihi;
5279#endif
Tim Peters772747b2001-08-09 22:21:55 +00005280
Antoine Pitrouab868312009-01-10 15:40:25 +00005281 aligned_end = (const unsigned char *) ((size_t) e & ~LONG_PTR_MASK);
Tim Peters772747b2001-08-09 22:21:55 +00005282 while (q < e) {
Victor Stinner24729f32011-11-10 20:31:37 +01005283 Py_UCS4 ch;
Antoine Pitrouab868312009-01-10 15:40:25 +00005284 /* First check for possible aligned read of a C 'long'. Unaligned
5285 reads are more expensive, better to defer to another iteration. */
5286 if (!((size_t) q & LONG_PTR_MASK)) {
5287 /* Fast path for runs of non-surrogate chars. */
5288 register const unsigned char *_q = q;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005289 int kind = PyUnicode_KIND(unicode);
5290 void *data = PyUnicode_DATA(unicode);
5291 while (_q < aligned_end) {
5292 unsigned long block = * (unsigned long *) _q;
5293 unsigned short *pblock = (unsigned short*)&block;
5294 Py_UCS4 maxch;
5295 if (native_ordering) {
5296 /* Can use buffer directly */
5297 if (block & FAST_CHAR_MASK)
Antoine Pitrouab868312009-01-10 15:40:25 +00005298 break;
Antoine Pitrouab868312009-01-10 15:40:25 +00005299 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005300 else {
5301 /* Need to byte-swap */
5302 unsigned char *_p = (unsigned char*)pblock;
5303 if (block & SWAPPED_FAST_CHAR_MASK)
Antoine Pitrouab868312009-01-10 15:40:25 +00005304 break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005305 _p[0] = _q[1];
5306 _p[1] = _q[0];
5307 _p[2] = _q[3];
5308 _p[3] = _q[2];
Antoine Pitrouab868312009-01-10 15:40:25 +00005309#if (SIZEOF_LONG == 8)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005310 _p[4] = _q[5];
5311 _p[5] = _q[4];
5312 _p[6] = _q[7];
5313 _p[7] = _q[6];
Antoine Pitrouab868312009-01-10 15:40:25 +00005314#endif
Antoine Pitrouab868312009-01-10 15:40:25 +00005315 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005316 maxch = Py_MAX(pblock[0], pblock[1]);
5317#if SIZEOF_LONG == 8
5318 maxch = Py_MAX(maxch, Py_MAX(pblock[2], pblock[3]));
5319#endif
5320 if (maxch > PyUnicode_MAX_CHAR_VALUE(unicode)) {
5321 if (unicode_widen(&unicode, maxch) < 0)
5322 goto onError;
5323 kind = PyUnicode_KIND(unicode);
5324 data = PyUnicode_DATA(unicode);
5325 }
5326 PyUnicode_WRITE(kind, data, outpos++, pblock[0]);
5327 PyUnicode_WRITE(kind, data, outpos++, pblock[1]);
5328#if SIZEOF_LONG == 8
5329 PyUnicode_WRITE(kind, data, outpos++, pblock[2]);
5330 PyUnicode_WRITE(kind, data, outpos++, pblock[3]);
5331#endif
5332 _q += SIZEOF_LONG;
Antoine Pitrouab868312009-01-10 15:40:25 +00005333 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005334 q = _q;
5335 if (q >= e)
5336 break;
5337 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005338 ch = (q[ihi] << 8) | q[ilo];
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005339
Benjamin Peterson14339b62009-01-31 16:36:08 +00005340 q += 2;
Benjamin Peterson29060642009-01-31 22:14:21 +00005341
5342 if (ch < 0xD800 || ch > 0xDFFF) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005343 if (unicode_putchar(&unicode, &outpos, ch) < 0)
5344 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005345 continue;
5346 }
5347
5348 /* UTF-16 code pair: */
5349 if (q > e) {
5350 errmsg = "unexpected end of data";
5351 startinpos = (((const char *)q) - 2) - starts;
5352 endinpos = ((const char *)e) + 1 - starts;
5353 goto utf16Error;
5354 }
5355 if (0xD800 <= ch && ch <= 0xDBFF) {
5356 Py_UNICODE ch2 = (q[ihi] << 8) | q[ilo];
5357 q += 2;
5358 if (0xDC00 <= ch2 && ch2 <= 0xDFFF) {
Victor Stinner62aa4d02011-11-09 00:03:45 +01005359 if (unicode_putchar(&unicode, &outpos,
5360 (((ch & 0x3FF)<<10) |
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005361 (ch2 & 0x3FF)) + 0x10000) < 0)
5362 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005363 continue;
5364 }
5365 else {
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005366 errmsg = "illegal UTF-16 surrogate";
Benjamin Peterson29060642009-01-31 22:14:21 +00005367 startinpos = (((const char *)q)-4)-starts;
5368 endinpos = startinpos+2;
5369 goto utf16Error;
5370 }
5371
Benjamin Peterson14339b62009-01-31 16:36:08 +00005372 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005373 errmsg = "illegal encoding";
5374 startinpos = (((const char *)q)-2)-starts;
5375 endinpos = startinpos+2;
5376 /* Fall through to report the error */
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005377
Benjamin Peterson29060642009-01-31 22:14:21 +00005378 utf16Error:
Benjamin Peterson29060642009-01-31 22:14:21 +00005379 if (unicode_decode_call_errorhandler(
Antoine Pitrouab868312009-01-10 15:40:25 +00005380 errors,
5381 &errorHandler,
5382 "utf16", errmsg,
5383 &starts,
5384 (const char **)&e,
5385 &startinpos,
5386 &endinpos,
5387 &exc,
5388 (const char **)&q,
5389 &unicode,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005390 &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00005391 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005392 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005393 /* remaining byte at the end? (size should be even) */
5394 if (e == q) {
5395 if (!consumed) {
5396 errmsg = "truncated data";
5397 startinpos = ((const char *)q) - starts;
5398 endinpos = ((const char *)e) + 1 - starts;
Antoine Pitrouab868312009-01-10 15:40:25 +00005399 if (unicode_decode_call_errorhandler(
5400 errors,
5401 &errorHandler,
5402 "utf16", errmsg,
5403 &starts,
5404 (const char **)&e,
5405 &startinpos,
5406 &endinpos,
5407 &exc,
5408 (const char **)&q,
5409 &unicode,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005410 &outpos))
Antoine Pitrouab868312009-01-10 15:40:25 +00005411 goto onError;
5412 /* The remaining input chars are ignored if the callback
5413 chooses to skip the input */
5414 }
5415 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005416
5417 if (byteorder)
5418 *byteorder = bo;
5419
Walter Dörwald69652032004-09-07 20:24:22 +00005420 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005421 *consumed = (const char *)q-starts;
Walter Dörwald69652032004-09-07 20:24:22 +00005422
Guido van Rossumd57fd912000-03-10 22:53:23 +00005423 /* Adjust length */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005424 if (PyUnicode_Resize(&unicode, outpos) < 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005425 goto onError;
5426
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005427 Py_XDECREF(errorHandler);
5428 Py_XDECREF(exc);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02005429 assert(_PyUnicode_CheckConsistency(unicode, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01005430 return unicode;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005431
Benjamin Peterson29060642009-01-31 22:14:21 +00005432 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00005433 Py_DECREF(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005434 Py_XDECREF(errorHandler);
5435 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005436 return NULL;
5437}
5438
Antoine Pitrouab868312009-01-10 15:40:25 +00005439#undef FAST_CHAR_MASK
5440#undef SWAPPED_FAST_CHAR_MASK
5441
Tim Peters772747b2001-08-09 22:21:55 +00005442PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005443_PyUnicode_EncodeUTF16(PyObject *str,
5444 const char *errors,
5445 int byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005446{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005447 int kind;
5448 void *data;
5449 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005450 PyObject *v;
Tim Peters772747b2001-08-09 22:21:55 +00005451 unsigned char *p;
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005452 Py_ssize_t nsize, bytesize;
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005453 Py_ssize_t i, pairs;
Tim Peters772747b2001-08-09 22:21:55 +00005454 /* Offsets from p for storing byte pairs in the right order. */
5455#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5456 int ihi = 1, ilo = 0;
5457#else
5458 int ihi = 0, ilo = 1;
5459#endif
5460
Benjamin Peterson29060642009-01-31 22:14:21 +00005461#define STORECHAR(CH) \
5462 do { \
5463 p[ihi] = ((CH) >> 8) & 0xff; \
5464 p[ilo] = (CH) & 0xff; \
5465 p += 2; \
Tim Peters772747b2001-08-09 22:21:55 +00005466 } while(0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005467
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005468 if (!PyUnicode_Check(str)) {
5469 PyErr_BadArgument();
5470 return NULL;
5471 }
5472 if (PyUnicode_READY(str) < 0)
5473 return NULL;
5474 kind = PyUnicode_KIND(str);
5475 data = PyUnicode_DATA(str);
5476 len = PyUnicode_GET_LENGTH(str);
Victor Stinner0e368262011-11-10 20:12:49 +01005477
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005478 pairs = 0;
5479 if (kind == PyUnicode_4BYTE_KIND)
5480 for (i = 0; i < len; i++)
5481 if (PyUnicode_READ(kind, data, i) >= 0x10000)
5482 pairs++;
5483 /* 2 * (len + pairs + (byteorder == 0)) */
5484 if (len > PY_SSIZE_T_MAX - pairs - (byteorder == 0))
Benjamin Peterson29060642009-01-31 22:14:21 +00005485 return PyErr_NoMemory();
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005486 nsize = len + pairs + (byteorder == 0);
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005487 bytesize = nsize * 2;
5488 if (bytesize / 2 != nsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005489 return PyErr_NoMemory();
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005490 v = PyBytes_FromStringAndSize(NULL, bytesize);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005491 if (v == NULL)
5492 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005493
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005494 p = (unsigned char *)PyBytes_AS_STRING(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005495 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005496 STORECHAR(0xFEFF);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005497 if (len == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005498 goto done;
Tim Peters772747b2001-08-09 22:21:55 +00005499
5500 if (byteorder == -1) {
5501 /* force LE */
5502 ihi = 1;
5503 ilo = 0;
5504 }
5505 else if (byteorder == 1) {
5506 /* force BE */
5507 ihi = 0;
5508 ilo = 1;
5509 }
5510
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005511 for (i = 0; i < len; i++) {
5512 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
5513 Py_UCS4 ch2 = 0;
Benjamin Peterson29060642009-01-31 22:14:21 +00005514 if (ch >= 0x10000) {
5515 ch2 = 0xDC00 | ((ch-0x10000) & 0x3FF);
5516 ch = 0xD800 | ((ch-0x10000) >> 10);
5517 }
Tim Peters772747b2001-08-09 22:21:55 +00005518 STORECHAR(ch);
5519 if (ch2)
5520 STORECHAR(ch2);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005521 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005522
5523 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005524 return v;
Tim Peters772747b2001-08-09 22:21:55 +00005525#undef STORECHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00005526}
5527
Alexander Belopolsky40018472011-02-26 01:02:56 +00005528PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005529PyUnicode_EncodeUTF16(const Py_UNICODE *s,
5530 Py_ssize_t size,
5531 const char *errors,
5532 int byteorder)
5533{
5534 PyObject *result;
5535 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5536 if (tmp == NULL)
5537 return NULL;
5538 result = _PyUnicode_EncodeUTF16(tmp, errors, byteorder);
5539 Py_DECREF(tmp);
5540 return result;
5541}
5542
5543PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005544PyUnicode_AsUTF16String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005545{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005546 return _PyUnicode_EncodeUTF16(unicode, NULL, 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005547}
5548
5549/* --- Unicode Escape Codec ----------------------------------------------- */
5550
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005551/* Helper function for PyUnicode_DecodeUnicodeEscape, determines
5552 if all the escapes in the string make it still a valid ASCII string.
5553 Returns -1 if any escapes were found which cause the string to
5554 pop out of ASCII range. Otherwise returns the length of the
5555 required buffer to hold the string.
5556 */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02005557static Py_ssize_t
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005558length_of_escaped_ascii_string(const char *s, Py_ssize_t size)
5559{
5560 const unsigned char *p = (const unsigned char *)s;
5561 const unsigned char *end = p + size;
5562 Py_ssize_t length = 0;
5563
5564 if (size < 0)
5565 return -1;
5566
5567 for (; p < end; ++p) {
5568 if (*p > 127) {
5569 /* Non-ASCII */
5570 return -1;
5571 }
5572 else if (*p != '\\') {
5573 /* Normal character */
5574 ++length;
5575 }
5576 else {
5577 /* Backslash-escape, check next char */
5578 ++p;
5579 /* Escape sequence reaches till end of string or
5580 non-ASCII follow-up. */
5581 if (p >= end || *p > 127)
5582 return -1;
5583 switch (*p) {
5584 case '\n':
5585 /* backslash + \n result in zero characters */
5586 break;
5587 case '\\': case '\'': case '\"':
5588 case 'b': case 'f': case 't':
5589 case 'n': case 'r': case 'v': case 'a':
5590 ++length;
5591 break;
5592 case '0': case '1': case '2': case '3':
5593 case '4': case '5': case '6': case '7':
5594 case 'x': case 'u': case 'U': case 'N':
5595 /* these do not guarantee ASCII characters */
5596 return -1;
5597 default:
5598 /* count the backslash + the other character */
5599 length += 2;
5600 }
5601 }
5602 }
5603 return length;
5604}
5605
5606/* Similar to PyUnicode_WRITE but either write into wstr field
5607 or treat string as ASCII. */
5608#define WRITE_ASCII_OR_WSTR(kind, buf, index, value) \
5609 do { \
5610 if ((kind) != PyUnicode_WCHAR_KIND) \
5611 ((unsigned char *)(buf))[(index)] = (unsigned char)(value); \
5612 else \
5613 ((Py_UNICODE *)(buf))[(index)] = (Py_UNICODE)(value); \
5614 } while (0)
5615
5616#define WRITE_WSTR(buf, index, value) \
5617 assert(kind == PyUnicode_WCHAR_KIND), \
5618 ((Py_UNICODE *)(buf))[(index)] = (Py_UNICODE)(value)
5619
5620
Fredrik Lundh06d12682001-01-24 07:59:11 +00005621static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
Marc-André Lemburg0f774e32000-06-28 16:43:35 +00005622
Alexander Belopolsky40018472011-02-26 01:02:56 +00005623PyObject *
5624PyUnicode_DecodeUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005625 Py_ssize_t size,
Victor Stinnerc17f5402011-09-29 00:16:58 +02005626 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005627{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005628 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005629 Py_ssize_t startinpos;
5630 Py_ssize_t endinpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005631 int j;
Victor Stinner7931d9a2011-11-04 00:22:48 +01005632 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005633 const char *end;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005634 char* message;
5635 Py_UCS4 chr = 0xffffffff; /* in case 'getcode' messes up */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005636 PyObject *errorHandler = NULL;
5637 PyObject *exc = NULL;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005638 Py_ssize_t len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005639 Py_ssize_t i;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005640
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005641 len = length_of_escaped_ascii_string(s, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005642
5643 /* After length_of_escaped_ascii_string() there are two alternatives,
5644 either the string is pure ASCII with named escapes like \n, etc.
5645 and we determined it's exact size (common case)
5646 or it contains \x, \u, ... escape sequences. then we create a
5647 legacy wchar string and resize it at the end of this function. */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005648 if (len >= 0) {
5649 v = PyUnicode_New(len, 127);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005650 if (!v)
5651 goto onError;
5652 assert(PyUnicode_KIND(v) == PyUnicode_1BYTE_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005653 }
5654 else {
5655 /* Escaped strings will always be longer than the resulting
5656 Unicode string, so we start with size here and then reduce the
5657 length after conversion to the true value.
5658 (but if the error callback returns a long replacement string
5659 we'll have to allocate more space) */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005660 v = PyUnicode_New(size, 127);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005661 if (!v)
5662 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005663 len = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005664 }
5665
Guido van Rossumd57fd912000-03-10 22:53:23 +00005666 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01005667 return v;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005668 i = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005669 end = s + size;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005670
Guido van Rossumd57fd912000-03-10 22:53:23 +00005671 while (s < end) {
5672 unsigned char c;
Victor Stinner24729f32011-11-10 20:31:37 +01005673 Py_UCS4 x;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005674 int digits;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005675
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005676 /* The only case in which i == ascii_length is a backslash
5677 followed by a newline. */
5678 assert(i <= len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005679
Guido van Rossumd57fd912000-03-10 22:53:23 +00005680 /* Non-escape characters are interpreted as Unicode ordinals */
5681 if (*s != '\\') {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005682 if (unicode_putchar(&v, &i, (unsigned char) *s++) < 0)
5683 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005684 continue;
5685 }
5686
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005687 startinpos = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005688 /* \ - Escapes */
5689 s++;
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005690 c = *s++;
5691 if (s > end)
5692 c = '\0'; /* Invalid after \ */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005693
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005694 /* The only case in which i == ascii_length is a backslash
5695 followed by a newline. */
5696 assert(i < len || (i == len && c == '\n'));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005697
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005698 switch (c) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005699
Benjamin Peterson29060642009-01-31 22:14:21 +00005700 /* \x escapes */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005701#define WRITECHAR(ch) \
5702 do { \
5703 if (unicode_putchar(&v, &i, ch) < 0) \
5704 goto onError; \
5705 }while(0)
5706
Guido van Rossumd57fd912000-03-10 22:53:23 +00005707 case '\n': break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005708 case '\\': WRITECHAR('\\'); break;
5709 case '\'': WRITECHAR('\''); break;
5710 case '\"': WRITECHAR('\"'); break;
5711 case 'b': WRITECHAR('\b'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005712 /* FF */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005713 case 'f': WRITECHAR('\014'); break;
5714 case 't': WRITECHAR('\t'); break;
5715 case 'n': WRITECHAR('\n'); break;
5716 case 'r': WRITECHAR('\r'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005717 /* VT */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005718 case 'v': WRITECHAR('\013'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005719 /* BEL, not classic C */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005720 case 'a': WRITECHAR('\007'); break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005721
Benjamin Peterson29060642009-01-31 22:14:21 +00005722 /* \OOO (octal) escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005723 case '0': case '1': case '2': case '3':
5724 case '4': case '5': case '6': case '7':
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005725 x = s[-1] - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005726 if (s < end && '0' <= *s && *s <= '7') {
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005727 x = (x<<3) + *s++ - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005728 if (s < end && '0' <= *s && *s <= '7')
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005729 x = (x<<3) + *s++ - '0';
Guido van Rossumd57fd912000-03-10 22:53:23 +00005730 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005731 WRITECHAR(x);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005732 break;
5733
Benjamin Peterson29060642009-01-31 22:14:21 +00005734 /* hex escapes */
5735 /* \xXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005736 case 'x':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005737 digits = 2;
5738 message = "truncated \\xXX escape";
5739 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005740
Benjamin Peterson29060642009-01-31 22:14:21 +00005741 /* \uXXXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005742 case 'u':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005743 digits = 4;
5744 message = "truncated \\uXXXX escape";
5745 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005746
Benjamin Peterson29060642009-01-31 22:14:21 +00005747 /* \UXXXXXXXX */
Fredrik Lundhdf846752000-09-03 11:29:49 +00005748 case 'U':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005749 digits = 8;
5750 message = "truncated \\UXXXXXXXX escape";
5751 hexescape:
5752 chr = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005753 if (s+digits>end) {
5754 endinpos = size;
5755 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005756 errors, &errorHandler,
5757 "unicodeescape", "end of string in escape sequence",
5758 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005759 &v, &i))
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005760 goto onError;
5761 goto nextByte;
5762 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005763 for (j = 0; j < digits; ++j) {
5764 c = (unsigned char) s[j];
David Malcolm96960882010-11-05 17:23:41 +00005765 if (!Py_ISXDIGIT(c)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005766 endinpos = (s+j+1)-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005767 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005768 errors, &errorHandler,
5769 "unicodeescape", message,
5770 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005771 &v, &i))
Fredrik Lundhdf846752000-09-03 11:29:49 +00005772 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005773 len = PyUnicode_GET_LENGTH(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005774 goto nextByte;
Fredrik Lundhdf846752000-09-03 11:29:49 +00005775 }
5776 chr = (chr<<4) & ~0xF;
5777 if (c >= '0' && c <= '9')
5778 chr += c - '0';
5779 else if (c >= 'a' && c <= 'f')
5780 chr += 10 + c - 'a';
5781 else
5782 chr += 10 + c - 'A';
5783 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005784 s += j;
Jeremy Hylton504de6b2003-10-06 05:08:26 +00005785 if (chr == 0xffffffff && PyErr_Occurred())
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005786 /* _decoding_error will have already written into the
5787 target buffer. */
5788 break;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005789 store:
Fredrik Lundhdf846752000-09-03 11:29:49 +00005790 /* when we get here, chr is a 32-bit unicode character */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005791 if (chr <= 0x10ffff) {
5792 WRITECHAR(chr);
Fredrik Lundhdf846752000-09-03 11:29:49 +00005793 } else {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005794 endinpos = s-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005795 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005796 errors, &errorHandler,
5797 "unicodeescape", "illegal Unicode character",
5798 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005799 &v, &i))
Fredrik Lundhdf846752000-09-03 11:29:49 +00005800 goto onError;
5801 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00005802 break;
5803
Benjamin Peterson29060642009-01-31 22:14:21 +00005804 /* \N{name} */
Fredrik Lundhccc74732001-02-18 22:13:49 +00005805 case 'N':
5806 message = "malformed \\N character escape";
5807 if (ucnhash_CAPI == NULL) {
5808 /* load the unicode data module */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005809 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
5810 PyUnicodeData_CAPSULE_NAME, 1);
Fredrik Lundhccc74732001-02-18 22:13:49 +00005811 if (ucnhash_CAPI == NULL)
5812 goto ucnhashError;
5813 }
5814 if (*s == '{') {
5815 const char *start = s+1;
5816 /* look for the closing brace */
5817 while (*s != '}' && s < end)
5818 s++;
5819 if (s > start && s < end && *s == '}') {
5820 /* found a name. look it up in the unicode database */
5821 message = "unknown Unicode character name";
5822 s++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005823 if (ucnhash_CAPI->getcode(NULL, start, (int)(s-start-1),
Ezio Melotti931b8aa2011-10-21 21:57:36 +03005824 &chr, 0))
Fredrik Lundhccc74732001-02-18 22:13:49 +00005825 goto store;
5826 }
5827 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005828 endinpos = s-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005829 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005830 errors, &errorHandler,
5831 "unicodeescape", message,
5832 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005833 &v, &i))
Fredrik Lundhccc74732001-02-18 22:13:49 +00005834 goto onError;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005835 break;
5836
5837 default:
Walter Dörwald8c077222002-03-25 11:16:18 +00005838 if (s > end) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005839 message = "\\ at end of string";
5840 s--;
5841 endinpos = s-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005842 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005843 errors, &errorHandler,
5844 "unicodeescape", message,
5845 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005846 &v, &i))
Walter Dörwald8c077222002-03-25 11:16:18 +00005847 goto onError;
5848 }
5849 else {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005850 WRITECHAR('\\');
5851 WRITECHAR(s[-1]);
Walter Dörwald8c077222002-03-25 11:16:18 +00005852 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00005853 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005854 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005855 nextByte:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005856 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005857 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005858#undef WRITECHAR
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005859
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005860 if (PyUnicode_Resize(&v, i) < 0)
5861 goto onError;
Walter Dörwaldd4ade082003-08-15 15:00:26 +00005862 Py_XDECREF(errorHandler);
5863 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02005864#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02005865 if (_PyUnicode_READY_REPLACE(&v)) {
5866 Py_DECREF(v);
5867 return NULL;
5868 }
Victor Stinner17efeed2011-10-04 20:05:46 +02005869#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02005870 assert(_PyUnicode_CheckConsistency(v, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01005871 return v;
Walter Dörwald8c077222002-03-25 11:16:18 +00005872
Benjamin Peterson29060642009-01-31 22:14:21 +00005873 ucnhashError:
Fredrik Lundh06d12682001-01-24 07:59:11 +00005874 PyErr_SetString(
5875 PyExc_UnicodeError,
5876 "\\N escapes not supported (can't load unicodedata module)"
5877 );
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00005878 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005879 Py_XDECREF(errorHandler);
5880 Py_XDECREF(exc);
Fredrik Lundhf6056062001-01-20 11:15:25 +00005881 return NULL;
5882
Benjamin Peterson29060642009-01-31 22:14:21 +00005883 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00005884 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005885 Py_XDECREF(errorHandler);
5886 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005887 return NULL;
5888}
5889
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005890#undef WRITE_ASCII_OR_WSTR
5891#undef WRITE_WSTR
5892
Guido van Rossumd57fd912000-03-10 22:53:23 +00005893/* Return a Unicode-Escape string version of the Unicode object.
5894
5895 If quotes is true, the string is enclosed in u"" or u'' quotes as
5896 appropriate.
5897
5898*/
5899
Alexander Belopolsky40018472011-02-26 01:02:56 +00005900PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005901PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005902{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005903 Py_ssize_t i, len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005904 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005905 char *p;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005906 int kind;
5907 void *data;
5908 Py_ssize_t expandsize = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005909
Thomas Wouters89f507f2006-12-13 04:49:30 +00005910 /* Initial allocation is based on the longest-possible unichr
5911 escape.
5912
5913 In wide (UTF-32) builds '\U00xxxxxx' is 10 chars per source
5914 unichr, so in this case it's the longest unichr escape. In
5915 narrow (UTF-16) builds this is five chars per source unichr
5916 since there are two unichrs in the surrogate pair, so in narrow
5917 (UTF-16) builds it's not the longest unichr escape.
5918
5919 In wide or narrow builds '\uxxxx' is 6 chars per source unichr,
5920 so in the narrow (UTF-16) build case it's the longest unichr
5921 escape.
5922 */
5923
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005924 if (!PyUnicode_Check(unicode)) {
5925 PyErr_BadArgument();
5926 return NULL;
5927 }
5928 if (PyUnicode_READY(unicode) < 0)
5929 return NULL;
5930 len = PyUnicode_GET_LENGTH(unicode);
5931 kind = PyUnicode_KIND(unicode);
5932 data = PyUnicode_DATA(unicode);
5933 switch(kind) {
5934 case PyUnicode_1BYTE_KIND: expandsize = 4; break;
5935 case PyUnicode_2BYTE_KIND: expandsize = 6; break;
5936 case PyUnicode_4BYTE_KIND: expandsize = 10; break;
5937 }
5938
5939 if (len == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005940 return PyBytes_FromStringAndSize(NULL, 0);
5941
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005942 if (len > (PY_SSIZE_T_MAX - 2 - 1) / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005943 return PyErr_NoMemory();
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005944
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005945 repr = PyBytes_FromStringAndSize(NULL,
Benjamin Peterson29060642009-01-31 22:14:21 +00005946 2
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005947 + expandsize*len
Benjamin Peterson29060642009-01-31 22:14:21 +00005948 + 1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005949 if (repr == NULL)
5950 return NULL;
5951
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005952 p = PyBytes_AS_STRING(repr);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005953
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005954 for (i = 0; i < len; i++) {
Victor Stinner3326cb62011-11-10 20:15:25 +01005955 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005956
Walter Dörwald79e913e2007-05-12 11:08:06 +00005957 /* Escape backslashes */
5958 if (ch == '\\') {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005959 *p++ = '\\';
5960 *p++ = (char) ch;
Walter Dörwald79e913e2007-05-12 11:08:06 +00005961 continue;
Tim Petersced69f82003-09-16 20:30:58 +00005962 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005963
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005964 /* Map 21-bit characters to '\U00xxxxxx' */
5965 else if (ch >= 0x10000) {
5966 *p++ = '\\';
5967 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005968 *p++ = Py_hexdigits[(ch >> 28) & 0x0000000F];
5969 *p++ = Py_hexdigits[(ch >> 24) & 0x0000000F];
5970 *p++ = Py_hexdigits[(ch >> 20) & 0x0000000F];
5971 *p++ = Py_hexdigits[(ch >> 16) & 0x0000000F];
5972 *p++ = Py_hexdigits[(ch >> 12) & 0x0000000F];
5973 *p++ = Py_hexdigits[(ch >> 8) & 0x0000000F];
5974 *p++ = Py_hexdigits[(ch >> 4) & 0x0000000F];
5975 *p++ = Py_hexdigits[ch & 0x0000000F];
Benjamin Peterson29060642009-01-31 22:14:21 +00005976 continue;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005977 }
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005978
Guido van Rossumd57fd912000-03-10 22:53:23 +00005979 /* Map 16-bit characters to '\uxxxx' */
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005980 if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005981 *p++ = '\\';
5982 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005983 *p++ = Py_hexdigits[(ch >> 12) & 0x000F];
5984 *p++ = Py_hexdigits[(ch >> 8) & 0x000F];
5985 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
5986 *p++ = Py_hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00005987 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005988
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005989 /* Map special whitespace to '\t', \n', '\r' */
5990 else if (ch == '\t') {
5991 *p++ = '\\';
5992 *p++ = 't';
5993 }
5994 else if (ch == '\n') {
5995 *p++ = '\\';
5996 *p++ = 'n';
5997 }
5998 else if (ch == '\r') {
5999 *p++ = '\\';
6000 *p++ = 'r';
6001 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006002
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006003 /* Map non-printable US ASCII to '\xhh' */
Marc-André Lemburg11326de2001-11-28 12:56:20 +00006004 else if (ch < ' ' || ch >= 0x7F) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006005 *p++ = '\\';
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006006 *p++ = 'x';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006007 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6008 *p++ = Py_hexdigits[ch & 0x000F];
Tim Petersced69f82003-09-16 20:30:58 +00006009 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006010
Guido van Rossumd57fd912000-03-10 22:53:23 +00006011 /* Copy everything else as-is */
6012 else
6013 *p++ = (char) ch;
6014 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006015
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006016 assert(p - PyBytes_AS_STRING(repr) > 0);
6017 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0)
6018 return NULL;
6019 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006020}
6021
Alexander Belopolsky40018472011-02-26 01:02:56 +00006022PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006023PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
6024 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006025{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006026 PyObject *result;
6027 PyObject *tmp = PyUnicode_FromUnicode(s, size);
6028 if (tmp == NULL)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006029 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006030 result = PyUnicode_AsUnicodeEscapeString(tmp);
6031 Py_DECREF(tmp);
6032 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006033}
6034
6035/* --- Raw Unicode Escape Codec ------------------------------------------- */
6036
Alexander Belopolsky40018472011-02-26 01:02:56 +00006037PyObject *
6038PyUnicode_DecodeRawUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006039 Py_ssize_t size,
6040 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006041{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006042 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006043 Py_ssize_t startinpos;
6044 Py_ssize_t endinpos;
6045 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01006046 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006047 const char *end;
6048 const char *bs;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006049 PyObject *errorHandler = NULL;
6050 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006051
Guido van Rossumd57fd912000-03-10 22:53:23 +00006052 /* Escaped strings will always be longer than the resulting
6053 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006054 length after conversion to the true value. (But decoding error
6055 handler might have to resize the string) */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006056 v = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006057 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006058 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006059 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01006060 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006061 outpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006062 end = s + size;
6063 while (s < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006064 unsigned char c;
6065 Py_UCS4 x;
6066 int i;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006067 int count;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006068
Benjamin Peterson29060642009-01-31 22:14:21 +00006069 /* Non-escape characters are interpreted as Unicode ordinals */
6070 if (*s != '\\') {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006071 if (unicode_putchar(&v, &outpos, (unsigned char)*s++) < 0)
6072 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00006073 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006074 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006075 startinpos = s-starts;
6076
6077 /* \u-escapes are only interpreted iff the number of leading
6078 backslashes if odd */
6079 bs = s;
6080 for (;s < end;) {
6081 if (*s != '\\')
6082 break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006083 if (unicode_putchar(&v, &outpos, (unsigned char)*s++) < 0)
6084 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00006085 }
6086 if (((s - bs) & 1) == 0 ||
6087 s >= end ||
6088 (*s != 'u' && *s != 'U')) {
6089 continue;
6090 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006091 outpos--;
Benjamin Peterson29060642009-01-31 22:14:21 +00006092 count = *s=='u' ? 4 : 8;
6093 s++;
6094
6095 /* \uXXXX with 4 hex digits, \Uxxxxxxxx with 8 */
Benjamin Peterson29060642009-01-31 22:14:21 +00006096 for (x = 0, i = 0; i < count; ++i, ++s) {
6097 c = (unsigned char)*s;
David Malcolm96960882010-11-05 17:23:41 +00006098 if (!Py_ISXDIGIT(c)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006099 endinpos = s-starts;
6100 if (unicode_decode_call_errorhandler(
6101 errors, &errorHandler,
6102 "rawunicodeescape", "truncated \\uXXXX",
6103 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006104 &v, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00006105 goto onError;
6106 goto nextByte;
6107 }
6108 x = (x<<4) & ~0xF;
6109 if (c >= '0' && c <= '9')
6110 x += c - '0';
6111 else if (c >= 'a' && c <= 'f')
6112 x += 10 + c - 'a';
6113 else
6114 x += 10 + c - 'A';
6115 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006116 if (x <= 0x10ffff) {
6117 if (unicode_putchar(&v, &outpos, x) < 0)
6118 goto onError;
Christian Heimesfe337bf2008-03-23 21:54:12 +00006119 } else {
6120 endinpos = s-starts;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006121 if (unicode_decode_call_errorhandler(
6122 errors, &errorHandler,
6123 "rawunicodeescape", "\\Uxxxxxxxx out of range",
Benjamin Peterson29060642009-01-31 22:14:21 +00006124 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006125 &v, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00006126 goto onError;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006127 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006128 nextByte:
6129 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006130 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006131 if (PyUnicode_Resize(&v, outpos) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006132 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006133 Py_XDECREF(errorHandler);
6134 Py_XDECREF(exc);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02006135 assert(_PyUnicode_CheckConsistency(v, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01006136 return v;
Tim Petersced69f82003-09-16 20:30:58 +00006137
Benjamin Peterson29060642009-01-31 22:14:21 +00006138 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00006139 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006140 Py_XDECREF(errorHandler);
6141 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006142 return NULL;
6143}
6144
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006145
Alexander Belopolsky40018472011-02-26 01:02:56 +00006146PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006147PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006148{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006149 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006150 char *p;
6151 char *q;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006152 Py_ssize_t expandsize, pos;
6153 int kind;
6154 void *data;
6155 Py_ssize_t len;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006156
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006157 if (!PyUnicode_Check(unicode)) {
6158 PyErr_BadArgument();
6159 return NULL;
6160 }
6161 if (PyUnicode_READY(unicode) < 0)
6162 return NULL;
6163 kind = PyUnicode_KIND(unicode);
6164 data = PyUnicode_DATA(unicode);
6165 len = PyUnicode_GET_LENGTH(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006166
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006167 switch(kind) {
6168 case PyUnicode_1BYTE_KIND: expandsize = 4; break;
6169 case PyUnicode_2BYTE_KIND: expandsize = 6; break;
6170 case PyUnicode_4BYTE_KIND: expandsize = 10; break;
6171 }
Victor Stinner0e368262011-11-10 20:12:49 +01006172
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006173 if (len > PY_SSIZE_T_MAX / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00006174 return PyErr_NoMemory();
Benjamin Peterson14339b62009-01-31 16:36:08 +00006175
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006176 repr = PyBytes_FromStringAndSize(NULL, expandsize * len);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006177 if (repr == NULL)
6178 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006179 if (len == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006180 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006181
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006182 p = q = PyBytes_AS_STRING(repr);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006183 for (pos = 0; pos < len; pos++) {
6184 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Benjamin Peterson29060642009-01-31 22:14:21 +00006185 /* Map 32-bit characters to '\Uxxxxxxxx' */
6186 if (ch >= 0x10000) {
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006187 *p++ = '\\';
6188 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006189 *p++ = Py_hexdigits[(ch >> 28) & 0xf];
6190 *p++ = Py_hexdigits[(ch >> 24) & 0xf];
6191 *p++ = Py_hexdigits[(ch >> 20) & 0xf];
6192 *p++ = Py_hexdigits[(ch >> 16) & 0xf];
6193 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6194 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6195 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6196 *p++ = Py_hexdigits[ch & 15];
Tim Petersced69f82003-09-16 20:30:58 +00006197 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006198 /* Map 16-bit characters to '\uxxxx' */
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006199 else if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006200 *p++ = '\\';
6201 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006202 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6203 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6204 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6205 *p++ = Py_hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006206 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006207 /* Copy everything else as-is */
6208 else
Guido van Rossumd57fd912000-03-10 22:53:23 +00006209 *p++ = (char) ch;
6210 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00006211
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006212 assert(p > q);
6213 if (_PyBytes_Resize(&repr, p - q) < 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006214 return NULL;
6215 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006216}
6217
Alexander Belopolsky40018472011-02-26 01:02:56 +00006218PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006219PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
6220 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006221{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006222 PyObject *result;
6223 PyObject *tmp = PyUnicode_FromUnicode(s, size);
6224 if (tmp == NULL)
Walter Dörwald711005d2007-05-12 12:03:26 +00006225 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006226 result = PyUnicode_AsRawUnicodeEscapeString(tmp);
6227 Py_DECREF(tmp);
6228 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006229}
6230
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006231/* --- Unicode Internal Codec ------------------------------------------- */
6232
Alexander Belopolsky40018472011-02-26 01:02:56 +00006233PyObject *
6234_PyUnicode_DecodeUnicodeInternal(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006235 Py_ssize_t size,
6236 const char *errors)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006237{
6238 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006239 Py_ssize_t startinpos;
6240 Py_ssize_t endinpos;
6241 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01006242 PyObject *v;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006243 const char *end;
6244 const char *reason;
6245 PyObject *errorHandler = NULL;
6246 PyObject *exc = NULL;
6247
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006248 if (PyErr_WarnEx(PyExc_DeprecationWarning,
Ezio Melotti11060a42011-11-16 09:39:10 +02006249 "unicode_internal codec has been deprecated",
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006250 1))
6251 return NULL;
6252
Thomas Wouters89f507f2006-12-13 04:49:30 +00006253 /* XXX overflow detection missing */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006254 v = PyUnicode_New((size+Py_UNICODE_SIZE-1)/ Py_UNICODE_SIZE, 127);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006255 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006256 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006257 if (PyUnicode_GET_LENGTH(v) == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01006258 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006259 outpos = 0;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006260 end = s + size;
6261
6262 while (s < end) {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006263 Py_UNICODE uch;
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006264 Py_UCS4 ch;
6265 /* We copy the raw representation one byte at a time because the
6266 pointer may be unaligned (see test_codeccallbacks). */
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006267 ((char *) &uch)[0] = s[0];
6268 ((char *) &uch)[1] = s[1];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006269#ifdef Py_UNICODE_WIDE
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006270 ((char *) &uch)[2] = s[2];
6271 ((char *) &uch)[3] = s[3];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006272#endif
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006273 ch = uch;
6274
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006275 /* We have to sanity check the raw data, otherwise doom looms for
6276 some malformed UCS-4 data. */
6277 if (
Benjamin Peterson29060642009-01-31 22:14:21 +00006278#ifdef Py_UNICODE_WIDE
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006279 ch > 0x10ffff ||
Benjamin Peterson29060642009-01-31 22:14:21 +00006280#endif
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006281 end-s < Py_UNICODE_SIZE
6282 )
Benjamin Peterson29060642009-01-31 22:14:21 +00006283 {
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006284 startinpos = s - starts;
6285 if (end-s < Py_UNICODE_SIZE) {
6286 endinpos = end-starts;
6287 reason = "truncated input";
6288 }
6289 else {
6290 endinpos = s - starts + Py_UNICODE_SIZE;
6291 reason = "illegal code point (> 0x10FFFF)";
6292 }
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006293 if (unicode_decode_call_errorhandler(
6294 errors, &errorHandler,
6295 "unicode_internal", reason,
Walter Dörwalde78178e2007-07-30 13:31:40 +00006296 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006297 &v, &outpos))
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006298 goto onError;
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006299 continue;
6300 }
6301
6302 s += Py_UNICODE_SIZE;
6303#ifndef Py_UNICODE_WIDE
6304 if (ch >= 0xD800 && ch <= 0xDBFF && s < end)
6305 {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006306 Py_UNICODE uch2;
6307 ((char *) &uch2)[0] = s[0];
6308 ((char *) &uch2)[1] = s[1];
6309 if (uch2 >= 0xDC00 && uch2 <= 0xDFFF)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006310 {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006311 ch = (((uch & 0x3FF)<<10) | (uch2 & 0x3FF)) + 0x10000;
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006312 s += Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006313 }
6314 }
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006315#endif
6316
6317 if (unicode_putchar(&v, &outpos, ch) < 0)
6318 goto onError;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006319 }
6320
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006321 if (PyUnicode_Resize(&v, outpos) < 0)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006322 goto onError;
6323 Py_XDECREF(errorHandler);
6324 Py_XDECREF(exc);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02006325 assert(_PyUnicode_CheckConsistency(v, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01006326 return v;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006327
Benjamin Peterson29060642009-01-31 22:14:21 +00006328 onError:
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006329 Py_XDECREF(v);
6330 Py_XDECREF(errorHandler);
6331 Py_XDECREF(exc);
6332 return NULL;
6333}
6334
Guido van Rossumd57fd912000-03-10 22:53:23 +00006335/* --- Latin-1 Codec ------------------------------------------------------ */
6336
Alexander Belopolsky40018472011-02-26 01:02:56 +00006337PyObject *
6338PyUnicode_DecodeLatin1(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006339 Py_ssize_t size,
6340 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006341{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006342 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Victor Stinnere57b1c02011-09-28 22:20:48 +02006343 return _PyUnicode_FromUCS1((unsigned char*)s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006344}
6345
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006346/* create or adjust a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006347static void
6348make_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006349 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006350 PyObject *unicode,
6351 Py_ssize_t startpos, Py_ssize_t endpos,
6352 const char *reason)
6353{
6354 if (*exceptionObject == NULL) {
6355 *exceptionObject = PyObject_CallFunction(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006356 PyExc_UnicodeEncodeError, "sOnns",
Martin v. Löwis9e816682011-11-02 12:45:42 +01006357 encoding, unicode, startpos, endpos, reason);
6358 }
6359 else {
6360 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
6361 goto onError;
6362 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
6363 goto onError;
6364 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
6365 goto onError;
6366 return;
6367 onError:
6368 Py_DECREF(*exceptionObject);
6369 *exceptionObject = NULL;
6370 }
6371}
6372
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006373/* raises a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006374static void
6375raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006376 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006377 PyObject *unicode,
6378 Py_ssize_t startpos, Py_ssize_t endpos,
6379 const char *reason)
6380{
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006381 make_encode_exception(exceptionObject,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006382 encoding, unicode, startpos, endpos, reason);
6383 if (*exceptionObject != NULL)
6384 PyCodec_StrictErrors(*exceptionObject);
6385}
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006386
6387/* error handling callback helper:
6388 build arguments, call the callback and check the arguments,
6389 put the result into newpos and return the replacement string, which
6390 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006391static PyObject *
6392unicode_encode_call_errorhandler(const char *errors,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006393 PyObject **errorHandler,
6394 const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006395 PyObject *unicode, PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006396 Py_ssize_t startpos, Py_ssize_t endpos,
6397 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006398{
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006399 static char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006400 Py_ssize_t len;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006401 PyObject *restuple;
6402 PyObject *resunicode;
6403
6404 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006405 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006406 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006407 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006408 }
6409
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006410 if (PyUnicode_READY(unicode) < 0)
6411 return NULL;
6412 len = PyUnicode_GET_LENGTH(unicode);
6413
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006414 make_encode_exception(exceptionObject,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006415 encoding, unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006416 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006417 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006418
6419 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00006420 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006421 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006422 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006423 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006424 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00006425 Py_DECREF(restuple);
6426 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006427 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006428 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00006429 &resunicode, newpos)) {
6430 Py_DECREF(restuple);
6431 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006432 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006433 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
6434 PyErr_SetString(PyExc_TypeError, &argparse[3]);
6435 Py_DECREF(restuple);
6436 return NULL;
6437 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006438 if (*newpos<0)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006439 *newpos = len + *newpos;
6440 if (*newpos<0 || *newpos>len) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006441 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
6442 Py_DECREF(restuple);
6443 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00006444 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006445 Py_INCREF(resunicode);
6446 Py_DECREF(restuple);
6447 return resunicode;
6448}
6449
Alexander Belopolsky40018472011-02-26 01:02:56 +00006450static PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006451unicode_encode_ucs1(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006452 const char *errors,
Victor Stinnerfcd96532011-11-04 00:28:50 +01006453 unsigned int limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006454{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006455 /* input state */
6456 Py_ssize_t pos=0, size;
6457 int kind;
6458 void *data;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006459 /* output object */
6460 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006461 /* pointer into the output */
6462 char *str;
6463 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00006464 Py_ssize_t ressize;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006465 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
6466 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006467 PyObject *errorHandler = NULL;
6468 PyObject *exc = NULL;
6469 /* the following variable is used for caching string comparisons
6470 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
6471 int known_errorHandler = -1;
6472
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006473 if (PyUnicode_READY(unicode) < 0)
6474 return NULL;
6475 size = PyUnicode_GET_LENGTH(unicode);
6476 kind = PyUnicode_KIND(unicode);
6477 data = PyUnicode_DATA(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006478 /* allocate enough for a simple encoding without
6479 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00006480 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00006481 return PyBytes_FromStringAndSize(NULL, 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006482 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006483 if (res == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00006484 return NULL;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006485 str = PyBytes_AS_STRING(res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006486 ressize = size;
6487
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006488 while (pos < size) {
6489 Py_UCS4 c = PyUnicode_READ(kind, data, pos);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006490
Benjamin Peterson29060642009-01-31 22:14:21 +00006491 /* can we encode this? */
6492 if (c<limit) {
6493 /* no overflow check, because we know that the space is enough */
6494 *str++ = (char)c;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006495 ++pos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006496 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006497 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006498 Py_ssize_t requiredsize;
6499 PyObject *repunicode;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006500 Py_ssize_t repsize, newpos, respos, i;
Benjamin Peterson29060642009-01-31 22:14:21 +00006501 /* startpos for collecting unencodable chars */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006502 Py_ssize_t collstart = pos;
6503 Py_ssize_t collend = pos;
Benjamin Peterson29060642009-01-31 22:14:21 +00006504 /* find all unecodable characters */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006505 while ((collend < size) && (PyUnicode_READ(kind, data, collend)>=limit))
Benjamin Peterson29060642009-01-31 22:14:21 +00006506 ++collend;
6507 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
6508 if (known_errorHandler==-1) {
6509 if ((errors==NULL) || (!strcmp(errors, "strict")))
6510 known_errorHandler = 1;
6511 else if (!strcmp(errors, "replace"))
6512 known_errorHandler = 2;
6513 else if (!strcmp(errors, "ignore"))
6514 known_errorHandler = 3;
6515 else if (!strcmp(errors, "xmlcharrefreplace"))
6516 known_errorHandler = 4;
6517 else
6518 known_errorHandler = 0;
6519 }
6520 switch (known_errorHandler) {
6521 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006522 raise_encode_exception(&exc, encoding, unicode, collstart, collend, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006523 goto onError;
6524 case 2: /* replace */
6525 while (collstart++<collend)
6526 *str++ = '?'; /* fall through */
6527 case 3: /* ignore */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006528 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006529 break;
6530 case 4: /* xmlcharrefreplace */
6531 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006532 /* determine replacement size */
6533 for (i = collstart, repsize = 0; i < collend; ++i) {
6534 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
6535 if (ch < 10)
Benjamin Peterson29060642009-01-31 22:14:21 +00006536 repsize += 2+1+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006537 else if (ch < 100)
Benjamin Peterson29060642009-01-31 22:14:21 +00006538 repsize += 2+2+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006539 else if (ch < 1000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006540 repsize += 2+3+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006541 else if (ch < 10000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006542 repsize += 2+4+1;
Hye-Shik Chang40e95092003-12-22 01:31:13 +00006543#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00006544 else
6545 repsize += 2+5+1;
Hye-Shik Chang40e95092003-12-22 01:31:13 +00006546#else
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006547 else if (ch < 100000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006548 repsize += 2+5+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006549 else if (ch < 1000000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006550 repsize += 2+6+1;
6551 else
6552 repsize += 2+7+1;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00006553#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00006554 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006555 requiredsize = respos+repsize+(size-collend);
Benjamin Peterson29060642009-01-31 22:14:21 +00006556 if (requiredsize > ressize) {
6557 if (requiredsize<2*ressize)
6558 requiredsize = 2*ressize;
6559 if (_PyBytes_Resize(&res, requiredsize))
6560 goto onError;
6561 str = PyBytes_AS_STRING(res) + respos;
6562 ressize = requiredsize;
6563 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006564 /* generate replacement */
6565 for (i = collstart; i < collend; ++i) {
6566 str += sprintf(str, "&#%d;", PyUnicode_READ(kind, data, i));
Benjamin Peterson29060642009-01-31 22:14:21 +00006567 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006568 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006569 break;
6570 default:
6571 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006572 encoding, reason, unicode, &exc,
6573 collstart, collend, &newpos);
6574 if (repunicode == NULL || (PyUnicode_Check(repunicode) &&
6575 PyUnicode_READY(repunicode) < 0))
Benjamin Peterson29060642009-01-31 22:14:21 +00006576 goto onError;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006577 if (PyBytes_Check(repunicode)) {
6578 /* Directly copy bytes result to output. */
6579 repsize = PyBytes_Size(repunicode);
6580 if (repsize > 1) {
6581 /* Make room for all additional bytes. */
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006582 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006583 if (_PyBytes_Resize(&res, ressize+repsize-1)) {
6584 Py_DECREF(repunicode);
6585 goto onError;
6586 }
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006587 str = PyBytes_AS_STRING(res) + respos;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006588 ressize += repsize-1;
6589 }
6590 memcpy(str, PyBytes_AsString(repunicode), repsize);
6591 str += repsize;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006592 pos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006593 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006594 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006595 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006596 /* need more space? (at least enough for what we
6597 have+the replacement+the rest of the string, so
6598 we won't have to check space for encodable characters) */
6599 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006600 repsize = PyUnicode_GET_LENGTH(repunicode);
6601 requiredsize = respos+repsize+(size-collend);
Benjamin Peterson29060642009-01-31 22:14:21 +00006602 if (requiredsize > ressize) {
6603 if (requiredsize<2*ressize)
6604 requiredsize = 2*ressize;
6605 if (_PyBytes_Resize(&res, requiredsize)) {
6606 Py_DECREF(repunicode);
6607 goto onError;
6608 }
6609 str = PyBytes_AS_STRING(res) + respos;
6610 ressize = requiredsize;
6611 }
6612 /* check if there is anything unencodable in the replacement
6613 and copy it to the output */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006614 for (i = 0; repsize-->0; ++i, ++str) {
6615 c = PyUnicode_READ_CHAR(repunicode, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00006616 if (c >= limit) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006617 raise_encode_exception(&exc, encoding, unicode,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006618 pos, pos+1, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006619 Py_DECREF(repunicode);
6620 goto onError;
6621 }
6622 *str = (char)c;
6623 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006624 pos = newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006625 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006626 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00006627 }
6628 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006629 /* Resize if we allocated to much */
6630 size = str - PyBytes_AS_STRING(res);
6631 if (size < ressize) { /* If this falls res will be NULL */
Alexandre Vassalottibad1b922008-12-27 09:49:09 +00006632 assert(size >= 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006633 if (_PyBytes_Resize(&res, size) < 0)
6634 goto onError;
6635 }
6636
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006637 Py_XDECREF(errorHandler);
6638 Py_XDECREF(exc);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006639 return res;
6640
6641 onError:
6642 Py_XDECREF(res);
6643 Py_XDECREF(errorHandler);
6644 Py_XDECREF(exc);
6645 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006646}
6647
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006648/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006649PyObject *
6650PyUnicode_EncodeLatin1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006651 Py_ssize_t size,
6652 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006653{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006654 PyObject *result;
6655 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6656 if (unicode == NULL)
6657 return NULL;
6658 result = unicode_encode_ucs1(unicode, errors, 256);
6659 Py_DECREF(unicode);
6660 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006661}
6662
Alexander Belopolsky40018472011-02-26 01:02:56 +00006663PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006664_PyUnicode_AsLatin1String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006665{
6666 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006667 PyErr_BadArgument();
6668 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006669 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006670 if (PyUnicode_READY(unicode) == -1)
6671 return NULL;
6672 /* Fast path: if it is a one-byte string, construct
6673 bytes object directly. */
6674 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND)
6675 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6676 PyUnicode_GET_LENGTH(unicode));
6677 /* Non-Latin-1 characters present. Defer to above function to
6678 raise the exception. */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006679 return unicode_encode_ucs1(unicode, errors, 256);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006680}
6681
6682PyObject*
6683PyUnicode_AsLatin1String(PyObject *unicode)
6684{
6685 return _PyUnicode_AsLatin1String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006686}
6687
6688/* --- 7-bit ASCII Codec -------------------------------------------------- */
6689
Alexander Belopolsky40018472011-02-26 01:02:56 +00006690PyObject *
6691PyUnicode_DecodeASCII(const char *s,
6692 Py_ssize_t size,
6693 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006694{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006695 const char *starts = s;
Victor Stinner7931d9a2011-11-04 00:22:48 +01006696 PyObject *v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006697 int kind;
6698 void *data;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006699 Py_ssize_t startinpos;
6700 Py_ssize_t endinpos;
6701 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006702 const char *e;
Victor Stinner702c7342011-10-05 13:50:52 +02006703 int has_error;
6704 const unsigned char *p = (const unsigned char *)s;
6705 const unsigned char *end = p + size;
6706 const unsigned char *aligned_end = (const unsigned char *) ((size_t) end & ~LONG_PTR_MASK);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006707 PyObject *errorHandler = NULL;
6708 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006709
Guido van Rossumd57fd912000-03-10 22:53:23 +00006710 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Victor Stinner702c7342011-10-05 13:50:52 +02006711 if (size == 1 && (unsigned char)s[0] < 128)
6712 return get_latin1_char((unsigned char)s[0]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006713
Victor Stinner702c7342011-10-05 13:50:52 +02006714 has_error = 0;
6715 while (p < end && !has_error) {
6716 /* Fast path, see below in PyUnicode_DecodeUTF8Stateful for
6717 an explanation. */
6718 if (!((size_t) p & LONG_PTR_MASK)) {
6719 /* Help register allocation */
6720 register const unsigned char *_p = p;
6721 while (_p < aligned_end) {
6722 unsigned long value = *(unsigned long *) _p;
6723 if (value & ASCII_CHAR_MASK) {
6724 has_error = 1;
6725 break;
6726 }
6727 _p += SIZEOF_LONG;
6728 }
6729 if (_p == end)
6730 break;
6731 if (has_error)
6732 break;
6733 p = _p;
6734 }
6735 if (*p & 0x80) {
6736 has_error = 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006737 break;
Victor Stinner702c7342011-10-05 13:50:52 +02006738 }
6739 else {
6740 ++p;
6741 }
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00006742 }
Victor Stinner702c7342011-10-05 13:50:52 +02006743 if (!has_error)
6744 return unicode_fromascii((const unsigned char *)s, size);
Tim Petersced69f82003-09-16 20:30:58 +00006745
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006746 v = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006747 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006748 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006749 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01006750 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006751 kind = PyUnicode_KIND(v);
6752 data = PyUnicode_DATA(v);
6753 outpos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006754 e = s + size;
6755 while (s < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006756 register unsigned char c = (unsigned char)*s;
6757 if (c < 128) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006758 PyUnicode_WRITE(kind, data, outpos++, c);
Benjamin Peterson29060642009-01-31 22:14:21 +00006759 ++s;
6760 }
6761 else {
6762 startinpos = s-starts;
6763 endinpos = startinpos + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00006764 if (unicode_decode_call_errorhandler(
6765 errors, &errorHandler,
6766 "ascii", "ordinal not in range(128)",
6767 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006768 &v, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00006769 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006770 kind = PyUnicode_KIND(v);
6771 data = PyUnicode_DATA(v);
Benjamin Peterson29060642009-01-31 22:14:21 +00006772 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006773 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006774 if (PyUnicode_Resize(&v, outpos) < 0)
6775 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006776 Py_XDECREF(errorHandler);
6777 Py_XDECREF(exc);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02006778 assert(_PyUnicode_CheckConsistency(v, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01006779 return v;
Tim Petersced69f82003-09-16 20:30:58 +00006780
Benjamin Peterson29060642009-01-31 22:14:21 +00006781 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00006782 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006783 Py_XDECREF(errorHandler);
6784 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006785 return NULL;
6786}
6787
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006788/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006789PyObject *
6790PyUnicode_EncodeASCII(const Py_UNICODE *p,
6791 Py_ssize_t size,
6792 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006793{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006794 PyObject *result;
6795 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6796 if (unicode == NULL)
6797 return NULL;
6798 result = unicode_encode_ucs1(unicode, errors, 128);
6799 Py_DECREF(unicode);
6800 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006801}
6802
Alexander Belopolsky40018472011-02-26 01:02:56 +00006803PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006804_PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006805{
6806 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006807 PyErr_BadArgument();
6808 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006809 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006810 if (PyUnicode_READY(unicode) == -1)
6811 return NULL;
6812 /* Fast path: if it is an ASCII-only string, construct bytes object
6813 directly. Else defer to above function to raise the exception. */
6814 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
6815 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6816 PyUnicode_GET_LENGTH(unicode));
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006817 return unicode_encode_ucs1(unicode, errors, 128);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006818}
6819
6820PyObject *
6821PyUnicode_AsASCIIString(PyObject *unicode)
6822{
6823 return _PyUnicode_AsASCIIString(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006824}
6825
Victor Stinner99b95382011-07-04 14:23:54 +02006826#ifdef HAVE_MBCS
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006827
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006828/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006829
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00006830#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006831#define NEED_RETRY
6832#endif
6833
Victor Stinner3a50e702011-10-18 21:21:00 +02006834#ifndef WC_ERR_INVALID_CHARS
6835# define WC_ERR_INVALID_CHARS 0x0080
6836#endif
6837
6838static char*
6839code_page_name(UINT code_page, PyObject **obj)
6840{
6841 *obj = NULL;
6842 if (code_page == CP_ACP)
6843 return "mbcs";
6844 if (code_page == CP_UTF7)
6845 return "CP_UTF7";
6846 if (code_page == CP_UTF8)
6847 return "CP_UTF8";
6848
6849 *obj = PyBytes_FromFormat("cp%u", code_page);
6850 if (*obj == NULL)
6851 return NULL;
6852 return PyBytes_AS_STRING(*obj);
6853}
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006854
Alexander Belopolsky40018472011-02-26 01:02:56 +00006855static int
Victor Stinner3a50e702011-10-18 21:21:00 +02006856is_dbcs_lead_byte(UINT code_page, const char *s, int offset)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006857{
6858 const char *curr = s + offset;
Victor Stinner3a50e702011-10-18 21:21:00 +02006859 const char *prev;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006860
Victor Stinner3a50e702011-10-18 21:21:00 +02006861 if (!IsDBCSLeadByteEx(code_page, *curr))
6862 return 0;
6863
6864 prev = CharPrevExA(code_page, s, curr, 0);
6865 if (prev == curr)
6866 return 1;
6867 /* FIXME: This code is limited to "true" double-byte encodings,
6868 as it assumes an incomplete character consists of a single
6869 byte. */
6870 if (curr - prev == 2)
6871 return 1;
6872 if (!IsDBCSLeadByteEx(code_page, *prev))
6873 return 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006874 return 0;
6875}
6876
Victor Stinner3a50e702011-10-18 21:21:00 +02006877static DWORD
6878decode_code_page_flags(UINT code_page)
6879{
6880 if (code_page == CP_UTF7) {
6881 /* The CP_UTF7 decoder only supports flags=0 */
6882 return 0;
6883 }
6884 else
6885 return MB_ERR_INVALID_CHARS;
6886}
6887
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006888/*
Victor Stinner3a50e702011-10-18 21:21:00 +02006889 * Decode a byte string from a Windows code page into unicode object in strict
6890 * mode.
6891 *
6892 * Returns consumed size if succeed, returns -2 on decode error, or raise a
6893 * WindowsError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006894 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006895static int
Victor Stinner3a50e702011-10-18 21:21:00 +02006896decode_code_page_strict(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01006897 PyObject **v,
Victor Stinner3a50e702011-10-18 21:21:00 +02006898 const char *in,
6899 int insize)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006900{
Victor Stinner3a50e702011-10-18 21:21:00 +02006901 const DWORD flags = decode_code_page_flags(code_page);
Victor Stinner24729f32011-11-10 20:31:37 +01006902 wchar_t *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02006903 DWORD outsize;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006904
6905 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02006906 assert(insize > 0);
6907 outsize = MultiByteToWideChar(code_page, flags, in, insize, NULL, 0);
6908 if (outsize <= 0)
6909 goto error;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006910
6911 if (*v == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006912 /* Create unicode object */
Victor Stinner76a31a62011-11-04 00:05:13 +01006913 *v = (PyObject*)_PyUnicode_New(outsize);
Benjamin Peterson29060642009-01-31 22:14:21 +00006914 if (*v == NULL)
6915 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02006916 out = PyUnicode_AS_UNICODE(*v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006917 }
6918 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006919 /* Extend unicode object */
Victor Stinner3a50e702011-10-18 21:21:00 +02006920 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
Victor Stinner76a31a62011-11-04 00:05:13 +01006921 if (PyUnicode_Resize(v, n + outsize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006922 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02006923 out = PyUnicode_AS_UNICODE(*v) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006924 }
6925
6926 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02006927 outsize = MultiByteToWideChar(code_page, flags, in, insize, out, outsize);
6928 if (outsize <= 0)
6929 goto error;
6930 return insize;
Victor Stinner554f3f02010-06-16 23:33:54 +00006931
Victor Stinner3a50e702011-10-18 21:21:00 +02006932error:
6933 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
6934 return -2;
6935 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00006936 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006937}
6938
Victor Stinner3a50e702011-10-18 21:21:00 +02006939/*
6940 * Decode a byte string from a code page into unicode object with an error
6941 * handler.
6942 *
6943 * Returns consumed size if succeed, or raise a WindowsError or
6944 * UnicodeDecodeError exception and returns -1 on error.
6945 */
6946static int
6947decode_code_page_errors(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01006948 PyObject **v,
6949 const char *in, const int size,
Victor Stinner3a50e702011-10-18 21:21:00 +02006950 const char *errors)
6951{
6952 const char *startin = in;
6953 const char *endin = in + size;
6954 const DWORD flags = decode_code_page_flags(code_page);
6955 /* Ideally, we should get reason from FormatMessage. This is the Windows
6956 2000 English version of the message. */
6957 const char *reason = "No mapping for the Unicode character exists "
6958 "in the target code page.";
6959 /* each step cannot decode more than 1 character, but a character can be
6960 represented as a surrogate pair */
6961 wchar_t buffer[2], *startout, *out;
6962 int insize, outsize;
6963 PyObject *errorHandler = NULL;
6964 PyObject *exc = NULL;
6965 PyObject *encoding_obj = NULL;
6966 char *encoding;
6967 DWORD err;
6968 int ret = -1;
6969
6970 assert(size > 0);
6971
6972 encoding = code_page_name(code_page, &encoding_obj);
6973 if (encoding == NULL)
6974 return -1;
6975
6976 if (errors == NULL || strcmp(errors, "strict") == 0) {
6977 /* The last error was ERROR_NO_UNICODE_TRANSLATION, then we raise a
6978 UnicodeDecodeError. */
6979 make_decode_exception(&exc, encoding, in, size, 0, 0, reason);
6980 if (exc != NULL) {
6981 PyCodec_StrictErrors(exc);
6982 Py_CLEAR(exc);
6983 }
6984 goto error;
6985 }
6986
6987 if (*v == NULL) {
6988 /* Create unicode object */
6989 if (size > PY_SSIZE_T_MAX / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
6990 PyErr_NoMemory();
6991 goto error;
6992 }
Victor Stinner76a31a62011-11-04 00:05:13 +01006993 *v = (PyObject*)_PyUnicode_New(size * Py_ARRAY_LENGTH(buffer));
Victor Stinner3a50e702011-10-18 21:21:00 +02006994 if (*v == NULL)
6995 goto error;
6996 startout = PyUnicode_AS_UNICODE(*v);
6997 }
6998 else {
6999 /* Extend unicode object */
7000 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
7001 if (size > (PY_SSIZE_T_MAX - n) / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
7002 PyErr_NoMemory();
7003 goto error;
7004 }
Victor Stinner76a31a62011-11-04 00:05:13 +01007005 if (PyUnicode_Resize(v, n + size * Py_ARRAY_LENGTH(buffer)) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007006 goto error;
7007 startout = PyUnicode_AS_UNICODE(*v) + n;
7008 }
7009
7010 /* Decode the byte string character per character */
7011 out = startout;
7012 while (in < endin)
7013 {
7014 /* Decode a character */
7015 insize = 1;
7016 do
7017 {
7018 outsize = MultiByteToWideChar(code_page, flags,
7019 in, insize,
7020 buffer, Py_ARRAY_LENGTH(buffer));
7021 if (outsize > 0)
7022 break;
7023 err = GetLastError();
7024 if (err != ERROR_NO_UNICODE_TRANSLATION
7025 && err != ERROR_INSUFFICIENT_BUFFER)
7026 {
7027 PyErr_SetFromWindowsErr(0);
7028 goto error;
7029 }
7030 insize++;
7031 }
7032 /* 4=maximum length of a UTF-8 sequence */
7033 while (insize <= 4 && (in + insize) <= endin);
7034
7035 if (outsize <= 0) {
7036 Py_ssize_t startinpos, endinpos, outpos;
7037
7038 startinpos = in - startin;
7039 endinpos = startinpos + 1;
7040 outpos = out - PyUnicode_AS_UNICODE(*v);
7041 if (unicode_decode_call_errorhandler(
7042 errors, &errorHandler,
7043 encoding, reason,
7044 &startin, &endin, &startinpos, &endinpos, &exc, &in,
Victor Stinner596a6c42011-11-09 00:02:18 +01007045 v, &outpos))
Victor Stinner3a50e702011-10-18 21:21:00 +02007046 {
7047 goto error;
7048 }
Victor Stinner596a6c42011-11-09 00:02:18 +01007049 out = PyUnicode_AS_UNICODE(*v) + outpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007050 }
7051 else {
7052 in += insize;
7053 memcpy(out, buffer, outsize * sizeof(wchar_t));
7054 out += outsize;
7055 }
7056 }
7057
7058 /* write a NUL character at the end */
7059 *out = 0;
7060
7061 /* Extend unicode object */
7062 outsize = out - startout;
7063 assert(outsize <= PyUnicode_WSTR_LENGTH(*v));
Victor Stinner76a31a62011-11-04 00:05:13 +01007064 if (PyUnicode_Resize(v, outsize) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007065 goto error;
Victor Stinner76a31a62011-11-04 00:05:13 +01007066 ret = size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007067
7068error:
7069 Py_XDECREF(encoding_obj);
7070 Py_XDECREF(errorHandler);
7071 Py_XDECREF(exc);
7072 return ret;
7073}
7074
Victor Stinner3a50e702011-10-18 21:21:00 +02007075static PyObject *
7076decode_code_page_stateful(int code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007077 const char *s, Py_ssize_t size,
7078 const char *errors, Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007079{
Victor Stinner76a31a62011-11-04 00:05:13 +01007080 PyObject *v = NULL;
7081 int chunk_size, final, converted, done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007082
Victor Stinner3a50e702011-10-18 21:21:00 +02007083 if (code_page < 0) {
7084 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7085 return NULL;
7086 }
7087
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007088 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00007089 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007090
Victor Stinner76a31a62011-11-04 00:05:13 +01007091 do
7092 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007093#ifdef NEED_RETRY
Victor Stinner76a31a62011-11-04 00:05:13 +01007094 if (size > INT_MAX) {
7095 chunk_size = INT_MAX;
7096 final = 0;
7097 done = 0;
7098 }
7099 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007100#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007101 {
7102 chunk_size = (int)size;
7103 final = (consumed == NULL);
7104 done = 1;
7105 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007106
Victor Stinner76a31a62011-11-04 00:05:13 +01007107 /* Skip trailing lead-byte unless 'final' is set */
7108 if (!final && is_dbcs_lead_byte(code_page, s, chunk_size - 1))
7109 --chunk_size;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007110
Victor Stinner76a31a62011-11-04 00:05:13 +01007111 if (chunk_size == 0 && done) {
7112 if (v != NULL)
7113 break;
7114 Py_INCREF(unicode_empty);
7115 return unicode_empty;
7116 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007117
Victor Stinner76a31a62011-11-04 00:05:13 +01007118
7119 converted = decode_code_page_strict(code_page, &v,
7120 s, chunk_size);
7121 if (converted == -2)
7122 converted = decode_code_page_errors(code_page, &v,
7123 s, chunk_size,
7124 errors);
7125 assert(converted != 0);
7126
7127 if (converted < 0) {
7128 Py_XDECREF(v);
7129 return NULL;
7130 }
7131
7132 if (consumed)
7133 *consumed += converted;
7134
7135 s += converted;
7136 size -= converted;
7137 } while (!done);
Victor Stinner3a50e702011-10-18 21:21:00 +02007138
Victor Stinner17efeed2011-10-04 20:05:46 +02007139#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02007140 if (_PyUnicode_READY_REPLACE(&v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007141 Py_DECREF(v);
7142 return NULL;
7143 }
Victor Stinner17efeed2011-10-04 20:05:46 +02007144#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02007145 assert(_PyUnicode_CheckConsistency(v, 1));
Victor Stinner76a31a62011-11-04 00:05:13 +01007146 return v;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007147}
7148
Alexander Belopolsky40018472011-02-26 01:02:56 +00007149PyObject *
Victor Stinner3a50e702011-10-18 21:21:00 +02007150PyUnicode_DecodeCodePageStateful(int code_page,
7151 const char *s,
7152 Py_ssize_t size,
7153 const char *errors,
7154 Py_ssize_t *consumed)
7155{
7156 return decode_code_page_stateful(code_page, s, size, errors, consumed);
7157}
7158
7159PyObject *
7160PyUnicode_DecodeMBCSStateful(const char *s,
7161 Py_ssize_t size,
7162 const char *errors,
7163 Py_ssize_t *consumed)
7164{
7165 return decode_code_page_stateful(CP_ACP, s, size, errors, consumed);
7166}
7167
7168PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00007169PyUnicode_DecodeMBCS(const char *s,
7170 Py_ssize_t size,
7171 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007172{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007173 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
7174}
7175
Victor Stinner3a50e702011-10-18 21:21:00 +02007176static DWORD
7177encode_code_page_flags(UINT code_page, const char *errors)
7178{
7179 if (code_page == CP_UTF8) {
7180 if (winver.dwMajorVersion >= 6)
7181 /* CP_UTF8 supports WC_ERR_INVALID_CHARS on Windows Vista
7182 and later */
7183 return WC_ERR_INVALID_CHARS;
7184 else
7185 /* CP_UTF8 only supports flags=0 on Windows older than Vista */
7186 return 0;
7187 }
7188 else if (code_page == CP_UTF7) {
7189 /* CP_UTF7 only supports flags=0 */
7190 return 0;
7191 }
7192 else {
7193 if (errors != NULL && strcmp(errors, "replace") == 0)
7194 return 0;
7195 else
7196 return WC_NO_BEST_FIT_CHARS;
7197 }
7198}
7199
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007200/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007201 * Encode a Unicode string to a Windows code page into a byte string in strict
7202 * mode.
7203 *
7204 * Returns consumed characters if succeed, returns -2 on encode error, or raise
7205 * a WindowsError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007206 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007207static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007208encode_code_page_strict(UINT code_page, PyObject **outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007209 PyObject *unicode, Py_ssize_t offset, int len,
Victor Stinner3a50e702011-10-18 21:21:00 +02007210 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007211{
Victor Stinner554f3f02010-06-16 23:33:54 +00007212 BOOL usedDefaultChar = FALSE;
Victor Stinner3a50e702011-10-18 21:21:00 +02007213 BOOL *pusedDefaultChar = &usedDefaultChar;
7214 int outsize;
Victor Stinner554f3f02010-06-16 23:33:54 +00007215 PyObject *exc = NULL;
Victor Stinner24729f32011-11-10 20:31:37 +01007216 wchar_t *p;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007217 Py_ssize_t size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007218 const DWORD flags = encode_code_page_flags(code_page, NULL);
7219 char *out;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007220 /* Create a substring so that we can get the UTF-16 representation
7221 of just the slice under consideration. */
7222 PyObject *substring;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007223
Martin v. Löwis3d325192011-11-04 18:23:06 +01007224 assert(len > 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007225
Victor Stinner3a50e702011-10-18 21:21:00 +02007226 if (code_page != CP_UTF8 && code_page != CP_UTF7)
Victor Stinner554f3f02010-06-16 23:33:54 +00007227 pusedDefaultChar = &usedDefaultChar;
Victor Stinner3a50e702011-10-18 21:21:00 +02007228 else
Victor Stinner554f3f02010-06-16 23:33:54 +00007229 pusedDefaultChar = NULL;
Victor Stinner554f3f02010-06-16 23:33:54 +00007230
Victor Stinner2fc507f2011-11-04 20:06:39 +01007231 substring = PyUnicode_Substring(unicode, offset, offset+len);
7232 if (substring == NULL)
7233 return -1;
7234 p = PyUnicode_AsUnicodeAndSize(substring, &size);
7235 if (p == NULL) {
7236 Py_DECREF(substring);
7237 return -1;
7238 }
Martin v. Löwis3d325192011-11-04 18:23:06 +01007239
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007240 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007241 outsize = WideCharToMultiByte(code_page, flags,
7242 p, size,
7243 NULL, 0,
7244 NULL, pusedDefaultChar);
7245 if (outsize <= 0)
7246 goto error;
7247 /* If we used a default char, then we failed! */
Victor Stinner2fc507f2011-11-04 20:06:39 +01007248 if (pusedDefaultChar && *pusedDefaultChar) {
7249 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007250 return -2;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007251 }
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007252
Victor Stinner3a50e702011-10-18 21:21:00 +02007253 if (*outbytes == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007254 /* Create string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007255 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007256 if (*outbytes == NULL) {
7257 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007258 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007259 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007260 out = PyBytes_AS_STRING(*outbytes);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007261 }
7262 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007263 /* Extend string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007264 const Py_ssize_t n = PyBytes_Size(*outbytes);
7265 if (outsize > PY_SSIZE_T_MAX - n) {
7266 PyErr_NoMemory();
Victor Stinner2fc507f2011-11-04 20:06:39 +01007267 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007268 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007269 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007270 if (_PyBytes_Resize(outbytes, n + outsize) < 0) {
7271 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007272 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007273 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007274 out = PyBytes_AS_STRING(*outbytes) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007275 }
7276
7277 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007278 outsize = WideCharToMultiByte(code_page, flags,
7279 p, size,
7280 out, outsize,
7281 NULL, pusedDefaultChar);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007282 Py_CLEAR(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007283 if (outsize <= 0)
7284 goto error;
7285 if (pusedDefaultChar && *pusedDefaultChar)
7286 return -2;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007287 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00007288
Victor Stinner3a50e702011-10-18 21:21:00 +02007289error:
Victor Stinner2fc507f2011-11-04 20:06:39 +01007290 Py_XDECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007291 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7292 return -2;
7293 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007294 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007295}
7296
Victor Stinner3a50e702011-10-18 21:21:00 +02007297/*
7298 * Encode a Unicode string to a Windows code page into a byte string using a
7299 * error handler.
7300 *
7301 * Returns consumed characters if succeed, or raise a WindowsError and returns
7302 * -1 on other error.
7303 */
7304static int
7305encode_code_page_errors(UINT code_page, PyObject **outbytes,
Victor Stinner7581cef2011-11-03 22:32:33 +01007306 PyObject *unicode, Py_ssize_t unicode_offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007307 Py_ssize_t insize, const char* errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007308{
Victor Stinner3a50e702011-10-18 21:21:00 +02007309 const DWORD flags = encode_code_page_flags(code_page, errors);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007310 Py_ssize_t pos = unicode_offset;
7311 Py_ssize_t endin = unicode_offset + insize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007312 /* Ideally, we should get reason from FormatMessage. This is the Windows
7313 2000 English version of the message. */
7314 const char *reason = "invalid character";
7315 /* 4=maximum length of a UTF-8 sequence */
7316 char buffer[4];
7317 BOOL usedDefaultChar = FALSE, *pusedDefaultChar;
7318 Py_ssize_t outsize;
7319 char *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007320 PyObject *errorHandler = NULL;
7321 PyObject *exc = NULL;
7322 PyObject *encoding_obj = NULL;
7323 char *encoding;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007324 Py_ssize_t newpos, newoutsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007325 PyObject *rep;
7326 int ret = -1;
7327
7328 assert(insize > 0);
7329
7330 encoding = code_page_name(code_page, &encoding_obj);
7331 if (encoding == NULL)
7332 return -1;
7333
7334 if (errors == NULL || strcmp(errors, "strict") == 0) {
7335 /* The last error was ERROR_NO_UNICODE_TRANSLATION,
7336 then we raise a UnicodeEncodeError. */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007337 make_encode_exception(&exc, encoding, unicode, 0, 0, reason);
Victor Stinner3a50e702011-10-18 21:21:00 +02007338 if (exc != NULL) {
7339 PyCodec_StrictErrors(exc);
7340 Py_DECREF(exc);
7341 }
7342 Py_XDECREF(encoding_obj);
7343 return -1;
7344 }
7345
7346 if (code_page != CP_UTF8 && code_page != CP_UTF7)
7347 pusedDefaultChar = &usedDefaultChar;
7348 else
7349 pusedDefaultChar = NULL;
7350
7351 if (Py_ARRAY_LENGTH(buffer) > PY_SSIZE_T_MAX / insize) {
7352 PyErr_NoMemory();
7353 goto error;
7354 }
7355 outsize = insize * Py_ARRAY_LENGTH(buffer);
7356
7357 if (*outbytes == NULL) {
7358 /* Create string object */
7359 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
7360 if (*outbytes == NULL)
7361 goto error;
7362 out = PyBytes_AS_STRING(*outbytes);
7363 }
7364 else {
7365 /* Extend string object */
7366 Py_ssize_t n = PyBytes_Size(*outbytes);
7367 if (n > PY_SSIZE_T_MAX - outsize) {
7368 PyErr_NoMemory();
7369 goto error;
7370 }
7371 if (_PyBytes_Resize(outbytes, n + outsize) < 0)
7372 goto error;
7373 out = PyBytes_AS_STRING(*outbytes) + n;
7374 }
7375
7376 /* Encode the string character per character */
Martin v. Löwis3d325192011-11-04 18:23:06 +01007377 while (pos < endin)
Victor Stinner3a50e702011-10-18 21:21:00 +02007378 {
Victor Stinner2fc507f2011-11-04 20:06:39 +01007379 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, pos);
7380 wchar_t chars[2];
7381 int charsize;
7382 if (ch < 0x10000) {
7383 chars[0] = (wchar_t)ch;
7384 charsize = 1;
7385 }
7386 else {
7387 ch -= 0x10000;
7388 chars[0] = 0xd800 + (ch >> 10);
7389 chars[1] = 0xdc00 + (ch & 0x3ff);
7390 charsize = 2;
7391 }
7392
Victor Stinner3a50e702011-10-18 21:21:00 +02007393 outsize = WideCharToMultiByte(code_page, flags,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007394 chars, charsize,
Victor Stinner3a50e702011-10-18 21:21:00 +02007395 buffer, Py_ARRAY_LENGTH(buffer),
7396 NULL, pusedDefaultChar);
7397 if (outsize > 0) {
7398 if (pusedDefaultChar == NULL || !(*pusedDefaultChar))
7399 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007400 pos++;
Victor Stinner3a50e702011-10-18 21:21:00 +02007401 memcpy(out, buffer, outsize);
7402 out += outsize;
7403 continue;
7404 }
7405 }
7406 else if (GetLastError() != ERROR_NO_UNICODE_TRANSLATION) {
7407 PyErr_SetFromWindowsErr(0);
7408 goto error;
7409 }
7410
Victor Stinner3a50e702011-10-18 21:21:00 +02007411 rep = unicode_encode_call_errorhandler(
7412 errors, &errorHandler, encoding, reason,
Victor Stinner7581cef2011-11-03 22:32:33 +01007413 unicode, &exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007414 pos, pos + 1, &newpos);
Victor Stinner3a50e702011-10-18 21:21:00 +02007415 if (rep == NULL)
7416 goto error;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007417 pos = newpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007418
7419 if (PyBytes_Check(rep)) {
7420 outsize = PyBytes_GET_SIZE(rep);
7421 if (outsize != 1) {
7422 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7423 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7424 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7425 Py_DECREF(rep);
7426 goto error;
7427 }
7428 out = PyBytes_AS_STRING(*outbytes) + offset;
7429 }
7430 memcpy(out, PyBytes_AS_STRING(rep), outsize);
7431 out += outsize;
7432 }
7433 else {
7434 Py_ssize_t i;
7435 enum PyUnicode_Kind kind;
7436 void *data;
7437
7438 if (PyUnicode_READY(rep) < 0) {
7439 Py_DECREF(rep);
7440 goto error;
7441 }
7442
7443 outsize = PyUnicode_GET_LENGTH(rep);
7444 if (outsize != 1) {
7445 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7446 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7447 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7448 Py_DECREF(rep);
7449 goto error;
7450 }
7451 out = PyBytes_AS_STRING(*outbytes) + offset;
7452 }
7453 kind = PyUnicode_KIND(rep);
7454 data = PyUnicode_DATA(rep);
7455 for (i=0; i < outsize; i++) {
7456 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7457 if (ch > 127) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007458 raise_encode_exception(&exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007459 encoding, unicode,
7460 pos, pos + 1,
Victor Stinner3a50e702011-10-18 21:21:00 +02007461 "unable to encode error handler result to ASCII");
7462 Py_DECREF(rep);
7463 goto error;
7464 }
7465 *out = (unsigned char)ch;
7466 out++;
7467 }
7468 }
7469 Py_DECREF(rep);
7470 }
7471 /* write a NUL byte */
7472 *out = 0;
7473 outsize = out - PyBytes_AS_STRING(*outbytes);
7474 assert(outsize <= PyBytes_GET_SIZE(*outbytes));
7475 if (_PyBytes_Resize(outbytes, outsize) < 0)
7476 goto error;
7477 ret = 0;
7478
7479error:
7480 Py_XDECREF(encoding_obj);
7481 Py_XDECREF(errorHandler);
7482 Py_XDECREF(exc);
7483 return ret;
7484}
7485
Victor Stinner3a50e702011-10-18 21:21:00 +02007486static PyObject *
7487encode_code_page(int code_page,
Victor Stinner7581cef2011-11-03 22:32:33 +01007488 PyObject *unicode,
Victor Stinner3a50e702011-10-18 21:21:00 +02007489 const char *errors)
7490{
Martin v. Löwis3d325192011-11-04 18:23:06 +01007491 Py_ssize_t len;
Victor Stinner3a50e702011-10-18 21:21:00 +02007492 PyObject *outbytes = NULL;
Victor Stinner7581cef2011-11-03 22:32:33 +01007493 Py_ssize_t offset;
Victor Stinner76a31a62011-11-04 00:05:13 +01007494 int chunk_len, ret, done;
Victor Stinner7581cef2011-11-03 22:32:33 +01007495
Victor Stinner2fc507f2011-11-04 20:06:39 +01007496 if (PyUnicode_READY(unicode) < 0)
7497 return NULL;
7498 len = PyUnicode_GET_LENGTH(unicode);
Guido van Rossum03e29f12000-05-04 15:52:20 +00007499
Victor Stinner3a50e702011-10-18 21:21:00 +02007500 if (code_page < 0) {
7501 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7502 return NULL;
7503 }
7504
Martin v. Löwis3d325192011-11-04 18:23:06 +01007505 if (len == 0)
Victor Stinner76a31a62011-11-04 00:05:13 +01007506 return PyBytes_FromStringAndSize(NULL, 0);
7507
Victor Stinner7581cef2011-11-03 22:32:33 +01007508 offset = 0;
7509 do
7510 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007511#ifdef NEED_RETRY
Victor Stinner2fc507f2011-11-04 20:06:39 +01007512 /* UTF-16 encoding may double the size, so use only INT_MAX/2
Martin v. Löwis3d325192011-11-04 18:23:06 +01007513 chunks. */
7514 if (len > INT_MAX/2) {
7515 chunk_len = INT_MAX/2;
Victor Stinner76a31a62011-11-04 00:05:13 +01007516 done = 0;
7517 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007518 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007519#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007520 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007521 chunk_len = (int)len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007522 done = 1;
7523 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007524
Victor Stinner76a31a62011-11-04 00:05:13 +01007525 ret = encode_code_page_strict(code_page, &outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007526 unicode, offset, chunk_len,
Victor Stinner76a31a62011-11-04 00:05:13 +01007527 errors);
7528 if (ret == -2)
7529 ret = encode_code_page_errors(code_page, &outbytes,
7530 unicode, offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007531 chunk_len, errors);
Victor Stinner7581cef2011-11-03 22:32:33 +01007532 if (ret < 0) {
7533 Py_XDECREF(outbytes);
7534 return NULL;
7535 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007536
Victor Stinner7581cef2011-11-03 22:32:33 +01007537 offset += chunk_len;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007538 len -= chunk_len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007539 } while (!done);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007540
Victor Stinner3a50e702011-10-18 21:21:00 +02007541 return outbytes;
7542}
7543
7544PyObject *
7545PyUnicode_EncodeMBCS(const Py_UNICODE *p,
7546 Py_ssize_t size,
7547 const char *errors)
7548{
Victor Stinner7581cef2011-11-03 22:32:33 +01007549 PyObject *unicode, *res;
7550 unicode = PyUnicode_FromUnicode(p, size);
7551 if (unicode == NULL)
7552 return NULL;
7553 res = encode_code_page(CP_ACP, unicode, errors);
7554 Py_DECREF(unicode);
7555 return res;
Victor Stinner3a50e702011-10-18 21:21:00 +02007556}
7557
7558PyObject *
7559PyUnicode_EncodeCodePage(int code_page,
7560 PyObject *unicode,
7561 const char *errors)
7562{
Victor Stinner7581cef2011-11-03 22:32:33 +01007563 return encode_code_page(code_page, unicode, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007564}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007565
Alexander Belopolsky40018472011-02-26 01:02:56 +00007566PyObject *
7567PyUnicode_AsMBCSString(PyObject *unicode)
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007568{
7569 if (!PyUnicode_Check(unicode)) {
7570 PyErr_BadArgument();
7571 return NULL;
7572 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007573 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007574}
7575
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007576#undef NEED_RETRY
7577
Victor Stinner99b95382011-07-04 14:23:54 +02007578#endif /* HAVE_MBCS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007579
Guido van Rossumd57fd912000-03-10 22:53:23 +00007580/* --- Character Mapping Codec -------------------------------------------- */
7581
Alexander Belopolsky40018472011-02-26 01:02:56 +00007582PyObject *
7583PyUnicode_DecodeCharmap(const char *s,
7584 Py_ssize_t size,
7585 PyObject *mapping,
7586 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007587{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007588 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007589 Py_ssize_t startinpos;
7590 Py_ssize_t endinpos;
7591 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007592 const char *e;
Victor Stinner7931d9a2011-11-04 00:22:48 +01007593 PyObject *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007594 Py_ssize_t extrachars = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007595 PyObject *errorHandler = NULL;
7596 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00007597
Guido van Rossumd57fd912000-03-10 22:53:23 +00007598 /* Default to Latin-1 */
7599 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007600 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007601
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007602 v = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007603 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007604 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007605 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01007606 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007607 outpos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007608 e = s + size;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007609 if (PyUnicode_CheckExact(mapping)) {
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007610 Py_ssize_t maplen;
7611 enum PyUnicode_Kind kind;
7612 void *data;
7613 Py_UCS4 x;
7614
7615 if (PyUnicode_READY(mapping) < 0)
7616 return NULL;
7617
7618 maplen = PyUnicode_GET_LENGTH(mapping);
7619 data = PyUnicode_DATA(mapping);
7620 kind = PyUnicode_KIND(mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00007621 while (s < e) {
7622 unsigned char ch = *s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007623
Benjamin Peterson29060642009-01-31 22:14:21 +00007624 if (ch < maplen)
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007625 x = PyUnicode_READ(kind, data, ch);
7626 else
7627 x = 0xfffe; /* invalid value */
Guido van Rossumd57fd912000-03-10 22:53:23 +00007628
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007629 if (x == 0xfffe)
7630 {
Benjamin Peterson29060642009-01-31 22:14:21 +00007631 /* undefined mapping */
Benjamin Peterson29060642009-01-31 22:14:21 +00007632 startinpos = s-starts;
7633 endinpos = startinpos+1;
7634 if (unicode_decode_call_errorhandler(
7635 errors, &errorHandler,
7636 "charmap", "character maps to <undefined>",
7637 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007638 &v, &outpos)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007639 goto onError;
7640 }
7641 continue;
7642 }
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007643
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007644 if (unicode_putchar(&v, &outpos, x) < 0)
7645 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00007646 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007647 }
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007648 }
7649 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007650 while (s < e) {
7651 unsigned char ch = *s;
7652 PyObject *w, *x;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007653
Benjamin Peterson29060642009-01-31 22:14:21 +00007654 /* Get mapping (char ordinal -> integer, Unicode char or None) */
7655 w = PyLong_FromLong((long)ch);
7656 if (w == NULL)
7657 goto onError;
7658 x = PyObject_GetItem(mapping, w);
7659 Py_DECREF(w);
7660 if (x == NULL) {
7661 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7662 /* No mapping found means: mapping is undefined. */
7663 PyErr_Clear();
7664 x = Py_None;
7665 Py_INCREF(x);
7666 } else
7667 goto onError;
7668 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007669
Benjamin Peterson29060642009-01-31 22:14:21 +00007670 /* Apply mapping */
7671 if (PyLong_Check(x)) {
7672 long value = PyLong_AS_LONG(x);
7673 if (value < 0 || value > 65535) {
7674 PyErr_SetString(PyExc_TypeError,
7675 "character mapping must be in range(65536)");
7676 Py_DECREF(x);
7677 goto onError;
7678 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007679 if (unicode_putchar(&v, &outpos, value) < 0)
7680 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00007681 }
7682 else if (x == Py_None) {
7683 /* undefined mapping */
Benjamin Peterson29060642009-01-31 22:14:21 +00007684 startinpos = s-starts;
7685 endinpos = startinpos+1;
7686 if (unicode_decode_call_errorhandler(
7687 errors, &errorHandler,
7688 "charmap", "character maps to <undefined>",
7689 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007690 &v, &outpos)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007691 Py_DECREF(x);
7692 goto onError;
7693 }
7694 Py_DECREF(x);
7695 continue;
7696 }
7697 else if (PyUnicode_Check(x)) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007698 Py_ssize_t targetsize;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007699
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007700 if (PyUnicode_READY(x) < 0)
7701 goto onError;
7702 targetsize = PyUnicode_GET_LENGTH(x);
7703
7704 if (targetsize == 1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007705 /* 1-1 mapping */
Victor Stinner62aa4d02011-11-09 00:03:45 +01007706 if (unicode_putchar(&v, &outpos,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007707 PyUnicode_READ_CHAR(x, 0)) < 0)
7708 goto onError;
7709 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007710 else if (targetsize > 1) {
7711 /* 1-n mapping */
7712 if (targetsize > extrachars) {
7713 /* resize first */
Benjamin Peterson29060642009-01-31 22:14:21 +00007714 Py_ssize_t needed = (targetsize - extrachars) + \
7715 (targetsize << 2);
7716 extrachars += needed;
7717 /* XXX overflow detection missing */
Victor Stinner7931d9a2011-11-04 00:22:48 +01007718 if (PyUnicode_Resize(&v,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007719 PyUnicode_GET_LENGTH(v) + needed) < 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007720 Py_DECREF(x);
7721 goto onError;
7722 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007723 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007724 if (unicode_widen(&v, PyUnicode_MAX_CHAR_VALUE(x)) < 0)
7725 goto onError;
7726 PyUnicode_CopyCharacters(v, outpos, x, 0, targetsize);
7727 outpos += targetsize;
Benjamin Peterson29060642009-01-31 22:14:21 +00007728 extrachars -= targetsize;
7729 }
7730 /* 1-0 mapping: skip the character */
7731 }
7732 else {
7733 /* wrong return value */
7734 PyErr_SetString(PyExc_TypeError,
7735 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00007736 Py_DECREF(x);
7737 goto onError;
7738 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007739 Py_DECREF(x);
7740 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007741 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00007742 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007743 if (PyUnicode_Resize(&v, outpos) < 0)
Antoine Pitroua8f63c02011-11-08 18:37:16 +01007744 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007745 Py_XDECREF(errorHandler);
7746 Py_XDECREF(exc);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02007747 assert(_PyUnicode_CheckConsistency(v, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01007748 return v;
Tim Petersced69f82003-09-16 20:30:58 +00007749
Benjamin Peterson29060642009-01-31 22:14:21 +00007750 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007751 Py_XDECREF(errorHandler);
7752 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007753 Py_XDECREF(v);
7754 return NULL;
7755}
7756
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007757/* Charmap encoding: the lookup table */
7758
Alexander Belopolsky40018472011-02-26 01:02:56 +00007759struct encoding_map {
Benjamin Peterson29060642009-01-31 22:14:21 +00007760 PyObject_HEAD
7761 unsigned char level1[32];
7762 int count2, count3;
7763 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007764};
7765
7766static PyObject*
7767encoding_map_size(PyObject *obj, PyObject* args)
7768{
7769 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007770 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00007771 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007772}
7773
7774static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007775 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00007776 PyDoc_STR("Return the size (in bytes) of this object") },
7777 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007778};
7779
7780static void
7781encoding_map_dealloc(PyObject* o)
7782{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007783 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007784}
7785
7786static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007787 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007788 "EncodingMap", /*tp_name*/
7789 sizeof(struct encoding_map), /*tp_basicsize*/
7790 0, /*tp_itemsize*/
7791 /* methods */
7792 encoding_map_dealloc, /*tp_dealloc*/
7793 0, /*tp_print*/
7794 0, /*tp_getattr*/
7795 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00007796 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00007797 0, /*tp_repr*/
7798 0, /*tp_as_number*/
7799 0, /*tp_as_sequence*/
7800 0, /*tp_as_mapping*/
7801 0, /*tp_hash*/
7802 0, /*tp_call*/
7803 0, /*tp_str*/
7804 0, /*tp_getattro*/
7805 0, /*tp_setattro*/
7806 0, /*tp_as_buffer*/
7807 Py_TPFLAGS_DEFAULT, /*tp_flags*/
7808 0, /*tp_doc*/
7809 0, /*tp_traverse*/
7810 0, /*tp_clear*/
7811 0, /*tp_richcompare*/
7812 0, /*tp_weaklistoffset*/
7813 0, /*tp_iter*/
7814 0, /*tp_iternext*/
7815 encoding_map_methods, /*tp_methods*/
7816 0, /*tp_members*/
7817 0, /*tp_getset*/
7818 0, /*tp_base*/
7819 0, /*tp_dict*/
7820 0, /*tp_descr_get*/
7821 0, /*tp_descr_set*/
7822 0, /*tp_dictoffset*/
7823 0, /*tp_init*/
7824 0, /*tp_alloc*/
7825 0, /*tp_new*/
7826 0, /*tp_free*/
7827 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007828};
7829
7830PyObject*
7831PyUnicode_BuildEncodingMap(PyObject* string)
7832{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007833 PyObject *result;
7834 struct encoding_map *mresult;
7835 int i;
7836 int need_dict = 0;
7837 unsigned char level1[32];
7838 unsigned char level2[512];
7839 unsigned char *mlevel1, *mlevel2, *mlevel3;
7840 int count2 = 0, count3 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007841 int kind;
7842 void *data;
7843 Py_UCS4 ch;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007844
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007845 if (!PyUnicode_Check(string) || PyUnicode_GET_LENGTH(string) != 256) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007846 PyErr_BadArgument();
7847 return NULL;
7848 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007849 kind = PyUnicode_KIND(string);
7850 data = PyUnicode_DATA(string);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007851 memset(level1, 0xFF, sizeof level1);
7852 memset(level2, 0xFF, sizeof level2);
7853
7854 /* If there isn't a one-to-one mapping of NULL to \0,
7855 or if there are non-BMP characters, we need to use
7856 a mapping dictionary. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007857 if (PyUnicode_READ(kind, data, 0) != 0)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007858 need_dict = 1;
7859 for (i = 1; i < 256; i++) {
7860 int l1, l2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007861 ch = PyUnicode_READ(kind, data, i);
7862 if (ch == 0 || ch > 0xFFFF) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007863 need_dict = 1;
7864 break;
7865 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007866 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007867 /* unmapped character */
7868 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007869 l1 = ch >> 11;
7870 l2 = ch >> 7;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007871 if (level1[l1] == 0xFF)
7872 level1[l1] = count2++;
7873 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00007874 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007875 }
7876
7877 if (count2 >= 0xFF || count3 >= 0xFF)
7878 need_dict = 1;
7879
7880 if (need_dict) {
7881 PyObject *result = PyDict_New();
7882 PyObject *key, *value;
7883 if (!result)
7884 return NULL;
7885 for (i = 0; i < 256; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007886 key = PyLong_FromLong(PyUnicode_READ(kind, data, i));
Christian Heimes217cfd12007-12-02 14:31:20 +00007887 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007888 if (!key || !value)
7889 goto failed1;
7890 if (PyDict_SetItem(result, key, value) == -1)
7891 goto failed1;
7892 Py_DECREF(key);
7893 Py_DECREF(value);
7894 }
7895 return result;
7896 failed1:
7897 Py_XDECREF(key);
7898 Py_XDECREF(value);
7899 Py_DECREF(result);
7900 return NULL;
7901 }
7902
7903 /* Create a three-level trie */
7904 result = PyObject_MALLOC(sizeof(struct encoding_map) +
7905 16*count2 + 128*count3 - 1);
7906 if (!result)
7907 return PyErr_NoMemory();
7908 PyObject_Init(result, &EncodingMapType);
7909 mresult = (struct encoding_map*)result;
7910 mresult->count2 = count2;
7911 mresult->count3 = count3;
7912 mlevel1 = mresult->level1;
7913 mlevel2 = mresult->level23;
7914 mlevel3 = mresult->level23 + 16*count2;
7915 memcpy(mlevel1, level1, 32);
7916 memset(mlevel2, 0xFF, 16*count2);
7917 memset(mlevel3, 0, 128*count3);
7918 count3 = 0;
7919 for (i = 1; i < 256; i++) {
7920 int o1, o2, o3, i2, i3;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007921 if (PyUnicode_READ(kind, data, i) == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007922 /* unmapped character */
7923 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007924 o1 = PyUnicode_READ(kind, data, i)>>11;
7925 o2 = (PyUnicode_READ(kind, data, i)>>7) & 0xF;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007926 i2 = 16*mlevel1[o1] + o2;
7927 if (mlevel2[i2] == 0xFF)
7928 mlevel2[i2] = count3++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007929 o3 = PyUnicode_READ(kind, data, i) & 0x7F;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007930 i3 = 128*mlevel2[i2] + o3;
7931 mlevel3[i3] = i;
7932 }
7933 return result;
7934}
7935
7936static int
Victor Stinner22168992011-11-20 17:09:18 +01007937encoding_map_lookup(Py_UCS4 c, PyObject *mapping)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007938{
7939 struct encoding_map *map = (struct encoding_map*)mapping;
7940 int l1 = c>>11;
7941 int l2 = (c>>7) & 0xF;
7942 int l3 = c & 0x7F;
7943 int i;
7944
Victor Stinner22168992011-11-20 17:09:18 +01007945 if (c > 0xFFFF)
Benjamin Peterson29060642009-01-31 22:14:21 +00007946 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007947 if (c == 0)
7948 return 0;
7949 /* level 1*/
7950 i = map->level1[l1];
7951 if (i == 0xFF) {
7952 return -1;
7953 }
7954 /* level 2*/
7955 i = map->level23[16*i+l2];
7956 if (i == 0xFF) {
7957 return -1;
7958 }
7959 /* level 3 */
7960 i = map->level23[16*map->count2 + 128*i + l3];
7961 if (i == 0) {
7962 return -1;
7963 }
7964 return i;
7965}
7966
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007967/* Lookup the character ch in the mapping. If the character
7968 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00007969 error occurred). */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007970static PyObject *
Victor Stinner22168992011-11-20 17:09:18 +01007971charmapencode_lookup(Py_UCS4 c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007972{
Christian Heimes217cfd12007-12-02 14:31:20 +00007973 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007974 PyObject *x;
7975
7976 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007977 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007978 x = PyObject_GetItem(mapping, w);
7979 Py_DECREF(w);
7980 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007981 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7982 /* No mapping found means: mapping is undefined. */
7983 PyErr_Clear();
7984 x = Py_None;
7985 Py_INCREF(x);
7986 return x;
7987 } else
7988 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007989 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00007990 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00007991 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00007992 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007993 long value = PyLong_AS_LONG(x);
7994 if (value < 0 || value > 255) {
7995 PyErr_SetString(PyExc_TypeError,
7996 "character mapping must be in range(256)");
7997 Py_DECREF(x);
7998 return NULL;
7999 }
8000 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008001 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008002 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008003 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008004 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008005 /* wrong return value */
8006 PyErr_Format(PyExc_TypeError,
8007 "character mapping must return integer, bytes or None, not %.400s",
8008 x->ob_type->tp_name);
8009 Py_DECREF(x);
8010 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008011 }
8012}
8013
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008014static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00008015charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008016{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008017 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
8018 /* exponentially overallocate to minimize reallocations */
8019 if (requiredsize < 2*outsize)
8020 requiredsize = 2*outsize;
8021 if (_PyBytes_Resize(outobj, requiredsize))
8022 return -1;
8023 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008024}
8025
Benjamin Peterson14339b62009-01-31 16:36:08 +00008026typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00008027 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Alexander Belopolsky40018472011-02-26 01:02:56 +00008028} charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008029/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00008030 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008031 space is available. Return a new reference to the object that
8032 was put in the output buffer, or Py_None, if the mapping was undefined
8033 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00008034 reallocation error occurred. The caller must decref the result */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008035static charmapencode_result
Victor Stinner22168992011-11-20 17:09:18 +01008036charmapencode_output(Py_UCS4 c, PyObject *mapping,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008037 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008038{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008039 PyObject *rep;
8040 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00008041 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008042
Christian Heimes90aa7642007-12-19 02:45:37 +00008043 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008044 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008045 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008046 if (res == -1)
8047 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00008048 if (outsize<requiredsize)
8049 if (charmapencode_resize(outobj, outpos, requiredsize))
8050 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00008051 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008052 outstart[(*outpos)++] = (char)res;
8053 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008054 }
8055
8056 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008057 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008058 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008059 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008060 Py_DECREF(rep);
8061 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008062 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008063 if (PyLong_Check(rep)) {
8064 Py_ssize_t requiredsize = *outpos+1;
8065 if (outsize<requiredsize)
8066 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8067 Py_DECREF(rep);
8068 return enc_EXCEPTION;
8069 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008070 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008071 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008072 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008073 else {
8074 const char *repchars = PyBytes_AS_STRING(rep);
8075 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
8076 Py_ssize_t requiredsize = *outpos+repsize;
8077 if (outsize<requiredsize)
8078 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8079 Py_DECREF(rep);
8080 return enc_EXCEPTION;
8081 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008082 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008083 memcpy(outstart + *outpos, repchars, repsize);
8084 *outpos += repsize;
8085 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008086 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008087 Py_DECREF(rep);
8088 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008089}
8090
8091/* handle an error in PyUnicode_EncodeCharmap
8092 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008093static int
8094charmap_encoding_error(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008095 PyObject *unicode, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008096 PyObject **exceptionObject,
Walter Dörwalde5402fb2003-08-14 20:25:29 +00008097 int *known_errorHandler, PyObject **errorHandler, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00008098 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008099{
8100 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008101 Py_ssize_t size, repsize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008102 Py_ssize_t newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008103 Py_UNICODE *uni2;
8104 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008105 Py_ssize_t collstartpos = *inpos;
8106 Py_ssize_t collendpos = *inpos+1;
8107 Py_ssize_t collpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008108 char *encoding = "charmap";
8109 char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008110 charmapencode_result x;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008111 Py_UCS4 ch;
Brian Curtin2787ea42011-11-02 15:09:37 -05008112 int val;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008113
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008114 if (PyUnicode_READY(unicode) < 0)
8115 return -1;
8116 size = PyUnicode_GET_LENGTH(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008117 /* find all unencodable characters */
8118 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008119 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00008120 if (Py_TYPE(mapping) == &EncodingMapType) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008121 ch = PyUnicode_READ_CHAR(unicode, collendpos);
Brian Curtin2787ea42011-11-02 15:09:37 -05008122 val = encoding_map_lookup(ch, mapping);
8123 if (val != -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008124 break;
8125 ++collendpos;
8126 continue;
8127 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008128
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008129 ch = PyUnicode_READ_CHAR(unicode, collendpos);
8130 rep = charmapencode_lookup(ch, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008131 if (rep==NULL)
8132 return -1;
8133 else if (rep!=Py_None) {
8134 Py_DECREF(rep);
8135 break;
8136 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008137 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00008138 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008139 }
8140 /* cache callback name lookup
8141 * (if not done yet, i.e. it's the first error) */
8142 if (*known_errorHandler==-1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008143 if ((errors==NULL) || (!strcmp(errors, "strict")))
8144 *known_errorHandler = 1;
8145 else if (!strcmp(errors, "replace"))
8146 *known_errorHandler = 2;
8147 else if (!strcmp(errors, "ignore"))
8148 *known_errorHandler = 3;
8149 else if (!strcmp(errors, "xmlcharrefreplace"))
8150 *known_errorHandler = 4;
8151 else
8152 *known_errorHandler = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008153 }
8154 switch (*known_errorHandler) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008155 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008156 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008157 return -1;
8158 case 2: /* replace */
8159 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008160 x = charmapencode_output('?', mapping, res, respos);
8161 if (x==enc_EXCEPTION) {
8162 return -1;
8163 }
8164 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008165 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008166 return -1;
8167 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008168 }
8169 /* fall through */
8170 case 3: /* ignore */
8171 *inpos = collendpos;
8172 break;
8173 case 4: /* xmlcharrefreplace */
8174 /* generate replacement (temporarily (mis)uses p) */
8175 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008176 char buffer[2+29+1+1];
8177 char *cp;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008178 sprintf(buffer, "&#%d;", (int)PyUnicode_READ_CHAR(unicode, collpos));
Benjamin Peterson29060642009-01-31 22:14:21 +00008179 for (cp = buffer; *cp; ++cp) {
8180 x = charmapencode_output(*cp, mapping, res, respos);
8181 if (x==enc_EXCEPTION)
8182 return -1;
8183 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008184 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008185 return -1;
8186 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008187 }
8188 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008189 *inpos = collendpos;
8190 break;
8191 default:
8192 repunicode = unicode_encode_call_errorhandler(errors, errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008193 encoding, reason, unicode, exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00008194 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008195 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008196 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00008197 if (PyBytes_Check(repunicode)) {
8198 /* Directly copy bytes result to output. */
8199 Py_ssize_t outsize = PyBytes_Size(*res);
8200 Py_ssize_t requiredsize;
8201 repsize = PyBytes_Size(repunicode);
8202 requiredsize = *respos + repsize;
8203 if (requiredsize > outsize)
8204 /* Make room for all additional bytes. */
8205 if (charmapencode_resize(res, respos, requiredsize)) {
8206 Py_DECREF(repunicode);
8207 return -1;
8208 }
8209 memcpy(PyBytes_AsString(*res) + *respos,
8210 PyBytes_AsString(repunicode), repsize);
8211 *respos += repsize;
8212 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008213 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00008214 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008215 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008216 /* generate replacement */
8217 repsize = PyUnicode_GET_SIZE(repunicode);
8218 for (uni2 = PyUnicode_AS_UNICODE(repunicode); repsize-->0; ++uni2) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008219 x = charmapencode_output(*uni2, mapping, res, respos);
8220 if (x==enc_EXCEPTION) {
8221 return -1;
8222 }
8223 else if (x==enc_FAILED) {
8224 Py_DECREF(repunicode);
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008225 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008226 return -1;
8227 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008228 }
8229 *inpos = newpos;
8230 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008231 }
8232 return 0;
8233}
8234
Alexander Belopolsky40018472011-02-26 01:02:56 +00008235PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008236_PyUnicode_EncodeCharmap(PyObject *unicode,
8237 PyObject *mapping,
8238 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008239{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008240 /* output object */
8241 PyObject *res = NULL;
8242 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008243 Py_ssize_t inpos = 0;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008244 Py_ssize_t size;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008245 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008246 Py_ssize_t respos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008247 PyObject *errorHandler = NULL;
8248 PyObject *exc = NULL;
8249 /* the following variable is used for caching string comparisons
8250 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8251 * 3=ignore, 4=xmlcharrefreplace */
8252 int known_errorHandler = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008253
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008254 if (PyUnicode_READY(unicode) < 0)
8255 return NULL;
8256 size = PyUnicode_GET_LENGTH(unicode);
8257
Guido van Rossumd57fd912000-03-10 22:53:23 +00008258 /* Default to Latin-1 */
8259 if (mapping == NULL)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008260 return unicode_encode_ucs1(unicode, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008261
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008262 /* allocate enough for a simple encoding without
8263 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00008264 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008265 if (res == NULL)
8266 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00008267 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008268 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008269
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008270 while (inpos<size) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008271 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, inpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008272 /* try to encode it */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008273 charmapencode_result x = charmapencode_output(ch, mapping, &res, &respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008274 if (x==enc_EXCEPTION) /* error */
8275 goto onError;
8276 if (x==enc_FAILED) { /* unencodable character */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008277 if (charmap_encoding_error(unicode, &inpos, mapping,
Benjamin Peterson29060642009-01-31 22:14:21 +00008278 &exc,
8279 &known_errorHandler, &errorHandler, errors,
8280 &res, &respos)) {
8281 goto onError;
8282 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008283 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008284 else
8285 /* done with this character => adjust input position */
8286 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008287 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008288
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008289 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00008290 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00008291 if (_PyBytes_Resize(&res, respos) < 0)
8292 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00008293
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008294 Py_XDECREF(exc);
8295 Py_XDECREF(errorHandler);
8296 return res;
8297
Benjamin Peterson29060642009-01-31 22:14:21 +00008298 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008299 Py_XDECREF(res);
8300 Py_XDECREF(exc);
8301 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008302 return NULL;
8303}
8304
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008305/* Deprecated */
8306PyObject *
8307PyUnicode_EncodeCharmap(const Py_UNICODE *p,
8308 Py_ssize_t size,
8309 PyObject *mapping,
8310 const char *errors)
8311{
8312 PyObject *result;
8313 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8314 if (unicode == NULL)
8315 return NULL;
8316 result = _PyUnicode_EncodeCharmap(unicode, mapping, errors);
8317 Py_DECREF(unicode);
Victor Stinnerfc026c92011-11-04 00:24:51 +01008318 return result;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008319}
8320
Alexander Belopolsky40018472011-02-26 01:02:56 +00008321PyObject *
8322PyUnicode_AsCharmapString(PyObject *unicode,
8323 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008324{
8325 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008326 PyErr_BadArgument();
8327 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008328 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008329 return _PyUnicode_EncodeCharmap(unicode, mapping, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008330}
8331
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008332/* create or adjust a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008333static void
8334make_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008335 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008336 Py_ssize_t startpos, Py_ssize_t endpos,
8337 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008338{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008339 if (*exceptionObject == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008340 *exceptionObject = _PyUnicodeTranslateError_Create(
8341 unicode, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008342 }
8343 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008344 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
8345 goto onError;
8346 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
8347 goto onError;
8348 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
8349 goto onError;
8350 return;
8351 onError:
8352 Py_DECREF(*exceptionObject);
8353 *exceptionObject = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008354 }
8355}
8356
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008357/* raises a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008358static void
8359raise_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008360 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008361 Py_ssize_t startpos, Py_ssize_t endpos,
8362 const char *reason)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008363{
8364 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008365 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008366 if (*exceptionObject != NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008367 PyCodec_StrictErrors(*exceptionObject);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008368}
8369
8370/* error handling callback helper:
8371 build arguments, call the callback and check the arguments,
8372 put the result into newpos and return the replacement string, which
8373 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008374static PyObject *
8375unicode_translate_call_errorhandler(const char *errors,
8376 PyObject **errorHandler,
8377 const char *reason,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008378 PyObject *unicode, PyObject **exceptionObject,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008379 Py_ssize_t startpos, Py_ssize_t endpos,
8380 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008381{
Benjamin Peterson142957c2008-07-04 19:55:29 +00008382 static char *argparse = "O!n;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008383
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008384 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008385 PyObject *restuple;
8386 PyObject *resunicode;
8387
8388 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008389 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008390 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008391 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008392 }
8393
8394 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008395 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008396 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008397 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008398
8399 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00008400 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008401 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008402 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008403 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00008404 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00008405 Py_DECREF(restuple);
8406 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008407 }
8408 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type,
Benjamin Peterson29060642009-01-31 22:14:21 +00008409 &resunicode, &i_newpos)) {
8410 Py_DECREF(restuple);
8411 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008412 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00008413 if (i_newpos<0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008414 *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008415 else
8416 *newpos = i_newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008417 if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008418 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
8419 Py_DECREF(restuple);
8420 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00008421 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008422 Py_INCREF(resunicode);
8423 Py_DECREF(restuple);
8424 return resunicode;
8425}
8426
8427/* Lookup the character ch in the mapping and put the result in result,
8428 which must be decrefed by the caller.
8429 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008430static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008431charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008432{
Christian Heimes217cfd12007-12-02 14:31:20 +00008433 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008434 PyObject *x;
8435
8436 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008437 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008438 x = PyObject_GetItem(mapping, w);
8439 Py_DECREF(w);
8440 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008441 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8442 /* No mapping found means: use 1:1 mapping. */
8443 PyErr_Clear();
8444 *result = NULL;
8445 return 0;
8446 } else
8447 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008448 }
8449 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008450 *result = x;
8451 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008452 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008453 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008454 long value = PyLong_AS_LONG(x);
8455 long max = PyUnicode_GetMax();
8456 if (value < 0 || value > max) {
8457 PyErr_Format(PyExc_TypeError,
Guido van Rossum5a2f7e602007-10-24 21:13:09 +00008458 "character mapping must be in range(0x%x)", max+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00008459 Py_DECREF(x);
8460 return -1;
8461 }
8462 *result = x;
8463 return 0;
8464 }
8465 else if (PyUnicode_Check(x)) {
8466 *result = x;
8467 return 0;
8468 }
8469 else {
8470 /* wrong return value */
8471 PyErr_SetString(PyExc_TypeError,
8472 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00008473 Py_DECREF(x);
8474 return -1;
8475 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008476}
8477/* ensure that *outobj is at least requiredsize characters long,
Benjamin Peterson29060642009-01-31 22:14:21 +00008478 if not reallocate and adjust various state variables.
8479 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008480static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008481charmaptranslate_makespace(Py_UCS4 **outobj, Py_ssize_t *psize,
Benjamin Peterson29060642009-01-31 22:14:21 +00008482 Py_ssize_t requiredsize)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008483{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008484 Py_ssize_t oldsize = *psize;
Walter Dörwald4894c302003-10-24 14:25:28 +00008485 if (requiredsize > oldsize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008486 /* exponentially overallocate to minimize reallocations */
8487 if (requiredsize < 2 * oldsize)
8488 requiredsize = 2 * oldsize;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008489 *outobj = PyMem_Realloc(*outobj, requiredsize * sizeof(Py_UCS4));
8490 if (*outobj == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008491 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008492 *psize = requiredsize;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008493 }
8494 return 0;
8495}
8496/* lookup the character, put the result in the output string and adjust
8497 various state variables. Return a new reference to the object that
8498 was put in the output buffer in *result, or Py_None, if the mapping was
8499 undefined (in which case no character was written).
8500 The called must decref result.
8501 Return 0 on success, -1 on error. */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008502static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008503charmaptranslate_output(PyObject *input, Py_ssize_t ipos,
8504 PyObject *mapping, Py_UCS4 **output,
8505 Py_ssize_t *osize, Py_ssize_t *opos,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008506 PyObject **res)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008507{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008508 Py_UCS4 curinp = PyUnicode_READ_CHAR(input, ipos);
8509 if (charmaptranslate_lookup(curinp, mapping, res))
Benjamin Peterson29060642009-01-31 22:14:21 +00008510 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008511 if (*res==NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008512 /* not found => default to 1:1 mapping */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008513 (*output)[(*opos)++] = curinp;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008514 }
8515 else if (*res==Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008516 ;
Christian Heimes217cfd12007-12-02 14:31:20 +00008517 else if (PyLong_Check(*res)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008518 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008519 (*output)[(*opos)++] = (Py_UCS4)PyLong_AS_LONG(*res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008520 }
8521 else if (PyUnicode_Check(*res)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008522 Py_ssize_t repsize;
8523 if (PyUnicode_READY(*res) == -1)
8524 return -1;
8525 repsize = PyUnicode_GET_LENGTH(*res);
Benjamin Peterson29060642009-01-31 22:14:21 +00008526 if (repsize==1) {
8527 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008528 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +00008529 }
8530 else if (repsize!=0) {
8531 /* more than one character */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008532 Py_ssize_t requiredsize = *opos +
8533 (PyUnicode_GET_LENGTH(input) - ipos) +
Benjamin Peterson29060642009-01-31 22:14:21 +00008534 repsize - 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008535 Py_ssize_t i;
8536 if (charmaptranslate_makespace(output, osize, requiredsize))
Benjamin Peterson29060642009-01-31 22:14:21 +00008537 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008538 for(i = 0; i < repsize; i++)
8539 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00008540 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008541 }
8542 else
Benjamin Peterson29060642009-01-31 22:14:21 +00008543 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008544 return 0;
8545}
8546
Alexander Belopolsky40018472011-02-26 01:02:56 +00008547PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008548_PyUnicode_TranslateCharmap(PyObject *input,
8549 PyObject *mapping,
8550 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008551{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008552 /* input object */
8553 char *idata;
8554 Py_ssize_t size, i;
8555 int kind;
8556 /* output buffer */
8557 Py_UCS4 *output = NULL;
8558 Py_ssize_t osize;
8559 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008560 /* current output position */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008561 Py_ssize_t opos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008562 char *reason = "character maps to <undefined>";
8563 PyObject *errorHandler = NULL;
8564 PyObject *exc = NULL;
8565 /* the following variable is used for caching string comparisons
8566 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8567 * 3=ignore, 4=xmlcharrefreplace */
8568 int known_errorHandler = -1;
8569
Guido van Rossumd57fd912000-03-10 22:53:23 +00008570 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008571 PyErr_BadArgument();
8572 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008573 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008574
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008575 if (PyUnicode_READY(input) == -1)
8576 return NULL;
8577 idata = (char*)PyUnicode_DATA(input);
8578 kind = PyUnicode_KIND(input);
8579 size = PyUnicode_GET_LENGTH(input);
8580 i = 0;
8581
8582 if (size == 0) {
8583 Py_INCREF(input);
8584 return input;
8585 }
8586
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008587 /* allocate enough for a simple 1:1 translation without
8588 replacements, if we need more, we'll resize */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008589 osize = size;
8590 output = PyMem_Malloc(osize * sizeof(Py_UCS4));
8591 opos = 0;
8592 if (output == NULL) {
8593 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00008594 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008595 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008596
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008597 while (i<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008598 /* try to encode it */
8599 PyObject *x = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008600 if (charmaptranslate_output(input, i, mapping,
8601 &output, &osize, &opos, &x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008602 Py_XDECREF(x);
8603 goto onError;
8604 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008605 Py_XDECREF(x);
Benjamin Peterson29060642009-01-31 22:14:21 +00008606 if (x!=Py_None) /* it worked => adjust input pointer */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008607 ++i;
Benjamin Peterson29060642009-01-31 22:14:21 +00008608 else { /* untranslatable character */
8609 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
8610 Py_ssize_t repsize;
8611 Py_ssize_t newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008612 Py_ssize_t uni2;
Benjamin Peterson29060642009-01-31 22:14:21 +00008613 /* startpos for collecting untranslatable chars */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008614 Py_ssize_t collstart = i;
8615 Py_ssize_t collend = i+1;
8616 Py_ssize_t coll;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008617
Benjamin Peterson29060642009-01-31 22:14:21 +00008618 /* find all untranslatable characters */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008619 while (collend < size) {
8620 if (charmaptranslate_lookup(PyUnicode_READ(kind,idata, collend), mapping, &x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008621 goto onError;
8622 Py_XDECREF(x);
8623 if (x!=Py_None)
8624 break;
8625 ++collend;
8626 }
8627 /* cache callback name lookup
8628 * (if not done yet, i.e. it's the first error) */
8629 if (known_errorHandler==-1) {
8630 if ((errors==NULL) || (!strcmp(errors, "strict")))
8631 known_errorHandler = 1;
8632 else if (!strcmp(errors, "replace"))
8633 known_errorHandler = 2;
8634 else if (!strcmp(errors, "ignore"))
8635 known_errorHandler = 3;
8636 else if (!strcmp(errors, "xmlcharrefreplace"))
8637 known_errorHandler = 4;
8638 else
8639 known_errorHandler = 0;
8640 }
8641 switch (known_errorHandler) {
8642 case 1: /* strict */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008643 raise_translate_exception(&exc, input, collstart,
8644 collend, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008645 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00008646 case 2: /* replace */
8647 /* No need to check for space, this is a 1:1 replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008648 for (coll = collstart; coll<collend; coll++)
8649 output[opos++] = '?';
Benjamin Peterson29060642009-01-31 22:14:21 +00008650 /* fall through */
8651 case 3: /* ignore */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008652 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008653 break;
8654 case 4: /* xmlcharrefreplace */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008655 /* generate replacement (temporarily (mis)uses i) */
8656 for (i = collstart; i < collend; ++i) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008657 char buffer[2+29+1+1];
8658 char *cp;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008659 sprintf(buffer, "&#%d;", PyUnicode_READ(kind, idata, i));
8660 if (charmaptranslate_makespace(&output, &osize,
8661 opos+strlen(buffer)+(size-collend)))
Benjamin Peterson29060642009-01-31 22:14:21 +00008662 goto onError;
8663 for (cp = buffer; *cp; ++cp)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008664 output[opos++] = *cp;
Benjamin Peterson29060642009-01-31 22:14:21 +00008665 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008666 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008667 break;
8668 default:
8669 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008670 reason, input, &exc,
8671 collstart, collend, &newpos);
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02008672 if (repunicode == NULL || _PyUnicode_READY_REPLACE(&repunicode))
Benjamin Peterson29060642009-01-31 22:14:21 +00008673 goto onError;
8674 /* generate replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008675 repsize = PyUnicode_GET_LENGTH(repunicode);
8676 if (charmaptranslate_makespace(&output, &osize,
8677 opos+repsize+(size-collend))) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008678 Py_DECREF(repunicode);
8679 goto onError;
8680 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008681 for (uni2 = 0; repsize-->0; ++uni2)
8682 output[opos++] = PyUnicode_READ_CHAR(repunicode, uni2);
8683 i = newpos;
Benjamin Peterson29060642009-01-31 22:14:21 +00008684 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008685 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008686 }
8687 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008688 res = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND, output, opos);
8689 if (!res)
8690 goto onError;
8691 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008692 Py_XDECREF(exc);
8693 Py_XDECREF(errorHandler);
8694 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008695
Benjamin Peterson29060642009-01-31 22:14:21 +00008696 onError:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008697 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008698 Py_XDECREF(exc);
8699 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008700 return NULL;
8701}
8702
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008703/* Deprecated. Use PyUnicode_Translate instead. */
8704PyObject *
8705PyUnicode_TranslateCharmap(const Py_UNICODE *p,
8706 Py_ssize_t size,
8707 PyObject *mapping,
8708 const char *errors)
8709{
8710 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8711 if (!unicode)
8712 return NULL;
8713 return _PyUnicode_TranslateCharmap(unicode, mapping, errors);
8714}
8715
Alexander Belopolsky40018472011-02-26 01:02:56 +00008716PyObject *
8717PyUnicode_Translate(PyObject *str,
8718 PyObject *mapping,
8719 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008720{
8721 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +00008722
Guido van Rossumd57fd912000-03-10 22:53:23 +00008723 str = PyUnicode_FromObject(str);
8724 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008725 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008726 result = _PyUnicode_TranslateCharmap(str, mapping, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008727 Py_DECREF(str);
8728 return result;
Tim Petersced69f82003-09-16 20:30:58 +00008729
Benjamin Peterson29060642009-01-31 22:14:21 +00008730 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00008731 Py_XDECREF(str);
8732 return NULL;
8733}
Tim Petersced69f82003-09-16 20:30:58 +00008734
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008735static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02008736fix_decimal_and_space_to_ascii(PyObject *self)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008737{
8738 /* No need to call PyUnicode_READY(self) because this function is only
8739 called as a callback from fixup() which does it already. */
8740 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
8741 const int kind = PyUnicode_KIND(self);
8742 void *data = PyUnicode_DATA(self);
8743 Py_UCS4 maxchar = 0, ch, fixed;
8744 Py_ssize_t i;
8745
8746 for (i = 0; i < len; ++i) {
8747 ch = PyUnicode_READ(kind, data, i);
8748 fixed = 0;
8749 if (ch > 127) {
8750 if (Py_UNICODE_ISSPACE(ch))
8751 fixed = ' ';
8752 else {
8753 const int decimal = Py_UNICODE_TODECIMAL(ch);
8754 if (decimal >= 0)
8755 fixed = '0' + decimal;
8756 }
8757 if (fixed != 0) {
8758 if (fixed > maxchar)
8759 maxchar = fixed;
8760 PyUnicode_WRITE(kind, data, i, fixed);
8761 }
8762 else if (ch > maxchar)
8763 maxchar = ch;
8764 }
8765 else if (ch > maxchar)
8766 maxchar = ch;
8767 }
8768
8769 return maxchar;
8770}
8771
8772PyObject *
8773_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
8774{
8775 if (!PyUnicode_Check(unicode)) {
8776 PyErr_BadInternalCall();
8777 return NULL;
8778 }
8779 if (PyUnicode_READY(unicode) == -1)
8780 return NULL;
8781 if (PyUnicode_MAX_CHAR_VALUE(unicode) <= 127) {
8782 /* If the string is already ASCII, just return the same string */
8783 Py_INCREF(unicode);
8784 return unicode;
8785 }
Victor Stinner9310abb2011-10-05 00:59:23 +02008786 return fixup(unicode, fix_decimal_and_space_to_ascii);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008787}
8788
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008789PyObject *
8790PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
8791 Py_ssize_t length)
8792{
8793 PyObject *result;
8794 Py_UNICODE *p; /* write pointer into result */
8795 Py_ssize_t i;
8796 /* Copy to a new string */
8797 result = (PyObject *)_PyUnicode_New(length);
8798 Py_UNICODE_COPY(PyUnicode_AS_UNICODE(result), s, length);
8799 if (result == NULL)
8800 return result;
8801 p = PyUnicode_AS_UNICODE(result);
8802 /* Iterate over code points */
8803 for (i = 0; i < length; i++) {
8804 Py_UNICODE ch =s[i];
8805 if (ch > 127) {
8806 int decimal = Py_UNICODE_TODECIMAL(ch);
8807 if (decimal >= 0)
8808 p[i] = '0' + decimal;
8809 }
8810 }
Victor Stinner17efeed2011-10-04 20:05:46 +02008811#ifndef DONT_MAKE_RESULT_READY
8812 if (_PyUnicode_READY_REPLACE(&result)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008813 Py_DECREF(result);
8814 return NULL;
8815 }
Victor Stinner17efeed2011-10-04 20:05:46 +02008816#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02008817 assert(_PyUnicode_CheckConsistency(result, 1));
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008818 return result;
8819}
Guido van Rossum9e896b32000-04-05 20:11:21 +00008820/* --- Decimal Encoder ---------------------------------------------------- */
8821
Alexander Belopolsky40018472011-02-26 01:02:56 +00008822int
8823PyUnicode_EncodeDecimal(Py_UNICODE *s,
8824 Py_ssize_t length,
8825 char *output,
8826 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00008827{
8828 Py_UNICODE *p, *end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008829 PyObject *errorHandler = NULL;
8830 PyObject *exc = NULL;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008831 PyObject *unicode;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008832 const char *encoding = "decimal";
8833 const char *reason = "invalid decimal Unicode string";
8834 /* the following variable is used for caching string comparisons
8835 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
8836 int known_errorHandler = -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008837
8838 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008839 PyErr_BadArgument();
8840 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008841 }
8842
8843 p = s;
8844 end = s + length;
8845 while (p < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008846 register Py_UNICODE ch = *p;
8847 int decimal;
8848 PyObject *repunicode;
8849 Py_ssize_t repsize;
8850 Py_ssize_t newpos;
8851 Py_UNICODE *uni2;
8852 Py_UNICODE *collstart;
8853 Py_UNICODE *collend;
Tim Petersced69f82003-09-16 20:30:58 +00008854
Benjamin Peterson29060642009-01-31 22:14:21 +00008855 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008856 *output++ = ' ';
Benjamin Peterson29060642009-01-31 22:14:21 +00008857 ++p;
8858 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008859 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008860 decimal = Py_UNICODE_TODECIMAL(ch);
8861 if (decimal >= 0) {
8862 *output++ = '0' + decimal;
8863 ++p;
8864 continue;
8865 }
8866 if (0 < ch && ch < 256) {
8867 *output++ = (char)ch;
8868 ++p;
8869 continue;
8870 }
8871 /* All other characters are considered unencodable */
8872 collstart = p;
8873 collend = p+1;
8874 while (collend < end) {
8875 if ((0 < *collend && *collend < 256) ||
8876 !Py_UNICODE_ISSPACE(*collend) ||
8877 Py_UNICODE_TODECIMAL(*collend))
8878 break;
8879 }
8880 /* cache callback name lookup
8881 * (if not done yet, i.e. it's the first error) */
8882 if (known_errorHandler==-1) {
8883 if ((errors==NULL) || (!strcmp(errors, "strict")))
8884 known_errorHandler = 1;
8885 else if (!strcmp(errors, "replace"))
8886 known_errorHandler = 2;
8887 else if (!strcmp(errors, "ignore"))
8888 known_errorHandler = 3;
8889 else if (!strcmp(errors, "xmlcharrefreplace"))
8890 known_errorHandler = 4;
8891 else
8892 known_errorHandler = 0;
8893 }
8894 switch (known_errorHandler) {
8895 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008896 unicode = PyUnicode_FromUnicode(s, length);
8897 if (unicode == NULL)
8898 goto onError;
8899 raise_encode_exception(&exc, encoding, unicode, collstart-s, collend-s, reason);
8900 Py_DECREF(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00008901 goto onError;
8902 case 2: /* replace */
8903 for (p = collstart; p < collend; ++p)
8904 *output++ = '?';
8905 /* fall through */
8906 case 3: /* ignore */
8907 p = collend;
8908 break;
8909 case 4: /* xmlcharrefreplace */
8910 /* generate replacement (temporarily (mis)uses p) */
8911 for (p = collstart; p < collend; ++p)
8912 output += sprintf(output, "&#%d;", (int)*p);
8913 p = collend;
8914 break;
8915 default:
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008916 unicode = PyUnicode_FromUnicode(s, length);
8917 if (unicode == NULL)
8918 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00008919 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008920 encoding, reason, unicode, &exc,
Benjamin Peterson29060642009-01-31 22:14:21 +00008921 collstart-s, collend-s, &newpos);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008922 Py_DECREF(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00008923 if (repunicode == NULL)
8924 goto onError;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008925 if (!PyUnicode_Check(repunicode)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00008926 /* Byte results not supported, since they have no decimal property. */
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008927 PyErr_SetString(PyExc_TypeError, "error handler should return unicode");
8928 Py_DECREF(repunicode);
8929 goto onError;
8930 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008931 /* generate replacement */
8932 repsize = PyUnicode_GET_SIZE(repunicode);
8933 for (uni2 = PyUnicode_AS_UNICODE(repunicode); repsize-->0; ++uni2) {
8934 Py_UNICODE ch = *uni2;
8935 if (Py_UNICODE_ISSPACE(ch))
8936 *output++ = ' ';
8937 else {
8938 decimal = Py_UNICODE_TODECIMAL(ch);
8939 if (decimal >= 0)
8940 *output++ = '0' + decimal;
8941 else if (0 < ch && ch < 256)
8942 *output++ = (char)ch;
8943 else {
8944 Py_DECREF(repunicode);
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008945 unicode = PyUnicode_FromUnicode(s, length);
8946 if (unicode == NULL)
8947 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00008948 raise_encode_exception(&exc, encoding,
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008949 unicode, collstart-s, collend-s, reason);
8950 Py_DECREF(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00008951 goto onError;
8952 }
8953 }
8954 }
8955 p = s + newpos;
8956 Py_DECREF(repunicode);
8957 }
Guido van Rossum9e896b32000-04-05 20:11:21 +00008958 }
8959 /* 0-terminate the output string */
8960 *output++ = '\0';
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008961 Py_XDECREF(exc);
8962 Py_XDECREF(errorHandler);
Guido van Rossum9e896b32000-04-05 20:11:21 +00008963 return 0;
8964
Benjamin Peterson29060642009-01-31 22:14:21 +00008965 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008966 Py_XDECREF(exc);
8967 Py_XDECREF(errorHandler);
Guido van Rossum9e896b32000-04-05 20:11:21 +00008968 return -1;
8969}
8970
Guido van Rossumd57fd912000-03-10 22:53:23 +00008971/* --- Helpers ------------------------------------------------------------ */
8972
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008973static Py_ssize_t
Victor Stinner794d5672011-10-10 03:21:36 +02008974any_find_slice(int direction, PyObject* s1, PyObject* s2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008975 Py_ssize_t start,
8976 Py_ssize_t end)
8977{
8978 int kind1, kind2, kind;
8979 void *buf1, *buf2;
8980 Py_ssize_t len1, len2, result;
8981
8982 kind1 = PyUnicode_KIND(s1);
8983 kind2 = PyUnicode_KIND(s2);
8984 kind = kind1 > kind2 ? kind1 : kind2;
8985 buf1 = PyUnicode_DATA(s1);
8986 buf2 = PyUnicode_DATA(s2);
8987 if (kind1 != kind)
8988 buf1 = _PyUnicode_AsKind(s1, kind);
8989 if (!buf1)
8990 return -2;
8991 if (kind2 != kind)
8992 buf2 = _PyUnicode_AsKind(s2, kind);
8993 if (!buf2) {
8994 if (kind1 != kind) PyMem_Free(buf1);
8995 return -2;
8996 }
8997 len1 = PyUnicode_GET_LENGTH(s1);
8998 len2 = PyUnicode_GET_LENGTH(s2);
8999
Victor Stinner794d5672011-10-10 03:21:36 +02009000 if (direction > 0) {
9001 switch(kind) {
9002 case PyUnicode_1BYTE_KIND:
9003 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9004 result = asciilib_find_slice(buf1, len1, buf2, len2, start, end);
9005 else
9006 result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end);
9007 break;
9008 case PyUnicode_2BYTE_KIND:
9009 result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end);
9010 break;
9011 case PyUnicode_4BYTE_KIND:
9012 result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end);
9013 break;
9014 default:
9015 assert(0); result = -2;
9016 }
9017 }
9018 else {
9019 switch(kind) {
9020 case PyUnicode_1BYTE_KIND:
9021 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9022 result = asciilib_rfind_slice(buf1, len1, buf2, len2, start, end);
9023 else
9024 result = ucs1lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9025 break;
9026 case PyUnicode_2BYTE_KIND:
9027 result = ucs2lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9028 break;
9029 case PyUnicode_4BYTE_KIND:
9030 result = ucs4lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9031 break;
9032 default:
9033 assert(0); result = -2;
9034 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009035 }
9036
9037 if (kind1 != kind)
9038 PyMem_Free(buf1);
9039 if (kind2 != kind)
9040 PyMem_Free(buf2);
9041
9042 return result;
9043}
9044
9045Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +02009046_PyUnicode_InsertThousandsGrouping(PyObject *unicode, int kind, void *data,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009047 Py_ssize_t n_buffer,
9048 void *digits, Py_ssize_t n_digits,
9049 Py_ssize_t min_width,
9050 const char *grouping,
9051 const char *thousands_sep)
9052{
9053 switch(kind) {
9054 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009055 if (unicode != NULL && PyUnicode_IS_ASCII(unicode))
9056 return _PyUnicode_ascii_InsertThousandsGrouping(
9057 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
9058 min_width, grouping, thousands_sep);
9059 else
9060 return _PyUnicode_ucs1_InsertThousandsGrouping(
9061 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
9062 min_width, grouping, thousands_sep);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009063 case PyUnicode_2BYTE_KIND:
9064 return _PyUnicode_ucs2_InsertThousandsGrouping(
9065 (Py_UCS2*)data, n_buffer, (Py_UCS2*)digits, n_digits,
9066 min_width, grouping, thousands_sep);
9067 case PyUnicode_4BYTE_KIND:
9068 return _PyUnicode_ucs4_InsertThousandsGrouping(
9069 (Py_UCS4*)data, n_buffer, (Py_UCS4*)digits, n_digits,
9070 min_width, grouping, thousands_sep);
9071 }
9072 assert(0);
9073 return -1;
9074}
9075
9076
Thomas Wouters477c8d52006-05-27 19:21:47 +00009077/* helper macro to fixup start/end slice values */
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009078#define ADJUST_INDICES(start, end, len) \
9079 if (end > len) \
9080 end = len; \
9081 else if (end < 0) { \
9082 end += len; \
9083 if (end < 0) \
9084 end = 0; \
9085 } \
9086 if (start < 0) { \
9087 start += len; \
9088 if (start < 0) \
9089 start = 0; \
9090 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009091
Alexander Belopolsky40018472011-02-26 01:02:56 +00009092Py_ssize_t
9093PyUnicode_Count(PyObject *str,
9094 PyObject *substr,
9095 Py_ssize_t start,
9096 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009097{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009098 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009099 PyObject* str_obj;
9100 PyObject* sub_obj;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009101 int kind1, kind2, kind;
9102 void *buf1 = NULL, *buf2 = NULL;
9103 Py_ssize_t len1, len2;
Tim Petersced69f82003-09-16 20:30:58 +00009104
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009105 str_obj = PyUnicode_FromObject(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009106 if (!str_obj || PyUnicode_READY(str_obj) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00009107 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009108 sub_obj = PyUnicode_FromObject(substr);
Victor Stinnere9a29352011-10-01 02:14:59 +02009109 if (!sub_obj || PyUnicode_READY(sub_obj) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009110 Py_DECREF(str_obj);
9111 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009112 }
Tim Petersced69f82003-09-16 20:30:58 +00009113
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009114 kind1 = PyUnicode_KIND(str_obj);
9115 kind2 = PyUnicode_KIND(sub_obj);
9116 kind = kind1 > kind2 ? kind1 : kind2;
9117 buf1 = PyUnicode_DATA(str_obj);
9118 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009119 buf1 = _PyUnicode_AsKind(str_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009120 if (!buf1)
9121 goto onError;
9122 buf2 = PyUnicode_DATA(sub_obj);
9123 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009124 buf2 = _PyUnicode_AsKind(sub_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009125 if (!buf2)
9126 goto onError;
9127 len1 = PyUnicode_GET_LENGTH(str_obj);
9128 len2 = PyUnicode_GET_LENGTH(sub_obj);
9129
9130 ADJUST_INDICES(start, end, len1);
9131 switch(kind) {
9132 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009133 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sub_obj))
9134 result = asciilib_count(
9135 ((Py_UCS1*)buf1) + start, end - start,
9136 buf2, len2, PY_SSIZE_T_MAX
9137 );
9138 else
9139 result = ucs1lib_count(
9140 ((Py_UCS1*)buf1) + start, end - start,
9141 buf2, len2, PY_SSIZE_T_MAX
9142 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009143 break;
9144 case PyUnicode_2BYTE_KIND:
9145 result = ucs2lib_count(
9146 ((Py_UCS2*)buf1) + start, end - start,
9147 buf2, len2, PY_SSIZE_T_MAX
9148 );
9149 break;
9150 case PyUnicode_4BYTE_KIND:
9151 result = ucs4lib_count(
9152 ((Py_UCS4*)buf1) + start, end - start,
9153 buf2, len2, PY_SSIZE_T_MAX
9154 );
9155 break;
9156 default:
9157 assert(0); result = 0;
9158 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009159
9160 Py_DECREF(sub_obj);
9161 Py_DECREF(str_obj);
9162
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009163 if (kind1 != kind)
9164 PyMem_Free(buf1);
9165 if (kind2 != kind)
9166 PyMem_Free(buf2);
9167
Guido van Rossumd57fd912000-03-10 22:53:23 +00009168 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009169 onError:
9170 Py_DECREF(sub_obj);
9171 Py_DECREF(str_obj);
9172 if (kind1 != kind && buf1)
9173 PyMem_Free(buf1);
9174 if (kind2 != kind && buf2)
9175 PyMem_Free(buf2);
9176 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009177}
9178
Alexander Belopolsky40018472011-02-26 01:02:56 +00009179Py_ssize_t
9180PyUnicode_Find(PyObject *str,
9181 PyObject *sub,
9182 Py_ssize_t start,
9183 Py_ssize_t end,
9184 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009185{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009186 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009187
Guido van Rossumd57fd912000-03-10 22:53:23 +00009188 str = PyUnicode_FromObject(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009189 if (!str || PyUnicode_READY(str) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00009190 return -2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009191 sub = PyUnicode_FromObject(sub);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009192 if (!sub || PyUnicode_READY(sub) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009193 Py_DECREF(str);
9194 return -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009195 }
Tim Petersced69f82003-09-16 20:30:58 +00009196
Victor Stinner794d5672011-10-10 03:21:36 +02009197 result = any_find_slice(direction,
9198 str, sub, start, end
9199 );
Thomas Wouters477c8d52006-05-27 19:21:47 +00009200
Guido van Rossumd57fd912000-03-10 22:53:23 +00009201 Py_DECREF(str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009202 Py_DECREF(sub);
9203
Guido van Rossumd57fd912000-03-10 22:53:23 +00009204 return result;
9205}
9206
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009207Py_ssize_t
9208PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
9209 Py_ssize_t start, Py_ssize_t end,
9210 int direction)
9211{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009212 int kind;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009213 Py_ssize_t result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009214 if (PyUnicode_READY(str) == -1)
9215 return -2;
Victor Stinner267aa242011-10-02 01:08:37 +02009216 if (start < 0 || end < 0) {
9217 PyErr_SetString(PyExc_IndexError, "string index out of range");
9218 return -2;
9219 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009220 if (end > PyUnicode_GET_LENGTH(str))
9221 end = PyUnicode_GET_LENGTH(str);
9222 kind = PyUnicode_KIND(str);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009223 result = findchar(PyUnicode_1BYTE_DATA(str) + kind*start,
9224 kind, end-start, ch, direction);
9225 if (result == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009226 return -1;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009227 else
9228 return start + result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009229}
9230
Alexander Belopolsky40018472011-02-26 01:02:56 +00009231static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009232tailmatch(PyObject *self,
9233 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009234 Py_ssize_t start,
9235 Py_ssize_t end,
9236 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009237{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009238 int kind_self;
9239 int kind_sub;
9240 void *data_self;
9241 void *data_sub;
9242 Py_ssize_t offset;
9243 Py_ssize_t i;
9244 Py_ssize_t end_sub;
9245
9246 if (PyUnicode_READY(self) == -1 ||
9247 PyUnicode_READY(substring) == -1)
9248 return 0;
9249
9250 if (PyUnicode_GET_LENGTH(substring) == 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009251 return 1;
9252
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009253 ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
9254 end -= PyUnicode_GET_LENGTH(substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009255 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00009256 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009257
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009258 kind_self = PyUnicode_KIND(self);
9259 data_self = PyUnicode_DATA(self);
9260 kind_sub = PyUnicode_KIND(substring);
9261 data_sub = PyUnicode_DATA(substring);
9262 end_sub = PyUnicode_GET_LENGTH(substring) - 1;
9263
9264 if (direction > 0)
9265 offset = end;
9266 else
9267 offset = start;
9268
9269 if (PyUnicode_READ(kind_self, data_self, offset) ==
9270 PyUnicode_READ(kind_sub, data_sub, 0) &&
9271 PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
9272 PyUnicode_READ(kind_sub, data_sub, end_sub)) {
9273 /* If both are of the same kind, memcmp is sufficient */
9274 if (kind_self == kind_sub) {
9275 return ! memcmp((char *)data_self +
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009276 (offset * PyUnicode_KIND(substring)),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009277 data_sub,
9278 PyUnicode_GET_LENGTH(substring) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009279 PyUnicode_KIND(substring));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009280 }
9281 /* otherwise we have to compare each character by first accesing it */
9282 else {
9283 /* We do not need to compare 0 and len(substring)-1 because
9284 the if statement above ensured already that they are equal
9285 when we end up here. */
9286 // TODO: honor direction and do a forward or backwards search
9287 for (i = 1; i < end_sub; ++i) {
9288 if (PyUnicode_READ(kind_self, data_self, offset + i) !=
9289 PyUnicode_READ(kind_sub, data_sub, i))
9290 return 0;
9291 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009292 return 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009293 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009294 }
9295
9296 return 0;
9297}
9298
Alexander Belopolsky40018472011-02-26 01:02:56 +00009299Py_ssize_t
9300PyUnicode_Tailmatch(PyObject *str,
9301 PyObject *substr,
9302 Py_ssize_t start,
9303 Py_ssize_t end,
9304 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009305{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009306 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009307
Guido van Rossumd57fd912000-03-10 22:53:23 +00009308 str = PyUnicode_FromObject(str);
9309 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009310 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009311 substr = PyUnicode_FromObject(substr);
9312 if (substr == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009313 Py_DECREF(str);
9314 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009315 }
Tim Petersced69f82003-09-16 20:30:58 +00009316
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009317 result = tailmatch(str, substr,
Benjamin Peterson29060642009-01-31 22:14:21 +00009318 start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009319 Py_DECREF(str);
9320 Py_DECREF(substr);
9321 return result;
9322}
9323
Guido van Rossumd57fd912000-03-10 22:53:23 +00009324/* Apply fixfct filter to the Unicode object self and return a
9325 reference to the modified object */
9326
Alexander Belopolsky40018472011-02-26 01:02:56 +00009327static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009328fixup(PyObject *self,
9329 Py_UCS4 (*fixfct)(PyObject *s))
Guido van Rossumd57fd912000-03-10 22:53:23 +00009330{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009331 PyObject *u;
9332 Py_UCS4 maxchar_old, maxchar_new = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009333
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009334 if (PyUnicode_READY(self) == -1)
9335 return NULL;
9336 maxchar_old = PyUnicode_MAX_CHAR_VALUE(self);
9337 u = PyUnicode_New(PyUnicode_GET_LENGTH(self),
9338 maxchar_old);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009339 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009340 return NULL;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009341
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009342 Py_MEMCPY(PyUnicode_1BYTE_DATA(u), PyUnicode_1BYTE_DATA(self),
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009343 PyUnicode_GET_LENGTH(u) * PyUnicode_KIND(u));
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009344
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009345 /* fix functions return the new maximum character in a string,
9346 if the kind of the resulting unicode object does not change,
9347 everything is fine. Otherwise we need to change the string kind
9348 and re-run the fix function. */
Victor Stinner9310abb2011-10-05 00:59:23 +02009349 maxchar_new = fixfct(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009350 if (maxchar_new == 0)
9351 /* do nothing, keep maxchar_new at 0 which means no changes. */;
9352 else if (maxchar_new <= 127)
9353 maxchar_new = 127;
9354 else if (maxchar_new <= 255)
9355 maxchar_new = 255;
9356 else if (maxchar_new <= 65535)
9357 maxchar_new = 65535;
9358 else
9359 maxchar_new = 1114111; /* 0x10ffff */
9360
9361 if (!maxchar_new && PyUnicode_CheckExact(self)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009362 /* fixfct should return TRUE if it modified the buffer. If
9363 FALSE, return a reference to the original buffer instead
9364 (to save space, not time) */
9365 Py_INCREF(self);
9366 Py_DECREF(u);
Victor Stinner7931d9a2011-11-04 00:22:48 +01009367 return self;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009368 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009369 else if (maxchar_new == maxchar_old) {
9370 return u;
9371 }
9372 else {
9373 /* In case the maximum character changed, we need to
9374 convert the string to the new category. */
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009375 PyObject *v = PyUnicode_New(PyUnicode_GET_LENGTH(self), maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009376 if (v == NULL) {
9377 Py_DECREF(u);
9378 return NULL;
9379 }
9380 if (maxchar_new > maxchar_old) {
9381 /* If the maxchar increased so that the kind changed, not all
9382 characters are representable anymore and we need to fix the
9383 string again. This only happens in very few cases. */
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009384 copy_characters(v, 0, self, 0, PyUnicode_GET_LENGTH(self));
Victor Stinner9310abb2011-10-05 00:59:23 +02009385 maxchar_old = fixfct(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009386 assert(maxchar_old > 0 && maxchar_old <= maxchar_new);
9387 }
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009388 else {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009389 copy_characters(v, 0, u, 0, PyUnicode_GET_LENGTH(self));
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009390 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009391
9392 Py_DECREF(u);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009393 assert(_PyUnicode_CheckConsistency(v, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009394 return v;
9395 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009396}
9397
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009398static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009399fixupper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009400{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009401 /* No need to call PyUnicode_READY(self) because this function is only
9402 called as a callback from fixup() which does it already. */
9403 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9404 const int kind = PyUnicode_KIND(self);
9405 void *data = PyUnicode_DATA(self);
9406 int touched = 0;
9407 Py_UCS4 maxchar = 0;
9408 Py_ssize_t i;
Tim Petersced69f82003-09-16 20:30:58 +00009409
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009410 for (i = 0; i < len; ++i) {
9411 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9412 const Py_UCS4 up = Py_UNICODE_TOUPPER(ch);
9413 if (up != ch) {
9414 if (up > maxchar)
9415 maxchar = up;
9416 PyUnicode_WRITE(kind, data, i, up);
9417 touched = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00009418 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009419 else if (ch > maxchar)
9420 maxchar = ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009421 }
9422
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009423 if (touched)
9424 return maxchar;
9425 else
9426 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009427}
9428
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009429static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009430fixlower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009431{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009432 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
9433 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9434 const int kind = PyUnicode_KIND(self);
9435 void *data = PyUnicode_DATA(self);
9436 int touched = 0;
9437 Py_UCS4 maxchar = 0;
9438 Py_ssize_t i;
Tim Petersced69f82003-09-16 20:30:58 +00009439
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009440 for(i = 0; i < len; ++i) {
9441 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9442 const Py_UCS4 lo = Py_UNICODE_TOLOWER(ch);
9443 if (lo != ch) {
9444 if (lo > maxchar)
9445 maxchar = lo;
9446 PyUnicode_WRITE(kind, data, i, lo);
9447 touched = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00009448 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009449 else if (ch > maxchar)
9450 maxchar = ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009451 }
9452
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009453 if (touched)
9454 return maxchar;
9455 else
9456 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009457}
9458
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009459static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009460fixswapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009461{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009462 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
9463 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9464 const int kind = PyUnicode_KIND(self);
9465 void *data = PyUnicode_DATA(self);
9466 int touched = 0;
9467 Py_UCS4 maxchar = 0;
9468 Py_ssize_t i;
Tim Petersced69f82003-09-16 20:30:58 +00009469
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009470 for(i = 0; i < len; ++i) {
9471 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9472 Py_UCS4 nu = 0;
9473
9474 if (Py_UNICODE_ISUPPER(ch))
9475 nu = Py_UNICODE_TOLOWER(ch);
9476 else if (Py_UNICODE_ISLOWER(ch))
9477 nu = Py_UNICODE_TOUPPER(ch);
9478
9479 if (nu != 0) {
9480 if (nu > maxchar)
9481 maxchar = nu;
9482 PyUnicode_WRITE(kind, data, i, nu);
9483 touched = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009484 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009485 else if (ch > maxchar)
9486 maxchar = ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009487 }
9488
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009489 if (touched)
9490 return maxchar;
9491 else
9492 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009493}
9494
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009495static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009496fixcapitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009497{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009498 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
9499 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9500 const int kind = PyUnicode_KIND(self);
9501 void *data = PyUnicode_DATA(self);
9502 int touched = 0;
9503 Py_UCS4 maxchar = 0;
9504 Py_ssize_t i = 0;
9505 Py_UCS4 ch;
Tim Petersced69f82003-09-16 20:30:58 +00009506
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009507 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009508 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009509
9510 ch = PyUnicode_READ(kind, data, i);
9511 if (!Py_UNICODE_ISUPPER(ch)) {
9512 maxchar = Py_UNICODE_TOUPPER(ch);
9513 PyUnicode_WRITE(kind, data, i, maxchar);
9514 touched = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009515 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009516 ++i;
9517 for(; i < len; ++i) {
9518 ch = PyUnicode_READ(kind, data, i);
9519 if (!Py_UNICODE_ISLOWER(ch)) {
9520 const Py_UCS4 lo = Py_UNICODE_TOLOWER(ch);
9521 if (lo > maxchar)
9522 maxchar = lo;
9523 PyUnicode_WRITE(kind, data, i, lo);
9524 touched = 1;
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009525 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009526 else if (ch > maxchar)
9527 maxchar = ch;
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009528 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009529
9530 if (touched)
9531 return maxchar;
9532 else
9533 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009534}
9535
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009536static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009537fixtitle(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009538{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009539 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
9540 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9541 const int kind = PyUnicode_KIND(self);
9542 void *data = PyUnicode_DATA(self);
9543 Py_UCS4 maxchar = 0;
9544 Py_ssize_t i = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009545 int previous_is_cased;
9546
9547 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009548 if (len == 1) {
9549 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9550 const Py_UCS4 ti = Py_UNICODE_TOTITLE(ch);
9551 if (ti != ch) {
9552 PyUnicode_WRITE(kind, data, i, ti);
9553 return ti;
Benjamin Peterson29060642009-01-31 22:14:21 +00009554 }
9555 else
9556 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009557 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009558 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009559 for(; i < len; ++i) {
9560 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9561 Py_UCS4 nu;
Tim Petersced69f82003-09-16 20:30:58 +00009562
Benjamin Peterson29060642009-01-31 22:14:21 +00009563 if (previous_is_cased)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009564 nu = Py_UNICODE_TOLOWER(ch);
Benjamin Peterson29060642009-01-31 22:14:21 +00009565 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009566 nu = Py_UNICODE_TOTITLE(ch);
9567
9568 if (nu > maxchar)
9569 maxchar = nu;
9570 PyUnicode_WRITE(kind, data, i, nu);
Tim Petersced69f82003-09-16 20:30:58 +00009571
Benjamin Peterson29060642009-01-31 22:14:21 +00009572 if (Py_UNICODE_ISLOWER(ch) ||
9573 Py_UNICODE_ISUPPER(ch) ||
9574 Py_UNICODE_ISTITLE(ch))
9575 previous_is_cased = 1;
9576 else
9577 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009578 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009579 return maxchar;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009580}
9581
Tim Peters8ce9f162004-08-27 01:49:32 +00009582PyObject *
9583PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009584{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009585 PyObject *sep = NULL;
Victor Stinnerdd077322011-10-07 17:02:31 +02009586 Py_ssize_t seplen;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009587 PyObject *res = NULL; /* the result */
Tim Peters05eba1f2004-08-27 21:32:02 +00009588 PyObject *fseq; /* PySequence_Fast(seq) */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009589 Py_ssize_t seqlen; /* len(fseq) -- number of items in sequence */
9590 PyObject **items;
Tim Peters8ce9f162004-08-27 01:49:32 +00009591 PyObject *item;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009592 Py_ssize_t sz, i, res_offset;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009593 Py_UCS4 maxchar;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009594 Py_UCS4 item_maxchar;
Victor Stinnerdd077322011-10-07 17:02:31 +02009595 int use_memcpy;
9596 unsigned char *res_data = NULL, *sep_data = NULL;
9597 PyObject *last_obj;
9598 unsigned int kind = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009599
Tim Peters05eba1f2004-08-27 21:32:02 +00009600 fseq = PySequence_Fast(seq, "");
9601 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009602 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00009603 }
9604
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009605 /* NOTE: the following code can't call back into Python code,
9606 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00009607 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009608
Tim Peters05eba1f2004-08-27 21:32:02 +00009609 seqlen = PySequence_Fast_GET_SIZE(fseq);
9610 /* If empty sequence, return u"". */
9611 if (seqlen == 0) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009612 Py_DECREF(fseq);
9613 Py_INCREF(unicode_empty);
9614 res = unicode_empty;
9615 return res;
Tim Peters05eba1f2004-08-27 21:32:02 +00009616 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009617
Tim Peters05eba1f2004-08-27 21:32:02 +00009618 /* If singleton sequence with an exact Unicode, return that. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009619 last_obj = NULL;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009620 items = PySequence_Fast_ITEMS(fseq);
Victor Stinneracf47b82011-10-06 12:32:37 +02009621 if (seqlen == 1) {
9622 if (PyUnicode_CheckExact(items[0])) {
9623 res = items[0];
9624 Py_INCREF(res);
9625 Py_DECREF(fseq);
9626 return res;
9627 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009628 seplen = 0;
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009629 maxchar = 0;
Tim Peters8ce9f162004-08-27 01:49:32 +00009630 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009631 else {
Victor Stinneracf47b82011-10-06 12:32:37 +02009632 /* Set up sep and seplen */
9633 if (separator == NULL) {
9634 /* fall back to a blank space separator */
9635 sep = PyUnicode_FromOrdinal(' ');
9636 if (!sep)
9637 goto onError;
Victor Stinnerdd077322011-10-07 17:02:31 +02009638 seplen = 1;
Victor Stinneracf47b82011-10-06 12:32:37 +02009639 maxchar = 32;
Tim Peters05eba1f2004-08-27 21:32:02 +00009640 }
Victor Stinneracf47b82011-10-06 12:32:37 +02009641 else {
9642 if (!PyUnicode_Check(separator)) {
9643 PyErr_Format(PyExc_TypeError,
9644 "separator: expected str instance,"
9645 " %.80s found",
9646 Py_TYPE(separator)->tp_name);
9647 goto onError;
9648 }
9649 if (PyUnicode_READY(separator))
9650 goto onError;
9651 sep = separator;
9652 seplen = PyUnicode_GET_LENGTH(separator);
9653 maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
9654 /* inc refcount to keep this code path symmetric with the
9655 above case of a blank separator */
9656 Py_INCREF(sep);
9657 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009658 last_obj = sep;
Tim Peters05eba1f2004-08-27 21:32:02 +00009659 }
9660
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009661 /* There are at least two things to join, or else we have a subclass
9662 * of str in the sequence.
9663 * Do a pre-pass to figure out the total amount of space we'll
9664 * need (sz), and see whether all argument are strings.
9665 */
9666 sz = 0;
Victor Stinnerdd077322011-10-07 17:02:31 +02009667#ifdef Py_DEBUG
9668 use_memcpy = 0;
9669#else
9670 use_memcpy = 1;
9671#endif
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009672 for (i = 0; i < seqlen; i++) {
9673 const Py_ssize_t old_sz = sz;
9674 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009675 if (!PyUnicode_Check(item)) {
9676 PyErr_Format(PyExc_TypeError,
9677 "sequence item %zd: expected str instance,"
9678 " %.80s found",
9679 i, Py_TYPE(item)->tp_name);
9680 goto onError;
9681 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009682 if (PyUnicode_READY(item) == -1)
9683 goto onError;
9684 sz += PyUnicode_GET_LENGTH(item);
9685 item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009686 maxchar = Py_MAX(maxchar, item_maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009687 if (i != 0)
9688 sz += seplen;
9689 if (sz < old_sz || sz > PY_SSIZE_T_MAX) {
9690 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009691 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009692 goto onError;
9693 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009694 if (use_memcpy && last_obj != NULL) {
9695 if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
9696 use_memcpy = 0;
9697 }
9698 last_obj = item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009699 }
Tim Petersced69f82003-09-16 20:30:58 +00009700
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009701 res = PyUnicode_New(sz, maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009702 if (res == NULL)
9703 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +00009704
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009705 /* Catenate everything. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009706#ifdef Py_DEBUG
9707 use_memcpy = 0;
9708#else
9709 if (use_memcpy) {
9710 res_data = PyUnicode_1BYTE_DATA(res);
9711 kind = PyUnicode_KIND(res);
9712 if (seplen != 0)
9713 sep_data = PyUnicode_1BYTE_DATA(sep);
9714 }
9715#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009716 for (i = 0, res_offset = 0; i < seqlen; ++i) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009717 Py_ssize_t itemlen;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009718 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009719 /* Copy item, and maybe the separator. */
Victor Stinner9ce5a832011-10-03 23:36:02 +02009720 if (i && seplen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009721 if (use_memcpy) {
9722 Py_MEMCPY(res_data,
9723 sep_data,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009724 kind * seplen);
9725 res_data += kind * seplen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009726 }
9727 else {
9728 copy_characters(res, res_offset, sep, 0, seplen);
9729 res_offset += seplen;
9730 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009731 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009732 itemlen = PyUnicode_GET_LENGTH(item);
9733 if (itemlen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009734 if (use_memcpy) {
9735 Py_MEMCPY(res_data,
9736 PyUnicode_DATA(item),
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009737 kind * itemlen);
9738 res_data += kind * itemlen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009739 }
9740 else {
9741 copy_characters(res, res_offset, item, 0, itemlen);
9742 res_offset += itemlen;
9743 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009744 }
Tim Peters05eba1f2004-08-27 21:32:02 +00009745 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009746 if (use_memcpy)
9747 assert(res_data == PyUnicode_1BYTE_DATA(res)
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009748 + kind * PyUnicode_GET_LENGTH(res));
Victor Stinnerdd077322011-10-07 17:02:31 +02009749 else
9750 assert(res_offset == PyUnicode_GET_LENGTH(res));
Tim Peters8ce9f162004-08-27 01:49:32 +00009751
Tim Peters05eba1f2004-08-27 21:32:02 +00009752 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009753 Py_XDECREF(sep);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009754 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009755 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009756
Benjamin Peterson29060642009-01-31 22:14:21 +00009757 onError:
Tim Peters05eba1f2004-08-27 21:32:02 +00009758 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009759 Py_XDECREF(sep);
Tim Peters8ce9f162004-08-27 01:49:32 +00009760 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009761 return NULL;
9762}
9763
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009764#define FILL(kind, data, value, start, length) \
9765 do { \
9766 Py_ssize_t i_ = 0; \
9767 assert(kind != PyUnicode_WCHAR_KIND); \
9768 switch ((kind)) { \
9769 case PyUnicode_1BYTE_KIND: { \
9770 unsigned char * to_ = (unsigned char *)((data)) + (start); \
9771 memset(to_, (unsigned char)value, length); \
9772 break; \
9773 } \
9774 case PyUnicode_2BYTE_KIND: { \
9775 Py_UCS2 * to_ = (Py_UCS2 *)((data)) + (start); \
9776 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9777 break; \
9778 } \
9779 default: { \
9780 Py_UCS4 * to_ = (Py_UCS4 *)((data)) + (start); \
9781 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9782 break; \
9783 } \
9784 } \
9785 } while (0)
9786
Victor Stinner9310abb2011-10-05 00:59:23 +02009787static PyObject *
9788pad(PyObject *self,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009789 Py_ssize_t left,
9790 Py_ssize_t right,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009791 Py_UCS4 fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009792{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009793 PyObject *u;
9794 Py_UCS4 maxchar;
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009795 int kind;
9796 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009797
9798 if (left < 0)
9799 left = 0;
9800 if (right < 0)
9801 right = 0;
9802
Tim Peters7a29bd52001-09-12 03:03:31 +00009803 if (left == 0 && right == 0 && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00009804 Py_INCREF(self);
9805 return self;
9806 }
9807
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009808 if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
9809 right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +00009810 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
9811 return NULL;
9812 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009813 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
9814 if (fill > maxchar)
9815 maxchar = fill;
9816 u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009817 if (!u)
9818 return NULL;
9819
9820 kind = PyUnicode_KIND(u);
9821 data = PyUnicode_DATA(u);
9822 if (left)
9823 FILL(kind, data, fill, 0, left);
9824 if (right)
9825 FILL(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009826 copy_characters(u, left, self, 0, _PyUnicode_LENGTH(self));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009827 assert(_PyUnicode_CheckConsistency(u, 1));
9828 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009829}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009830#undef FILL
Guido van Rossumd57fd912000-03-10 22:53:23 +00009831
Alexander Belopolsky40018472011-02-26 01:02:56 +00009832PyObject *
9833PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009834{
Guido van Rossumd57fd912000-03-10 22:53:23 +00009835 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009836
9837 string = PyUnicode_FromObject(string);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009838 if (string == NULL || PyUnicode_READY(string) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00009839 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009840
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009841 switch(PyUnicode_KIND(string)) {
9842 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009843 if (PyUnicode_IS_ASCII(string))
9844 list = asciilib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009845 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009846 PyUnicode_GET_LENGTH(string), keepends);
9847 else
9848 list = ucs1lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009849 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009850 PyUnicode_GET_LENGTH(string), keepends);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009851 break;
9852 case PyUnicode_2BYTE_KIND:
9853 list = ucs2lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009854 string, PyUnicode_2BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009855 PyUnicode_GET_LENGTH(string), keepends);
9856 break;
9857 case PyUnicode_4BYTE_KIND:
9858 list = ucs4lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009859 string, PyUnicode_4BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009860 PyUnicode_GET_LENGTH(string), keepends);
9861 break;
9862 default:
9863 assert(0);
9864 list = 0;
9865 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009866 Py_DECREF(string);
9867 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009868}
9869
Alexander Belopolsky40018472011-02-26 01:02:56 +00009870static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009871split(PyObject *self,
9872 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009873 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009874{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009875 int kind1, kind2, kind;
9876 void *buf1, *buf2;
9877 Py_ssize_t len1, len2;
9878 PyObject* out;
9879
Guido van Rossumd57fd912000-03-10 22:53:23 +00009880 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00009881 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009882
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009883 if (PyUnicode_READY(self) == -1)
9884 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009885
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009886 if (substring == NULL)
9887 switch(PyUnicode_KIND(self)) {
9888 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009889 if (PyUnicode_IS_ASCII(self))
9890 return asciilib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009891 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009892 PyUnicode_GET_LENGTH(self), maxcount
9893 );
9894 else
9895 return ucs1lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009896 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009897 PyUnicode_GET_LENGTH(self), maxcount
9898 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009899 case PyUnicode_2BYTE_KIND:
9900 return ucs2lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009901 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009902 PyUnicode_GET_LENGTH(self), maxcount
9903 );
9904 case PyUnicode_4BYTE_KIND:
9905 return ucs4lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009906 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009907 PyUnicode_GET_LENGTH(self), maxcount
9908 );
9909 default:
9910 assert(0);
9911 return NULL;
9912 }
9913
9914 if (PyUnicode_READY(substring) == -1)
9915 return NULL;
9916
9917 kind1 = PyUnicode_KIND(self);
9918 kind2 = PyUnicode_KIND(substring);
9919 kind = kind1 > kind2 ? kind1 : kind2;
9920 buf1 = PyUnicode_DATA(self);
9921 buf2 = PyUnicode_DATA(substring);
9922 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009923 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009924 if (!buf1)
9925 return NULL;
9926 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009927 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009928 if (!buf2) {
9929 if (kind1 != kind) PyMem_Free(buf1);
9930 return NULL;
9931 }
9932 len1 = PyUnicode_GET_LENGTH(self);
9933 len2 = PyUnicode_GET_LENGTH(substring);
9934
9935 switch(kind) {
9936 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009937 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
9938 out = asciilib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009939 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +02009940 else
9941 out = ucs1lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009942 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009943 break;
9944 case PyUnicode_2BYTE_KIND:
9945 out = ucs2lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009946 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009947 break;
9948 case PyUnicode_4BYTE_KIND:
9949 out = ucs4lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009950 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009951 break;
9952 default:
9953 out = NULL;
9954 }
9955 if (kind1 != kind)
9956 PyMem_Free(buf1);
9957 if (kind2 != kind)
9958 PyMem_Free(buf2);
9959 return out;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009960}
9961
Alexander Belopolsky40018472011-02-26 01:02:56 +00009962static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009963rsplit(PyObject *self,
9964 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009965 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009966{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009967 int kind1, kind2, kind;
9968 void *buf1, *buf2;
9969 Py_ssize_t len1, len2;
9970 PyObject* out;
9971
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009972 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00009973 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009974
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009975 if (PyUnicode_READY(self) == -1)
9976 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009977
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009978 if (substring == NULL)
9979 switch(PyUnicode_KIND(self)) {
9980 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009981 if (PyUnicode_IS_ASCII(self))
9982 return asciilib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009983 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009984 PyUnicode_GET_LENGTH(self), maxcount
9985 );
9986 else
9987 return ucs1lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009988 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009989 PyUnicode_GET_LENGTH(self), maxcount
9990 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009991 case PyUnicode_2BYTE_KIND:
9992 return ucs2lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009993 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009994 PyUnicode_GET_LENGTH(self), maxcount
9995 );
9996 case PyUnicode_4BYTE_KIND:
9997 return ucs4lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009998 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009999 PyUnicode_GET_LENGTH(self), maxcount
10000 );
10001 default:
10002 assert(0);
10003 return NULL;
10004 }
10005
10006 if (PyUnicode_READY(substring) == -1)
10007 return NULL;
10008
10009 kind1 = PyUnicode_KIND(self);
10010 kind2 = PyUnicode_KIND(substring);
10011 kind = kind1 > kind2 ? kind1 : kind2;
10012 buf1 = PyUnicode_DATA(self);
10013 buf2 = PyUnicode_DATA(substring);
10014 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010015 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010016 if (!buf1)
10017 return NULL;
10018 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010019 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010020 if (!buf2) {
10021 if (kind1 != kind) PyMem_Free(buf1);
10022 return NULL;
10023 }
10024 len1 = PyUnicode_GET_LENGTH(self);
10025 len2 = PyUnicode_GET_LENGTH(substring);
10026
10027 switch(kind) {
10028 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010029 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10030 out = asciilib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010031 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010032 else
10033 out = ucs1lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010034 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010035 break;
10036 case PyUnicode_2BYTE_KIND:
10037 out = ucs2lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010038 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010039 break;
10040 case PyUnicode_4BYTE_KIND:
10041 out = ucs4lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010042 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010043 break;
10044 default:
10045 out = NULL;
10046 }
10047 if (kind1 != kind)
10048 PyMem_Free(buf1);
10049 if (kind2 != kind)
10050 PyMem_Free(buf2);
10051 return out;
10052}
10053
10054static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010055anylib_find(int kind, PyObject *str1, void *buf1, Py_ssize_t len1,
10056 PyObject *str2, void *buf2, Py_ssize_t len2, Py_ssize_t offset)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010057{
10058 switch(kind) {
10059 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010060 if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
10061 return asciilib_find(buf1, len1, buf2, len2, offset);
10062 else
10063 return ucs1lib_find(buf1, len1, buf2, len2, offset);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010064 case PyUnicode_2BYTE_KIND:
10065 return ucs2lib_find(buf1, len1, buf2, len2, offset);
10066 case PyUnicode_4BYTE_KIND:
10067 return ucs4lib_find(buf1, len1, buf2, len2, offset);
10068 }
10069 assert(0);
10070 return -1;
10071}
10072
10073static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010074anylib_count(int kind, PyObject *sstr, void* sbuf, Py_ssize_t slen,
10075 PyObject *str1, void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010076{
10077 switch(kind) {
10078 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010079 if (PyUnicode_IS_ASCII(sstr) && PyUnicode_IS_ASCII(str1))
10080 return asciilib_count(sbuf, slen, buf1, len1, maxcount);
10081 else
10082 return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010083 case PyUnicode_2BYTE_KIND:
10084 return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
10085 case PyUnicode_4BYTE_KIND:
10086 return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
10087 }
10088 assert(0);
10089 return 0;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010090}
10091
Alexander Belopolsky40018472011-02-26 01:02:56 +000010092static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010093replace(PyObject *self, PyObject *str1,
10094 PyObject *str2, Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010095{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010096 PyObject *u;
10097 char *sbuf = PyUnicode_DATA(self);
10098 char *buf1 = PyUnicode_DATA(str1);
10099 char *buf2 = PyUnicode_DATA(str2);
10100 int srelease = 0, release1 = 0, release2 = 0;
10101 int skind = PyUnicode_KIND(self);
10102 int kind1 = PyUnicode_KIND(str1);
10103 int kind2 = PyUnicode_KIND(str2);
10104 Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
10105 Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
10106 Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010107 int mayshrink;
10108 Py_UCS4 maxchar, maxchar_str2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010109
10110 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010111 maxcount = PY_SSIZE_T_MAX;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010112 else if (maxcount == 0 || slen == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010113 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010114
Victor Stinner59de0ee2011-10-07 10:01:28 +020010115 if (str1 == str2)
10116 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010117 if (skind < kind1)
10118 /* substring too wide to be present */
10119 goto nothing;
10120
Victor Stinner49a0a212011-10-12 23:46:10 +020010121 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
10122 maxchar_str2 = PyUnicode_MAX_CHAR_VALUE(str2);
10123 /* Replacing str1 with str2 may cause a maxchar reduction in the
10124 result string. */
10125 mayshrink = (maxchar_str2 < maxchar);
10126 maxchar = Py_MAX(maxchar, maxchar_str2);
10127
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010128 if (len1 == len2) {
Antoine Pitroucbfdee32010-01-13 08:58:08 +000010129 Py_ssize_t i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010130 /* same length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010131 if (len1 == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010132 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010133 if (len1 == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010134 /* replace characters */
Victor Stinner49a0a212011-10-12 23:46:10 +020010135 Py_UCS4 u1, u2;
10136 int rkind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010137 u1 = PyUnicode_READ_CHAR(str1, 0);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +020010138 if (findchar(sbuf, PyUnicode_KIND(self),
10139 slen, u1, 1) < 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010140 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010141 u2 = PyUnicode_READ_CHAR(str2, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010142 u = PyUnicode_New(slen, maxchar);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010143 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010144 goto error;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020010145 copy_characters(u, 0, self, 0, slen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010146 rkind = PyUnicode_KIND(u);
10147 for (i = 0; i < PyUnicode_GET_LENGTH(u); i++)
10148 if (PyUnicode_READ(rkind, PyUnicode_DATA(u), i) == u1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010149 if (--maxcount < 0)
10150 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010151 PyUnicode_WRITE(rkind, PyUnicode_DATA(u), i, u2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010152 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010153 }
10154 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010155 int rkind = skind;
10156 char *res;
Victor Stinner25a4b292011-10-06 12:31:55 +020010157
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010158 if (kind1 < rkind) {
10159 /* widen substring */
10160 buf1 = _PyUnicode_AsKind(str1, rkind);
10161 if (!buf1) goto error;
10162 release1 = 1;
10163 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010164 i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010165 if (i < 0)
10166 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010167 if (rkind > kind2) {
10168 /* widen replacement */
10169 buf2 = _PyUnicode_AsKind(str2, rkind);
10170 if (!buf2) goto error;
10171 release2 = 1;
10172 }
10173 else if (rkind < kind2) {
10174 /* widen self and buf1 */
10175 rkind = kind2;
10176 if (release1) PyMem_Free(buf1);
10177 sbuf = _PyUnicode_AsKind(self, rkind);
10178 if (!sbuf) goto error;
10179 srelease = 1;
10180 buf1 = _PyUnicode_AsKind(str1, rkind);
10181 if (!buf1) goto error;
10182 release1 = 1;
10183 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010184 u = PyUnicode_New(slen, maxchar);
10185 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010186 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010187 assert(PyUnicode_KIND(u) == rkind);
10188 res = PyUnicode_DATA(u);
Victor Stinner25a4b292011-10-06 12:31:55 +020010189
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010190 memcpy(res, sbuf, rkind * slen);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010191 /* change everything in-place, starting with this one */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010192 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010193 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010194 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010195 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010196
10197 while ( --maxcount > 0) {
Victor Stinnerc3cec782011-10-05 21:24:08 +020010198 i = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010199 sbuf+rkind*i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010200 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010201 if (i == -1)
10202 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010203 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010204 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010205 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010206 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010207 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010208 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010209 }
10210 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010211 Py_ssize_t n, i, j, ires;
10212 Py_ssize_t product, new_size;
10213 int rkind = skind;
10214 char *res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010215
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010216 if (kind1 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010217 /* widen substring */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010218 buf1 = _PyUnicode_AsKind(str1, rkind);
10219 if (!buf1) goto error;
10220 release1 = 1;
10221 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010222 n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010223 if (n == 0)
10224 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010225 if (kind2 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010226 /* widen replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010227 buf2 = _PyUnicode_AsKind(str2, rkind);
10228 if (!buf2) goto error;
10229 release2 = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010230 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010231 else if (kind2 > rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010232 /* widen self and buf1 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010233 rkind = kind2;
10234 sbuf = _PyUnicode_AsKind(self, rkind);
10235 if (!sbuf) goto error;
10236 srelease = 1;
10237 if (release1) PyMem_Free(buf1);
10238 buf1 = _PyUnicode_AsKind(str1, rkind);
10239 if (!buf1) goto error;
10240 release1 = 1;
10241 }
10242 /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
10243 PyUnicode_GET_LENGTH(str1))); */
10244 product = n * (len2-len1);
10245 if ((product / (len2-len1)) != n) {
10246 PyErr_SetString(PyExc_OverflowError,
10247 "replace string is too long");
10248 goto error;
10249 }
10250 new_size = slen + product;
Victor Stinner49a0a212011-10-12 23:46:10 +020010251 if (new_size == 0) {
10252 Py_INCREF(unicode_empty);
10253 u = unicode_empty;
10254 goto done;
10255 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010256 if (new_size < 0 || new_size > (PY_SSIZE_T_MAX >> (rkind-1))) {
10257 PyErr_SetString(PyExc_OverflowError,
10258 "replace string is too long");
10259 goto error;
10260 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010261 u = PyUnicode_New(new_size, maxchar);
10262 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010263 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010264 assert(PyUnicode_KIND(u) == rkind);
10265 res = PyUnicode_DATA(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010266 ires = i = 0;
10267 if (len1 > 0) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010268 while (n-- > 0) {
10269 /* look for next match */
Victor Stinnerc3cec782011-10-05 21:24:08 +020010270 j = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010271 sbuf + rkind * i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010272 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010273 if (j == -1)
10274 break;
10275 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010276 /* copy unchanged part [i:j] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010277 memcpy(res + rkind * ires,
10278 sbuf + rkind * i,
10279 rkind * (j-i));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010280 ires += j - i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010281 }
10282 /* copy substitution string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010283 if (len2 > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010284 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010285 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010286 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010287 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010288 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010289 i = j + len1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010290 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010291 if (i < slen)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010292 /* copy tail [i:] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010293 memcpy(res + rkind * ires,
10294 sbuf + rkind * i,
10295 rkind * (slen-i));
Victor Stinner49a0a212011-10-12 23:46:10 +020010296 }
10297 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010298 /* interleave */
10299 while (n > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010300 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010301 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010302 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010303 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010304 if (--n <= 0)
10305 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010306 memcpy(res + rkind * ires,
10307 sbuf + rkind * i,
10308 rkind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010309 ires++;
10310 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010311 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010312 memcpy(res + rkind * ires,
10313 sbuf + rkind * i,
10314 rkind * (slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +000010315 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010316 }
10317
10318 if (mayshrink) {
Victor Stinner25a4b292011-10-06 12:31:55 +020010319 unicode_adjust_maxchar(&u);
10320 if (u == NULL)
10321 goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010322 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010323
10324 done:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010325 if (srelease)
10326 PyMem_FREE(sbuf);
10327 if (release1)
10328 PyMem_FREE(buf1);
10329 if (release2)
10330 PyMem_FREE(buf2);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010331 assert(_PyUnicode_CheckConsistency(u, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010332 return u;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010333
Benjamin Peterson29060642009-01-31 22:14:21 +000010334 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +000010335 /* nothing to replace; return original string (when possible) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010336 if (srelease)
10337 PyMem_FREE(sbuf);
10338 if (release1)
10339 PyMem_FREE(buf1);
10340 if (release2)
10341 PyMem_FREE(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010342 if (PyUnicode_CheckExact(self)) {
10343 Py_INCREF(self);
Victor Stinner7931d9a2011-11-04 00:22:48 +010010344 return self;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010345 }
Victor Stinner034f6cf2011-09-30 02:26:44 +020010346 return PyUnicode_Copy(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010347 error:
10348 if (srelease && sbuf)
10349 PyMem_FREE(sbuf);
10350 if (release1 && buf1)
10351 PyMem_FREE(buf1);
10352 if (release2 && buf2)
10353 PyMem_FREE(buf2);
10354 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010355}
10356
10357/* --- Unicode Object Methods --------------------------------------------- */
10358
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010359PyDoc_STRVAR(title__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010360 "S.title() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010361\n\
10362Return a titlecased version of S, i.e. words start with title case\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010363characters, all remaining cased characters have lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010364
10365static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010366unicode_title(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010367{
Guido van Rossumd57fd912000-03-10 22:53:23 +000010368 return fixup(self, fixtitle);
10369}
10370
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010371PyDoc_STRVAR(capitalize__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010372 "S.capitalize() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010373\n\
10374Return a capitalized version of S, i.e. make the first character\n\
Senthil Kumarane51ee8a2010-07-05 12:00:56 +000010375have upper case and the rest lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010376
10377static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010378unicode_capitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010379{
Guido van Rossumd57fd912000-03-10 22:53:23 +000010380 return fixup(self, fixcapitalize);
10381}
10382
10383#if 0
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010384PyDoc_STRVAR(capwords__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010385 "S.capwords() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010386\n\
10387Apply .capitalize() to all words in S and return the result with\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010388normalized whitespace (all whitespace strings are replaced by ' ').");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010389
10390static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010391unicode_capwords(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010392{
10393 PyObject *list;
10394 PyObject *item;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010395 Py_ssize_t i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010396
Guido van Rossumd57fd912000-03-10 22:53:23 +000010397 /* Split into words */
10398 list = split(self, NULL, -1);
10399 if (!list)
10400 return NULL;
10401
10402 /* Capitalize each word */
10403 for (i = 0; i < PyList_GET_SIZE(list); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010404 item = fixup(PyList_GET_ITEM(list, i),
Benjamin Peterson29060642009-01-31 22:14:21 +000010405 fixcapitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010406 if (item == NULL)
10407 goto onError;
10408 Py_DECREF(PyList_GET_ITEM(list, i));
10409 PyList_SET_ITEM(list, i, item);
10410 }
10411
10412 /* Join the words to form a new string */
10413 item = PyUnicode_Join(NULL, list);
10414
Benjamin Peterson29060642009-01-31 22:14:21 +000010415 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000010416 Py_DECREF(list);
Victor Stinner7931d9a2011-11-04 00:22:48 +010010417 return item;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010418}
10419#endif
10420
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010421/* Argument converter. Coerces to a single unicode character */
10422
10423static int
10424convert_uc(PyObject *obj, void *addr)
10425{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010426 Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010427 PyObject *uniobj;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010428
Benjamin Peterson14339b62009-01-31 16:36:08 +000010429 uniobj = PyUnicode_FromObject(obj);
10430 if (uniobj == NULL) {
10431 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010432 "The fill character cannot be converted to Unicode");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010433 return 0;
10434 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010435 if (PyUnicode_GET_LENGTH(uniobj) != 1) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010436 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010437 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010438 Py_DECREF(uniobj);
10439 return 0;
10440 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010441 *fillcharloc = PyUnicode_READ_CHAR(uniobj, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010442 Py_DECREF(uniobj);
10443 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010444}
10445
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010446PyDoc_STRVAR(center__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010447 "S.center(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010448\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010449Return S centered in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010450done using the specified fill character (default is a space)");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010451
10452static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010453unicode_center(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010454{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010455 Py_ssize_t marg, left;
10456 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010457 Py_UCS4 fillchar = ' ';
10458
Victor Stinnere9a29352011-10-01 02:14:59 +020010459 if (!PyArg_ParseTuple(args, "n|O&:center", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010460 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010461
Victor Stinnere9a29352011-10-01 02:14:59 +020010462 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010463 return NULL;
10464
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010465 if (_PyUnicode_LENGTH(self) >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000010466 Py_INCREF(self);
Victor Stinner7931d9a2011-11-04 00:22:48 +010010467 return self;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010468 }
10469
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010470 marg = width - _PyUnicode_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010471 left = marg / 2 + (marg & width & 1);
10472
Victor Stinner9310abb2011-10-05 00:59:23 +020010473 return pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010474}
10475
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010476/* This function assumes that str1 and str2 are readied by the caller. */
10477
Marc-André Lemburge5034372000-08-08 08:04:29 +000010478static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010479unicode_compare(PyObject *str1, PyObject *str2)
Marc-André Lemburge5034372000-08-08 08:04:29 +000010480{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010481 int kind1, kind2;
10482 void *data1, *data2;
10483 Py_ssize_t len1, len2, i;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010484
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010485 kind1 = PyUnicode_KIND(str1);
10486 kind2 = PyUnicode_KIND(str2);
10487 data1 = PyUnicode_DATA(str1);
10488 data2 = PyUnicode_DATA(str2);
10489 len1 = PyUnicode_GET_LENGTH(str1);
10490 len2 = PyUnicode_GET_LENGTH(str2);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010491
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010492 for (i = 0; i < len1 && i < len2; ++i) {
10493 Py_UCS4 c1, c2;
10494 c1 = PyUnicode_READ(kind1, data1, i);
10495 c2 = PyUnicode_READ(kind2, data2, i);
Fredrik Lundh45714e92001-06-26 16:39:36 +000010496
10497 if (c1 != c2)
10498 return (c1 < c2) ? -1 : 1;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010499 }
10500
10501 return (len1 < len2) ? -1 : (len1 != len2);
10502}
10503
Alexander Belopolsky40018472011-02-26 01:02:56 +000010504int
10505PyUnicode_Compare(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010506{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010507 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10508 if (PyUnicode_READY(left) == -1 ||
10509 PyUnicode_READY(right) == -1)
10510 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010511 return unicode_compare(left, right);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010512 }
Guido van Rossum09dc34f2007-05-04 04:17:33 +000010513 PyErr_Format(PyExc_TypeError,
10514 "Can't compare %.100s and %.100s",
10515 left->ob_type->tp_name,
10516 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010517 return -1;
10518}
10519
Martin v. Löwis5b222132007-06-10 09:51:05 +000010520int
10521PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
10522{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010523 Py_ssize_t i;
10524 int kind;
10525 void *data;
10526 Py_UCS4 chr;
10527
Victor Stinner910337b2011-10-03 03:20:16 +020010528 assert(_PyUnicode_CHECK(uni));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010529 if (PyUnicode_READY(uni) == -1)
10530 return -1;
10531 kind = PyUnicode_KIND(uni);
10532 data = PyUnicode_DATA(uni);
Martin v. Löwis5b222132007-06-10 09:51:05 +000010533 /* Compare Unicode string and source character set string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010534 for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
10535 if (chr != str[i])
10536 return (chr < (unsigned char)(str[i])) ? -1 : 1;
Benjamin Peterson8667a9b2010-01-09 21:45:28 +000010537 /* This check keeps Python strings that end in '\0' from comparing equal
10538 to C strings identical up to that point. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010539 if (PyUnicode_GET_LENGTH(uni) != i || chr)
Benjamin Peterson29060642009-01-31 22:14:21 +000010540 return 1; /* uni is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010541 if (str[i])
Benjamin Peterson29060642009-01-31 22:14:21 +000010542 return -1; /* str is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010543 return 0;
10544}
10545
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010546
Benjamin Peterson29060642009-01-31 22:14:21 +000010547#define TEST_COND(cond) \
Benjamin Peterson14339b62009-01-31 16:36:08 +000010548 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010549
Alexander Belopolsky40018472011-02-26 01:02:56 +000010550PyObject *
10551PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010552{
10553 int result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010554
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010555 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10556 PyObject *v;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010557 if (PyUnicode_READY(left) == -1 ||
10558 PyUnicode_READY(right) == -1)
10559 return NULL;
10560 if (PyUnicode_GET_LENGTH(left) != PyUnicode_GET_LENGTH(right) ||
10561 PyUnicode_KIND(left) != PyUnicode_KIND(right)) {
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010562 if (op == Py_EQ) {
10563 Py_INCREF(Py_False);
10564 return Py_False;
10565 }
10566 if (op == Py_NE) {
10567 Py_INCREF(Py_True);
10568 return Py_True;
10569 }
10570 }
10571 if (left == right)
10572 result = 0;
10573 else
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010574 result = unicode_compare(left, right);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010575
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010576 /* Convert the return value to a Boolean */
10577 switch (op) {
10578 case Py_EQ:
10579 v = TEST_COND(result == 0);
10580 break;
10581 case Py_NE:
10582 v = TEST_COND(result != 0);
10583 break;
10584 case Py_LE:
10585 v = TEST_COND(result <= 0);
10586 break;
10587 case Py_GE:
10588 v = TEST_COND(result >= 0);
10589 break;
10590 case Py_LT:
10591 v = TEST_COND(result == -1);
10592 break;
10593 case Py_GT:
10594 v = TEST_COND(result == 1);
10595 break;
10596 default:
10597 PyErr_BadArgument();
10598 return NULL;
10599 }
10600 Py_INCREF(v);
10601 return v;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010602 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000010603
Brian Curtindfc80e32011-08-10 20:28:54 -050010604 Py_RETURN_NOTIMPLEMENTED;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010605}
10606
Alexander Belopolsky40018472011-02-26 01:02:56 +000010607int
10608PyUnicode_Contains(PyObject *container, PyObject *element)
Guido van Rossum403d68b2000-03-13 15:55:09 +000010609{
Thomas Wouters477c8d52006-05-27 19:21:47 +000010610 PyObject *str, *sub;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010611 int kind1, kind2, kind;
10612 void *buf1, *buf2;
10613 Py_ssize_t len1, len2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010614 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010615
10616 /* Coerce the two arguments */
Thomas Wouters477c8d52006-05-27 19:21:47 +000010617 sub = PyUnicode_FromObject(element);
10618 if (!sub) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010619 PyErr_Format(PyExc_TypeError,
10620 "'in <string>' requires string as left operand, not %s",
10621 element->ob_type->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010622 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010623 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010624 if (PyUnicode_READY(sub) == -1)
10625 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010626
Thomas Wouters477c8d52006-05-27 19:21:47 +000010627 str = PyUnicode_FromObject(container);
Victor Stinnere9a29352011-10-01 02:14:59 +020010628 if (!str || PyUnicode_READY(str) == -1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010629 Py_DECREF(sub);
10630 return -1;
10631 }
10632
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010633 kind1 = PyUnicode_KIND(str);
10634 kind2 = PyUnicode_KIND(sub);
10635 kind = kind1 > kind2 ? kind1 : kind2;
10636 buf1 = PyUnicode_DATA(str);
10637 buf2 = PyUnicode_DATA(sub);
10638 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010639 buf1 = _PyUnicode_AsKind(str, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010640 if (!buf1) {
10641 Py_DECREF(sub);
10642 return -1;
10643 }
10644 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010645 buf2 = _PyUnicode_AsKind(sub, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010646 if (!buf2) {
10647 Py_DECREF(sub);
10648 if (kind1 != kind) PyMem_Free(buf1);
10649 return -1;
10650 }
10651 len1 = PyUnicode_GET_LENGTH(str);
10652 len2 = PyUnicode_GET_LENGTH(sub);
10653
10654 switch(kind) {
10655 case PyUnicode_1BYTE_KIND:
10656 result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
10657 break;
10658 case PyUnicode_2BYTE_KIND:
10659 result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
10660 break;
10661 case PyUnicode_4BYTE_KIND:
10662 result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
10663 break;
10664 default:
10665 result = -1;
10666 assert(0);
10667 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000010668
10669 Py_DECREF(str);
10670 Py_DECREF(sub);
10671
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010672 if (kind1 != kind)
10673 PyMem_Free(buf1);
10674 if (kind2 != kind)
10675 PyMem_Free(buf2);
10676
Guido van Rossum403d68b2000-03-13 15:55:09 +000010677 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010678}
10679
Guido van Rossumd57fd912000-03-10 22:53:23 +000010680/* Concat to string or Unicode object giving a new Unicode object. */
10681
Alexander Belopolsky40018472011-02-26 01:02:56 +000010682PyObject *
10683PyUnicode_Concat(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010684{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010685 PyObject *u = NULL, *v = NULL, *w;
Victor Stinner127226b2011-10-13 01:12:34 +020010686 Py_UCS4 maxchar, maxchar2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010687
10688 /* Coerce the two arguments */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010689 u = PyUnicode_FromObject(left);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010690 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010691 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010692 v = PyUnicode_FromObject(right);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010693 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010694 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010695
10696 /* Shortcuts */
Victor Stinnera464fc12011-10-02 20:39:30 +020010697 if (v == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010698 Py_DECREF(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010699 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010700 }
Victor Stinnera464fc12011-10-02 20:39:30 +020010701 if (u == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010702 Py_DECREF(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010703 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010704 }
10705
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010706 maxchar = PyUnicode_MAX_CHAR_VALUE(u);
Victor Stinner127226b2011-10-13 01:12:34 +020010707 maxchar2 = PyUnicode_MAX_CHAR_VALUE(v);
10708 maxchar = Py_MAX(maxchar, maxchar2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010709
Guido van Rossumd57fd912000-03-10 22:53:23 +000010710 /* Concat the two Unicode strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010711 w = PyUnicode_New(
10712 PyUnicode_GET_LENGTH(u) + PyUnicode_GET_LENGTH(v),
10713 maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010714 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010715 goto onError;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020010716 copy_characters(w, 0, u, 0, PyUnicode_GET_LENGTH(u));
10717 copy_characters(w, PyUnicode_GET_LENGTH(u), v, 0, PyUnicode_GET_LENGTH(v));
Guido van Rossumd57fd912000-03-10 22:53:23 +000010718 Py_DECREF(u);
10719 Py_DECREF(v);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010720 assert(_PyUnicode_CheckConsistency(w, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010721 return w;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010722
Benjamin Peterson29060642009-01-31 22:14:21 +000010723 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000010724 Py_XDECREF(u);
10725 Py_XDECREF(v);
10726 return NULL;
10727}
10728
Victor Stinnerb0923652011-10-04 01:17:31 +020010729static void
10730unicode_append_inplace(PyObject **p_left, PyObject *right)
10731{
10732 Py_ssize_t left_len, right_len, new_len;
Victor Stinnerb0923652011-10-04 01:17:31 +020010733
10734 assert(PyUnicode_IS_READY(*p_left));
10735 assert(PyUnicode_IS_READY(right));
10736
10737 left_len = PyUnicode_GET_LENGTH(*p_left);
10738 right_len = PyUnicode_GET_LENGTH(right);
10739 if (left_len > PY_SSIZE_T_MAX - right_len) {
10740 PyErr_SetString(PyExc_OverflowError,
10741 "strings are too large to concat");
10742 goto error;
10743 }
10744 new_len = left_len + right_len;
10745
10746 /* Now we own the last reference to 'left', so we can resize it
10747 * in-place.
10748 */
10749 if (unicode_resize(p_left, new_len) != 0) {
10750 /* XXX if _PyUnicode_Resize() fails, 'left' has been
10751 * deallocated so it cannot be put back into
10752 * 'variable'. The MemoryError is raised when there
10753 * is no value in 'variable', which might (very
10754 * remotely) be a cause of incompatibilities.
10755 */
10756 goto error;
10757 }
10758 /* copy 'right' into the newly allocated area of 'left' */
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020010759 copy_characters(*p_left, left_len, right, 0, right_len);
10760 _PyUnicode_DIRTY(*p_left);
Victor Stinnerb0923652011-10-04 01:17:31 +020010761 return;
10762
10763error:
10764 Py_DECREF(*p_left);
10765 *p_left = NULL;
10766}
10767
Walter Dörwald1ab83302007-05-18 17:15:44 +000010768void
Victor Stinner23e56682011-10-03 03:54:37 +020010769PyUnicode_Append(PyObject **p_left, PyObject *right)
Walter Dörwald1ab83302007-05-18 17:15:44 +000010770{
Victor Stinner23e56682011-10-03 03:54:37 +020010771 PyObject *left, *res;
10772
10773 if (p_left == NULL) {
10774 if (!PyErr_Occurred())
10775 PyErr_BadInternalCall();
Benjamin Peterson14339b62009-01-31 16:36:08 +000010776 return;
10777 }
Victor Stinner23e56682011-10-03 03:54:37 +020010778 left = *p_left;
10779 if (right == NULL || !PyUnicode_Check(left)) {
10780 if (!PyErr_Occurred())
10781 PyErr_BadInternalCall();
10782 goto error;
10783 }
10784
Victor Stinnere1335c72011-10-04 20:53:03 +020010785 if (PyUnicode_READY(left))
10786 goto error;
10787 if (PyUnicode_READY(right))
10788 goto error;
10789
Victor Stinner23e56682011-10-03 03:54:37 +020010790 if (PyUnicode_CheckExact(left) && left != unicode_empty
10791 && PyUnicode_CheckExact(right) && right != unicode_empty
10792 && unicode_resizable(left)
10793 && (_PyUnicode_KIND(right) <= _PyUnicode_KIND(left)
10794 || _PyUnicode_WSTR(left) != NULL))
10795 {
Victor Stinnerb0923652011-10-04 01:17:31 +020010796 /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
10797 to change the structure size, but characters are stored just after
Georg Brandl7597add2011-10-05 16:36:47 +020010798 the structure, and so it requires to move all characters which is
Victor Stinnerb0923652011-10-04 01:17:31 +020010799 not so different than duplicating the string. */
10800 if (!(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
Victor Stinner23e56682011-10-03 03:54:37 +020010801 {
Victor Stinnerb0923652011-10-04 01:17:31 +020010802 unicode_append_inplace(p_left, right);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010803 if (p_left != NULL)
10804 assert(_PyUnicode_CheckConsistency(*p_left, 1));
Victor Stinner23e56682011-10-03 03:54:37 +020010805 return;
10806 }
10807 }
10808
10809 res = PyUnicode_Concat(left, right);
10810 if (res == NULL)
10811 goto error;
10812 Py_DECREF(left);
10813 *p_left = res;
10814 return;
10815
10816error:
10817 Py_DECREF(*p_left);
10818 *p_left = NULL;
Walter Dörwald1ab83302007-05-18 17:15:44 +000010819}
10820
10821void
10822PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
10823{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010824 PyUnicode_Append(pleft, right);
10825 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +000010826}
10827
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010828PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010829 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010830\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000010831Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010832string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010833interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010834
10835static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010836unicode_count(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010837{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010838 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010839 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010840 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010841 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010842 int kind1, kind2, kind;
10843 void *buf1, *buf2;
10844 Py_ssize_t len1, len2, iresult;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010845
Jesus Ceaac451502011-04-20 17:09:23 +020010846 if (!stringlib_parse_args_finds_unicode("count", args, &substring,
10847 &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000010848 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000010849
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010850 kind1 = PyUnicode_KIND(self);
10851 kind2 = PyUnicode_KIND(substring);
10852 kind = kind1 > kind2 ? kind1 : kind2;
10853 buf1 = PyUnicode_DATA(self);
10854 buf2 = PyUnicode_DATA(substring);
10855 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010856 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010857 if (!buf1) {
10858 Py_DECREF(substring);
10859 return NULL;
10860 }
10861 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010862 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010863 if (!buf2) {
10864 Py_DECREF(substring);
10865 if (kind1 != kind) PyMem_Free(buf1);
10866 return NULL;
10867 }
10868 len1 = PyUnicode_GET_LENGTH(self);
10869 len2 = PyUnicode_GET_LENGTH(substring);
10870
10871 ADJUST_INDICES(start, end, len1);
10872 switch(kind) {
10873 case PyUnicode_1BYTE_KIND:
10874 iresult = ucs1lib_count(
10875 ((Py_UCS1*)buf1) + start, end - start,
10876 buf2, len2, PY_SSIZE_T_MAX
10877 );
10878 break;
10879 case PyUnicode_2BYTE_KIND:
10880 iresult = ucs2lib_count(
10881 ((Py_UCS2*)buf1) + start, end - start,
10882 buf2, len2, PY_SSIZE_T_MAX
10883 );
10884 break;
10885 case PyUnicode_4BYTE_KIND:
10886 iresult = ucs4lib_count(
10887 ((Py_UCS4*)buf1) + start, end - start,
10888 buf2, len2, PY_SSIZE_T_MAX
10889 );
10890 break;
10891 default:
10892 assert(0); iresult = 0;
10893 }
10894
10895 result = PyLong_FromSsize_t(iresult);
10896
10897 if (kind1 != kind)
10898 PyMem_Free(buf1);
10899 if (kind2 != kind)
10900 PyMem_Free(buf2);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010901
10902 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010903
Guido van Rossumd57fd912000-03-10 22:53:23 +000010904 return result;
10905}
10906
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010907PyDoc_STRVAR(encode__doc__,
Victor Stinnerc911bbf2010-11-07 19:04:46 +000010908 "S.encode(encoding='utf-8', errors='strict') -> bytes\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010909\n\
Victor Stinnere14e2122010-11-07 18:41:46 +000010910Encode S using the codec registered for encoding. Default encoding\n\
10911is 'utf-8'. errors may be given to set a different error\n\
Fred Drakee4315f52000-05-09 19:53:39 +000010912handling scheme. Default is 'strict' meaning that encoding errors raise\n\
Walter Dörwald3aeb6322002-09-02 13:14:32 +000010913a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
10914'xmlcharrefreplace' as well as any other name registered with\n\
10915codecs.register_error that can handle UnicodeEncodeErrors.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010916
10917static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010918unicode_encode(PyObject *self, PyObject *args, PyObject *kwargs)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010919{
Benjamin Peterson308d6372009-09-18 21:42:35 +000010920 static char *kwlist[] = {"encoding", "errors", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000010921 char *encoding = NULL;
10922 char *errors = NULL;
Guido van Rossum35d94282007-08-27 18:20:11 +000010923
Benjamin Peterson308d6372009-09-18 21:42:35 +000010924 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:encode",
10925 kwlist, &encoding, &errors))
Guido van Rossumd57fd912000-03-10 22:53:23 +000010926 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010927 return PyUnicode_AsEncodedString(self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +000010928}
10929
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010930PyDoc_STRVAR(expandtabs__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010931 "S.expandtabs([tabsize]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010932\n\
10933Return a copy of S where all tab characters are expanded using spaces.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010934If tabsize is not given, a tab size of 8 characters is assumed.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010935
10936static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010937unicode_expandtabs(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010938{
Antoine Pitroue71d5742011-10-04 15:55:09 +020010939 Py_ssize_t i, j, line_pos, src_len, incr;
10940 Py_UCS4 ch;
10941 PyObject *u;
10942 void *src_data, *dest_data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010943 int tabsize = 8;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010944 int kind;
Antoine Pitroue19aa382011-10-04 16:04:01 +020010945 int found;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010946
10947 if (!PyArg_ParseTuple(args, "|i:expandtabs", &tabsize))
Benjamin Peterson29060642009-01-31 22:14:21 +000010948 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010949
Antoine Pitrou22425222011-10-04 19:10:51 +020010950 if (PyUnicode_READY(self) == -1)
10951 return NULL;
10952
Thomas Wouters7e474022000-07-16 12:04:32 +000010953 /* First pass: determine size of output string */
Antoine Pitroue71d5742011-10-04 15:55:09 +020010954 src_len = PyUnicode_GET_LENGTH(self);
10955 i = j = line_pos = 0;
10956 kind = PyUnicode_KIND(self);
10957 src_data = PyUnicode_DATA(self);
Antoine Pitroue19aa382011-10-04 16:04:01 +020010958 found = 0;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010959 for (; i < src_len; i++) {
10960 ch = PyUnicode_READ(kind, src_data, i);
10961 if (ch == '\t') {
Antoine Pitroue19aa382011-10-04 16:04:01 +020010962 found = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000010963 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020010964 incr = tabsize - (line_pos % tabsize); /* cannot overflow */
Benjamin Peterson29060642009-01-31 22:14:21 +000010965 if (j > PY_SSIZE_T_MAX - incr)
Antoine Pitroue71d5742011-10-04 15:55:09 +020010966 goto overflow;
10967 line_pos += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000010968 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010969 }
Benjamin Peterson29060642009-01-31 22:14:21 +000010970 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010971 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000010972 if (j > PY_SSIZE_T_MAX - 1)
Antoine Pitroue71d5742011-10-04 15:55:09 +020010973 goto overflow;
10974 line_pos++;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010975 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010976 if (ch == '\n' || ch == '\r')
10977 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010978 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020010979 }
Antoine Pitroue19aa382011-10-04 16:04:01 +020010980 if (!found && PyUnicode_CheckExact(self)) {
Victor Stinner7931d9a2011-11-04 00:22:48 +010010981 Py_INCREF(self);
10982 return self;
Antoine Pitroue19aa382011-10-04 16:04:01 +020010983 }
Guido van Rossumcd16bf62007-06-13 18:07:49 +000010984
Guido van Rossumd57fd912000-03-10 22:53:23 +000010985 /* Second pass: create output string and fill it */
Antoine Pitroue71d5742011-10-04 15:55:09 +020010986 u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +000010987 if (!u)
10988 return NULL;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010989 dest_data = PyUnicode_DATA(u);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010990
Antoine Pitroue71d5742011-10-04 15:55:09 +020010991 i = j = line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010992
Antoine Pitroue71d5742011-10-04 15:55:09 +020010993 for (; i < src_len; i++) {
10994 ch = PyUnicode_READ(kind, src_data, i);
10995 if (ch == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +000010996 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020010997 incr = tabsize - (line_pos % tabsize);
10998 line_pos += incr;
10999 while (incr--) {
11000 PyUnicode_WRITE(kind, dest_data, j, ' ');
11001 j++;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011002 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011003 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011004 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011005 else {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011006 line_pos++;
11007 PyUnicode_WRITE(kind, dest_data, j, ch);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011008 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011009 if (ch == '\n' || ch == '\r')
11010 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011011 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011012 }
11013 assert (j == PyUnicode_GET_LENGTH(u));
Victor Stinner17efeed2011-10-04 20:05:46 +020011014#ifndef DONT_MAKE_RESULT_READY
11015 if (_PyUnicode_READY_REPLACE(&u)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011016 Py_DECREF(u);
11017 return NULL;
11018 }
Victor Stinner17efeed2011-10-04 20:05:46 +020011019#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020011020 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +010011021 return u;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011022
Antoine Pitroue71d5742011-10-04 15:55:09 +020011023 overflow:
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011024 PyErr_SetString(PyExc_OverflowError, "new string is too long");
11025 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011026}
11027
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011028PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011029 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011030\n\
11031Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080011032such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011033arguments start and end are interpreted as in slice notation.\n\
11034\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011035Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011036
11037static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011038unicode_find(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011039{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011040 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011041 Py_ssize_t start;
11042 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011043 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011044
Jesus Ceaac451502011-04-20 17:09:23 +020011045 if (!stringlib_parse_args_finds_unicode("find", args, &substring,
11046 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011047 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011048
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011049 if (PyUnicode_READY(self) == -1)
11050 return NULL;
11051 if (PyUnicode_READY(substring) == -1)
11052 return NULL;
11053
Victor Stinner7931d9a2011-11-04 00:22:48 +010011054 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011055
11056 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011057
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011058 if (result == -2)
11059 return NULL;
11060
Christian Heimes217cfd12007-12-02 14:31:20 +000011061 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011062}
11063
11064static PyObject *
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011065unicode_getitem(PyObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011066{
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011067 Py_UCS4 ch = PyUnicode_ReadChar(self, index);
11068 if (ch == (Py_UCS4)-1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011069 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011070 return PyUnicode_FromOrdinal(ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011071}
11072
Guido van Rossumc2504932007-09-18 19:42:40 +000011073/* Believe it or not, this produces the same value for ASCII strings
Mark Dickinson57e683e2011-09-24 18:18:40 +010011074 as bytes_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +000011075static Py_hash_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011076unicode_hash(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011077{
Guido van Rossumc2504932007-09-18 19:42:40 +000011078 Py_ssize_t len;
Mark Dickinson57e683e2011-09-24 18:18:40 +010011079 Py_uhash_t x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011080
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011081 if (_PyUnicode_HASH(self) != -1)
11082 return _PyUnicode_HASH(self);
11083 if (PyUnicode_READY(self) == -1)
11084 return -1;
11085 len = PyUnicode_GET_LENGTH(self);
11086
11087 /* The hash function as a macro, gets expanded three times below. */
11088#define HASH(P) \
11089 x = (Py_uhash_t)*P << 7; \
11090 while (--len >= 0) \
11091 x = (1000003*x) ^ (Py_uhash_t)*P++;
11092
11093 switch (PyUnicode_KIND(self)) {
11094 case PyUnicode_1BYTE_KIND: {
11095 const unsigned char *c = PyUnicode_1BYTE_DATA(self);
11096 HASH(c);
11097 break;
11098 }
11099 case PyUnicode_2BYTE_KIND: {
11100 const Py_UCS2 *s = PyUnicode_2BYTE_DATA(self);
11101 HASH(s);
11102 break;
11103 }
11104 default: {
11105 Py_UCS4 *l;
11106 assert(PyUnicode_KIND(self) == PyUnicode_4BYTE_KIND &&
11107 "Impossible switch case in unicode_hash");
11108 l = PyUnicode_4BYTE_DATA(self);
11109 HASH(l);
11110 break;
11111 }
11112 }
11113 x ^= (Py_uhash_t)PyUnicode_GET_LENGTH(self);
11114
Guido van Rossumc2504932007-09-18 19:42:40 +000011115 if (x == -1)
11116 x = -2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011117 _PyUnicode_HASH(self) = x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011118 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011119}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011120#undef HASH
Guido van Rossumd57fd912000-03-10 22:53:23 +000011121
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011122PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011123 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011124\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011125Like S.find() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011126
11127static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011128unicode_index(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011129{
Martin v. Löwis18e16552006-02-15 17:27:45 +000011130 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011131 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011132 Py_ssize_t start;
11133 Py_ssize_t end;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011134
Jesus Ceaac451502011-04-20 17:09:23 +020011135 if (!stringlib_parse_args_finds_unicode("index", args, &substring,
11136 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011137 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011138
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011139 if (PyUnicode_READY(self) == -1)
11140 return NULL;
11141 if (PyUnicode_READY(substring) == -1)
11142 return NULL;
11143
Victor Stinner7931d9a2011-11-04 00:22:48 +010011144 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011145
11146 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011147
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011148 if (result == -2)
11149 return NULL;
11150
Guido van Rossumd57fd912000-03-10 22:53:23 +000011151 if (result < 0) {
11152 PyErr_SetString(PyExc_ValueError, "substring not found");
11153 return NULL;
11154 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011155
Christian Heimes217cfd12007-12-02 14:31:20 +000011156 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011157}
11158
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011159PyDoc_STRVAR(islower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011160 "S.islower() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011161\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011162Return True if all cased characters in S are lowercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011163at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011164
11165static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011166unicode_islower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011167{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011168 Py_ssize_t i, length;
11169 int kind;
11170 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011171 int cased;
11172
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011173 if (PyUnicode_READY(self) == -1)
11174 return NULL;
11175 length = PyUnicode_GET_LENGTH(self);
11176 kind = PyUnicode_KIND(self);
11177 data = PyUnicode_DATA(self);
11178
Guido van Rossumd57fd912000-03-10 22:53:23 +000011179 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011180 if (length == 1)
11181 return PyBool_FromLong(
11182 Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011183
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011184 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011185 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011186 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011187
Guido van Rossumd57fd912000-03-10 22:53:23 +000011188 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011189 for (i = 0; i < length; i++) {
11190 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011191
Benjamin Peterson29060642009-01-31 22:14:21 +000011192 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
11193 return PyBool_FromLong(0);
11194 else if (!cased && Py_UNICODE_ISLOWER(ch))
11195 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011196 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011197 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011198}
11199
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011200PyDoc_STRVAR(isupper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011201 "S.isupper() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011202\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011203Return True if all cased characters in S are uppercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011204at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011205
11206static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011207unicode_isupper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011208{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011209 Py_ssize_t i, length;
11210 int kind;
11211 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011212 int cased;
11213
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011214 if (PyUnicode_READY(self) == -1)
11215 return NULL;
11216 length = PyUnicode_GET_LENGTH(self);
11217 kind = PyUnicode_KIND(self);
11218 data = PyUnicode_DATA(self);
11219
Guido van Rossumd57fd912000-03-10 22:53:23 +000011220 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011221 if (length == 1)
11222 return PyBool_FromLong(
11223 Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011224
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011225 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011226 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011227 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011228
Guido van Rossumd57fd912000-03-10 22:53:23 +000011229 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011230 for (i = 0; i < length; i++) {
11231 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011232
Benjamin Peterson29060642009-01-31 22:14:21 +000011233 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
11234 return PyBool_FromLong(0);
11235 else if (!cased && Py_UNICODE_ISUPPER(ch))
11236 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011237 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011238 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011239}
11240
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011241PyDoc_STRVAR(istitle__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011242 "S.istitle() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011243\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011244Return True if S is a titlecased string and there is at least one\n\
11245character in S, i.e. upper- and titlecase characters may only\n\
11246follow uncased characters and lowercase characters only cased ones.\n\
11247Return False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011248
11249static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011250unicode_istitle(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011251{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011252 Py_ssize_t i, length;
11253 int kind;
11254 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011255 int cased, previous_is_cased;
11256
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011257 if (PyUnicode_READY(self) == -1)
11258 return NULL;
11259 length = PyUnicode_GET_LENGTH(self);
11260 kind = PyUnicode_KIND(self);
11261 data = PyUnicode_DATA(self);
11262
Guido van Rossumd57fd912000-03-10 22:53:23 +000011263 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011264 if (length == 1) {
11265 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11266 return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
11267 (Py_UNICODE_ISUPPER(ch) != 0));
11268 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011269
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011270 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011271 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011272 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011273
Guido van Rossumd57fd912000-03-10 22:53:23 +000011274 cased = 0;
11275 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011276 for (i = 0; i < length; i++) {
11277 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011278
Benjamin Peterson29060642009-01-31 22:14:21 +000011279 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
11280 if (previous_is_cased)
11281 return PyBool_FromLong(0);
11282 previous_is_cased = 1;
11283 cased = 1;
11284 }
11285 else if (Py_UNICODE_ISLOWER(ch)) {
11286 if (!previous_is_cased)
11287 return PyBool_FromLong(0);
11288 previous_is_cased = 1;
11289 cased = 1;
11290 }
11291 else
11292 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011293 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011294 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011295}
11296
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011297PyDoc_STRVAR(isspace__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011298 "S.isspace() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011299\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011300Return True if all characters in S are whitespace\n\
11301and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011302
11303static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011304unicode_isspace(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011305{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011306 Py_ssize_t i, length;
11307 int kind;
11308 void *data;
11309
11310 if (PyUnicode_READY(self) == -1)
11311 return NULL;
11312 length = PyUnicode_GET_LENGTH(self);
11313 kind = PyUnicode_KIND(self);
11314 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011315
Guido van Rossumd57fd912000-03-10 22:53:23 +000011316 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011317 if (length == 1)
11318 return PyBool_FromLong(
11319 Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011320
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011321 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011322 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011323 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011324
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011325 for (i = 0; i < length; i++) {
11326 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011327 if (!Py_UNICODE_ISSPACE(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011328 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011329 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011330 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011331}
11332
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011333PyDoc_STRVAR(isalpha__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011334 "S.isalpha() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011335\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011336Return True if all characters in S are alphabetic\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011337and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011338
11339static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011340unicode_isalpha(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011341{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011342 Py_ssize_t i, length;
11343 int kind;
11344 void *data;
11345
11346 if (PyUnicode_READY(self) == -1)
11347 return NULL;
11348 length = PyUnicode_GET_LENGTH(self);
11349 kind = PyUnicode_KIND(self);
11350 data = PyUnicode_DATA(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011351
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011352 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011353 if (length == 1)
11354 return PyBool_FromLong(
11355 Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011356
11357 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011358 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011359 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011360
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011361 for (i = 0; i < length; i++) {
11362 if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011363 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011364 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011365 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011366}
11367
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011368PyDoc_STRVAR(isalnum__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011369 "S.isalnum() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011370\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011371Return True if all characters in S are alphanumeric\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011372and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011373
11374static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011375unicode_isalnum(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011376{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011377 int kind;
11378 void *data;
11379 Py_ssize_t len, i;
11380
11381 if (PyUnicode_READY(self) == -1)
11382 return NULL;
11383
11384 kind = PyUnicode_KIND(self);
11385 data = PyUnicode_DATA(self);
11386 len = PyUnicode_GET_LENGTH(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011387
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011388 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011389 if (len == 1) {
11390 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11391 return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
11392 }
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011393
11394 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011395 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011396 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011397
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011398 for (i = 0; i < len; i++) {
11399 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011400 if (!Py_UNICODE_ISALNUM(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011401 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011402 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011403 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011404}
11405
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011406PyDoc_STRVAR(isdecimal__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011407 "S.isdecimal() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011408\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011409Return True if there are only decimal characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011410False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011411
11412static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011413unicode_isdecimal(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011414{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011415 Py_ssize_t i, length;
11416 int kind;
11417 void *data;
11418
11419 if (PyUnicode_READY(self) == -1)
11420 return NULL;
11421 length = PyUnicode_GET_LENGTH(self);
11422 kind = PyUnicode_KIND(self);
11423 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011424
Guido van Rossumd57fd912000-03-10 22:53:23 +000011425 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011426 if (length == 1)
11427 return PyBool_FromLong(
11428 Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011429
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011430 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011431 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011432 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011433
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011434 for (i = 0; i < length; i++) {
11435 if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011436 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011437 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011438 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011439}
11440
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011441PyDoc_STRVAR(isdigit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011442 "S.isdigit() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011443\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011444Return True if all characters in S are digits\n\
11445and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011446
11447static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011448unicode_isdigit(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011449{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011450 Py_ssize_t i, length;
11451 int kind;
11452 void *data;
11453
11454 if (PyUnicode_READY(self) == -1)
11455 return NULL;
11456 length = PyUnicode_GET_LENGTH(self);
11457 kind = PyUnicode_KIND(self);
11458 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011459
Guido van Rossumd57fd912000-03-10 22:53:23 +000011460 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011461 if (length == 1) {
11462 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11463 return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
11464 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011465
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011466 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011467 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011468 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011469
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011470 for (i = 0; i < length; i++) {
11471 if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011472 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011473 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011474 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011475}
11476
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011477PyDoc_STRVAR(isnumeric__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011478 "S.isnumeric() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011479\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011480Return True if there are only numeric characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011481False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011482
11483static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011484unicode_isnumeric(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011485{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011486 Py_ssize_t i, length;
11487 int kind;
11488 void *data;
11489
11490 if (PyUnicode_READY(self) == -1)
11491 return NULL;
11492 length = PyUnicode_GET_LENGTH(self);
11493 kind = PyUnicode_KIND(self);
11494 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011495
Guido van Rossumd57fd912000-03-10 22:53:23 +000011496 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011497 if (length == 1)
11498 return PyBool_FromLong(
11499 Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011500
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011501 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011502 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011503 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011504
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011505 for (i = 0; i < length; i++) {
11506 if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011507 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011508 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011509 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011510}
11511
Martin v. Löwis47383402007-08-15 07:32:56 +000011512int
11513PyUnicode_IsIdentifier(PyObject *self)
11514{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011515 int kind;
11516 void *data;
11517 Py_ssize_t i;
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011518 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +000011519
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011520 if (PyUnicode_READY(self) == -1) {
11521 Py_FatalError("identifier not ready");
Benjamin Peterson29060642009-01-31 22:14:21 +000011522 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011523 }
11524
11525 /* Special case for empty strings */
11526 if (PyUnicode_GET_LENGTH(self) == 0)
11527 return 0;
11528 kind = PyUnicode_KIND(self);
11529 data = PyUnicode_DATA(self);
Martin v. Löwis47383402007-08-15 07:32:56 +000011530
11531 /* PEP 3131 says that the first character must be in
11532 XID_Start and subsequent characters in XID_Continue,
11533 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +000011534 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +000011535 letters, digits, underscore). However, given the current
11536 definition of XID_Start and XID_Continue, it is sufficient
11537 to check just for these, except that _ must be allowed
11538 as starting an identifier. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011539 first = PyUnicode_READ(kind, data, 0);
Benjamin Petersonf413b802011-08-12 22:17:18 -050011540 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +000011541 return 0;
11542
Benjamin Peterson9c6e6a02011-09-28 08:09:05 -040011543 for (i = 1; i < PyUnicode_GET_LENGTH(self); i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011544 if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011545 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +000011546 return 1;
11547}
11548
11549PyDoc_STRVAR(isidentifier__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011550 "S.isidentifier() -> bool\n\
Martin v. Löwis47383402007-08-15 07:32:56 +000011551\n\
11552Return True if S is a valid identifier according\n\
11553to the language definition.");
11554
11555static PyObject*
11556unicode_isidentifier(PyObject *self)
11557{
11558 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
11559}
11560
Georg Brandl559e5d72008-06-11 18:37:52 +000011561PyDoc_STRVAR(isprintable__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011562 "S.isprintable() -> bool\n\
Georg Brandl559e5d72008-06-11 18:37:52 +000011563\n\
11564Return True if all characters in S are considered\n\
11565printable in repr() or S is empty, False otherwise.");
11566
11567static PyObject*
11568unicode_isprintable(PyObject *self)
11569{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011570 Py_ssize_t i, length;
11571 int kind;
11572 void *data;
11573
11574 if (PyUnicode_READY(self) == -1)
11575 return NULL;
11576 length = PyUnicode_GET_LENGTH(self);
11577 kind = PyUnicode_KIND(self);
11578 data = PyUnicode_DATA(self);
Georg Brandl559e5d72008-06-11 18:37:52 +000011579
11580 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011581 if (length == 1)
11582 return PyBool_FromLong(
11583 Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
Georg Brandl559e5d72008-06-11 18:37:52 +000011584
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011585 for (i = 0; i < length; i++) {
11586 if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
Georg Brandl559e5d72008-06-11 18:37:52 +000011587 Py_RETURN_FALSE;
11588 }
11589 }
11590 Py_RETURN_TRUE;
11591}
11592
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011593PyDoc_STRVAR(join__doc__,
Georg Brandl495f7b52009-10-27 15:28:25 +000011594 "S.join(iterable) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011595\n\
11596Return a string which is the concatenation of the strings in the\n\
Georg Brandl495f7b52009-10-27 15:28:25 +000011597iterable. The separator between elements is S.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011598
11599static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011600unicode_join(PyObject *self, PyObject *data)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011601{
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011602 return PyUnicode_Join(self, data);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011603}
11604
Martin v. Löwis18e16552006-02-15 17:27:45 +000011605static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011606unicode_length(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011607{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011608 if (PyUnicode_READY(self) == -1)
11609 return -1;
11610 return PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011611}
11612
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011613PyDoc_STRVAR(ljust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011614 "S.ljust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011615\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000011616Return S left-justified in a Unicode string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011617done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011618
11619static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020011620unicode_ljust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011621{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011622 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011623 Py_UCS4 fillchar = ' ';
11624
11625 if (PyUnicode_READY(self) == -1)
11626 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011627
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011628 if (!PyArg_ParseTuple(args, "n|O&:ljust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011629 return NULL;
11630
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011631 if (_PyUnicode_LENGTH(self) >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000011632 Py_INCREF(self);
Victor Stinner7931d9a2011-11-04 00:22:48 +010011633 return self;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011634 }
11635
Victor Stinner7931d9a2011-11-04 00:22:48 +010011636 return pad(self, 0, width - _PyUnicode_LENGTH(self), fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011637}
11638
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011639PyDoc_STRVAR(lower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011640 "S.lower() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011641\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011642Return a copy of the string S converted to lowercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011643
11644static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020011645unicode_lower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011646{
Guido van Rossumd57fd912000-03-10 22:53:23 +000011647 return fixup(self, fixlower);
11648}
11649
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011650#define LEFTSTRIP 0
11651#define RIGHTSTRIP 1
11652#define BOTHSTRIP 2
11653
11654/* Arrays indexed by above */
11655static const char *stripformat[] = {"|O:lstrip", "|O:rstrip", "|O:strip"};
11656
11657#define STRIPNAME(i) (stripformat[i]+3)
11658
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011659/* externally visible for str.strip(unicode) */
11660PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011661_PyUnicode_XStrip(PyObject *self, int striptype, PyObject *sepobj)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011662{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011663 void *data;
11664 int kind;
11665 Py_ssize_t i, j, len;
11666 BLOOM_MASK sepmask;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011667
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011668 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
11669 return NULL;
11670
11671 kind = PyUnicode_KIND(self);
11672 data = PyUnicode_DATA(self);
11673 len = PyUnicode_GET_LENGTH(self);
11674 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
11675 PyUnicode_DATA(sepobj),
11676 PyUnicode_GET_LENGTH(sepobj));
Thomas Wouters477c8d52006-05-27 19:21:47 +000011677
Benjamin Peterson14339b62009-01-31 16:36:08 +000011678 i = 0;
11679 if (striptype != RIGHTSTRIP) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011680 while (i < len &&
11681 BLOOM_MEMBER(sepmask, PyUnicode_READ(kind, data, i), sepobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011682 i++;
11683 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011684 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011685
Benjamin Peterson14339b62009-01-31 16:36:08 +000011686 j = len;
11687 if (striptype != LEFTSTRIP) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011688 do {
11689 j--;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011690 } while (j >= i &&
11691 BLOOM_MEMBER(sepmask, PyUnicode_READ(kind, data, j), sepobj));
Benjamin Peterson29060642009-01-31 22:14:21 +000011692 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011693 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011694
Victor Stinner7931d9a2011-11-04 00:22:48 +010011695 return PyUnicode_Substring(self, i, j);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011696}
11697
11698PyObject*
11699PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
11700{
11701 unsigned char *data;
11702 int kind;
Victor Stinner12bab6d2011-10-01 01:53:49 +020011703 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011704
Victor Stinnerde636f32011-10-01 03:55:54 +020011705 if (PyUnicode_READY(self) == -1)
11706 return NULL;
11707
11708 end = Py_MIN(end, PyUnicode_GET_LENGTH(self));
11709
Victor Stinner12bab6d2011-10-01 01:53:49 +020011710 if (start == 0 && end == PyUnicode_GET_LENGTH(self))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011711 {
Victor Stinner12bab6d2011-10-01 01:53:49 +020011712 if (PyUnicode_CheckExact(self)) {
11713 Py_INCREF(self);
11714 return self;
11715 }
11716 else
11717 return PyUnicode_Copy(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011718 }
11719
Victor Stinner12bab6d2011-10-01 01:53:49 +020011720 length = end - start;
11721 if (length == 1)
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011722 return unicode_getitem(self, start);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011723
Victor Stinnerde636f32011-10-01 03:55:54 +020011724 if (start < 0 || end < 0) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020011725 PyErr_SetString(PyExc_IndexError, "string index out of range");
11726 return NULL;
11727 }
11728
Victor Stinnerb9275c12011-10-05 14:01:42 +020011729 if (PyUnicode_IS_ASCII(self)) {
11730 kind = PyUnicode_KIND(self);
11731 data = PyUnicode_1BYTE_DATA(self);
11732 return unicode_fromascii(data + start, length);
11733 }
11734 else {
11735 kind = PyUnicode_KIND(self);
11736 data = PyUnicode_1BYTE_DATA(self);
11737 return PyUnicode_FromKindAndData(kind,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020011738 data + kind * start,
Victor Stinnerb9275c12011-10-05 14:01:42 +020011739 length);
11740 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011741}
Guido van Rossumd57fd912000-03-10 22:53:23 +000011742
11743static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011744do_strip(PyObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011745{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011746 int kind;
11747 void *data;
11748 Py_ssize_t len, i, j;
11749
11750 if (PyUnicode_READY(self) == -1)
11751 return NULL;
11752
11753 kind = PyUnicode_KIND(self);
11754 data = PyUnicode_DATA(self);
11755 len = PyUnicode_GET_LENGTH(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011756
Benjamin Peterson14339b62009-01-31 16:36:08 +000011757 i = 0;
11758 if (striptype != RIGHTSTRIP) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011759 while (i < len && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, i))) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000011760 i++;
11761 }
11762 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011763
Benjamin Peterson14339b62009-01-31 16:36:08 +000011764 j = len;
11765 if (striptype != LEFTSTRIP) {
11766 do {
11767 j--;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011768 } while (j >= i && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, j)));
Benjamin Peterson14339b62009-01-31 16:36:08 +000011769 j++;
11770 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011771
Victor Stinner7931d9a2011-11-04 00:22:48 +010011772 return PyUnicode_Substring(self, i, j);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011773}
11774
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011775
11776static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011777do_argstrip(PyObject *self, int striptype, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011778{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011779 PyObject *sep = NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011780
Benjamin Peterson14339b62009-01-31 16:36:08 +000011781 if (!PyArg_ParseTuple(args, (char *)stripformat[striptype], &sep))
11782 return NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011783
Benjamin Peterson14339b62009-01-31 16:36:08 +000011784 if (sep != NULL && sep != Py_None) {
11785 if (PyUnicode_Check(sep))
11786 return _PyUnicode_XStrip(self, striptype, sep);
11787 else {
11788 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000011789 "%s arg must be None or str",
11790 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +000011791 return NULL;
11792 }
11793 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011794
Benjamin Peterson14339b62009-01-31 16:36:08 +000011795 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011796}
11797
11798
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011799PyDoc_STRVAR(strip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011800 "S.strip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011801\n\
11802Return a copy of the string S with leading and trailing\n\
11803whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011804If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011805
11806static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011807unicode_strip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011808{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011809 if (PyTuple_GET_SIZE(args) == 0)
11810 return do_strip(self, BOTHSTRIP); /* Common case */
11811 else
11812 return do_argstrip(self, BOTHSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011813}
11814
11815
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011816PyDoc_STRVAR(lstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011817 "S.lstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011818\n\
11819Return a copy of the string S with leading whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011820If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011821
11822static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011823unicode_lstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011824{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011825 if (PyTuple_GET_SIZE(args) == 0)
11826 return do_strip(self, LEFTSTRIP); /* Common case */
11827 else
11828 return do_argstrip(self, LEFTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011829}
11830
11831
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011832PyDoc_STRVAR(rstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011833 "S.rstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011834\n\
11835Return a copy of the string S with trailing whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011836If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011837
11838static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011839unicode_rstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011840{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011841 if (PyTuple_GET_SIZE(args) == 0)
11842 return do_strip(self, RIGHTSTRIP); /* Common case */
11843 else
11844 return do_argstrip(self, RIGHTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011845}
11846
11847
Guido van Rossumd57fd912000-03-10 22:53:23 +000011848static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011849unicode_repeat(PyObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011850{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011851 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011852 Py_ssize_t nchars, n;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011853
Georg Brandl222de0f2009-04-12 12:01:50 +000011854 if (len < 1) {
11855 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +020011856 return unicode_empty;
Georg Brandl222de0f2009-04-12 12:01:50 +000011857 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011858
Tim Peters7a29bd52001-09-12 03:03:31 +000011859 if (len == 1 && PyUnicode_CheckExact(str)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000011860 /* no repeat, return original string */
11861 Py_INCREF(str);
Victor Stinner7931d9a2011-11-04 00:22:48 +010011862 return str;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011863 }
Tim Peters8f422462000-09-09 06:13:41 +000011864
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011865 if (PyUnicode_READY(str) == -1)
11866 return NULL;
11867
Victor Stinnerc759f3e2011-10-01 03:09:58 +020011868 if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
Victor Stinner67ca64c2011-10-01 02:47:29 +020011869 PyErr_SetString(PyExc_OverflowError,
11870 "repeated string is too long");
11871 return NULL;
11872 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011873 nchars = len * PyUnicode_GET_LENGTH(str);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011874
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011875 u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011876 if (!u)
11877 return NULL;
Victor Stinner67ca64c2011-10-01 02:47:29 +020011878 assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011879
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011880 if (PyUnicode_GET_LENGTH(str) == 1) {
11881 const int kind = PyUnicode_KIND(str);
11882 const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
11883 void *to = PyUnicode_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011884 if (kind == PyUnicode_1BYTE_KIND)
11885 memset(to, (unsigned char)fill_char, len);
11886 else {
11887 for (n = 0; n < len; ++n)
11888 PyUnicode_WRITE(kind, to, n, fill_char);
11889 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011890 }
11891 else {
11892 /* number of characters copied this far */
11893 Py_ssize_t done = PyUnicode_GET_LENGTH(str);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020011894 const Py_ssize_t char_size = PyUnicode_KIND(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011895 char *to = (char *) PyUnicode_DATA(u);
11896 Py_MEMCPY(to, PyUnicode_DATA(str),
11897 PyUnicode_GET_LENGTH(str) * char_size);
Benjamin Peterson29060642009-01-31 22:14:21 +000011898 while (done < nchars) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011899 n = (done <= nchars-done) ? done : nchars-done;
11900 Py_MEMCPY(to + (done * char_size), to, n * char_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011901 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +000011902 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011903 }
11904
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020011905 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011906 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011907}
11908
Alexander Belopolsky40018472011-02-26 01:02:56 +000011909PyObject *
11910PyUnicode_Replace(PyObject *obj,
11911 PyObject *subobj,
11912 PyObject *replobj,
11913 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011914{
11915 PyObject *self;
11916 PyObject *str1;
11917 PyObject *str2;
11918 PyObject *result;
11919
11920 self = PyUnicode_FromObject(obj);
Victor Stinnere9a29352011-10-01 02:14:59 +020011921 if (self == NULL || PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000011922 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011923 str1 = PyUnicode_FromObject(subobj);
Victor Stinnere9a29352011-10-01 02:14:59 +020011924 if (str1 == NULL || PyUnicode_READY(str1) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011925 Py_DECREF(self);
11926 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011927 }
11928 str2 = PyUnicode_FromObject(replobj);
Victor Stinnere9a29352011-10-01 02:14:59 +020011929 if (str2 == NULL || PyUnicode_READY(str2)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011930 Py_DECREF(self);
11931 Py_DECREF(str1);
11932 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011933 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011934 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011935 Py_DECREF(self);
11936 Py_DECREF(str1);
11937 Py_DECREF(str2);
11938 return result;
11939}
11940
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011941PyDoc_STRVAR(replace__doc__,
Ezio Melottic1897e72010-06-26 18:50:39 +000011942 "S.replace(old, new[, count]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011943\n\
11944Return a copy of S with all occurrences of substring\n\
Georg Brandlf08a9dd2008-06-10 16:57:31 +000011945old replaced by new. If the optional argument count is\n\
11946given, only the first count occurrences are replaced.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011947
11948static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011949unicode_replace(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011950{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011951 PyObject *str1;
11952 PyObject *str2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011953 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011954 PyObject *result;
11955
Martin v. Löwis18e16552006-02-15 17:27:45 +000011956 if (!PyArg_ParseTuple(args, "OO|n:replace", &str1, &str2, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011957 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011958 if (!PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000011959 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011960 str1 = PyUnicode_FromObject(str1);
11961 if (str1 == NULL || PyUnicode_READY(str1) == -1)
11962 return NULL;
11963 str2 = PyUnicode_FromObject(str2);
Victor Stinnere9a29352011-10-01 02:14:59 +020011964 if (str2 == NULL || PyUnicode_READY(str2) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011965 Py_DECREF(str1);
11966 return NULL;
Walter Dörwaldf6b56ae2003-02-09 23:42:56 +000011967 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011968
11969 result = replace(self, str1, str2, maxcount);
11970
11971 Py_DECREF(str1);
11972 Py_DECREF(str2);
11973 return result;
11974}
11975
Alexander Belopolsky40018472011-02-26 01:02:56 +000011976static PyObject *
11977unicode_repr(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011978{
Walter Dörwald79e913e2007-05-12 11:08:06 +000011979 PyObject *repr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011980 Py_ssize_t isize;
11981 Py_ssize_t osize, squote, dquote, i, o;
11982 Py_UCS4 max, quote;
11983 int ikind, okind;
11984 void *idata, *odata;
Walter Dörwald79e913e2007-05-12 11:08:06 +000011985
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011986 if (PyUnicode_READY(unicode) == -1)
Walter Dörwald79e913e2007-05-12 11:08:06 +000011987 return NULL;
11988
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011989 isize = PyUnicode_GET_LENGTH(unicode);
11990 idata = PyUnicode_DATA(unicode);
Walter Dörwald79e913e2007-05-12 11:08:06 +000011991
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011992 /* Compute length of output, quote characters, and
11993 maximum character */
11994 osize = 2; /* quotes */
11995 max = 127;
11996 squote = dquote = 0;
11997 ikind = PyUnicode_KIND(unicode);
11998 for (i = 0; i < isize; i++) {
11999 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
12000 switch (ch) {
12001 case '\'': squote++; osize++; break;
12002 case '"': dquote++; osize++; break;
12003 case '\\': case '\t': case '\r': case '\n':
12004 osize += 2; break;
12005 default:
12006 /* Fast-path ASCII */
12007 if (ch < ' ' || ch == 0x7f)
12008 osize += 4; /* \xHH */
12009 else if (ch < 0x7f)
12010 osize++;
12011 else if (Py_UNICODE_ISPRINTABLE(ch)) {
12012 osize++;
12013 max = ch > max ? ch : max;
12014 }
12015 else if (ch < 0x100)
12016 osize += 4; /* \xHH */
12017 else if (ch < 0x10000)
12018 osize += 6; /* \uHHHH */
12019 else
12020 osize += 10; /* \uHHHHHHHH */
12021 }
12022 }
12023
12024 quote = '\'';
12025 if (squote) {
12026 if (dquote)
12027 /* Both squote and dquote present. Use squote,
12028 and escape them */
12029 osize += squote;
12030 else
12031 quote = '"';
12032 }
12033
12034 repr = PyUnicode_New(osize, max);
12035 if (repr == NULL)
12036 return NULL;
12037 okind = PyUnicode_KIND(repr);
12038 odata = PyUnicode_DATA(repr);
12039
12040 PyUnicode_WRITE(okind, odata, 0, quote);
12041 PyUnicode_WRITE(okind, odata, osize-1, quote);
12042
12043 for (i = 0, o = 1; i < isize; i++) {
12044 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012045
12046 /* Escape quotes and backslashes */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012047 if ((ch == quote) || (ch == '\\')) {
12048 PyUnicode_WRITE(okind, odata, o++, '\\');
12049 PyUnicode_WRITE(okind, odata, o++, ch);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012050 continue;
12051 }
12052
Benjamin Peterson29060642009-01-31 22:14:21 +000012053 /* Map special whitespace to '\t', \n', '\r' */
Georg Brandl559e5d72008-06-11 18:37:52 +000012054 if (ch == '\t') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012055 PyUnicode_WRITE(okind, odata, o++, '\\');
12056 PyUnicode_WRITE(okind, odata, o++, 't');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012057 }
12058 else if (ch == '\n') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012059 PyUnicode_WRITE(okind, odata, o++, '\\');
12060 PyUnicode_WRITE(okind, odata, o++, 'n');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012061 }
12062 else if (ch == '\r') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012063 PyUnicode_WRITE(okind, odata, o++, '\\');
12064 PyUnicode_WRITE(okind, odata, o++, 'r');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012065 }
12066
12067 /* Map non-printable US ASCII to '\xhh' */
Georg Brandl559e5d72008-06-11 18:37:52 +000012068 else if (ch < ' ' || ch == 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012069 PyUnicode_WRITE(okind, odata, o++, '\\');
12070 PyUnicode_WRITE(okind, odata, o++, 'x');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012071 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12072 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012073 }
12074
Georg Brandl559e5d72008-06-11 18:37:52 +000012075 /* Copy ASCII characters as-is */
12076 else if (ch < 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012077 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000012078 }
12079
Benjamin Peterson29060642009-01-31 22:14:21 +000012080 /* Non-ASCII characters */
Georg Brandl559e5d72008-06-11 18:37:52 +000012081 else {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012082 /* Map Unicode whitespace and control characters
Georg Brandl559e5d72008-06-11 18:37:52 +000012083 (categories Z* and C* except ASCII space)
12084 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012085 if (!Py_UNICODE_ISPRINTABLE(ch)) {
Georg Brandl559e5d72008-06-11 18:37:52 +000012086 /* Map 8-bit characters to '\xhh' */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012087 if (ch <= 0xff) {
12088 PyUnicode_WRITE(okind, odata, o++, '\\');
12089 PyUnicode_WRITE(okind, odata, o++, 'x');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012090 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12091 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012092 }
12093 /* Map 21-bit characters to '\U00xxxxxx' */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012094 else if (ch >= 0x10000) {
12095 PyUnicode_WRITE(okind, odata, o++, '\\');
12096 PyUnicode_WRITE(okind, odata, o++, 'U');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012097 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 28) & 0xF]);
12098 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 24) & 0xF]);
12099 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 20) & 0xF]);
12100 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 16) & 0xF]);
12101 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12102 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12103 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12104 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012105 }
12106 /* Map 16-bit characters to '\uxxxx' */
12107 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012108 PyUnicode_WRITE(okind, odata, o++, '\\');
12109 PyUnicode_WRITE(okind, odata, o++, 'u');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012110 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12111 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12112 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12113 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012114 }
12115 }
12116 /* Copy characters as-is */
12117 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012118 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000012119 }
12120 }
Walter Dörwald79e913e2007-05-12 11:08:06 +000012121 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012122 /* Closing quote already added at the beginning */
Victor Stinner05d11892011-10-06 01:13:58 +020012123 assert(_PyUnicode_CheckConsistency(repr, 1));
Walter Dörwald79e913e2007-05-12 11:08:06 +000012124 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012125}
12126
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012127PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012128 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012129\n\
12130Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080012131such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012132arguments start and end are interpreted as in slice notation.\n\
12133\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012134Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012135
12136static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012137unicode_rfind(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012138{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012139 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012140 Py_ssize_t start;
12141 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012142 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012143
Jesus Ceaac451502011-04-20 17:09:23 +020012144 if (!stringlib_parse_args_finds_unicode("rfind", args, &substring,
12145 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012146 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012147
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012148 if (PyUnicode_READY(self) == -1)
12149 return NULL;
12150 if (PyUnicode_READY(substring) == -1)
12151 return NULL;
12152
Victor Stinner7931d9a2011-11-04 00:22:48 +010012153 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012154
12155 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012156
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012157 if (result == -2)
12158 return NULL;
12159
Christian Heimes217cfd12007-12-02 14:31:20 +000012160 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012161}
12162
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012163PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012164 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012165\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012166Like S.rfind() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012167
12168static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012169unicode_rindex(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012170{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012171 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012172 Py_ssize_t start;
12173 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012174 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012175
Jesus Ceaac451502011-04-20 17:09:23 +020012176 if (!stringlib_parse_args_finds_unicode("rindex", args, &substring,
12177 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012178 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012179
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012180 if (PyUnicode_READY(self) == -1)
12181 return NULL;
12182 if (PyUnicode_READY(substring) == -1)
12183 return NULL;
12184
Victor Stinner7931d9a2011-11-04 00:22:48 +010012185 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012186
12187 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012188
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012189 if (result == -2)
12190 return NULL;
12191
Guido van Rossumd57fd912000-03-10 22:53:23 +000012192 if (result < 0) {
12193 PyErr_SetString(PyExc_ValueError, "substring not found");
12194 return NULL;
12195 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012196
Christian Heimes217cfd12007-12-02 14:31:20 +000012197 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012198}
12199
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012200PyDoc_STRVAR(rjust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012201 "S.rjust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012202\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012203Return S right-justified in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012204done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012205
12206static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012207unicode_rjust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012208{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012209 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012210 Py_UCS4 fillchar = ' ';
12211
Victor Stinnere9a29352011-10-01 02:14:59 +020012212 if (!PyArg_ParseTuple(args, "n|O&:rjust", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012213 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012214
Victor Stinnere9a29352011-10-01 02:14:59 +020012215 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012216 return NULL;
12217
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012218 if (_PyUnicode_LENGTH(self) >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000012219 Py_INCREF(self);
Victor Stinner7931d9a2011-11-04 00:22:48 +010012220 return self;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012221 }
12222
Victor Stinner7931d9a2011-11-04 00:22:48 +010012223 return pad(self, width - _PyUnicode_LENGTH(self), 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012224}
12225
Alexander Belopolsky40018472011-02-26 01:02:56 +000012226PyObject *
12227PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012228{
12229 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +000012230
Guido van Rossumd57fd912000-03-10 22:53:23 +000012231 s = PyUnicode_FromObject(s);
12232 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012233 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012234 if (sep != NULL) {
12235 sep = PyUnicode_FromObject(sep);
12236 if (sep == NULL) {
12237 Py_DECREF(s);
12238 return NULL;
12239 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012240 }
12241
Victor Stinner9310abb2011-10-05 00:59:23 +020012242 result = split(s, sep, maxsplit);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012243
12244 Py_DECREF(s);
12245 Py_XDECREF(sep);
12246 return result;
12247}
12248
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012249PyDoc_STRVAR(split__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012250 "S.split([sep[, maxsplit]]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012251\n\
12252Return a list of the words in S, using sep as the\n\
12253delimiter string. If maxsplit is given, at most maxsplit\n\
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000012254splits are done. If sep is not specified or is None, any\n\
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +000012255whitespace string is a separator and empty strings are\n\
12256removed from the result.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012257
12258static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012259unicode_split(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012260{
12261 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012262 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012263
Martin v. Löwis18e16552006-02-15 17:27:45 +000012264 if (!PyArg_ParseTuple(args, "|On:split", &substring, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012265 return NULL;
12266
12267 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012268 return split(self, NULL, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012269 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012270 return split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012271 else
Victor Stinner7931d9a2011-11-04 00:22:48 +010012272 return PyUnicode_Split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012273}
12274
Thomas Wouters477c8d52006-05-27 19:21:47 +000012275PyObject *
12276PyUnicode_Partition(PyObject *str_in, PyObject *sep_in)
12277{
12278 PyObject* str_obj;
12279 PyObject* sep_obj;
12280 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012281 int kind1, kind2, kind;
12282 void *buf1 = NULL, *buf2 = NULL;
12283 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012284
12285 str_obj = PyUnicode_FromObject(str_in);
Victor Stinnere9a29352011-10-01 02:14:59 +020012286 if (!str_obj || PyUnicode_READY(str_obj) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000012287 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012288 sep_obj = PyUnicode_FromObject(sep_in);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012289 if (!sep_obj || PyUnicode_READY(sep_obj) == -1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000012290 Py_DECREF(str_obj);
12291 return NULL;
12292 }
12293
Victor Stinner14f8f022011-10-05 20:58:25 +020012294 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012295 kind2 = PyUnicode_KIND(sep_obj);
Victor Stinner14f8f022011-10-05 20:58:25 +020012296 kind = Py_MAX(kind1, kind2);
12297 buf1 = PyUnicode_DATA(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012298 if (kind1 != kind)
Victor Stinner14f8f022011-10-05 20:58:25 +020012299 buf1 = _PyUnicode_AsKind(str_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012300 if (!buf1)
12301 goto onError;
12302 buf2 = PyUnicode_DATA(sep_obj);
12303 if (kind2 != kind)
12304 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12305 if (!buf2)
12306 goto onError;
12307 len1 = PyUnicode_GET_LENGTH(str_obj);
12308 len2 = PyUnicode_GET_LENGTH(sep_obj);
12309
Victor Stinner14f8f022011-10-05 20:58:25 +020012310 switch(PyUnicode_KIND(str_obj)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012311 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012312 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12313 out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12314 else
12315 out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012316 break;
12317 case PyUnicode_2BYTE_KIND:
12318 out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12319 break;
12320 case PyUnicode_4BYTE_KIND:
12321 out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12322 break;
12323 default:
12324 assert(0);
12325 out = 0;
12326 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012327
12328 Py_DECREF(sep_obj);
12329 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012330 if (kind1 != kind)
12331 PyMem_Free(buf1);
12332 if (kind2 != kind)
12333 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012334
12335 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012336 onError:
12337 Py_DECREF(sep_obj);
12338 Py_DECREF(str_obj);
12339 if (kind1 != kind && buf1)
12340 PyMem_Free(buf1);
12341 if (kind2 != kind && buf2)
12342 PyMem_Free(buf2);
12343 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012344}
12345
12346
12347PyObject *
12348PyUnicode_RPartition(PyObject *str_in, PyObject *sep_in)
12349{
12350 PyObject* str_obj;
12351 PyObject* sep_obj;
12352 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012353 int kind1, kind2, kind;
12354 void *buf1 = NULL, *buf2 = NULL;
12355 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012356
12357 str_obj = PyUnicode_FromObject(str_in);
12358 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012359 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012360 sep_obj = PyUnicode_FromObject(sep_in);
12361 if (!sep_obj) {
12362 Py_DECREF(str_obj);
12363 return NULL;
12364 }
12365
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012366 kind1 = PyUnicode_KIND(str_in);
12367 kind2 = PyUnicode_KIND(sep_obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +020012368 kind = Py_MAX(kind1, kind2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012369 buf1 = PyUnicode_DATA(str_in);
12370 if (kind1 != kind)
12371 buf1 = _PyUnicode_AsKind(str_in, kind);
12372 if (!buf1)
12373 goto onError;
12374 buf2 = PyUnicode_DATA(sep_obj);
12375 if (kind2 != kind)
12376 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12377 if (!buf2)
12378 goto onError;
12379 len1 = PyUnicode_GET_LENGTH(str_obj);
12380 len2 = PyUnicode_GET_LENGTH(sep_obj);
12381
12382 switch(PyUnicode_KIND(str_in)) {
12383 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012384 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12385 out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12386 else
12387 out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012388 break;
12389 case PyUnicode_2BYTE_KIND:
12390 out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12391 break;
12392 case PyUnicode_4BYTE_KIND:
12393 out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12394 break;
12395 default:
12396 assert(0);
12397 out = 0;
12398 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012399
12400 Py_DECREF(sep_obj);
12401 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012402 if (kind1 != kind)
12403 PyMem_Free(buf1);
12404 if (kind2 != kind)
12405 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012406
12407 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012408 onError:
12409 Py_DECREF(sep_obj);
12410 Py_DECREF(str_obj);
12411 if (kind1 != kind && buf1)
12412 PyMem_Free(buf1);
12413 if (kind2 != kind && buf2)
12414 PyMem_Free(buf2);
12415 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012416}
12417
12418PyDoc_STRVAR(partition__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012419 "S.partition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012420\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012421Search for the separator sep in S, and return the part before it,\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012422the separator itself, and the part after it. If the separator is not\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012423found, return S and two empty strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012424
12425static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012426unicode_partition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012427{
Victor Stinner9310abb2011-10-05 00:59:23 +020012428 return PyUnicode_Partition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012429}
12430
12431PyDoc_STRVAR(rpartition__doc__,
Ezio Melotti5b2b2422010-01-25 11:58:28 +000012432 "S.rpartition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012433\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012434Search for the separator sep in S, starting at the end of S, and return\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012435the part before it, the separator itself, and the part after it. If the\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012436separator is not found, return two empty strings and S.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012437
12438static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012439unicode_rpartition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012440{
Victor Stinner9310abb2011-10-05 00:59:23 +020012441 return PyUnicode_RPartition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012442}
12443
Alexander Belopolsky40018472011-02-26 01:02:56 +000012444PyObject *
12445PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012446{
12447 PyObject *result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012448
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012449 s = PyUnicode_FromObject(s);
12450 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012451 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012452 if (sep != NULL) {
12453 sep = PyUnicode_FromObject(sep);
12454 if (sep == NULL) {
12455 Py_DECREF(s);
12456 return NULL;
12457 }
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012458 }
12459
Victor Stinner9310abb2011-10-05 00:59:23 +020012460 result = rsplit(s, sep, maxsplit);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012461
12462 Py_DECREF(s);
12463 Py_XDECREF(sep);
12464 return result;
12465}
12466
12467PyDoc_STRVAR(rsplit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012468 "S.rsplit([sep[, maxsplit]]) -> list of strings\n\
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012469\n\
12470Return a list of the words in S, using sep as the\n\
12471delimiter string, starting at the end of the string and\n\
12472working to the front. If maxsplit is given, at most maxsplit\n\
12473splits are done. If sep is not specified, any whitespace string\n\
12474is a separator.");
12475
12476static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012477unicode_rsplit(PyObject *self, PyObject *args)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012478{
12479 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012480 Py_ssize_t maxcount = -1;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012481
Martin v. Löwis18e16552006-02-15 17:27:45 +000012482 if (!PyArg_ParseTuple(args, "|On:rsplit", &substring, &maxcount))
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012483 return NULL;
12484
12485 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012486 return rsplit(self, NULL, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012487 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012488 return rsplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012489 else
Victor Stinner9310abb2011-10-05 00:59:23 +020012490 return PyUnicode_RSplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012491}
12492
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012493PyDoc_STRVAR(splitlines__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012494 "S.splitlines([keepends]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012495\n\
12496Return a list of the lines in S, breaking at line boundaries.\n\
Guido van Rossum86662912000-04-11 15:38:46 +000012497Line breaks are not included in the resulting list unless keepends\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012498is given and true.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012499
12500static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012501unicode_splitlines(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012502{
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012503 static char *kwlist[] = {"keepends", 0};
Guido van Rossum86662912000-04-11 15:38:46 +000012504 int keepends = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012505
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012506 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:splitlines",
12507 kwlist, &keepends))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012508 return NULL;
12509
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012510 return PyUnicode_Splitlines(self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012511}
12512
12513static
Guido van Rossumf15a29f2007-05-04 00:41:39 +000012514PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012515{
Walter Dörwald346737f2007-05-31 10:44:43 +000012516 if (PyUnicode_CheckExact(self)) {
12517 Py_INCREF(self);
12518 return self;
12519 } else
12520 /* Subtype -- return genuine unicode string with the same value. */
Victor Stinner034f6cf2011-09-30 02:26:44 +020012521 return PyUnicode_Copy(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012522}
12523
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012524PyDoc_STRVAR(swapcase__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012525 "S.swapcase() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012526\n\
12527Return a copy of S with uppercase characters converted to lowercase\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012528and vice versa.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012529
12530static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012531unicode_swapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012532{
Guido van Rossumd57fd912000-03-10 22:53:23 +000012533 return fixup(self, fixswapcase);
12534}
12535
Georg Brandlceee0772007-11-27 23:48:05 +000012536PyDoc_STRVAR(maketrans__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012537 "str.maketrans(x[, y[, z]]) -> dict (static method)\n\
Georg Brandlceee0772007-11-27 23:48:05 +000012538\n\
12539Return a translation table usable for str.translate().\n\
12540If there is only one argument, it must be a dictionary mapping Unicode\n\
12541ordinals (integers) or characters to Unicode ordinals, strings or None.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012542Character keys will be then converted to ordinals.\n\
Georg Brandlceee0772007-11-27 23:48:05 +000012543If there are two arguments, they must be strings of equal length, and\n\
12544in the resulting dictionary, each character in x will be mapped to the\n\
12545character at the same position in y. If there is a third argument, it\n\
12546must be a string, whose characters will be mapped to None in the result.");
12547
12548static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012549unicode_maketrans(PyObject *null, PyObject *args)
Georg Brandlceee0772007-11-27 23:48:05 +000012550{
12551 PyObject *x, *y = NULL, *z = NULL;
12552 PyObject *new = NULL, *key, *value;
12553 Py_ssize_t i = 0;
12554 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012555
Georg Brandlceee0772007-11-27 23:48:05 +000012556 if (!PyArg_ParseTuple(args, "O|UU:maketrans", &x, &y, &z))
12557 return NULL;
12558 new = PyDict_New();
12559 if (!new)
12560 return NULL;
12561 if (y != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012562 int x_kind, y_kind, z_kind;
12563 void *x_data, *y_data, *z_data;
12564
Georg Brandlceee0772007-11-27 23:48:05 +000012565 /* x must be a string too, of equal length */
Georg Brandlceee0772007-11-27 23:48:05 +000012566 if (!PyUnicode_Check(x)) {
12567 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
12568 "be a string if there is a second argument");
12569 goto err;
12570 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012571 if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012572 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
12573 "arguments must have equal length");
12574 goto err;
12575 }
12576 /* create entries for translating chars in x to those in y */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012577 x_kind = PyUnicode_KIND(x);
12578 y_kind = PyUnicode_KIND(y);
12579 x_data = PyUnicode_DATA(x);
12580 y_data = PyUnicode_DATA(y);
12581 for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
12582 key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
12583 value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000012584 if (!key || !value)
12585 goto err;
12586 res = PyDict_SetItem(new, key, value);
12587 Py_DECREF(key);
12588 Py_DECREF(value);
12589 if (res < 0)
12590 goto err;
12591 }
12592 /* create entries for deleting chars in z */
12593 if (z != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012594 z_kind = PyUnicode_KIND(z);
12595 z_data = PyUnicode_DATA(z);
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012596 for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012597 key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000012598 if (!key)
12599 goto err;
12600 res = PyDict_SetItem(new, key, Py_None);
12601 Py_DECREF(key);
12602 if (res < 0)
12603 goto err;
12604 }
12605 }
12606 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012607 int kind;
12608 void *data;
12609
Georg Brandlceee0772007-11-27 23:48:05 +000012610 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +000012611 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012612 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
12613 "to maketrans it must be a dict");
12614 goto err;
12615 }
12616 /* copy entries into the new dict, converting string keys to int keys */
12617 while (PyDict_Next(x, &i, &key, &value)) {
12618 if (PyUnicode_Check(key)) {
12619 /* convert string keys to integer keys */
12620 PyObject *newkey;
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012621 if (PyUnicode_GET_LENGTH(key) != 1) {
Georg Brandlceee0772007-11-27 23:48:05 +000012622 PyErr_SetString(PyExc_ValueError, "string keys in translate "
12623 "table must be of length 1");
12624 goto err;
12625 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012626 kind = PyUnicode_KIND(key);
12627 data = PyUnicode_DATA(key);
12628 newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
Georg Brandlceee0772007-11-27 23:48:05 +000012629 if (!newkey)
12630 goto err;
12631 res = PyDict_SetItem(new, newkey, value);
12632 Py_DECREF(newkey);
12633 if (res < 0)
12634 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +000012635 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012636 /* just keep integer keys */
12637 if (PyDict_SetItem(new, key, value) < 0)
12638 goto err;
12639 } else {
12640 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
12641 "be strings or integers");
12642 goto err;
12643 }
12644 }
12645 }
12646 return new;
12647 err:
12648 Py_DECREF(new);
12649 return NULL;
12650}
12651
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012652PyDoc_STRVAR(translate__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012653 "S.translate(table) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012654\n\
12655Return a copy of the string S, where all characters have been mapped\n\
12656through the given translation table, which must be a mapping of\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012657Unicode ordinals to Unicode ordinals, strings, or None.\n\
Walter Dörwald5c1ee172002-09-04 20:31:32 +000012658Unmapped characters are left untouched. Characters mapped to None\n\
12659are deleted.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012660
12661static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012662unicode_translate(PyObject *self, PyObject *table)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012663{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012664 return _PyUnicode_TranslateCharmap(self, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012665}
12666
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012667PyDoc_STRVAR(upper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012668 "S.upper() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012669\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012670Return a copy of S converted to uppercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012671
12672static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012673unicode_upper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012674{
Guido van Rossumd57fd912000-03-10 22:53:23 +000012675 return fixup(self, fixupper);
12676}
12677
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012678PyDoc_STRVAR(zfill__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012679 "S.zfill(width) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012680\n\
Benjamin Peterson9aa42992008-09-10 21:57:34 +000012681Pad a numeric string S with zeros on the left, to fill a field\n\
12682of the specified width. The string S is never truncated.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012683
12684static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012685unicode_zfill(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012686{
Martin v. Löwis18e16552006-02-15 17:27:45 +000012687 Py_ssize_t fill;
Victor Stinner9310abb2011-10-05 00:59:23 +020012688 PyObject *u;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012689 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012690 int kind;
12691 void *data;
12692 Py_UCS4 chr;
12693
12694 if (PyUnicode_READY(self) == -1)
12695 return NULL;
12696
Martin v. Löwis18e16552006-02-15 17:27:45 +000012697 if (!PyArg_ParseTuple(args, "n:zfill", &width))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012698 return NULL;
12699
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012700 if (PyUnicode_GET_LENGTH(self) >= width) {
Walter Dörwald0fe940c2002-04-15 18:42:15 +000012701 if (PyUnicode_CheckExact(self)) {
12702 Py_INCREF(self);
Victor Stinner7931d9a2011-11-04 00:22:48 +010012703 return self;
Walter Dörwald0fe940c2002-04-15 18:42:15 +000012704 }
12705 else
Victor Stinner7931d9a2011-11-04 00:22:48 +010012706 return PyUnicode_Copy(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012707 }
12708
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012709 fill = width - _PyUnicode_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012710
12711 u = pad(self, fill, 0, '0');
12712
Walter Dörwald068325e2002-04-15 13:36:47 +000012713 if (u == NULL)
12714 return NULL;
12715
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012716 kind = PyUnicode_KIND(u);
12717 data = PyUnicode_DATA(u);
12718 chr = PyUnicode_READ(kind, data, fill);
12719
12720 if (chr == '+' || chr == '-') {
Guido van Rossumd57fd912000-03-10 22:53:23 +000012721 /* move sign to beginning of string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012722 PyUnicode_WRITE(kind, data, 0, chr);
12723 PyUnicode_WRITE(kind, data, fill, '0');
Guido van Rossumd57fd912000-03-10 22:53:23 +000012724 }
12725
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012726 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +010012727 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012728}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012729
12730#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012731static PyObject *
12732unicode__decimal2ascii(PyObject *self)
12733{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012734 return PyUnicode_TransformDecimalAndSpaceToASCII(self);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012735}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012736#endif
12737
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012738PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012739 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012740\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000012741Return True if S starts with the specified prefix, False otherwise.\n\
12742With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012743With optional end, stop comparing S at that position.\n\
12744prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012745
12746static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012747unicode_startswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000012748 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012749{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012750 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012751 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012752 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012753 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012754 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012755
Jesus Ceaac451502011-04-20 17:09:23 +020012756 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000012757 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012758 if (PyTuple_Check(subobj)) {
12759 Py_ssize_t i;
12760 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012761 substring = PyUnicode_FromObject(PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012762 if (substring == NULL)
12763 return NULL;
12764 result = tailmatch(self, substring, start, end, -1);
12765 Py_DECREF(substring);
12766 if (result) {
12767 Py_RETURN_TRUE;
12768 }
12769 }
12770 /* nothing matched */
12771 Py_RETURN_FALSE;
12772 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012773 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030012774 if (substring == NULL) {
12775 if (PyErr_ExceptionMatches(PyExc_TypeError))
12776 PyErr_Format(PyExc_TypeError, "startswith first arg must be str or "
12777 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000012778 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030012779 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012780 result = tailmatch(self, substring, start, end, -1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012781 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012782 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012783}
12784
12785
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012786PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012787 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012788\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000012789Return True if S ends with the specified suffix, False otherwise.\n\
12790With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012791With optional end, stop comparing S at that position.\n\
12792suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012793
12794static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012795unicode_endswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000012796 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012797{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012798 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012799 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012800 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012801 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012802 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012803
Jesus Ceaac451502011-04-20 17:09:23 +020012804 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000012805 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012806 if (PyTuple_Check(subobj)) {
12807 Py_ssize_t i;
12808 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012809 substring = PyUnicode_FromObject(
Benjamin Peterson29060642009-01-31 22:14:21 +000012810 PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012811 if (substring == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000012812 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012813 result = tailmatch(self, substring, start, end, +1);
12814 Py_DECREF(substring);
12815 if (result) {
12816 Py_RETURN_TRUE;
12817 }
12818 }
12819 Py_RETURN_FALSE;
12820 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012821 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030012822 if (substring == NULL) {
12823 if (PyErr_ExceptionMatches(PyExc_TypeError))
12824 PyErr_Format(PyExc_TypeError, "endswith first arg must be str or "
12825 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000012826 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030012827 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012828 result = tailmatch(self, substring, start, end, +1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012829 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012830 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012831}
12832
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012833#include "stringlib/unicode_format.h"
Eric Smith8c663262007-08-25 02:26:07 +000012834
12835PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012836 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000012837\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012838Return a formatted version of S, using substitutions from args and kwargs.\n\
12839The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +000012840
Eric Smith27bbca62010-11-04 17:06:58 +000012841PyDoc_STRVAR(format_map__doc__,
12842 "S.format_map(mapping) -> str\n\
12843\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012844Return a formatted version of S, using substitutions from mapping.\n\
12845The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +000012846
Eric Smith4a7d76d2008-05-30 18:10:19 +000012847static PyObject *
12848unicode__format__(PyObject* self, PyObject* args)
12849{
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012850 PyObject *format_spec, *out;
Eric Smith4a7d76d2008-05-30 18:10:19 +000012851
12852 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
12853 return NULL;
12854
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012855 out = _PyUnicode_FormatAdvanced(self, format_spec, 0,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012856 PyUnicode_GET_LENGTH(format_spec));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012857 return out;
Eric Smith4a7d76d2008-05-30 18:10:19 +000012858}
12859
Eric Smith8c663262007-08-25 02:26:07 +000012860PyDoc_STRVAR(p_format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012861 "S.__format__(format_spec) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000012862\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012863Return a formatted version of S as described by format_spec.");
Eric Smith8c663262007-08-25 02:26:07 +000012864
12865static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012866unicode__sizeof__(PyObject *v)
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012867{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012868 Py_ssize_t size;
12869
12870 /* If it's a compact object, account for base structure +
12871 character data. */
12872 if (PyUnicode_IS_COMPACT_ASCII(v))
12873 size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(v) + 1;
12874 else if (PyUnicode_IS_COMPACT(v))
12875 size = sizeof(PyCompactUnicodeObject) +
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012876 (PyUnicode_GET_LENGTH(v) + 1) * PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012877 else {
12878 /* If it is a two-block object, account for base object, and
12879 for character block if present. */
12880 size = sizeof(PyUnicodeObject);
Victor Stinnerc3c74152011-10-02 20:39:55 +020012881 if (_PyUnicode_DATA_ANY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012882 size += (PyUnicode_GET_LENGTH(v) + 1) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012883 PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012884 }
12885 /* If the wstr pointer is present, account for it unless it is shared
Victor Stinnera3be6132011-10-03 02:16:37 +020012886 with the data pointer. Check if the data is not shared. */
Victor Stinner03490912011-10-03 23:45:12 +020012887 if (_PyUnicode_HAS_WSTR_MEMORY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012888 size += (PyUnicode_WSTR_LENGTH(v) + 1) * sizeof(wchar_t);
Victor Stinner829c0ad2011-10-03 01:08:02 +020012889 if (_PyUnicode_HAS_UTF8_MEMORY(v))
Victor Stinnere90fe6a2011-10-01 16:48:13 +020012890 size += PyUnicode_UTF8_LENGTH(v) + 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012891
12892 return PyLong_FromSsize_t(size);
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012893}
12894
12895PyDoc_STRVAR(sizeof__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012896 "S.__sizeof__() -> size of S in memory, in bytes");
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012897
12898static PyObject *
Victor Stinner034f6cf2011-09-30 02:26:44 +020012899unicode_getnewargs(PyObject *v)
Guido van Rossum5d9113d2003-01-29 17:58:45 +000012900{
Victor Stinner034f6cf2011-09-30 02:26:44 +020012901 PyObject *copy = PyUnicode_Copy(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012902 if (!copy)
12903 return NULL;
12904 return Py_BuildValue("(N)", copy);
Guido van Rossum5d9113d2003-01-29 17:58:45 +000012905}
12906
Guido van Rossumd57fd912000-03-10 22:53:23 +000012907static PyMethodDef unicode_methods[] = {
12908
12909 /* Order is according to common usage: often used methods should
12910 appear first, since lookup is done sequentially. */
12911
Benjamin Peterson28a4dce2010-12-12 01:33:04 +000012912 {"encode", (PyCFunction) unicode_encode, METH_VARARGS | METH_KEYWORDS, encode__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012913 {"replace", (PyCFunction) unicode_replace, METH_VARARGS, replace__doc__},
12914 {"split", (PyCFunction) unicode_split, METH_VARARGS, split__doc__},
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012915 {"rsplit", (PyCFunction) unicode_rsplit, METH_VARARGS, rsplit__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012916 {"join", (PyCFunction) unicode_join, METH_O, join__doc__},
12917 {"capitalize", (PyCFunction) unicode_capitalize, METH_NOARGS, capitalize__doc__},
12918 {"title", (PyCFunction) unicode_title, METH_NOARGS, title__doc__},
12919 {"center", (PyCFunction) unicode_center, METH_VARARGS, center__doc__},
12920 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
12921 {"expandtabs", (PyCFunction) unicode_expandtabs, METH_VARARGS, expandtabs__doc__},
12922 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000012923 {"partition", (PyCFunction) unicode_partition, METH_O, partition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012924 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
12925 {"ljust", (PyCFunction) unicode_ljust, METH_VARARGS, ljust__doc__},
12926 {"lower", (PyCFunction) unicode_lower, METH_NOARGS, lower__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012927 {"lstrip", (PyCFunction) unicode_lstrip, METH_VARARGS, lstrip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012928 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
12929 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
12930 {"rjust", (PyCFunction) unicode_rjust, METH_VARARGS, rjust__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012931 {"rstrip", (PyCFunction) unicode_rstrip, METH_VARARGS, rstrip__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000012932 {"rpartition", (PyCFunction) unicode_rpartition, METH_O, rpartition__doc__},
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012933 {"splitlines", (PyCFunction) unicode_splitlines, METH_VARARGS | METH_KEYWORDS, splitlines__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012934 {"strip", (PyCFunction) unicode_strip, METH_VARARGS, strip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012935 {"swapcase", (PyCFunction) unicode_swapcase, METH_NOARGS, swapcase__doc__},
12936 {"translate", (PyCFunction) unicode_translate, METH_O, translate__doc__},
12937 {"upper", (PyCFunction) unicode_upper, METH_NOARGS, upper__doc__},
12938 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
12939 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
12940 {"islower", (PyCFunction) unicode_islower, METH_NOARGS, islower__doc__},
12941 {"isupper", (PyCFunction) unicode_isupper, METH_NOARGS, isupper__doc__},
12942 {"istitle", (PyCFunction) unicode_istitle, METH_NOARGS, istitle__doc__},
12943 {"isspace", (PyCFunction) unicode_isspace, METH_NOARGS, isspace__doc__},
12944 {"isdecimal", (PyCFunction) unicode_isdecimal, METH_NOARGS, isdecimal__doc__},
12945 {"isdigit", (PyCFunction) unicode_isdigit, METH_NOARGS, isdigit__doc__},
12946 {"isnumeric", (PyCFunction) unicode_isnumeric, METH_NOARGS, isnumeric__doc__},
12947 {"isalpha", (PyCFunction) unicode_isalpha, METH_NOARGS, isalpha__doc__},
12948 {"isalnum", (PyCFunction) unicode_isalnum, METH_NOARGS, isalnum__doc__},
Martin v. Löwis47383402007-08-15 07:32:56 +000012949 {"isidentifier", (PyCFunction) unicode_isidentifier, METH_NOARGS, isidentifier__doc__},
Georg Brandl559e5d72008-06-11 18:37:52 +000012950 {"isprintable", (PyCFunction) unicode_isprintable, METH_NOARGS, isprintable__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012951 {"zfill", (PyCFunction) unicode_zfill, METH_VARARGS, zfill__doc__},
Eric Smith9cd1e092007-08-31 18:39:38 +000012952 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +000012953 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
Eric Smith4a7d76d2008-05-30 18:10:19 +000012954 {"__format__", (PyCFunction) unicode__format__, METH_VARARGS, p_format__doc__},
Georg Brandlceee0772007-11-27 23:48:05 +000012955 {"maketrans", (PyCFunction) unicode_maketrans,
12956 METH_VARARGS | METH_STATIC, maketrans__doc__},
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012957 {"__sizeof__", (PyCFunction) unicode__sizeof__, METH_NOARGS, sizeof__doc__},
Walter Dörwald068325e2002-04-15 13:36:47 +000012958#if 0
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012959 {"capwords", (PyCFunction) unicode_capwords, METH_NOARGS, capwords__doc__},
Guido van Rossumd57fd912000-03-10 22:53:23 +000012960#endif
12961
12962#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012963 /* These methods are just used for debugging the implementation. */
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012964 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000012965#endif
12966
Benjamin Peterson14339b62009-01-31 16:36:08 +000012967 {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000012968 {NULL, NULL}
12969};
12970
Neil Schemenauerce30bc92002-11-18 16:10:18 +000012971static PyObject *
12972unicode_mod(PyObject *v, PyObject *w)
12973{
Brian Curtindfc80e32011-08-10 20:28:54 -050012974 if (!PyUnicode_Check(v))
12975 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson29060642009-01-31 22:14:21 +000012976 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +000012977}
12978
12979static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012980 0, /*nb_add*/
12981 0, /*nb_subtract*/
12982 0, /*nb_multiply*/
12983 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +000012984};
12985
Guido van Rossumd57fd912000-03-10 22:53:23 +000012986static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012987 (lenfunc) unicode_length, /* sq_length */
12988 PyUnicode_Concat, /* sq_concat */
12989 (ssizeargfunc) unicode_repeat, /* sq_repeat */
12990 (ssizeargfunc) unicode_getitem, /* sq_item */
12991 0, /* sq_slice */
12992 0, /* sq_ass_item */
12993 0, /* sq_ass_slice */
12994 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +000012995};
12996
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012997static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012998unicode_subscript(PyObject* self, PyObject* item)
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012999{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013000 if (PyUnicode_READY(self) == -1)
13001 return NULL;
13002
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000013003 if (PyIndex_Check(item)) {
13004 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013005 if (i == -1 && PyErr_Occurred())
13006 return NULL;
13007 if (i < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013008 i += PyUnicode_GET_LENGTH(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013009 return unicode_getitem(self, i);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013010 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000013011 Py_ssize_t start, stop, step, slicelength, cur, i;
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013012 PyObject *result;
13013 void *src_data, *dest_data;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013014 int src_kind, dest_kind;
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013015 Py_UCS4 ch, max_char, kind_limit;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013016
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013017 if (PySlice_GetIndicesEx(item, PyUnicode_GET_LENGTH(self),
Benjamin Peterson29060642009-01-31 22:14:21 +000013018 &start, &stop, &step, &slicelength) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013019 return NULL;
13020 }
13021
13022 if (slicelength <= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013023 return PyUnicode_New(0, 0);
13024 } else if (start == 0 && step == 1 &&
13025 slicelength == PyUnicode_GET_LENGTH(self) &&
Thomas Woutersed03b412007-08-28 21:37:11 +000013026 PyUnicode_CheckExact(self)) {
13027 Py_INCREF(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013028 return self;
Thomas Woutersed03b412007-08-28 21:37:11 +000013029 } else if (step == 1) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013030 return PyUnicode_Substring(self,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013031 start, start + slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013032 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013033 /* General case */
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013034 src_kind = PyUnicode_KIND(self);
13035 src_data = PyUnicode_DATA(self);
Victor Stinner55c99112011-10-13 01:17:06 +020013036 if (!PyUnicode_IS_ASCII(self)) {
13037 kind_limit = kind_maxchar_limit(src_kind);
13038 max_char = 0;
13039 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
13040 ch = PyUnicode_READ(src_kind, src_data, cur);
13041 if (ch > max_char) {
13042 max_char = ch;
13043 if (max_char >= kind_limit)
13044 break;
13045 }
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013046 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013047 }
Victor Stinner55c99112011-10-13 01:17:06 +020013048 else
13049 max_char = 127;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013050 result = PyUnicode_New(slicelength, max_char);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013051 if (result == NULL)
13052 return NULL;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013053 dest_kind = PyUnicode_KIND(result);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013054 dest_data = PyUnicode_DATA(result);
13055
13056 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013057 Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
13058 PyUnicode_WRITE(dest_kind, dest_data, i, ch);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013059 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013060 assert(_PyUnicode_CheckConsistency(result, 1));
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013061 return result;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013062 } else {
13063 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
13064 return NULL;
13065 }
13066}
13067
13068static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013069 (lenfunc)unicode_length, /* mp_length */
13070 (binaryfunc)unicode_subscript, /* mp_subscript */
13071 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013072};
13073
Guido van Rossumd57fd912000-03-10 22:53:23 +000013074
Guido van Rossumd57fd912000-03-10 22:53:23 +000013075/* Helpers for PyUnicode_Format() */
13076
13077static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +000013078getnextarg(PyObject *args, Py_ssize_t arglen, Py_ssize_t *p_argidx)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013079{
Martin v. Löwis18e16552006-02-15 17:27:45 +000013080 Py_ssize_t argidx = *p_argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013081 if (argidx < arglen) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013082 (*p_argidx)++;
13083 if (arglen < 0)
13084 return args;
13085 else
13086 return PyTuple_GetItem(args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013087 }
13088 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013089 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013090 return NULL;
13091}
13092
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013093/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013094
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013095static PyObject *
13096formatfloat(PyObject *v, int flags, int prec, int type)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013097{
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013098 char *p;
13099 PyObject *result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013100 double x;
Tim Petersced69f82003-09-16 20:30:58 +000013101
Guido van Rossumd57fd912000-03-10 22:53:23 +000013102 x = PyFloat_AsDouble(v);
13103 if (x == -1.0 && PyErr_Occurred())
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013104 return NULL;
13105
Guido van Rossumd57fd912000-03-10 22:53:23 +000013106 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000013107 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +000013108
Eric Smith0923d1d2009-04-16 20:16:10 +000013109 p = PyOS_double_to_string(x, type, prec,
13110 (flags & F_ALT) ? Py_DTSF_ALT : 0, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013111 if (p == NULL)
13112 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013113 result = PyUnicode_DecodeASCII(p, strlen(p), NULL);
Eric Smith0923d1d2009-04-16 20:16:10 +000013114 PyMem_Free(p);
13115 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013116}
13117
Tim Peters38fd5b62000-09-21 05:43:11 +000013118static PyObject*
13119formatlong(PyObject *val, int flags, int prec, int type)
13120{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013121 char *buf;
13122 int len;
13123 PyObject *str; /* temporary string object. */
13124 PyObject *result;
Tim Peters38fd5b62000-09-21 05:43:11 +000013125
Benjamin Peterson14339b62009-01-31 16:36:08 +000013126 str = _PyBytes_FormatLong(val, flags, prec, type, &buf, &len);
13127 if (!str)
13128 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013129 result = PyUnicode_DecodeASCII(buf, len, NULL);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013130 Py_DECREF(str);
13131 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +000013132}
13133
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013134static Py_UCS4
13135formatchar(PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013136{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000013137 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000013138 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013139 if (PyUnicode_GET_LENGTH(v) == 1) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013140 return PyUnicode_READ_CHAR(v, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +000013141 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013142 goto onError;
13143 }
13144 else {
13145 /* Integer input truncated to a character */
13146 long x;
13147 x = PyLong_AsLong(v);
13148 if (x == -1 && PyErr_Occurred())
13149 goto onError;
13150
13151 if (x < 0 || x > 0x10ffff) {
13152 PyErr_SetString(PyExc_OverflowError,
13153 "%c arg not in range(0x110000)");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013154 return (Py_UCS4) -1;
Benjamin Peterson29060642009-01-31 22:14:21 +000013155 }
13156
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013157 return (Py_UCS4) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013158 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000013159
Benjamin Peterson29060642009-01-31 22:14:21 +000013160 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000013161 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013162 "%c requires int or char");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013163 return (Py_UCS4) -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013164}
13165
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013166static int
13167repeat_accumulate(_PyAccu *acc, PyObject *obj, Py_ssize_t count)
13168{
13169 int r;
13170 assert(count > 0);
13171 assert(PyUnicode_Check(obj));
13172 if (count > 5) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013173 PyObject *repeated = unicode_repeat(obj, count);
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013174 if (repeated == NULL)
13175 return -1;
13176 r = _PyAccu_Accumulate(acc, repeated);
13177 Py_DECREF(repeated);
13178 return r;
13179 }
13180 else {
13181 do {
13182 if (_PyAccu_Accumulate(acc, obj))
13183 return -1;
13184 } while (--count);
13185 return 0;
13186 }
13187}
13188
Alexander Belopolsky40018472011-02-26 01:02:56 +000013189PyObject *
13190PyUnicode_Format(PyObject *format, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013191{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013192 void *fmt;
13193 int fmtkind;
13194 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013195 int kind;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013196 int r;
13197 Py_ssize_t fmtcnt, fmtpos, arglen, argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013198 int args_owned = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013199 PyObject *dict = NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013200 PyObject *temp = NULL;
13201 PyObject *second = NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013202 PyObject *uformat;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013203 _PyAccu acc;
13204 static PyObject *plus, *minus, *blank, *zero, *percent;
13205
13206 if (!plus && !(plus = get_latin1_char('+')))
13207 return NULL;
13208 if (!minus && !(minus = get_latin1_char('-')))
13209 return NULL;
13210 if (!blank && !(blank = get_latin1_char(' ')))
13211 return NULL;
13212 if (!zero && !(zero = get_latin1_char('0')))
13213 return NULL;
13214 if (!percent && !(percent = get_latin1_char('%')))
13215 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000013216
Guido van Rossumd57fd912000-03-10 22:53:23 +000013217 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013218 PyErr_BadInternalCall();
13219 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013220 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013221 uformat = PyUnicode_FromObject(format);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013222 if (uformat == NULL || PyUnicode_READY(uformat) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000013223 return NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013224 if (_PyAccu_Init(&acc))
13225 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013226 fmt = PyUnicode_DATA(uformat);
13227 fmtkind = PyUnicode_KIND(uformat);
13228 fmtcnt = PyUnicode_GET_LENGTH(uformat);
13229 fmtpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013230
Guido van Rossumd57fd912000-03-10 22:53:23 +000013231 if (PyTuple_Check(args)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013232 arglen = PyTuple_Size(args);
13233 argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013234 }
13235 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013236 arglen = -1;
13237 argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013238 }
Christian Heimes90aa7642007-12-19 02:45:37 +000013239 if (Py_TYPE(args)->tp_as_mapping && !PyTuple_Check(args) &&
Christian Heimesf3863112007-11-22 07:46:41 +000013240 !PyUnicode_Check(args))
Benjamin Peterson29060642009-01-31 22:14:21 +000013241 dict = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013242
13243 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013244 if (PyUnicode_READ(fmtkind, fmt, fmtpos) != '%') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013245 PyObject *nonfmt;
13246 Py_ssize_t nonfmtpos;
13247 nonfmtpos = fmtpos++;
13248 while (fmtcnt >= 0 &&
13249 PyUnicode_READ(fmtkind, fmt, fmtpos) != '%') {
13250 fmtpos++;
13251 fmtcnt--;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013252 }
Victor Stinner7931d9a2011-11-04 00:22:48 +010013253 nonfmt = PyUnicode_Substring(uformat, nonfmtpos, fmtpos);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013254 if (nonfmt == NULL)
13255 goto onError;
13256 r = _PyAccu_Accumulate(&acc, nonfmt);
13257 Py_DECREF(nonfmt);
13258 if (r)
13259 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013260 }
13261 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013262 /* Got a format specifier */
13263 int flags = 0;
13264 Py_ssize_t width = -1;
13265 int prec = -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013266 Py_UCS4 c = '\0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013267 Py_UCS4 fill, sign;
Benjamin Peterson29060642009-01-31 22:14:21 +000013268 int isnumok;
13269 PyObject *v = NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013270 void *pbuf = NULL;
13271 Py_ssize_t pindex, len;
13272 PyObject *signobj = NULL, *fillobj = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013273
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013274 fmtpos++;
13275 if (PyUnicode_READ(fmtkind, fmt, fmtpos) == '(') {
13276 Py_ssize_t keystart;
Benjamin Peterson29060642009-01-31 22:14:21 +000013277 Py_ssize_t keylen;
13278 PyObject *key;
13279 int pcount = 1;
Christian Heimesa612dc02008-02-24 13:08:18 +000013280
Benjamin Peterson29060642009-01-31 22:14:21 +000013281 if (dict == NULL) {
13282 PyErr_SetString(PyExc_TypeError,
13283 "format requires a mapping");
13284 goto onError;
13285 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013286 ++fmtpos;
Benjamin Peterson29060642009-01-31 22:14:21 +000013287 --fmtcnt;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013288 keystart = fmtpos;
Benjamin Peterson29060642009-01-31 22:14:21 +000013289 /* Skip over balanced parentheses */
13290 while (pcount > 0 && --fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013291 if (PyUnicode_READ(fmtkind, fmt, fmtpos) == ')')
Benjamin Peterson29060642009-01-31 22:14:21 +000013292 --pcount;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013293 else if (PyUnicode_READ(fmtkind, fmt, fmtpos) == '(')
Benjamin Peterson29060642009-01-31 22:14:21 +000013294 ++pcount;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013295 fmtpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +000013296 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013297 keylen = fmtpos - keystart - 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000013298 if (fmtcnt < 0 || pcount > 0) {
13299 PyErr_SetString(PyExc_ValueError,
13300 "incomplete format key");
13301 goto onError;
13302 }
Victor Stinner7931d9a2011-11-04 00:22:48 +010013303 key = PyUnicode_Substring(uformat,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013304 keystart, keystart + keylen);
Benjamin Peterson29060642009-01-31 22:14:21 +000013305 if (key == NULL)
13306 goto onError;
13307 if (args_owned) {
13308 Py_DECREF(args);
13309 args_owned = 0;
13310 }
13311 args = PyObject_GetItem(dict, key);
13312 Py_DECREF(key);
13313 if (args == NULL) {
13314 goto onError;
13315 }
13316 args_owned = 1;
13317 arglen = -1;
13318 argidx = -2;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013319 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013320 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013321 switch (c = PyUnicode_READ(fmtkind, fmt, fmtpos++)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013322 case '-': flags |= F_LJUST; continue;
13323 case '+': flags |= F_SIGN; continue;
13324 case ' ': flags |= F_BLANK; continue;
13325 case '#': flags |= F_ALT; continue;
13326 case '0': flags |= F_ZERO; continue;
13327 }
13328 break;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013329 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013330 if (c == '*') {
13331 v = getnextarg(args, arglen, &argidx);
13332 if (v == NULL)
13333 goto onError;
13334 if (!PyLong_Check(v)) {
13335 PyErr_SetString(PyExc_TypeError,
13336 "* wants int");
13337 goto onError;
13338 }
13339 width = PyLong_AsLong(v);
13340 if (width == -1 && PyErr_Occurred())
13341 goto onError;
13342 if (width < 0) {
13343 flags |= F_LJUST;
13344 width = -width;
13345 }
13346 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013347 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013348 }
13349 else if (c >= '0' && c <= '9') {
13350 width = c - '0';
13351 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013352 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013353 if (c < '0' || c > '9')
13354 break;
13355 if ((width*10) / 10 != width) {
13356 PyErr_SetString(PyExc_ValueError,
13357 "width too big");
Benjamin Peterson14339b62009-01-31 16:36:08 +000013358 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +000013359 }
13360 width = width*10 + (c - '0');
13361 }
13362 }
13363 if (c == '.') {
13364 prec = 0;
13365 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013366 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013367 if (c == '*') {
13368 v = getnextarg(args, arglen, &argidx);
13369 if (v == NULL)
13370 goto onError;
13371 if (!PyLong_Check(v)) {
13372 PyErr_SetString(PyExc_TypeError,
13373 "* wants int");
13374 goto onError;
13375 }
13376 prec = PyLong_AsLong(v);
13377 if (prec == -1 && PyErr_Occurred())
13378 goto onError;
13379 if (prec < 0)
13380 prec = 0;
13381 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013382 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013383 }
13384 else if (c >= '0' && c <= '9') {
13385 prec = c - '0';
13386 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013387 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013388 if (c < '0' || c > '9')
13389 break;
13390 if ((prec*10) / 10 != prec) {
13391 PyErr_SetString(PyExc_ValueError,
13392 "prec too big");
13393 goto onError;
13394 }
13395 prec = prec*10 + (c - '0');
13396 }
13397 }
13398 } /* prec */
13399 if (fmtcnt >= 0) {
13400 if (c == 'h' || c == 'l' || c == 'L') {
13401 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013402 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013403 }
13404 }
13405 if (fmtcnt < 0) {
13406 PyErr_SetString(PyExc_ValueError,
13407 "incomplete format");
13408 goto onError;
13409 }
13410 if (c != '%') {
13411 v = getnextarg(args, arglen, &argidx);
13412 if (v == NULL)
13413 goto onError;
13414 }
13415 sign = 0;
13416 fill = ' ';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013417 fillobj = blank;
Benjamin Peterson29060642009-01-31 22:14:21 +000013418 switch (c) {
13419
13420 case '%':
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013421 _PyAccu_Accumulate(&acc, percent);
13422 continue;
Benjamin Peterson29060642009-01-31 22:14:21 +000013423
13424 case 's':
13425 case 'r':
13426 case 'a':
Victor Stinner808fc0a2010-03-22 12:50:40 +000013427 if (PyUnicode_CheckExact(v) && c == 's') {
Benjamin Peterson29060642009-01-31 22:14:21 +000013428 temp = v;
13429 Py_INCREF(temp);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013430 }
13431 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013432 if (c == 's')
13433 temp = PyObject_Str(v);
13434 else if (c == 'r')
13435 temp = PyObject_Repr(v);
13436 else
13437 temp = PyObject_ASCII(v);
13438 if (temp == NULL)
13439 goto onError;
13440 if (PyUnicode_Check(temp))
13441 /* nothing to do */;
13442 else {
13443 Py_DECREF(temp);
13444 PyErr_SetString(PyExc_TypeError,
13445 "%s argument has non-string str()");
13446 goto onError;
13447 }
13448 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013449 if (PyUnicode_READY(temp) == -1) {
13450 Py_CLEAR(temp);
13451 goto onError;
13452 }
13453 pbuf = PyUnicode_DATA(temp);
13454 kind = PyUnicode_KIND(temp);
13455 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013456 if (prec >= 0 && len > prec)
13457 len = prec;
13458 break;
13459
13460 case 'i':
13461 case 'd':
13462 case 'u':
13463 case 'o':
13464 case 'x':
13465 case 'X':
Benjamin Peterson29060642009-01-31 22:14:21 +000013466 isnumok = 0;
13467 if (PyNumber_Check(v)) {
13468 PyObject *iobj=NULL;
13469
13470 if (PyLong_Check(v)) {
13471 iobj = v;
13472 Py_INCREF(iobj);
13473 }
13474 else {
13475 iobj = PyNumber_Long(v);
13476 }
13477 if (iobj!=NULL) {
13478 if (PyLong_Check(iobj)) {
13479 isnumok = 1;
Senthil Kumaran9ebe08d2011-07-03 21:03:16 -070013480 temp = formatlong(iobj, flags, prec, (c == 'i'? 'd': c));
Benjamin Peterson29060642009-01-31 22:14:21 +000013481 Py_DECREF(iobj);
13482 if (!temp)
13483 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013484 if (PyUnicode_READY(temp) == -1) {
13485 Py_CLEAR(temp);
13486 goto onError;
13487 }
13488 pbuf = PyUnicode_DATA(temp);
13489 kind = PyUnicode_KIND(temp);
13490 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013491 sign = 1;
13492 }
13493 else {
13494 Py_DECREF(iobj);
13495 }
13496 }
13497 }
13498 if (!isnumok) {
13499 PyErr_Format(PyExc_TypeError,
13500 "%%%c format: a number is required, "
13501 "not %.200s", (char)c, Py_TYPE(v)->tp_name);
13502 goto onError;
13503 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013504 if (flags & F_ZERO) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013505 fill = '0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013506 fillobj = zero;
13507 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013508 break;
13509
13510 case 'e':
13511 case 'E':
13512 case 'f':
13513 case 'F':
13514 case 'g':
13515 case 'G':
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013516 temp = formatfloat(v, flags, prec, c);
13517 if (!temp)
Benjamin Peterson29060642009-01-31 22:14:21 +000013518 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013519 if (PyUnicode_READY(temp) == -1) {
13520 Py_CLEAR(temp);
13521 goto onError;
13522 }
13523 pbuf = PyUnicode_DATA(temp);
13524 kind = PyUnicode_KIND(temp);
13525 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013526 sign = 1;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013527 if (flags & F_ZERO) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013528 fill = '0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013529 fillobj = zero;
13530 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013531 break;
13532
13533 case 'c':
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013534 {
13535 Py_UCS4 ch = formatchar(v);
13536 if (ch == (Py_UCS4) -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000013537 goto onError;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013538 temp = _PyUnicode_FromUCS4(&ch, 1);
13539 if (temp == NULL)
13540 goto onError;
13541 pbuf = PyUnicode_DATA(temp);
13542 kind = PyUnicode_KIND(temp);
13543 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013544 break;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013545 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013546
13547 default:
13548 PyErr_Format(PyExc_ValueError,
13549 "unsupported format character '%c' (0x%x) "
13550 "at index %zd",
13551 (31<=c && c<=126) ? (char)c : '?',
13552 (int)c,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013553 fmtpos - 1);
Benjamin Peterson29060642009-01-31 22:14:21 +000013554 goto onError;
13555 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013556 /* pbuf is initialized here. */
13557 pindex = 0;
Benjamin Peterson29060642009-01-31 22:14:21 +000013558 if (sign) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013559 if (PyUnicode_READ(kind, pbuf, pindex) == '-') {
13560 signobj = minus;
Benjamin Peterson29060642009-01-31 22:14:21 +000013561 len--;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013562 pindex++;
13563 }
13564 else if (PyUnicode_READ(kind, pbuf, pindex) == '+') {
13565 signobj = plus;
13566 len--;
13567 pindex++;
Benjamin Peterson29060642009-01-31 22:14:21 +000013568 }
13569 else if (flags & F_SIGN)
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013570 signobj = plus;
Benjamin Peterson29060642009-01-31 22:14:21 +000013571 else if (flags & F_BLANK)
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013572 signobj = blank;
Benjamin Peterson29060642009-01-31 22:14:21 +000013573 else
13574 sign = 0;
13575 }
13576 if (width < len)
13577 width = len;
Benjamin Peterson29060642009-01-31 22:14:21 +000013578 if (sign) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013579 if (fill != ' ') {
13580 assert(signobj != NULL);
13581 if (_PyAccu_Accumulate(&acc, signobj))
13582 goto onError;
13583 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013584 if (width > len)
13585 width--;
13586 }
13587 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013588 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013589 assert(PyUnicode_READ(kind, pbuf, pindex + 1) == c);
Benjamin Peterson29060642009-01-31 22:14:21 +000013590 if (fill != ' ') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013591 second = get_latin1_char(
13592 PyUnicode_READ(kind, pbuf, pindex + 1));
13593 pindex += 2;
13594 if (second == NULL ||
13595 _PyAccu_Accumulate(&acc, zero) ||
13596 _PyAccu_Accumulate(&acc, second))
13597 goto onError;
13598 Py_CLEAR(second);
Benjamin Peterson29060642009-01-31 22:14:21 +000013599 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013600 width -= 2;
13601 if (width < 0)
13602 width = 0;
13603 len -= 2;
13604 }
13605 if (width > len && !(flags & F_LJUST)) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013606 assert(fillobj != NULL);
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013607 if (repeat_accumulate(&acc, fillobj, width - len))
13608 goto onError;
13609 width = len;
Benjamin Peterson29060642009-01-31 22:14:21 +000013610 }
13611 if (fill == ' ') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013612 if (sign) {
13613 assert(signobj != NULL);
13614 if (_PyAccu_Accumulate(&acc, signobj))
13615 goto onError;
13616 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013617 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013618 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
13619 assert(PyUnicode_READ(kind, pbuf, pindex+1) == c);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013620 second = get_latin1_char(
13621 PyUnicode_READ(kind, pbuf, pindex + 1));
13622 pindex += 2;
13623 if (second == NULL ||
13624 _PyAccu_Accumulate(&acc, zero) ||
13625 _PyAccu_Accumulate(&acc, second))
13626 goto onError;
13627 Py_CLEAR(second);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013628 }
13629 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013630 /* Copy all characters, preserving len */
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013631 if (temp != NULL) {
13632 assert(pbuf == PyUnicode_DATA(temp));
13633 v = PyUnicode_Substring(temp, pindex, pindex + len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013634 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013635 else {
13636 const char *p = (const char *) pbuf;
13637 assert(pbuf != NULL);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013638 p += kind * pindex;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013639 v = PyUnicode_FromKindAndData(kind, p, len);
13640 }
13641 if (v == NULL)
13642 goto onError;
13643 r = _PyAccu_Accumulate(&acc, v);
13644 Py_DECREF(v);
13645 if (r)
13646 goto onError;
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013647 if (width > len && repeat_accumulate(&acc, blank, width - len))
13648 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +000013649 if (dict && (argidx < arglen) && c != '%') {
13650 PyErr_SetString(PyExc_TypeError,
13651 "not all arguments converted during string formatting");
Benjamin Peterson29060642009-01-31 22:14:21 +000013652 goto onError;
13653 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013654 Py_CLEAR(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013655 } /* '%' */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013656 } /* until end */
13657 if (argidx < arglen && !dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013658 PyErr_SetString(PyExc_TypeError,
13659 "not all arguments converted during string formatting");
13660 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013661 }
13662
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013663 result = _PyAccu_Finish(&acc);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013664 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013665 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013666 }
13667 Py_DECREF(uformat);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013668 Py_XDECREF(temp);
13669 Py_XDECREF(second);
Victor Stinner7931d9a2011-11-04 00:22:48 +010013670 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013671
Benjamin Peterson29060642009-01-31 22:14:21 +000013672 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000013673 Py_DECREF(uformat);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013674 Py_XDECREF(temp);
13675 Py_XDECREF(second);
13676 _PyAccu_Destroy(&acc);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013677 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013678 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013679 }
13680 return NULL;
13681}
13682
Jeremy Hylton938ace62002-07-17 16:30:39 +000013683static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +000013684unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
13685
Tim Peters6d6c1a32001-08-02 04:15:00 +000013686static PyObject *
13687unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
13688{
Benjamin Peterson29060642009-01-31 22:14:21 +000013689 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013690 static char *kwlist[] = {"object", "encoding", "errors", 0};
13691 char *encoding = NULL;
13692 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000013693
Benjamin Peterson14339b62009-01-31 16:36:08 +000013694 if (type != &PyUnicode_Type)
13695 return unicode_subtype_new(type, args, kwds);
13696 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +000013697 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +000013698 return NULL;
13699 if (x == NULL)
Victor Stinner7931d9a2011-11-04 00:22:48 +010013700 return PyUnicode_New(0, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013701 if (encoding == NULL && errors == NULL)
13702 return PyObject_Str(x);
13703 else
Benjamin Peterson29060642009-01-31 22:14:21 +000013704 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +000013705}
13706
Guido van Rossume023fe02001-08-30 03:12:59 +000013707static PyObject *
13708unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
13709{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013710 PyObject *unicode, *self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013711 Py_ssize_t length, char_size;
13712 int share_wstr, share_utf8;
13713 unsigned int kind;
13714 void *data;
Guido van Rossume023fe02001-08-30 03:12:59 +000013715
Benjamin Peterson14339b62009-01-31 16:36:08 +000013716 assert(PyType_IsSubtype(type, &PyUnicode_Type));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013717
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013718 unicode = unicode_new(&PyUnicode_Type, args, kwds);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013719 if (unicode == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000013720 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020013721 assert(_PyUnicode_CHECK(unicode));
Victor Stinnere06e1452011-10-04 20:52:31 +020013722 if (PyUnicode_READY(unicode))
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013723 return NULL;
13724
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013725 self = type->tp_alloc(type, 0);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013726 if (self == NULL) {
13727 Py_DECREF(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013728 return NULL;
13729 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013730 kind = PyUnicode_KIND(unicode);
13731 length = PyUnicode_GET_LENGTH(unicode);
13732
13733 _PyUnicode_LENGTH(self) = length;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020013734#ifdef Py_DEBUG
13735 _PyUnicode_HASH(self) = -1;
13736#else
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013737 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020013738#endif
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013739 _PyUnicode_STATE(self).interned = 0;
13740 _PyUnicode_STATE(self).kind = kind;
13741 _PyUnicode_STATE(self).compact = 0;
Victor Stinner3cf46372011-10-03 14:42:15 +020013742 _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013743 _PyUnicode_STATE(self).ready = 1;
13744 _PyUnicode_WSTR(self) = NULL;
13745 _PyUnicode_UTF8_LENGTH(self) = 0;
13746 _PyUnicode_UTF8(self) = NULL;
13747 _PyUnicode_WSTR_LENGTH(self) = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +020013748 _PyUnicode_DATA_ANY(self) = NULL;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013749
13750 share_utf8 = 0;
13751 share_wstr = 0;
13752 if (kind == PyUnicode_1BYTE_KIND) {
13753 char_size = 1;
13754 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
13755 share_utf8 = 1;
13756 }
13757 else if (kind == PyUnicode_2BYTE_KIND) {
13758 char_size = 2;
13759 if (sizeof(wchar_t) == 2)
13760 share_wstr = 1;
13761 }
13762 else {
13763 assert(kind == PyUnicode_4BYTE_KIND);
13764 char_size = 4;
13765 if (sizeof(wchar_t) == 4)
13766 share_wstr = 1;
13767 }
13768
13769 /* Ensure we won't overflow the length. */
13770 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
13771 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013772 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013773 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013774 data = PyObject_MALLOC((length + 1) * char_size);
13775 if (data == NULL) {
13776 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013777 goto onError;
13778 }
13779
Victor Stinnerc3c74152011-10-02 20:39:55 +020013780 _PyUnicode_DATA_ANY(self) = data;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013781 if (share_utf8) {
13782 _PyUnicode_UTF8_LENGTH(self) = length;
13783 _PyUnicode_UTF8(self) = data;
13784 }
13785 if (share_wstr) {
13786 _PyUnicode_WSTR_LENGTH(self) = length;
13787 _PyUnicode_WSTR(self) = (wchar_t *)data;
13788 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013789
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013790 Py_MEMCPY(data, PyUnicode_DATA(unicode),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013791 kind * (length + 1));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013792 assert(_PyUnicode_CheckConsistency(self, 1));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020013793#ifdef Py_DEBUG
13794 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
13795#endif
Victor Stinnerdd18d3a2011-10-22 11:08:10 +020013796 Py_DECREF(unicode);
Victor Stinner7931d9a2011-11-04 00:22:48 +010013797 return self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013798
13799onError:
13800 Py_DECREF(unicode);
13801 Py_DECREF(self);
13802 return NULL;
Guido van Rossume023fe02001-08-30 03:12:59 +000013803}
13804
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013805PyDoc_STRVAR(unicode_doc,
Benjamin Peterson29060642009-01-31 22:14:21 +000013806 "str(string[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +000013807\n\
Collin Winterd474ce82007-08-07 19:42:11 +000013808Create a new string object from the given encoded string.\n\
Skip Montanaro35b37a52002-07-26 16:22:46 +000013809encoding defaults to the current default string encoding.\n\
13810errors can be 'strict', 'replace' or 'ignore' and defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +000013811
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013812static PyObject *unicode_iter(PyObject *seq);
13813
Guido van Rossumd57fd912000-03-10 22:53:23 +000013814PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000013815 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Benjamin Peterson14339b62009-01-31 16:36:08 +000013816 "str", /* tp_name */
13817 sizeof(PyUnicodeObject), /* tp_size */
13818 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013819 /* Slots */
Benjamin Peterson14339b62009-01-31 16:36:08 +000013820 (destructor)unicode_dealloc, /* tp_dealloc */
13821 0, /* tp_print */
13822 0, /* tp_getattr */
13823 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000013824 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000013825 unicode_repr, /* tp_repr */
13826 &unicode_as_number, /* tp_as_number */
13827 &unicode_as_sequence, /* tp_as_sequence */
13828 &unicode_as_mapping, /* tp_as_mapping */
13829 (hashfunc) unicode_hash, /* tp_hash*/
13830 0, /* tp_call*/
13831 (reprfunc) unicode_str, /* tp_str */
13832 PyObject_GenericGetAttr, /* tp_getattro */
13833 0, /* tp_setattro */
13834 0, /* tp_as_buffer */
13835 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Benjamin Peterson29060642009-01-31 22:14:21 +000013836 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
Benjamin Peterson14339b62009-01-31 16:36:08 +000013837 unicode_doc, /* tp_doc */
13838 0, /* tp_traverse */
13839 0, /* tp_clear */
13840 PyUnicode_RichCompare, /* tp_richcompare */
13841 0, /* tp_weaklistoffset */
13842 unicode_iter, /* tp_iter */
13843 0, /* tp_iternext */
13844 unicode_methods, /* tp_methods */
13845 0, /* tp_members */
13846 0, /* tp_getset */
13847 &PyBaseObject_Type, /* tp_base */
13848 0, /* tp_dict */
13849 0, /* tp_descr_get */
13850 0, /* tp_descr_set */
13851 0, /* tp_dictoffset */
13852 0, /* tp_init */
13853 0, /* tp_alloc */
13854 unicode_new, /* tp_new */
13855 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013856};
13857
13858/* Initialize the Unicode implementation */
13859
Victor Stinner3a50e702011-10-18 21:21:00 +020013860int _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013861{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013862 int i;
13863
Thomas Wouters477c8d52006-05-27 19:21:47 +000013864 /* XXX - move this array to unicodectype.c ? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013865 Py_UCS2 linebreak[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +000013866 0x000A, /* LINE FEED */
13867 0x000D, /* CARRIAGE RETURN */
13868 0x001C, /* FILE SEPARATOR */
13869 0x001D, /* GROUP SEPARATOR */
13870 0x001E, /* RECORD SEPARATOR */
13871 0x0085, /* NEXT LINE */
13872 0x2028, /* LINE SEPARATOR */
13873 0x2029, /* PARAGRAPH SEPARATOR */
13874 };
13875
Fred Drakee4315f52000-05-09 19:53:39 +000013876 /* Init the implementation */
Victor Stinnera464fc12011-10-02 20:39:30 +020013877 unicode_empty = PyUnicode_New(0, 0);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013878 assert(_PyUnicode_CheckConsistency(unicode_empty, 1));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013879 if (!unicode_empty)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013880 Py_FatalError("Can't create empty string");
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013881
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013882 for (i = 0; i < 256; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +000013883 unicode_latin1[i] = NULL;
Guido van Rossumcacfc072002-05-24 19:01:59 +000013884 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000013885 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +000013886
13887 /* initialize the linebreak bloom filter */
13888 bloom_linebreak = make_bloom_mask(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013889 PyUnicode_2BYTE_KIND, linebreak,
Victor Stinner63941882011-09-29 00:42:28 +020013890 Py_ARRAY_LENGTH(linebreak));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013891
13892 PyType_Ready(&EncodingMapType);
Victor Stinner3a50e702011-10-18 21:21:00 +020013893
13894#ifdef HAVE_MBCS
13895 winver.dwOSVersionInfoSize = sizeof(winver);
13896 if (!GetVersionEx((OSVERSIONINFO*)&winver)) {
13897 PyErr_SetFromWindowsErr(0);
13898 return -1;
13899 }
13900#endif
13901 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013902}
13903
13904/* Finalize the Unicode implementation */
13905
Christian Heimesa156e092008-02-16 07:38:31 +000013906int
13907PyUnicode_ClearFreeList(void)
13908{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013909 return 0;
Christian Heimesa156e092008-02-16 07:38:31 +000013910}
13911
Guido van Rossumd57fd912000-03-10 22:53:23 +000013912void
Thomas Wouters78890102000-07-22 19:25:51 +000013913_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013914{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013915 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013916
Guido van Rossum4ae8ef82000-10-03 18:09:04 +000013917 Py_XDECREF(unicode_empty);
13918 unicode_empty = NULL;
Barry Warsaw5b4c2282000-10-03 20:45:26 +000013919
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013920 for (i = 0; i < 256; i++) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013921 if (unicode_latin1[i]) {
13922 Py_DECREF(unicode_latin1[i]);
13923 unicode_latin1[i] = NULL;
13924 }
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013925 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020013926 _PyUnicode_ClearStaticStrings();
Christian Heimesa156e092008-02-16 07:38:31 +000013927 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +000013928}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000013929
Walter Dörwald16807132007-05-25 13:52:07 +000013930void
13931PyUnicode_InternInPlace(PyObject **p)
13932{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013933 register PyObject *s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013934 PyObject *t;
Victor Stinner4fae54c2011-10-03 02:01:52 +020013935#ifdef Py_DEBUG
13936 assert(s != NULL);
13937 assert(_PyUnicode_CHECK(s));
13938#else
Benjamin Peterson14339b62009-01-31 16:36:08 +000013939 if (s == NULL || !PyUnicode_Check(s))
Victor Stinner4fae54c2011-10-03 02:01:52 +020013940 return;
13941#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000013942 /* If it's a subclass, we don't really know what putting
13943 it in the interned dict might do. */
13944 if (!PyUnicode_CheckExact(s))
13945 return;
13946 if (PyUnicode_CHECK_INTERNED(s))
13947 return;
Victor Stinner1b4f9ce2011-10-03 13:28:14 +020013948 if (_PyUnicode_READY_REPLACE(p)) {
Victor Stinner6b56a7f2011-10-04 20:04:52 +020013949 assert(0 && "_PyUnicode_READY_REPLACE fail in PyUnicode_InternInPlace");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013950 return;
13951 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013952 s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013953 if (interned == NULL) {
13954 interned = PyDict_New();
13955 if (interned == NULL) {
13956 PyErr_Clear(); /* Don't leave an exception */
13957 return;
13958 }
13959 }
13960 /* It might be that the GetItem call fails even
13961 though the key is present in the dictionary,
13962 namely when this happens during a stack overflow. */
13963 Py_ALLOW_RECURSION
Victor Stinner7931d9a2011-11-04 00:22:48 +010013964 t = PyDict_GetItem(interned, s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013965 Py_END_ALLOW_RECURSION
Martin v. Löwis5b222132007-06-10 09:51:05 +000013966
Benjamin Peterson29060642009-01-31 22:14:21 +000013967 if (t) {
13968 Py_INCREF(t);
13969 Py_DECREF(*p);
13970 *p = t;
13971 return;
13972 }
Walter Dörwald16807132007-05-25 13:52:07 +000013973
Benjamin Peterson14339b62009-01-31 16:36:08 +000013974 PyThreadState_GET()->recursion_critical = 1;
Victor Stinner7931d9a2011-11-04 00:22:48 +010013975 if (PyDict_SetItem(interned, s, s) < 0) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013976 PyErr_Clear();
13977 PyThreadState_GET()->recursion_critical = 0;
13978 return;
13979 }
13980 PyThreadState_GET()->recursion_critical = 0;
13981 /* The two references in interned are not counted by refcnt.
13982 The deallocator will take care of this */
13983 Py_REFCNT(s) -= 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013984 _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000013985}
13986
13987void
13988PyUnicode_InternImmortal(PyObject **p)
13989{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013990 PyUnicode_InternInPlace(p);
13991 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
Victor Stinneraf9e4b82011-10-23 20:07:00 +020013992 _PyUnicode_STATE(*p).interned = SSTATE_INTERNED_IMMORTAL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013993 Py_INCREF(*p);
13994 }
Walter Dörwald16807132007-05-25 13:52:07 +000013995}
13996
13997PyObject *
13998PyUnicode_InternFromString(const char *cp)
13999{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014000 PyObject *s = PyUnicode_FromString(cp);
14001 if (s == NULL)
14002 return NULL;
14003 PyUnicode_InternInPlace(&s);
14004 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000014005}
14006
Alexander Belopolsky40018472011-02-26 01:02:56 +000014007void
14008_Py_ReleaseInternedUnicodeStrings(void)
Walter Dörwald16807132007-05-25 13:52:07 +000014009{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014010 PyObject *keys;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014011 PyObject *s;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014012 Py_ssize_t i, n;
14013 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000014014
Benjamin Peterson14339b62009-01-31 16:36:08 +000014015 if (interned == NULL || !PyDict_Check(interned))
14016 return;
14017 keys = PyDict_Keys(interned);
14018 if (keys == NULL || !PyList_Check(keys)) {
14019 PyErr_Clear();
14020 return;
14021 }
Walter Dörwald16807132007-05-25 13:52:07 +000014022
Benjamin Peterson14339b62009-01-31 16:36:08 +000014023 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
14024 detector, interned unicode strings are not forcibly deallocated;
14025 rather, we give them their stolen references back, and then clear
14026 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000014027
Benjamin Peterson14339b62009-01-31 16:36:08 +000014028 n = PyList_GET_SIZE(keys);
14029 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000014030 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014031 for (i = 0; i < n; i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014032 s = PyList_GET_ITEM(keys, i);
Victor Stinner6b56a7f2011-10-04 20:04:52 +020014033 if (PyUnicode_READY(s) == -1) {
14034 assert(0 && "could not ready string");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014035 fprintf(stderr, "could not ready string\n");
Victor Stinner6b56a7f2011-10-04 20:04:52 +020014036 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014037 switch (PyUnicode_CHECK_INTERNED(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014038 case SSTATE_NOT_INTERNED:
14039 /* XXX Shouldn't happen */
14040 break;
14041 case SSTATE_INTERNED_IMMORTAL:
14042 Py_REFCNT(s) += 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014043 immortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014044 break;
14045 case SSTATE_INTERNED_MORTAL:
14046 Py_REFCNT(s) += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014047 mortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014048 break;
14049 default:
14050 Py_FatalError("Inconsistent interned string state.");
14051 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014052 _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014053 }
14054 fprintf(stderr, "total size of all interned strings: "
14055 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
14056 "mortal/immortal\n", mortal_size, immortal_size);
14057 Py_DECREF(keys);
14058 PyDict_Clear(interned);
14059 Py_DECREF(interned);
14060 interned = NULL;
Walter Dörwald16807132007-05-25 13:52:07 +000014061}
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014062
14063
14064/********************* Unicode Iterator **************************/
14065
14066typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014067 PyObject_HEAD
14068 Py_ssize_t it_index;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014069 PyObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014070} unicodeiterobject;
14071
14072static void
14073unicodeiter_dealloc(unicodeiterobject *it)
14074{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014075 _PyObject_GC_UNTRACK(it);
14076 Py_XDECREF(it->it_seq);
14077 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014078}
14079
14080static int
14081unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
14082{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014083 Py_VISIT(it->it_seq);
14084 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014085}
14086
14087static PyObject *
14088unicodeiter_next(unicodeiterobject *it)
14089{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014090 PyObject *seq, *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014091
Benjamin Peterson14339b62009-01-31 16:36:08 +000014092 assert(it != NULL);
14093 seq = it->it_seq;
14094 if (seq == NULL)
14095 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020014096 assert(_PyUnicode_CHECK(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014097
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014098 if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
14099 int kind = PyUnicode_KIND(seq);
14100 void *data = PyUnicode_DATA(seq);
14101 Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
14102 item = PyUnicode_FromOrdinal(chr);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014103 if (item != NULL)
14104 ++it->it_index;
14105 return item;
14106 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014107
Benjamin Peterson14339b62009-01-31 16:36:08 +000014108 Py_DECREF(seq);
14109 it->it_seq = NULL;
14110 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014111}
14112
14113static PyObject *
14114unicodeiter_len(unicodeiterobject *it)
14115{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014116 Py_ssize_t len = 0;
14117 if (it->it_seq)
Victor Stinnerc4f281e2011-10-11 22:11:42 +020014118 len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014119 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014120}
14121
14122PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
14123
14124static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014125 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000014126 length_hint_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000014127 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014128};
14129
14130PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014131 PyVarObject_HEAD_INIT(&PyType_Type, 0)
14132 "str_iterator", /* tp_name */
14133 sizeof(unicodeiterobject), /* tp_basicsize */
14134 0, /* tp_itemsize */
14135 /* methods */
14136 (destructor)unicodeiter_dealloc, /* tp_dealloc */
14137 0, /* tp_print */
14138 0, /* tp_getattr */
14139 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000014140 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014141 0, /* tp_repr */
14142 0, /* tp_as_number */
14143 0, /* tp_as_sequence */
14144 0, /* tp_as_mapping */
14145 0, /* tp_hash */
14146 0, /* tp_call */
14147 0, /* tp_str */
14148 PyObject_GenericGetAttr, /* tp_getattro */
14149 0, /* tp_setattro */
14150 0, /* tp_as_buffer */
14151 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
14152 0, /* tp_doc */
14153 (traverseproc)unicodeiter_traverse, /* tp_traverse */
14154 0, /* tp_clear */
14155 0, /* tp_richcompare */
14156 0, /* tp_weaklistoffset */
14157 PyObject_SelfIter, /* tp_iter */
14158 (iternextfunc)unicodeiter_next, /* tp_iternext */
14159 unicodeiter_methods, /* tp_methods */
14160 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014161};
14162
14163static PyObject *
14164unicode_iter(PyObject *seq)
14165{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014166 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014167
Benjamin Peterson14339b62009-01-31 16:36:08 +000014168 if (!PyUnicode_Check(seq)) {
14169 PyErr_BadInternalCall();
14170 return NULL;
14171 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014172 if (PyUnicode_READY(seq) == -1)
14173 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014174 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
14175 if (it == NULL)
14176 return NULL;
14177 it->it_index = 0;
14178 Py_INCREF(seq);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014179 it->it_seq = seq;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014180 _PyObject_GC_TRACK(it);
14181 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014182}
14183
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010014184
14185size_t
14186Py_UNICODE_strlen(const Py_UNICODE *u)
14187{
14188 int res = 0;
14189 while(*u++)
14190 res++;
14191 return res;
14192}
14193
14194Py_UNICODE*
14195Py_UNICODE_strcpy(Py_UNICODE *s1, const Py_UNICODE *s2)
14196{
14197 Py_UNICODE *u = s1;
14198 while ((*u++ = *s2++));
14199 return s1;
14200}
14201
14202Py_UNICODE*
14203Py_UNICODE_strncpy(Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
14204{
14205 Py_UNICODE *u = s1;
14206 while ((*u++ = *s2++))
14207 if (n-- == 0)
14208 break;
14209 return s1;
14210}
14211
14212Py_UNICODE*
14213Py_UNICODE_strcat(Py_UNICODE *s1, const Py_UNICODE *s2)
14214{
14215 Py_UNICODE *u1 = s1;
14216 u1 += Py_UNICODE_strlen(u1);
14217 Py_UNICODE_strcpy(u1, s2);
14218 return s1;
14219}
14220
14221int
14222Py_UNICODE_strcmp(const Py_UNICODE *s1, const Py_UNICODE *s2)
14223{
14224 while (*s1 && *s2 && *s1 == *s2)
14225 s1++, s2++;
14226 if (*s1 && *s2)
14227 return (*s1 < *s2) ? -1 : +1;
14228 if (*s1)
14229 return 1;
14230 if (*s2)
14231 return -1;
14232 return 0;
14233}
14234
14235int
14236Py_UNICODE_strncmp(const Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
14237{
14238 register Py_UNICODE u1, u2;
14239 for (; n != 0; n--) {
14240 u1 = *s1;
14241 u2 = *s2;
14242 if (u1 != u2)
14243 return (u1 < u2) ? -1 : +1;
14244 if (u1 == '\0')
14245 return 0;
14246 s1++;
14247 s2++;
14248 }
14249 return 0;
14250}
14251
14252Py_UNICODE*
14253Py_UNICODE_strchr(const Py_UNICODE *s, Py_UNICODE c)
14254{
14255 const Py_UNICODE *p;
14256 for (p = s; *p; p++)
14257 if (*p == c)
14258 return (Py_UNICODE*)p;
14259 return NULL;
14260}
14261
14262Py_UNICODE*
14263Py_UNICODE_strrchr(const Py_UNICODE *s, Py_UNICODE c)
14264{
14265 const Py_UNICODE *p;
14266 p = s + Py_UNICODE_strlen(s);
14267 while (p != s) {
14268 p--;
14269 if (*p == c)
14270 return (Py_UNICODE*)p;
14271 }
14272 return NULL;
14273}
Victor Stinner331ea922010-08-10 16:37:20 +000014274
Victor Stinner71133ff2010-09-01 23:43:53 +000014275Py_UNICODE*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014276PyUnicode_AsUnicodeCopy(PyObject *unicode)
Victor Stinner71133ff2010-09-01 23:43:53 +000014277{
Victor Stinner577db2c2011-10-11 22:12:48 +020014278 Py_UNICODE *u, *copy;
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014279 Py_ssize_t len, size;
Victor Stinner71133ff2010-09-01 23:43:53 +000014280
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014281 if (!PyUnicode_Check(unicode)) {
14282 PyErr_BadArgument();
14283 return NULL;
14284 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014285 u = PyUnicode_AsUnicodeAndSize(unicode, &len);
Victor Stinner577db2c2011-10-11 22:12:48 +020014286 if (u == NULL)
14287 return NULL;
Victor Stinner71133ff2010-09-01 23:43:53 +000014288 /* Ensure we won't overflow the size. */
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014289 if (len > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
Victor Stinner71133ff2010-09-01 23:43:53 +000014290 PyErr_NoMemory();
14291 return NULL;
14292 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014293 size = len + 1; /* copy the null character */
Victor Stinner71133ff2010-09-01 23:43:53 +000014294 size *= sizeof(Py_UNICODE);
14295 copy = PyMem_Malloc(size);
14296 if (copy == NULL) {
14297 PyErr_NoMemory();
14298 return NULL;
14299 }
Victor Stinner577db2c2011-10-11 22:12:48 +020014300 memcpy(copy, u, size);
Victor Stinner71133ff2010-09-01 23:43:53 +000014301 return copy;
14302}
Martin v. Löwis5b222132007-06-10 09:51:05 +000014303
Georg Brandl66c221e2010-10-14 07:04:07 +000014304/* A _string module, to export formatter_parser and formatter_field_name_split
14305 to the string.Formatter class implemented in Python. */
14306
14307static PyMethodDef _string_methods[] = {
14308 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
14309 METH_O, PyDoc_STR("split the argument as a field name")},
14310 {"formatter_parser", (PyCFunction) formatter_parser,
14311 METH_O, PyDoc_STR("parse the argument as a format string")},
14312 {NULL, NULL}
14313};
14314
14315static struct PyModuleDef _string_module = {
14316 PyModuleDef_HEAD_INIT,
14317 "_string",
14318 PyDoc_STR("string helper module"),
14319 0,
14320 _string_methods,
14321 NULL,
14322 NULL,
14323 NULL,
14324 NULL
14325};
14326
14327PyMODINIT_FUNC
14328PyInit__string(void)
14329{
14330 return PyModule_Create(&_string_module);
14331}
14332
14333
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000014334#ifdef __cplusplus
14335}
14336#endif