blob: 6307a983e51ad3f7d2ecaea27dc65937448eeda3 [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 }
Victor Stinnerda29cc32011-11-21 14:31:41 +0100394 if (maxchar > 0x10FFFF) {
395 printf("Invalid Unicode string! {");
396 for (i=0; i < ascii->length; i++)
397 {
398 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
399 if (i)
400 printf(", U+%04x", ch);
401 else
402 printf("U+%04x", ch);
403 }
404 printf("} (len=%u)\n", ascii->length);
405 abort();
406 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200407 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinner77faf692011-11-20 18:56:05 +0100408 if (ascii->state.ascii == 0) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200409 assert(maxchar >= 128);
Victor Stinner77faf692011-11-20 18:56:05 +0100410 assert(maxchar <= 255);
411 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200412 else
413 assert(maxchar < 128);
414 }
Victor Stinner77faf692011-11-20 18:56:05 +0100415 else if (kind == PyUnicode_2BYTE_KIND) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200416 assert(maxchar >= 0x100);
Victor Stinner77faf692011-11-20 18:56:05 +0100417 assert(maxchar <= 0xFFFF);
418 }
419 else {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200420 assert(maxchar >= 0x10000);
Victor Stinner77faf692011-11-20 18:56:05 +0100421 assert(maxchar <= 0x10FFFF);
422 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200423 }
Benjamin Petersonccc51c12011-10-03 19:34:12 -0400424 return 1;
425}
Victor Stinner910337b2011-10-03 03:20:16 +0200426#endif
427
Victor Stinner3a50e702011-10-18 21:21:00 +0200428#ifdef HAVE_MBCS
429static OSVERSIONINFOEX winver;
430#endif
431
Thomas Wouters477c8d52006-05-27 19:21:47 +0000432/* --- Bloom Filters ----------------------------------------------------- */
433
434/* stuff to implement simple "bloom filters" for Unicode characters.
435 to keep things simple, we use a single bitmask, using the least 5
436 bits from each unicode characters as the bit index. */
437
438/* the linebreak mask is set up by Unicode_Init below */
439
Antoine Pitrouf068f942010-01-13 14:19:12 +0000440#if LONG_BIT >= 128
441#define BLOOM_WIDTH 128
442#elif LONG_BIT >= 64
443#define BLOOM_WIDTH 64
444#elif LONG_BIT >= 32
445#define BLOOM_WIDTH 32
446#else
447#error "LONG_BIT is smaller than 32"
448#endif
449
Thomas Wouters477c8d52006-05-27 19:21:47 +0000450#define BLOOM_MASK unsigned long
451
452static BLOOM_MASK bloom_linebreak;
453
Antoine Pitrouf068f942010-01-13 14:19:12 +0000454#define BLOOM_ADD(mask, ch) ((mask |= (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
455#define BLOOM(mask, ch) ((mask & (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000456
Benjamin Peterson29060642009-01-31 22:14:21 +0000457#define BLOOM_LINEBREAK(ch) \
458 ((ch) < 128U ? ascii_linebreak[(ch)] : \
459 (BLOOM(bloom_linebreak, (ch)) && Py_UNICODE_ISLINEBREAK(ch)))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000460
Alexander Belopolsky40018472011-02-26 01:02:56 +0000461Py_LOCAL_INLINE(BLOOM_MASK)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200462make_bloom_mask(int kind, void* ptr, Py_ssize_t len)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000463{
464 /* calculate simple bloom-style bitmask for a given unicode string */
465
Antoine Pitrouf068f942010-01-13 14:19:12 +0000466 BLOOM_MASK mask;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000467 Py_ssize_t i;
468
469 mask = 0;
470 for (i = 0; i < len; i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200471 BLOOM_ADD(mask, PyUnicode_READ(kind, ptr, i));
Thomas Wouters477c8d52006-05-27 19:21:47 +0000472
473 return mask;
474}
475
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200476#define BLOOM_MEMBER(mask, chr, str) \
477 (BLOOM(mask, chr) \
478 && (PyUnicode_FindChar(str, chr, 0, PyUnicode_GET_LENGTH(str), 1) >= 0))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000479
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200480/* Compilation of templated routines */
481
482#include "stringlib/asciilib.h"
483#include "stringlib/fastsearch.h"
484#include "stringlib/partition.h"
485#include "stringlib/split.h"
486#include "stringlib/count.h"
487#include "stringlib/find.h"
488#include "stringlib/find_max_char.h"
489#include "stringlib/localeutil.h"
490#include "stringlib/undef.h"
491
492#include "stringlib/ucs1lib.h"
493#include "stringlib/fastsearch.h"
494#include "stringlib/partition.h"
495#include "stringlib/split.h"
496#include "stringlib/count.h"
497#include "stringlib/find.h"
498#include "stringlib/find_max_char.h"
499#include "stringlib/localeutil.h"
500#include "stringlib/undef.h"
501
502#include "stringlib/ucs2lib.h"
503#include "stringlib/fastsearch.h"
504#include "stringlib/partition.h"
505#include "stringlib/split.h"
506#include "stringlib/count.h"
507#include "stringlib/find.h"
508#include "stringlib/find_max_char.h"
509#include "stringlib/localeutil.h"
510#include "stringlib/undef.h"
511
512#include "stringlib/ucs4lib.h"
513#include "stringlib/fastsearch.h"
514#include "stringlib/partition.h"
515#include "stringlib/split.h"
516#include "stringlib/count.h"
517#include "stringlib/find.h"
518#include "stringlib/find_max_char.h"
519#include "stringlib/localeutil.h"
520#include "stringlib/undef.h"
521
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200522#include "stringlib/unicodedefs.h"
523#include "stringlib/fastsearch.h"
524#include "stringlib/count.h"
525#include "stringlib/find.h"
526
Guido van Rossumd57fd912000-03-10 22:53:23 +0000527/* --- Unicode Object ----------------------------------------------------- */
528
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200529static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +0200530fixup(PyObject *self, Py_UCS4 (*fixfct)(PyObject *s));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200531
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200532Py_LOCAL_INLINE(Py_ssize_t) findchar(void *s, int kind,
533 Py_ssize_t size, Py_UCS4 ch,
534 int direction)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200535{
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200536 int mode = (direction == 1) ? FAST_SEARCH : FAST_RSEARCH;
537
538 switch (kind) {
539 case PyUnicode_1BYTE_KIND:
540 {
541 Py_UCS1 ch1 = (Py_UCS1) ch;
542 if (ch1 == ch)
543 return ucs1lib_fastsearch((Py_UCS1 *) s, size, &ch1, 1, 0, mode);
544 else
545 return -1;
546 }
547 case PyUnicode_2BYTE_KIND:
548 {
549 Py_UCS2 ch2 = (Py_UCS2) ch;
550 if (ch2 == ch)
551 return ucs2lib_fastsearch((Py_UCS2 *) s, size, &ch2, 1, 0, mode);
552 else
553 return -1;
554 }
555 case PyUnicode_4BYTE_KIND:
556 return ucs4lib_fastsearch((Py_UCS4 *) s, size, &ch, 1, 0, mode);
557 default:
558 assert(0);
559 return -1;
Victor Stinner9e7a1bc2011-10-13 00:18:12 +0200560 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200561}
562
Victor Stinnerfe226c02011-10-03 03:52:20 +0200563static PyObject*
564resize_compact(PyObject *unicode, Py_ssize_t length)
565{
566 Py_ssize_t char_size;
567 Py_ssize_t struct_size;
568 Py_ssize_t new_size;
569 int share_wstr;
570
571 assert(PyUnicode_IS_READY(unicode));
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200572 char_size = PyUnicode_KIND(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200573 if (PyUnicode_IS_COMPACT_ASCII(unicode))
574 struct_size = sizeof(PyASCIIObject);
575 else
576 struct_size = sizeof(PyCompactUnicodeObject);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200577 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200578
579 _Py_DEC_REFTOTAL;
580 _Py_ForgetReference(unicode);
581
582 if (length > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1)) {
583 PyErr_NoMemory();
584 return NULL;
585 }
586 new_size = (struct_size + (length + 1) * char_size);
587
588 unicode = (PyObject *)PyObject_REALLOC((char *)unicode, new_size);
589 if (unicode == NULL) {
590 PyObject_Del(unicode);
591 PyErr_NoMemory();
592 return NULL;
593 }
594 _Py_NewReference(unicode);
595 _PyUnicode_LENGTH(unicode) = length;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200596 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200597 _PyUnicode_WSTR(unicode) = PyUnicode_DATA(unicode);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200598 if (!PyUnicode_IS_COMPACT_ASCII(unicode))
599 _PyUnicode_WSTR_LENGTH(unicode) = length;
600 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200601 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
602 length, 0);
603 return unicode;
604}
605
Alexander Belopolsky40018472011-02-26 01:02:56 +0000606static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200607resize_inplace(PyObject *unicode, Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000608{
Victor Stinner95663112011-10-04 01:03:50 +0200609 wchar_t *wstr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200610 assert(!PyUnicode_IS_COMPACT(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200611 assert(Py_REFCNT(unicode) == 1);
Tim Petersced69f82003-09-16 20:30:58 +0000612
Victor Stinner95663112011-10-04 01:03:50 +0200613 _PyUnicode_DIRTY(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200614
615 if (PyUnicode_IS_READY(unicode)) {
616 Py_ssize_t char_size;
617 Py_ssize_t new_size;
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200618 int share_wstr, share_utf8;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200619 void *data;
620
621 data = _PyUnicode_DATA_ANY(unicode);
622 assert(data != NULL);
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200623 char_size = PyUnicode_KIND(unicode);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200624 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
625 share_utf8 = _PyUnicode_SHARE_UTF8(unicode);
Victor Stinner95663112011-10-04 01:03:50 +0200626 if (!share_utf8 && _PyUnicode_HAS_UTF8_MEMORY(unicode))
627 {
628 PyObject_DEL(_PyUnicode_UTF8(unicode));
629 _PyUnicode_UTF8(unicode) = NULL;
630 _PyUnicode_UTF8_LENGTH(unicode) = 0;
631 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200632
633 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
634 PyErr_NoMemory();
635 return -1;
636 }
637 new_size = (length + 1) * char_size;
638
639 data = (PyObject *)PyObject_REALLOC(data, new_size);
640 if (data == NULL) {
641 PyErr_NoMemory();
642 return -1;
643 }
644 _PyUnicode_DATA_ANY(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200645 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200646 _PyUnicode_WSTR(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200647 _PyUnicode_WSTR_LENGTH(unicode) = length;
648 }
649 if (share_utf8) {
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200650 _PyUnicode_UTF8(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200651 _PyUnicode_UTF8_LENGTH(unicode) = length;
652 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200653 _PyUnicode_LENGTH(unicode) = length;
654 PyUnicode_WRITE(PyUnicode_KIND(unicode), data, length, 0);
Victor Stinner95663112011-10-04 01:03:50 +0200655 if (share_wstr || _PyUnicode_WSTR(unicode) == NULL) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200656 assert(_PyUnicode_CheckConsistency(unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200657 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200658 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200659 }
Victor Stinner95663112011-10-04 01:03:50 +0200660 assert(_PyUnicode_WSTR(unicode) != NULL);
661
662 /* check for integer overflow */
663 if (length > PY_SSIZE_T_MAX / sizeof(wchar_t) - 1) {
664 PyErr_NoMemory();
665 return -1;
666 }
667 wstr = _PyUnicode_WSTR(unicode);
668 wstr = PyObject_REALLOC(wstr, sizeof(wchar_t) * (length + 1));
669 if (!wstr) {
670 PyErr_NoMemory();
671 return -1;
672 }
673 _PyUnicode_WSTR(unicode) = wstr;
674 _PyUnicode_WSTR(unicode)[length] = 0;
675 _PyUnicode_WSTR_LENGTH(unicode) = length;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200676 assert(_PyUnicode_CheckConsistency(unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +0000677 return 0;
678}
679
Victor Stinnerfe226c02011-10-03 03:52:20 +0200680static PyObject*
681resize_copy(PyObject *unicode, Py_ssize_t length)
682{
683 Py_ssize_t copy_length;
684 if (PyUnicode_IS_COMPACT(unicode)) {
685 PyObject *copy;
686 assert(PyUnicode_IS_READY(unicode));
687
688 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
689 if (copy == NULL)
690 return NULL;
691
692 copy_length = Py_MIN(length, PyUnicode_GET_LENGTH(unicode));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200693 copy_characters(copy, 0, unicode, 0, copy_length);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200694 return copy;
Victor Stinner8cfcbed2011-10-03 23:19:21 +0200695 }
696 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200697 PyObject *w;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200698 assert(_PyUnicode_WSTR(unicode) != NULL);
699 assert(_PyUnicode_DATA_ANY(unicode) == NULL);
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200700 w = (PyObject*)_PyUnicode_New(length);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200701 if (w == NULL)
702 return NULL;
703 copy_length = _PyUnicode_WSTR_LENGTH(unicode);
704 copy_length = Py_MIN(copy_length, length);
705 Py_UNICODE_COPY(_PyUnicode_WSTR(w), _PyUnicode_WSTR(unicode),
706 copy_length);
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200707 return w;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200708 }
709}
710
Guido van Rossumd57fd912000-03-10 22:53:23 +0000711/* We allocate one more byte to make sure the string is
Martin v. Löwis47383402007-08-15 07:32:56 +0000712 Ux0000 terminated; some code (e.g. new_identifier)
713 relies on that.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000714
715 XXX This allocator could further be enhanced by assuring that the
Benjamin Peterson29060642009-01-31 22:14:21 +0000716 free list never reduces its size below 1.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000717
718*/
719
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200720#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +0200721static int unicode_old_new_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200722#endif
723
Alexander Belopolsky40018472011-02-26 01:02:56 +0000724static PyUnicodeObject *
725_PyUnicode_New(Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000726{
727 register PyUnicodeObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200728 size_t new_size;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000729
Thomas Wouters477c8d52006-05-27 19:21:47 +0000730 /* Optimization for empty strings */
Guido van Rossumd57fd912000-03-10 22:53:23 +0000731 if (length == 0 && unicode_empty != NULL) {
732 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +0200733 return (PyUnicodeObject*)unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000734 }
735
Neal Norwitz3ce5d922008-08-24 07:08:55 +0000736 /* Ensure we won't overflow the size. */
737 if (length > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
738 return (PyUnicodeObject *)PyErr_NoMemory();
739 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200740 if (length < 0) {
741 PyErr_SetString(PyExc_SystemError,
742 "Negative size passed to _PyUnicode_New");
743 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000744 }
745
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200746#ifdef Py_DEBUG
747 ++unicode_old_new_calls;
748#endif
749
750 unicode = PyObject_New(PyUnicodeObject, &PyUnicode_Type);
751 if (unicode == NULL)
752 return NULL;
753 new_size = sizeof(Py_UNICODE) * ((size_t)length + 1);
754 _PyUnicode_WSTR(unicode) = (Py_UNICODE*) PyObject_MALLOC(new_size);
755 if (!_PyUnicode_WSTR(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +0000756 PyErr_NoMemory();
757 goto onError;
Guido van Rossum3c1bb802000-04-27 20:13:50 +0000758 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200759
Jeremy Hyltond8082792003-09-16 19:41:39 +0000760 /* Initialize the first element to guard against cases where
Tim Petersced69f82003-09-16 20:30:58 +0000761 * the caller fails before initializing str -- unicode_resize()
762 * reads str[0], and the Keep-Alive optimization can keep memory
763 * allocated for str alive across a call to unicode_dealloc(unicode).
764 * We don't want unicode_resize to read uninitialized memory in
765 * that case.
766 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200767 _PyUnicode_WSTR(unicode)[0] = 0;
768 _PyUnicode_WSTR(unicode)[length] = 0;
769 _PyUnicode_WSTR_LENGTH(unicode) = length;
770 _PyUnicode_HASH(unicode) = -1;
771 _PyUnicode_STATE(unicode).interned = 0;
772 _PyUnicode_STATE(unicode).kind = 0;
773 _PyUnicode_STATE(unicode).compact = 0;
774 _PyUnicode_STATE(unicode).ready = 0;
775 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +0200776 _PyUnicode_DATA_ANY(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200777 _PyUnicode_LENGTH(unicode) = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200778 _PyUnicode_UTF8(unicode) = NULL;
779 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner7931d9a2011-11-04 00:22:48 +0100780 assert(_PyUnicode_CheckConsistency((PyObject *)unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +0000781 return unicode;
Barry Warsaw51ac5802000-03-20 16:36:48 +0000782
Benjamin Peterson29060642009-01-31 22:14:21 +0000783 onError:
Amaury Forgeot d'Arc7888d082008-08-01 01:06:32 +0000784 /* XXX UNREF/NEWREF interface should be more symmetrical */
785 _Py_DEC_REFTOTAL;
Barry Warsaw51ac5802000-03-20 16:36:48 +0000786 _Py_ForgetReference((PyObject *)unicode);
Neil Schemenauer58aa8612002-04-12 03:07:20 +0000787 PyObject_Del(unicode);
Barry Warsaw51ac5802000-03-20 16:36:48 +0000788 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000789}
790
Victor Stinnerf42dc442011-10-02 23:33:16 +0200791static const char*
792unicode_kind_name(PyObject *unicode)
793{
Victor Stinner42dfd712011-10-03 14:41:45 +0200794 /* don't check consistency: unicode_kind_name() is called from
795 _PyUnicode_Dump() */
Victor Stinnerf42dc442011-10-02 23:33:16 +0200796 if (!PyUnicode_IS_COMPACT(unicode))
797 {
798 if (!PyUnicode_IS_READY(unicode))
799 return "wstr";
800 switch(PyUnicode_KIND(unicode))
801 {
802 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200803 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200804 return "legacy ascii";
805 else
806 return "legacy latin1";
807 case PyUnicode_2BYTE_KIND:
808 return "legacy UCS2";
809 case PyUnicode_4BYTE_KIND:
810 return "legacy UCS4";
811 default:
812 return "<legacy invalid kind>";
813 }
814 }
815 assert(PyUnicode_IS_READY(unicode));
816 switch(PyUnicode_KIND(unicode))
817 {
818 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200819 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200820 return "ascii";
821 else
Victor Stinnera3b334d2011-10-03 13:53:37 +0200822 return "latin1";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200823 case PyUnicode_2BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200824 return "UCS2";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200825 case PyUnicode_4BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200826 return "UCS4";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200827 default:
828 return "<invalid compact kind>";
829 }
830}
831
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200832#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +0200833static int unicode_new_new_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200834
835/* Functions wrapping macros for use in debugger */
836char *_PyUnicode_utf8(void *unicode){
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200837 return PyUnicode_UTF8(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200838}
839
840void *_PyUnicode_compact_data(void *unicode) {
841 return _PyUnicode_COMPACT_DATA(unicode);
842}
843void *_PyUnicode_data(void *unicode){
844 printf("obj %p\n", unicode);
845 printf("compact %d\n", PyUnicode_IS_COMPACT(unicode));
846 printf("compact ascii %d\n", PyUnicode_IS_COMPACT_ASCII(unicode));
847 printf("ascii op %p\n", ((void*)((PyASCIIObject*)(unicode) + 1)));
848 printf("compact op %p\n", ((void*)((PyCompactUnicodeObject*)(unicode) + 1)));
849 printf("compact data %p\n", _PyUnicode_COMPACT_DATA(unicode));
850 return PyUnicode_DATA(unicode);
851}
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200852
853void
854_PyUnicode_Dump(PyObject *op)
855{
856 PyASCIIObject *ascii = (PyASCIIObject *)op;
Victor Stinnera849a4b2011-10-03 12:12:11 +0200857 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
858 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
859 void *data;
Victor Stinner0d60e872011-10-23 19:47:19 +0200860
Victor Stinnera849a4b2011-10-03 12:12:11 +0200861 if (ascii->state.compact)
Victor Stinner0d60e872011-10-23 19:47:19 +0200862 {
863 if (ascii->state.ascii)
864 data = (ascii + 1);
865 else
866 data = (compact + 1);
867 }
Victor Stinnera849a4b2011-10-03 12:12:11 +0200868 else
869 data = unicode->data.any;
Victor Stinner0d60e872011-10-23 19:47:19 +0200870 printf("%s: len=%zu, ",unicode_kind_name(op), ascii->length);
871
Victor Stinnera849a4b2011-10-03 12:12:11 +0200872 if (ascii->wstr == data)
873 printf("shared ");
874 printf("wstr=%p", ascii->wstr);
Victor Stinner0d60e872011-10-23 19:47:19 +0200875
Victor Stinnera3b334d2011-10-03 13:53:37 +0200876 if (!(ascii->state.ascii == 1 && ascii->state.compact == 1)) {
Victor Stinnera849a4b2011-10-03 12:12:11 +0200877 printf(" (%zu), ", compact->wstr_length);
878 if (!ascii->state.compact && compact->utf8 == unicode->data.any)
879 printf("shared ");
880 printf("utf8=%p (%zu)", compact->utf8, compact->utf8_length);
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200881 }
Victor Stinnera849a4b2011-10-03 12:12:11 +0200882 printf(", data=%p\n", data);
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200883}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200884#endif
885
886PyObject *
887PyUnicode_New(Py_ssize_t size, Py_UCS4 maxchar)
888{
889 PyObject *obj;
890 PyCompactUnicodeObject *unicode;
891 void *data;
892 int kind_state;
Victor Stinner9e9d6892011-10-04 01:02:02 +0200893 int is_sharing, is_ascii;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200894 Py_ssize_t char_size;
895 Py_ssize_t struct_size;
896
897 /* Optimization for empty strings */
898 if (size == 0 && unicode_empty != NULL) {
899 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +0200900 return unicode_empty;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200901 }
902
903#ifdef Py_DEBUG
904 ++unicode_new_new_calls;
905#endif
906
Victor Stinner9e9d6892011-10-04 01:02:02 +0200907 is_ascii = 0;
908 is_sharing = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200909 struct_size = sizeof(PyCompactUnicodeObject);
910 if (maxchar < 128) {
911 kind_state = PyUnicode_1BYTE_KIND;
912 char_size = 1;
913 is_ascii = 1;
914 struct_size = sizeof(PyASCIIObject);
915 }
916 else if (maxchar < 256) {
917 kind_state = PyUnicode_1BYTE_KIND;
918 char_size = 1;
919 }
920 else if (maxchar < 65536) {
921 kind_state = PyUnicode_2BYTE_KIND;
922 char_size = 2;
923 if (sizeof(wchar_t) == 2)
924 is_sharing = 1;
925 }
926 else {
927 kind_state = PyUnicode_4BYTE_KIND;
928 char_size = 4;
929 if (sizeof(wchar_t) == 4)
930 is_sharing = 1;
931 }
932
933 /* Ensure we won't overflow the size. */
934 if (size < 0) {
935 PyErr_SetString(PyExc_SystemError,
936 "Negative size passed to PyUnicode_New");
937 return NULL;
938 }
939 if (size > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1))
940 return PyErr_NoMemory();
941
942 /* Duplicated allocation code from _PyObject_New() instead of a call to
943 * PyObject_New() so we are able to allocate space for the object and
944 * it's data buffer.
945 */
946 obj = (PyObject *) PyObject_MALLOC(struct_size + (size + 1) * char_size);
947 if (obj == NULL)
948 return PyErr_NoMemory();
949 obj = PyObject_INIT(obj, &PyUnicode_Type);
950 if (obj == NULL)
951 return NULL;
952
953 unicode = (PyCompactUnicodeObject *)obj;
954 if (is_ascii)
955 data = ((PyASCIIObject*)obj) + 1;
956 else
957 data = unicode + 1;
958 _PyUnicode_LENGTH(unicode) = size;
959 _PyUnicode_HASH(unicode) = -1;
960 _PyUnicode_STATE(unicode).interned = 0;
961 _PyUnicode_STATE(unicode).kind = kind_state;
962 _PyUnicode_STATE(unicode).compact = 1;
963 _PyUnicode_STATE(unicode).ready = 1;
964 _PyUnicode_STATE(unicode).ascii = is_ascii;
965 if (is_ascii) {
966 ((char*)data)[size] = 0;
967 _PyUnicode_WSTR(unicode) = NULL;
968 }
969 else if (kind_state == PyUnicode_1BYTE_KIND) {
970 ((char*)data)[size] = 0;
971 _PyUnicode_WSTR(unicode) = NULL;
972 _PyUnicode_WSTR_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200973 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +0200974 unicode->utf8_length = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200975 }
976 else {
977 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +0200978 unicode->utf8_length = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200979 if (kind_state == PyUnicode_2BYTE_KIND)
980 ((Py_UCS2*)data)[size] = 0;
981 else /* kind_state == PyUnicode_4BYTE_KIND */
982 ((Py_UCS4*)data)[size] = 0;
983 if (is_sharing) {
984 _PyUnicode_WSTR_LENGTH(unicode) = size;
985 _PyUnicode_WSTR(unicode) = (wchar_t *)data;
986 }
987 else {
988 _PyUnicode_WSTR_LENGTH(unicode) = 0;
989 _PyUnicode_WSTR(unicode) = NULL;
990 }
991 }
Victor Stinner7931d9a2011-11-04 00:22:48 +0100992 assert(_PyUnicode_CheckConsistency((PyObject*)unicode, 0));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200993 return obj;
994}
995
996#if SIZEOF_WCHAR_T == 2
997/* Helper function to convert a 16-bits wchar_t representation to UCS4, this
998 will decode surrogate pairs, the other conversions are implemented as macros
Georg Brandl7597add2011-10-05 16:36:47 +0200999 for efficiency.
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001000
1001 This function assumes that unicode can hold one more code point than wstr
1002 characters for a terminating null character. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001003static void
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001004unicode_convert_wchar_to_ucs4(const wchar_t *begin, const wchar_t *end,
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001005 PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001006{
1007 const wchar_t *iter;
1008 Py_UCS4 *ucs4_out;
1009
Victor Stinner910337b2011-10-03 03:20:16 +02001010 assert(unicode != NULL);
1011 assert(_PyUnicode_CHECK(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001012 assert(_PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
1013 ucs4_out = PyUnicode_4BYTE_DATA(unicode);
1014
1015 for (iter = begin; iter < end; ) {
1016 assert(ucs4_out < (PyUnicode_4BYTE_DATA(unicode) +
1017 _PyUnicode_GET_LENGTH(unicode)));
1018 if (*iter >= 0xD800 && *iter <= 0xDBFF
1019 && (iter+1) < end && iter[1] >= 0xDC00 && iter[1] <= 0xDFFF)
1020 {
1021 *ucs4_out++ = (((iter[0] & 0x3FF)<<10) | (iter[1] & 0x3FF)) + 0x10000;
1022 iter += 2;
1023 }
1024 else {
1025 *ucs4_out++ = *iter;
1026 iter++;
1027 }
1028 }
1029 assert(ucs4_out == (PyUnicode_4BYTE_DATA(unicode) +
1030 _PyUnicode_GET_LENGTH(unicode)));
1031
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001032}
1033#endif
1034
Victor Stinnercd9950f2011-10-02 00:34:53 +02001035static int
1036_PyUnicode_Dirty(PyObject *unicode)
1037{
Victor Stinner910337b2011-10-03 03:20:16 +02001038 assert(_PyUnicode_CHECK(unicode));
Victor Stinnercd9950f2011-10-02 00:34:53 +02001039 if (Py_REFCNT(unicode) != 1) {
Victor Stinner01698042011-10-04 00:04:26 +02001040 PyErr_SetString(PyExc_SystemError,
Victor Stinnercd9950f2011-10-02 00:34:53 +02001041 "Cannot modify a string having more than 1 reference");
1042 return -1;
1043 }
1044 _PyUnicode_DIRTY(unicode);
1045 return 0;
1046}
1047
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001048static int
1049_copy_characters(PyObject *to, Py_ssize_t to_start,
1050 PyObject *from, Py_ssize_t from_start,
1051 Py_ssize_t how_many, int check_maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001052{
Victor Stinnera0702ab2011-09-29 14:14:38 +02001053 unsigned int from_kind, to_kind;
1054 void *from_data, *to_data;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001055 int fast;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001056
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001057 assert(PyUnicode_Check(from));
1058 assert(PyUnicode_Check(to));
1059 assert(PyUnicode_IS_READY(from));
1060 assert(PyUnicode_IS_READY(to));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001061
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001062 assert(PyUnicode_GET_LENGTH(from) >= how_many);
1063 assert(to_start + how_many <= PyUnicode_GET_LENGTH(to));
1064 assert(0 <= how_many);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001065
Victor Stinnerf5ca1a22011-09-28 23:54:59 +02001066 if (how_many == 0)
1067 return 0;
1068
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001069 from_kind = PyUnicode_KIND(from);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001070 from_data = PyUnicode_DATA(from);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001071 to_kind = PyUnicode_KIND(to);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001072 to_data = PyUnicode_DATA(to);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001073
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001074#ifdef Py_DEBUG
1075 if (!check_maxchar
1076 && (from_kind > to_kind
1077 || (!PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to))))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001078 {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001079 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
1080 Py_UCS4 ch;
1081 Py_ssize_t i;
1082 for (i=0; i < how_many; i++) {
1083 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1084 assert(ch <= to_maxchar);
1085 }
1086 }
1087#endif
1088 fast = (from_kind == to_kind);
1089 if (check_maxchar
1090 && (!PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to)))
1091 {
1092 /* deny latin1 => ascii */
1093 fast = 0;
1094 }
1095
1096 if (fast) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +02001097 Py_MEMCPY((char*)to_data + to_kind * to_start,
1098 (char*)from_data + from_kind * from_start,
1099 to_kind * how_many);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001100 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001101 else if (from_kind == PyUnicode_1BYTE_KIND
1102 && to_kind == PyUnicode_2BYTE_KIND)
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001103 {
1104 _PyUnicode_CONVERT_BYTES(
1105 Py_UCS1, Py_UCS2,
1106 PyUnicode_1BYTE_DATA(from) + from_start,
1107 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1108 PyUnicode_2BYTE_DATA(to) + to_start
1109 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001110 }
Victor Stinner157f83f2011-09-28 21:41:31 +02001111 else if (from_kind == PyUnicode_1BYTE_KIND
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001112 && to_kind == PyUnicode_4BYTE_KIND)
1113 {
1114 _PyUnicode_CONVERT_BYTES(
1115 Py_UCS1, Py_UCS4,
1116 PyUnicode_1BYTE_DATA(from) + from_start,
1117 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1118 PyUnicode_4BYTE_DATA(to) + to_start
1119 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001120 }
1121 else if (from_kind == PyUnicode_2BYTE_KIND
1122 && to_kind == PyUnicode_4BYTE_KIND)
1123 {
1124 _PyUnicode_CONVERT_BYTES(
1125 Py_UCS2, Py_UCS4,
1126 PyUnicode_2BYTE_DATA(from) + from_start,
1127 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1128 PyUnicode_4BYTE_DATA(to) + to_start
1129 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001130 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001131 else {
Victor Stinnerf42dc442011-10-02 23:33:16 +02001132 /* check if max_char(from substring) <= max_char(to) */
1133 if (from_kind > to_kind
1134 /* latin1 => ascii */
Victor Stinnerb9275c12011-10-05 14:01:42 +02001135 || (!PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to)))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001136 {
Victor Stinnera0702ab2011-09-29 14:14:38 +02001137 /* slow path to check for character overflow */
1138 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001139 Py_UCS4 ch;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001140 Py_ssize_t i;
1141
Victor Stinner56c161a2011-10-06 02:47:11 +02001142#ifdef Py_DEBUG
Victor Stinnera0702ab2011-09-29 14:14:38 +02001143 for (i=0; i < how_many; i++) {
1144 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
Victor Stinner56c161a2011-10-06 02:47:11 +02001145 assert(ch <= to_maxchar);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001146 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1147 }
Victor Stinner56c161a2011-10-06 02:47:11 +02001148#else
1149 if (!check_maxchar) {
1150 for (i=0; i < how_many; i++) {
1151 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1152 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1153 }
1154 }
1155 else {
1156 for (i=0; i < how_many; i++) {
1157 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1158 if (ch > to_maxchar)
1159 return 1;
1160 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1161 }
1162 }
1163#endif
Victor Stinnera0702ab2011-09-29 14:14:38 +02001164 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001165 else {
Victor Stinner56c161a2011-10-06 02:47:11 +02001166 assert(0 && "inconsistent state");
1167 return 1;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001168 }
1169 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001170 return 0;
1171}
1172
1173static void
1174copy_characters(PyObject *to, Py_ssize_t to_start,
1175 PyObject *from, Py_ssize_t from_start,
1176 Py_ssize_t how_many)
1177{
1178 (void)_copy_characters(to, to_start, from, from_start, how_many, 0);
1179}
1180
1181Py_ssize_t
1182PyUnicode_CopyCharacters(PyObject *to, Py_ssize_t to_start,
1183 PyObject *from, Py_ssize_t from_start,
1184 Py_ssize_t how_many)
1185{
1186 int err;
1187
1188 if (!PyUnicode_Check(from) || !PyUnicode_Check(to)) {
1189 PyErr_BadInternalCall();
1190 return -1;
1191 }
1192
1193 if (PyUnicode_READY(from))
1194 return -1;
1195 if (PyUnicode_READY(to))
1196 return -1;
1197
1198 how_many = Py_MIN(PyUnicode_GET_LENGTH(from), how_many);
1199 if (to_start + how_many > PyUnicode_GET_LENGTH(to)) {
1200 PyErr_Format(PyExc_SystemError,
1201 "Cannot write %zi characters at %zi "
1202 "in a string of %zi characters",
1203 how_many, to_start, PyUnicode_GET_LENGTH(to));
1204 return -1;
1205 }
1206
1207 if (how_many == 0)
1208 return 0;
1209
1210 if (_PyUnicode_Dirty(to))
1211 return -1;
1212
1213 err = _copy_characters(to, to_start, from, from_start, how_many, 1);
1214 if (err) {
1215 PyErr_Format(PyExc_SystemError,
1216 "Cannot copy %s characters "
1217 "into a string of %s characters",
1218 unicode_kind_name(from),
1219 unicode_kind_name(to));
1220 return -1;
1221 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001222 return how_many;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001223}
1224
Victor Stinner17222162011-09-28 22:15:37 +02001225/* Find the maximum code point and count the number of surrogate pairs so a
1226 correct string length can be computed before converting a string to UCS4.
1227 This function counts single surrogates as a character and not as a pair.
1228
1229 Return 0 on success, or -1 on error. */
1230static int
1231find_maxchar_surrogates(const wchar_t *begin, const wchar_t *end,
1232 Py_UCS4 *maxchar, Py_ssize_t *num_surrogates)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001233{
1234 const wchar_t *iter;
1235
Victor Stinnerc53be962011-10-02 21:33:54 +02001236 assert(num_surrogates != NULL && maxchar != NULL);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001237 *num_surrogates = 0;
1238 *maxchar = 0;
1239
1240 for (iter = begin; iter < end; ) {
Victor Stinnerae864852011-10-05 14:02:44 +02001241 if (*iter > *maxchar) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001242 *maxchar = *iter;
Victor Stinnerae864852011-10-05 14:02:44 +02001243#if SIZEOF_WCHAR_T != 2
1244 if (*maxchar >= 0x10000)
1245 return 0;
1246#endif
1247 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001248#if SIZEOF_WCHAR_T == 2
1249 if (*iter >= 0xD800 && *iter <= 0xDBFF
1250 && (iter+1) < end && iter[1] >= 0xDC00 && iter[1] <= 0xDFFF)
1251 {
1252 Py_UCS4 surrogate_val;
1253 surrogate_val = (((iter[0] & 0x3FF)<<10)
1254 | (iter[1] & 0x3FF)) + 0x10000;
1255 ++(*num_surrogates);
1256 if (surrogate_val > *maxchar)
1257 *maxchar = surrogate_val;
1258 iter += 2;
1259 }
1260 else
1261 iter++;
1262#else
1263 iter++;
1264#endif
1265 }
1266 return 0;
1267}
1268
1269#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +02001270static int unicode_ready_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001271#endif
1272
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02001273static int
1274unicode_ready(PyObject **p_obj, int replace)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001275{
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001276 PyObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001277 wchar_t *end;
1278 Py_UCS4 maxchar = 0;
1279 Py_ssize_t num_surrogates;
1280#if SIZEOF_WCHAR_T == 2
1281 Py_ssize_t length_wo_surrogates;
1282#endif
1283
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02001284 assert(p_obj != NULL);
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001285 unicode = *p_obj;
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02001286
Georg Brandl7597add2011-10-05 16:36:47 +02001287 /* _PyUnicode_Ready() is only intended for old-style API usage where
Victor Stinnerd8f65102011-09-29 19:43:17 +02001288 strings were created using _PyObject_New() and where no canonical
1289 representation (the str field) has been set yet aka strings
1290 which are not yet ready. */
Victor Stinner910337b2011-10-03 03:20:16 +02001291 assert(_PyUnicode_CHECK(unicode));
1292 assert(_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001293 assert(_PyUnicode_WSTR(unicode) != NULL);
Victor Stinnerc3c74152011-10-02 20:39:55 +02001294 assert(_PyUnicode_DATA_ANY(unicode) == NULL);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001295 assert(_PyUnicode_UTF8(unicode) == NULL);
Victor Stinnerd8f65102011-09-29 19:43:17 +02001296 /* Actually, it should neither be interned nor be anything else: */
1297 assert(_PyUnicode_STATE(unicode).interned == SSTATE_NOT_INTERNED);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001298
1299#ifdef Py_DEBUG
1300 ++unicode_ready_calls;
1301#endif
1302
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02001303#ifdef Py_DEBUG
1304 assert(!replace || Py_REFCNT(unicode) == 1);
1305#else
1306 if (replace && Py_REFCNT(unicode) != 1)
1307 replace = 0;
1308#endif
1309 if (replace) {
1310 Py_ssize_t len = _PyUnicode_WSTR_LENGTH(unicode);
1311 wchar_t *wstr = _PyUnicode_WSTR(unicode);
1312 /* Optimization for empty strings */
1313 if (len == 0) {
1314 Py_INCREF(unicode_empty);
1315 Py_DECREF(*p_obj);
1316 *p_obj = unicode_empty;
1317 return 0;
1318 }
1319 if (len == 1 && wstr[0] < 256) {
1320 PyObject *latin1_char = get_latin1_char((unsigned char)wstr[0]);
1321 if (latin1_char == NULL)
1322 return -1;
1323 Py_DECREF(*p_obj);
1324 *p_obj = latin1_char;
1325 return 0;
1326 }
1327 }
1328
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001329 end = _PyUnicode_WSTR(unicode) + _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinner17222162011-09-28 22:15:37 +02001330 if (find_maxchar_surrogates(_PyUnicode_WSTR(unicode), end,
Victor Stinnerd8f65102011-09-29 19:43:17 +02001331 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001332 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001333
1334 if (maxchar < 256) {
Victor Stinnerc3c74152011-10-02 20:39:55 +02001335 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(_PyUnicode_WSTR_LENGTH(unicode) + 1);
1336 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001337 PyErr_NoMemory();
1338 return -1;
1339 }
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001340 _PyUnicode_CONVERT_BYTES(wchar_t, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001341 _PyUnicode_WSTR(unicode), end,
1342 PyUnicode_1BYTE_DATA(unicode));
1343 PyUnicode_1BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1344 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1345 _PyUnicode_STATE(unicode).kind = PyUnicode_1BYTE_KIND;
1346 if (maxchar < 128) {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001347 _PyUnicode_STATE(unicode).ascii = 1;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001348 _PyUnicode_UTF8(unicode) = _PyUnicode_DATA_ANY(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001349 _PyUnicode_UTF8_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001350 }
1351 else {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001352 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001353 _PyUnicode_UTF8(unicode) = NULL;
1354 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001355 }
1356 PyObject_FREE(_PyUnicode_WSTR(unicode));
1357 _PyUnicode_WSTR(unicode) = NULL;
1358 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1359 }
1360 /* In this case we might have to convert down from 4-byte native
1361 wchar_t to 2-byte unicode. */
1362 else if (maxchar < 65536) {
1363 assert(num_surrogates == 0 &&
1364 "FindMaxCharAndNumSurrogatePairs() messed up");
1365
Victor Stinner506f5922011-09-28 22:34:18 +02001366#if SIZEOF_WCHAR_T == 2
1367 /* We can share representations and are done. */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001368 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Victor Stinner506f5922011-09-28 22:34:18 +02001369 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1370 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1371 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001372 _PyUnicode_UTF8(unicode) = NULL;
1373 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001374#else
1375 /* sizeof(wchar_t) == 4 */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001376 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(
Victor Stinner506f5922011-09-28 22:34:18 +02001377 2 * (_PyUnicode_WSTR_LENGTH(unicode) + 1));
Victor Stinnerc3c74152011-10-02 20:39:55 +02001378 if (!_PyUnicode_DATA_ANY(unicode)) {
Victor Stinner506f5922011-09-28 22:34:18 +02001379 PyErr_NoMemory();
1380 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001381 }
Victor Stinner506f5922011-09-28 22:34:18 +02001382 _PyUnicode_CONVERT_BYTES(wchar_t, Py_UCS2,
1383 _PyUnicode_WSTR(unicode), end,
1384 PyUnicode_2BYTE_DATA(unicode));
1385 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1386 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1387 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001388 _PyUnicode_UTF8(unicode) = NULL;
1389 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001390 PyObject_FREE(_PyUnicode_WSTR(unicode));
1391 _PyUnicode_WSTR(unicode) = NULL;
1392 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1393#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001394 }
1395 /* maxchar exeeds 16 bit, wee need 4 bytes for unicode characters */
1396 else {
1397#if SIZEOF_WCHAR_T == 2
1398 /* in case the native representation is 2-bytes, we need to allocate a
1399 new normalized 4-byte version. */
1400 length_wo_surrogates = _PyUnicode_WSTR_LENGTH(unicode) - num_surrogates;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001401 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(4 * (length_wo_surrogates + 1));
1402 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001403 PyErr_NoMemory();
1404 return -1;
1405 }
1406 _PyUnicode_LENGTH(unicode) = length_wo_surrogates;
1407 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001408 _PyUnicode_UTF8(unicode) = NULL;
1409 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner126c5592011-10-03 04:17:10 +02001410 /* unicode_convert_wchar_to_ucs4() requires a ready string */
1411 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerc53be962011-10-02 21:33:54 +02001412 unicode_convert_wchar_to_ucs4(_PyUnicode_WSTR(unicode), end, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001413 PyObject_FREE(_PyUnicode_WSTR(unicode));
1414 _PyUnicode_WSTR(unicode) = NULL;
1415 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1416#else
1417 assert(num_surrogates == 0);
1418
Victor Stinnerc3c74152011-10-02 20:39:55 +02001419 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001420 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001421 _PyUnicode_UTF8(unicode) = NULL;
1422 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001423 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
1424#endif
1425 PyUnicode_4BYTE_DATA(unicode)[_PyUnicode_LENGTH(unicode)] = '\0';
1426 }
1427 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001428 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001429 return 0;
1430}
1431
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02001432int
1433_PyUnicode_ReadyReplace(PyObject **op)
1434{
1435 return unicode_ready(op, 1);
1436}
1437
1438int
1439_PyUnicode_Ready(PyObject *op)
1440{
1441 return unicode_ready(&op, 0);
1442}
1443
Alexander Belopolsky40018472011-02-26 01:02:56 +00001444static void
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001445unicode_dealloc(register PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001446{
Walter Dörwald16807132007-05-25 13:52:07 +00001447 switch (PyUnicode_CHECK_INTERNED(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001448 case SSTATE_NOT_INTERNED:
1449 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001450
Benjamin Peterson29060642009-01-31 22:14:21 +00001451 case SSTATE_INTERNED_MORTAL:
1452 /* revive dead object temporarily for DelItem */
1453 Py_REFCNT(unicode) = 3;
Victor Stinner7931d9a2011-11-04 00:22:48 +01001454 if (PyDict_DelItem(interned, unicode) != 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00001455 Py_FatalError(
1456 "deletion of interned string failed");
1457 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001458
Benjamin Peterson29060642009-01-31 22:14:21 +00001459 case SSTATE_INTERNED_IMMORTAL:
1460 Py_FatalError("Immortal interned string died.");
Walter Dörwald16807132007-05-25 13:52:07 +00001461
Benjamin Peterson29060642009-01-31 22:14:21 +00001462 default:
1463 Py_FatalError("Inconsistent interned string state.");
Walter Dörwald16807132007-05-25 13:52:07 +00001464 }
1465
Victor Stinner03490912011-10-03 23:45:12 +02001466 if (_PyUnicode_HAS_WSTR_MEMORY(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001467 PyObject_DEL(_PyUnicode_WSTR(unicode));
Victor Stinner829c0ad2011-10-03 01:08:02 +02001468 if (_PyUnicode_HAS_UTF8_MEMORY(unicode))
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001469 PyObject_DEL(_PyUnicode_UTF8(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001470
1471 if (PyUnicode_IS_COMPACT(unicode)) {
Victor Stinner7931d9a2011-11-04 00:22:48 +01001472 Py_TYPE(unicode)->tp_free(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001473 }
1474 else {
Victor Stinnerc3c74152011-10-02 20:39:55 +02001475 if (_PyUnicode_DATA_ANY(unicode))
1476 PyObject_DEL(_PyUnicode_DATA_ANY(unicode));
Victor Stinner7931d9a2011-11-04 00:22:48 +01001477 Py_TYPE(unicode)->tp_free(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001478 }
1479}
1480
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001481#ifdef Py_DEBUG
1482static int
1483unicode_is_singleton(PyObject *unicode)
1484{
1485 PyASCIIObject *ascii = (PyASCIIObject *)unicode;
1486 if (unicode == unicode_empty)
1487 return 1;
1488 if (ascii->state.kind != PyUnicode_WCHAR_KIND && ascii->length == 1)
1489 {
1490 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, 0);
1491 if (ch < 256 && unicode_latin1[ch] == unicode)
1492 return 1;
1493 }
1494 return 0;
1495}
1496#endif
1497
Alexander Belopolsky40018472011-02-26 01:02:56 +00001498static int
Victor Stinnerfe226c02011-10-03 03:52:20 +02001499unicode_resizable(PyObject *unicode)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001500{
Victor Stinnerfe226c02011-10-03 03:52:20 +02001501 if (Py_REFCNT(unicode) != 1)
1502 return 0;
1503 if (PyUnicode_CHECK_INTERNED(unicode))
1504 return 0;
Victor Stinner77bb47b2011-10-03 20:06:05 +02001505#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001506 /* singleton refcount is greater than 1 */
1507 assert(!unicode_is_singleton(unicode));
Victor Stinner77bb47b2011-10-03 20:06:05 +02001508#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +02001509 return 1;
1510}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001511
Victor Stinnerfe226c02011-10-03 03:52:20 +02001512static int
1513unicode_resize(PyObject **p_unicode, Py_ssize_t length)
1514{
1515 PyObject *unicode;
1516 Py_ssize_t old_length;
1517
1518 assert(p_unicode != NULL);
1519 unicode = *p_unicode;
1520
1521 assert(unicode != NULL);
1522 assert(PyUnicode_Check(unicode));
1523 assert(0 <= length);
1524
Victor Stinner910337b2011-10-03 03:20:16 +02001525 if (_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001526 old_length = PyUnicode_WSTR_LENGTH(unicode);
1527 else
1528 old_length = PyUnicode_GET_LENGTH(unicode);
1529 if (old_length == length)
1530 return 0;
1531
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001532 if (length == 0) {
1533 Py_DECREF(*p_unicode);
1534 *p_unicode = unicode_empty;
1535 Py_INCREF(*p_unicode);
1536 return 0;
1537 }
1538
Victor Stinnerfe226c02011-10-03 03:52:20 +02001539 if (!unicode_resizable(unicode)) {
1540 PyObject *copy = resize_copy(unicode, length);
1541 if (copy == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001542 return -1;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001543 Py_DECREF(*p_unicode);
1544 *p_unicode = copy;
Benjamin Peterson29060642009-01-31 22:14:21 +00001545 return 0;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001546 }
1547
Victor Stinnerfe226c02011-10-03 03:52:20 +02001548 if (PyUnicode_IS_COMPACT(unicode)) {
1549 *p_unicode = resize_compact(unicode, length);
1550 if (*p_unicode == NULL)
1551 return -1;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001552 assert(_PyUnicode_CheckConsistency(*p_unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001553 return 0;
Benjamin Peterson4bfce8f2011-10-03 19:35:07 -04001554 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001555 return resize_inplace(unicode, length);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001556}
1557
Alexander Belopolsky40018472011-02-26 01:02:56 +00001558int
Victor Stinnerfe226c02011-10-03 03:52:20 +02001559PyUnicode_Resize(PyObject **p_unicode, Py_ssize_t length)
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001560{
Victor Stinnerfe226c02011-10-03 03:52:20 +02001561 PyObject *unicode;
1562 if (p_unicode == NULL) {
1563 PyErr_BadInternalCall();
1564 return -1;
1565 }
1566 unicode = *p_unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001567 if (unicode == NULL || !PyUnicode_Check(unicode) || length < 0)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001568 {
1569 PyErr_BadInternalCall();
1570 return -1;
1571 }
1572 return unicode_resize(p_unicode, length);
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001573}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001574
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001575static int
Victor Stinner0a045ef2011-11-09 00:02:42 +01001576unicode_widen(PyObject **p_unicode, unsigned int maxchar)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001577{
1578 PyObject *result;
1579 assert(PyUnicode_IS_READY(*p_unicode));
1580 if (maxchar <= PyUnicode_MAX_CHAR_VALUE(*p_unicode))
1581 return 0;
1582 result = PyUnicode_New(PyUnicode_GET_LENGTH(*p_unicode),
1583 maxchar);
1584 if (result == NULL)
1585 return -1;
1586 PyUnicode_CopyCharacters(result, 0, *p_unicode, 0,
1587 PyUnicode_GET_LENGTH(*p_unicode));
1588 Py_DECREF(*p_unicode);
1589 *p_unicode = result;
1590 return 0;
1591}
1592
1593static int
1594unicode_putchar(PyObject **p_unicode, Py_ssize_t *pos,
1595 Py_UCS4 ch)
1596{
1597 if (unicode_widen(p_unicode, ch) < 0)
1598 return -1;
1599 PyUnicode_WRITE(PyUnicode_KIND(*p_unicode),
1600 PyUnicode_DATA(*p_unicode),
1601 (*pos)++, ch);
1602 return 0;
1603}
1604
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001605static PyObject*
1606get_latin1_char(unsigned char ch)
1607{
Victor Stinnera464fc12011-10-02 20:39:30 +02001608 PyObject *unicode = unicode_latin1[ch];
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001609 if (!unicode) {
Victor Stinnera464fc12011-10-02 20:39:30 +02001610 unicode = PyUnicode_New(1, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001611 if (!unicode)
1612 return NULL;
1613 PyUnicode_1BYTE_DATA(unicode)[0] = ch;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001614 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001615 unicode_latin1[ch] = unicode;
1616 }
1617 Py_INCREF(unicode);
Victor Stinnera464fc12011-10-02 20:39:30 +02001618 return unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001619}
1620
Alexander Belopolsky40018472011-02-26 01:02:56 +00001621PyObject *
1622PyUnicode_FromUnicode(const Py_UNICODE *u, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001623{
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001624 PyObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001625 Py_UCS4 maxchar = 0;
1626 Py_ssize_t num_surrogates;
1627
1628 if (u == NULL)
1629 return (PyObject*)_PyUnicode_New(size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001630
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001631 /* If the Unicode data is known at construction time, we can apply
1632 some optimizations which share commonly used objects. */
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001633
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001634 /* Optimization for empty strings */
1635 if (size == 0 && unicode_empty != NULL) {
1636 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001637 return unicode_empty;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001638 }
Tim Petersced69f82003-09-16 20:30:58 +00001639
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001640 /* Single character Unicode objects in the Latin-1 range are
1641 shared when using this constructor */
1642 if (size == 1 && *u < 256)
1643 return get_latin1_char((unsigned char)*u);
1644
1645 /* If not empty and not single character, copy the Unicode data
1646 into the new object */
Victor Stinnerd8f65102011-09-29 19:43:17 +02001647 if (find_maxchar_surrogates(u, u + size,
1648 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001649 return NULL;
1650
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001651 unicode = PyUnicode_New(size - num_surrogates,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001652 maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001653 if (!unicode)
1654 return NULL;
1655
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001656 switch (PyUnicode_KIND(unicode)) {
1657 case PyUnicode_1BYTE_KIND:
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001658 _PyUnicode_CONVERT_BYTES(Py_UNICODE, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001659 u, u + size, PyUnicode_1BYTE_DATA(unicode));
1660 break;
1661 case PyUnicode_2BYTE_KIND:
1662#if Py_UNICODE_SIZE == 2
1663 Py_MEMCPY(PyUnicode_2BYTE_DATA(unicode), u, size * 2);
1664#else
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001665 _PyUnicode_CONVERT_BYTES(Py_UNICODE, Py_UCS2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001666 u, u + size, PyUnicode_2BYTE_DATA(unicode));
1667#endif
1668 break;
1669 case PyUnicode_4BYTE_KIND:
1670#if SIZEOF_WCHAR_T == 2
1671 /* This is the only case which has to process surrogates, thus
1672 a simple copy loop is not enough and we need a function. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001673 unicode_convert_wchar_to_ucs4(u, u + size, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001674#else
1675 assert(num_surrogates == 0);
1676 Py_MEMCPY(PyUnicode_4BYTE_DATA(unicode), u, size * 4);
1677#endif
1678 break;
1679 default:
1680 assert(0 && "Impossible state");
1681 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00001682
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001683 assert(_PyUnicode_CheckConsistency(unicode, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001684 return unicode;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001685}
1686
Alexander Belopolsky40018472011-02-26 01:02:56 +00001687PyObject *
1688PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size)
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001689{
Benjamin Peterson14339b62009-01-31 16:36:08 +00001690 if (size < 0) {
1691 PyErr_SetString(PyExc_SystemError,
Benjamin Peterson29060642009-01-31 22:14:21 +00001692 "Negative size passed to PyUnicode_FromStringAndSize");
Benjamin Peterson14339b62009-01-31 16:36:08 +00001693 return NULL;
1694 }
Christian Heimes33fe8092008-04-13 13:53:33 +00001695
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001696 /* If the Unicode data is known at construction time, we can apply
Martin v. Löwis9c121062007-08-05 20:26:11 +00001697 some optimizations which share commonly used objects.
1698 Also, this means the input must be UTF-8, so fall back to the
1699 UTF-8 decoder at the end. */
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001700 if (u != NULL) {
1701
Benjamin Peterson29060642009-01-31 22:14:21 +00001702 /* Optimization for empty strings */
1703 if (size == 0 && unicode_empty != NULL) {
1704 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001705 return unicode_empty;
Benjamin Peterson14339b62009-01-31 16:36:08 +00001706 }
Benjamin Peterson29060642009-01-31 22:14:21 +00001707
1708 /* Single characters are shared when using this constructor.
1709 Restrict to ASCII, since the input must be UTF-8. */
Victor Stinner9faa3842011-10-23 20:06:00 +02001710 if (size == 1 && (unsigned char)*u < 128)
1711 return get_latin1_char((unsigned char)*u);
Martin v. Löwis9c121062007-08-05 20:26:11 +00001712
1713 return PyUnicode_DecodeUTF8(u, size, NULL);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001714 }
1715
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001716 return (PyObject *)_PyUnicode_New(size);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001717}
1718
Alexander Belopolsky40018472011-02-26 01:02:56 +00001719PyObject *
1720PyUnicode_FromString(const char *u)
Walter Dörwaldd2034312007-05-18 16:29:38 +00001721{
1722 size_t size = strlen(u);
1723 if (size > PY_SSIZE_T_MAX) {
1724 PyErr_SetString(PyExc_OverflowError, "input too long");
1725 return NULL;
1726 }
1727
1728 return PyUnicode_FromStringAndSize(u, size);
1729}
1730
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001731PyObject *
1732_PyUnicode_FromId(_Py_Identifier *id)
1733{
1734 if (!id->object) {
1735 id->object = PyUnicode_FromString(id->string);
1736 if (!id->object)
1737 return NULL;
1738 PyUnicode_InternInPlace(&id->object);
1739 assert(!id->next);
1740 id->next = static_strings;
1741 static_strings = id;
1742 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001743 return id->object;
1744}
1745
1746void
1747_PyUnicode_ClearStaticStrings()
1748{
1749 _Py_Identifier *i;
1750 for (i = static_strings; i; i = i->next) {
1751 Py_DECREF(i->object);
1752 i->object = NULL;
1753 i->next = NULL;
1754 }
1755}
1756
Victor Stinnere57b1c02011-09-28 22:20:48 +02001757static PyObject*
Victor Stinner0617b6e2011-10-05 23:26:01 +02001758unicode_fromascii(const unsigned char* s, Py_ssize_t size)
Victor Stinner702c7342011-10-05 13:50:52 +02001759{
Victor Stinner0617b6e2011-10-05 23:26:01 +02001760 PyObject *res;
1761#ifdef Py_DEBUG
1762 const unsigned char *p;
1763 const unsigned char *end = s + size;
1764 for (p=s; p < end; p++) {
1765 assert(*p < 128);
1766 }
1767#endif
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001768 if (size == 1)
1769 return get_latin1_char(s[0]);
Victor Stinner0617b6e2011-10-05 23:26:01 +02001770 res = PyUnicode_New(size, 127);
Victor Stinner702c7342011-10-05 13:50:52 +02001771 if (!res)
1772 return NULL;
Victor Stinner0617b6e2011-10-05 23:26:01 +02001773 memcpy(PyUnicode_1BYTE_DATA(res), s, size);
Victor Stinner702c7342011-10-05 13:50:52 +02001774 return res;
1775}
1776
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001777static Py_UCS4
1778kind_maxchar_limit(unsigned int kind)
1779{
1780 switch(kind) {
1781 case PyUnicode_1BYTE_KIND:
1782 return 0x80;
1783 case PyUnicode_2BYTE_KIND:
1784 return 0x100;
1785 case PyUnicode_4BYTE_KIND:
1786 return 0x10000;
1787 default:
1788 assert(0 && "invalid kind");
1789 return 0x10ffff;
1790 }
1791}
1792
Victor Stinner702c7342011-10-05 13:50:52 +02001793static PyObject*
Victor Stinnere57b1c02011-09-28 22:20:48 +02001794_PyUnicode_FromUCS1(const unsigned char* u, Py_ssize_t size)
Mark Dickinson081dfee2009-03-18 14:47:41 +00001795{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001796 PyObject *res;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001797 unsigned char max_char = 127;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001798
1799 assert(size >= 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001800 if (size == 1)
1801 return get_latin1_char(u[0]);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001802 max_char = ucs1lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001803 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001804 if (!res)
1805 return NULL;
1806 memcpy(PyUnicode_1BYTE_DATA(res), u, size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001807 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001808 return res;
Mark Dickinson081dfee2009-03-18 14:47:41 +00001809}
1810
Victor Stinnere57b1c02011-09-28 22:20:48 +02001811static PyObject*
1812_PyUnicode_FromUCS2(const Py_UCS2 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001813{
1814 PyObject *res;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001815 Py_UCS2 max_char = 0;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001816
1817 assert(size >= 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001818 if (size == 1 && u[0] < 256)
Victor Stinner4e101002011-10-11 23:27:52 +02001819 return get_latin1_char((unsigned char)u[0]);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001820 max_char = ucs2lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001821 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001822 if (!res)
1823 return NULL;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001824 if (max_char >= 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001825 memcpy(PyUnicode_2BYTE_DATA(res), u, sizeof(Py_UCS2)*size);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001826 else {
1827 _PyUnicode_CONVERT_BYTES(
1828 Py_UCS2, Py_UCS1, u, u + size, PyUnicode_1BYTE_DATA(res));
1829 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001830 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001831 return res;
1832}
1833
Victor Stinnere57b1c02011-09-28 22:20:48 +02001834static PyObject*
1835_PyUnicode_FromUCS4(const Py_UCS4 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001836{
1837 PyObject *res;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001838 Py_UCS4 max_char = 0;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001839
1840 assert(size >= 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001841 if (size == 1 && u[0] < 256)
1842 return get_latin1_char(u[0]);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001843 max_char = ucs4lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001844 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001845 if (!res)
1846 return NULL;
Antoine Pitrou950468e2011-10-11 22:45:48 +02001847 if (max_char < 256)
1848 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, u, u + size,
1849 PyUnicode_1BYTE_DATA(res));
1850 else if (max_char < 0x10000)
1851 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, u, u + size,
1852 PyUnicode_2BYTE_DATA(res));
1853 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001854 memcpy(PyUnicode_4BYTE_DATA(res), u, sizeof(Py_UCS4)*size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001855 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001856 return res;
1857}
1858
1859PyObject*
1860PyUnicode_FromKindAndData(int kind, const void *buffer, Py_ssize_t size)
1861{
1862 switch(kind) {
1863 case PyUnicode_1BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02001864 return _PyUnicode_FromUCS1(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001865 case PyUnicode_2BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02001866 return _PyUnicode_FromUCS2(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001867 case PyUnicode_4BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02001868 return _PyUnicode_FromUCS4(buffer, size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001869 default:
1870 assert(0 && "invalid kind");
1871 PyErr_SetString(PyExc_SystemError, "invalid kind");
1872 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001873 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001874}
1875
Victor Stinner25a4b292011-10-06 12:31:55 +02001876/* Ensure that a string uses the most efficient storage, if it is not the
1877 case: create a new string with of the right kind. Write NULL into *p_unicode
1878 on error. */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02001879static void
Victor Stinner25a4b292011-10-06 12:31:55 +02001880unicode_adjust_maxchar(PyObject **p_unicode)
1881{
1882 PyObject *unicode, *copy;
1883 Py_UCS4 max_char;
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001884 Py_ssize_t len;
Victor Stinner25a4b292011-10-06 12:31:55 +02001885 unsigned int kind;
1886
1887 assert(p_unicode != NULL);
1888 unicode = *p_unicode;
1889 assert(PyUnicode_IS_READY(unicode));
1890 if (PyUnicode_IS_ASCII(unicode))
1891 return;
1892
1893 len = PyUnicode_GET_LENGTH(unicode);
1894 kind = PyUnicode_KIND(unicode);
1895 if (kind == PyUnicode_1BYTE_KIND) {
1896 const Py_UCS1 *u = PyUnicode_1BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001897 max_char = ucs1lib_find_max_char(u, u + len);
1898 if (max_char >= 128)
1899 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02001900 }
1901 else if (kind == PyUnicode_2BYTE_KIND) {
1902 const Py_UCS2 *u = PyUnicode_2BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001903 max_char = ucs2lib_find_max_char(u, u + len);
1904 if (max_char >= 256)
1905 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02001906 }
1907 else {
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001908 const Py_UCS4 *u = PyUnicode_4BYTE_DATA(unicode);
Victor Stinner25a4b292011-10-06 12:31:55 +02001909 assert(kind == PyUnicode_4BYTE_KIND);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001910 max_char = ucs4lib_find_max_char(u, u + len);
1911 if (max_char >= 0x10000)
1912 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02001913 }
Victor Stinner25a4b292011-10-06 12:31:55 +02001914 copy = PyUnicode_New(len, max_char);
1915 copy_characters(copy, 0, unicode, 0, len);
1916 Py_DECREF(unicode);
1917 *p_unicode = copy;
1918}
1919
Victor Stinner034f6cf2011-09-30 02:26:44 +02001920PyObject*
1921PyUnicode_Copy(PyObject *unicode)
1922{
Victor Stinnerc841e7d2011-10-01 01:34:32 +02001923 Py_ssize_t size;
1924 PyObject *copy;
1925 void *data;
1926
Victor Stinner034f6cf2011-09-30 02:26:44 +02001927 if (!PyUnicode_Check(unicode)) {
1928 PyErr_BadInternalCall();
1929 return NULL;
1930 }
1931 if (PyUnicode_READY(unicode))
1932 return NULL;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02001933
1934 size = PyUnicode_GET_LENGTH(unicode);
1935 copy = PyUnicode_New(size, PyUnicode_MAX_CHAR_VALUE(unicode));
1936 if (!copy)
1937 return NULL;
1938 assert(PyUnicode_KIND(copy) == PyUnicode_KIND(unicode));
1939
1940 data = PyUnicode_DATA(unicode);
1941 switch (PyUnicode_KIND(unicode))
1942 {
1943 case PyUnicode_1BYTE_KIND:
1944 memcpy(PyUnicode_1BYTE_DATA(copy), data, size);
1945 break;
1946 case PyUnicode_2BYTE_KIND:
1947 memcpy(PyUnicode_2BYTE_DATA(copy), data, sizeof(Py_UCS2) * size);
1948 break;
1949 case PyUnicode_4BYTE_KIND:
1950 memcpy(PyUnicode_4BYTE_DATA(copy), data, sizeof(Py_UCS4) * size);
1951 break;
1952 default:
1953 assert(0);
1954 break;
1955 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001956 assert(_PyUnicode_CheckConsistency(copy, 1));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02001957 return copy;
Victor Stinner034f6cf2011-09-30 02:26:44 +02001958}
1959
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001960
Victor Stinnerbc603d12011-10-02 01:00:40 +02001961/* Widen Unicode objects to larger buffers. Don't write terminating null
1962 character. Return NULL on error. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001963
1964void*
1965_PyUnicode_AsKind(PyObject *s, unsigned int kind)
1966{
Victor Stinnerbc603d12011-10-02 01:00:40 +02001967 Py_ssize_t len;
1968 void *result;
1969 unsigned int skind;
1970
1971 if (PyUnicode_READY(s))
1972 return NULL;
1973
1974 len = PyUnicode_GET_LENGTH(s);
1975 skind = PyUnicode_KIND(s);
1976 if (skind >= kind) {
Victor Stinner01698042011-10-04 00:04:26 +02001977 PyErr_SetString(PyExc_SystemError, "invalid widening attempt");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001978 return NULL;
1979 }
1980 switch(kind) {
Victor Stinnerbc603d12011-10-02 01:00:40 +02001981 case PyUnicode_2BYTE_KIND:
1982 result = PyMem_Malloc(len * sizeof(Py_UCS2));
1983 if (!result)
1984 return PyErr_NoMemory();
1985 assert(skind == PyUnicode_1BYTE_KIND);
1986 _PyUnicode_CONVERT_BYTES(
1987 Py_UCS1, Py_UCS2,
1988 PyUnicode_1BYTE_DATA(s),
1989 PyUnicode_1BYTE_DATA(s) + len,
1990 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001991 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02001992 case PyUnicode_4BYTE_KIND:
1993 result = PyMem_Malloc(len * sizeof(Py_UCS4));
1994 if (!result)
1995 return PyErr_NoMemory();
1996 if (skind == PyUnicode_2BYTE_KIND) {
1997 _PyUnicode_CONVERT_BYTES(
1998 Py_UCS2, Py_UCS4,
1999 PyUnicode_2BYTE_DATA(s),
2000 PyUnicode_2BYTE_DATA(s) + len,
2001 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002002 }
Victor Stinnerbc603d12011-10-02 01:00:40 +02002003 else {
2004 assert(skind == PyUnicode_1BYTE_KIND);
2005 _PyUnicode_CONVERT_BYTES(
2006 Py_UCS1, Py_UCS4,
2007 PyUnicode_1BYTE_DATA(s),
2008 PyUnicode_1BYTE_DATA(s) + len,
2009 result);
2010 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002011 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002012 default:
2013 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002014 }
Victor Stinner01698042011-10-04 00:04:26 +02002015 PyErr_SetString(PyExc_SystemError, "invalid kind");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002016 return NULL;
2017}
2018
2019static Py_UCS4*
2020as_ucs4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2021 int copy_null)
2022{
2023 int kind;
2024 void *data;
2025 Py_ssize_t len, targetlen;
2026 if (PyUnicode_READY(string) == -1)
2027 return NULL;
2028 kind = PyUnicode_KIND(string);
2029 data = PyUnicode_DATA(string);
2030 len = PyUnicode_GET_LENGTH(string);
2031 targetlen = len;
2032 if (copy_null)
2033 targetlen++;
2034 if (!target) {
2035 if (PY_SSIZE_T_MAX / sizeof(Py_UCS4) < targetlen) {
2036 PyErr_NoMemory();
2037 return NULL;
2038 }
2039 target = PyMem_Malloc(targetlen * sizeof(Py_UCS4));
2040 if (!target) {
2041 PyErr_NoMemory();
2042 return NULL;
2043 }
2044 }
2045 else {
2046 if (targetsize < targetlen) {
2047 PyErr_Format(PyExc_SystemError,
2048 "string is longer than the buffer");
2049 if (copy_null && 0 < targetsize)
2050 target[0] = 0;
2051 return NULL;
2052 }
2053 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002054 if (kind == PyUnicode_1BYTE_KIND) {
2055 Py_UCS1 *start = (Py_UCS1 *) data;
2056 _PyUnicode_CONVERT_BYTES(Py_UCS1, Py_UCS4, start, start + len, target);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002057 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002058 else if (kind == PyUnicode_2BYTE_KIND) {
2059 Py_UCS2 *start = (Py_UCS2 *) data;
2060 _PyUnicode_CONVERT_BYTES(Py_UCS2, Py_UCS4, start, start + len, target);
2061 }
2062 else {
2063 assert(kind == PyUnicode_4BYTE_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002064 Py_MEMCPY(target, data, len * sizeof(Py_UCS4));
Antoine Pitrou950468e2011-10-11 22:45:48 +02002065 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002066 if (copy_null)
2067 target[len] = 0;
2068 return target;
2069}
2070
2071Py_UCS4*
2072PyUnicode_AsUCS4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2073 int copy_null)
2074{
Antoine Pitroude20b0b2011-11-10 21:47:38 +01002075 if (target == NULL || targetsize < 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002076 PyErr_BadInternalCall();
2077 return NULL;
2078 }
2079 return as_ucs4(string, target, targetsize, copy_null);
2080}
2081
2082Py_UCS4*
2083PyUnicode_AsUCS4Copy(PyObject *string)
2084{
2085 return as_ucs4(string, NULL, 0, 1);
2086}
2087
2088#ifdef HAVE_WCHAR_H
Mark Dickinson081dfee2009-03-18 14:47:41 +00002089
Alexander Belopolsky40018472011-02-26 01:02:56 +00002090PyObject *
2091PyUnicode_FromWideChar(register const wchar_t *w, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002092{
Guido van Rossumd57fd912000-03-10 22:53:23 +00002093 if (w == NULL) {
Martin v. Löwis790465f2008-04-05 20:41:37 +00002094 if (size == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002095 return PyUnicode_New(0, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +00002096 PyErr_BadInternalCall();
2097 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002098 }
2099
Martin v. Löwis790465f2008-04-05 20:41:37 +00002100 if (size == -1) {
2101 size = wcslen(w);
2102 }
2103
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002104 return PyUnicode_FromUnicode(w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002105}
2106
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002107#endif /* HAVE_WCHAR_H */
Mark Dickinson081dfee2009-03-18 14:47:41 +00002108
Walter Dörwald346737f2007-05-31 10:44:43 +00002109static void
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002110makefmt(char *fmt, int longflag, int longlongflag, int size_tflag,
2111 int zeropad, int width, int precision, char c)
Walter Dörwald346737f2007-05-31 10:44:43 +00002112{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002113 *fmt++ = '%';
2114 if (width) {
2115 if (zeropad)
2116 *fmt++ = '0';
2117 fmt += sprintf(fmt, "%d", width);
2118 }
2119 if (precision)
2120 fmt += sprintf(fmt, ".%d", precision);
2121 if (longflag)
2122 *fmt++ = 'l';
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002123 else if (longlongflag) {
2124 /* longlongflag should only ever be nonzero on machines with
2125 HAVE_LONG_LONG defined */
2126#ifdef HAVE_LONG_LONG
2127 char *f = PY_FORMAT_LONG_LONG;
2128 while (*f)
2129 *fmt++ = *f++;
2130#else
2131 /* we shouldn't ever get here */
2132 assert(0);
2133 *fmt++ = 'l';
2134#endif
2135 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002136 else if (size_tflag) {
2137 char *f = PY_FORMAT_SIZE_T;
2138 while (*f)
2139 *fmt++ = *f++;
2140 }
2141 *fmt++ = c;
2142 *fmt = '\0';
Walter Dörwald346737f2007-05-31 10:44:43 +00002143}
2144
Victor Stinner96865452011-03-01 23:44:09 +00002145/* helper for PyUnicode_FromFormatV() */
2146
2147static const char*
2148parse_format_flags(const char *f,
2149 int *p_width, int *p_precision,
2150 int *p_longflag, int *p_longlongflag, int *p_size_tflag)
2151{
2152 int width, precision, longflag, longlongflag, size_tflag;
2153
2154 /* parse the width.precision part, e.g. "%2.5s" => width=2, precision=5 */
2155 f++;
2156 width = 0;
2157 while (Py_ISDIGIT((unsigned)*f))
2158 width = (width*10) + *f++ - '0';
2159 precision = 0;
2160 if (*f == '.') {
2161 f++;
2162 while (Py_ISDIGIT((unsigned)*f))
2163 precision = (precision*10) + *f++ - '0';
2164 if (*f == '%') {
2165 /* "%.3%s" => f points to "3" */
2166 f--;
2167 }
2168 }
2169 if (*f == '\0') {
2170 /* bogus format "%.1" => go backward, f points to "1" */
2171 f--;
2172 }
2173 if (p_width != NULL)
2174 *p_width = width;
2175 if (p_precision != NULL)
2176 *p_precision = precision;
2177
2178 /* Handle %ld, %lu, %lld and %llu. */
2179 longflag = 0;
2180 longlongflag = 0;
Victor Stinnere7faec12011-03-02 00:01:53 +00002181 size_tflag = 0;
Victor Stinner96865452011-03-01 23:44:09 +00002182
2183 if (*f == 'l') {
Victor Stinner6d970f42011-03-02 00:04:25 +00002184 if (f[1] == 'd' || f[1] == 'u' || f[1] == 'i') {
Victor Stinner96865452011-03-01 23:44:09 +00002185 longflag = 1;
2186 ++f;
2187 }
2188#ifdef HAVE_LONG_LONG
2189 else if (f[1] == 'l' &&
Victor Stinner6d970f42011-03-02 00:04:25 +00002190 (f[2] == 'd' || f[2] == 'u' || f[2] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002191 longlongflag = 1;
2192 f += 2;
2193 }
2194#endif
2195 }
2196 /* handle the size_t flag. */
Victor Stinner6d970f42011-03-02 00:04:25 +00002197 else if (*f == 'z' && (f[1] == 'd' || f[1] == 'u' || f[1] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002198 size_tflag = 1;
2199 ++f;
2200 }
2201 if (p_longflag != NULL)
2202 *p_longflag = longflag;
2203 if (p_longlongflag != NULL)
2204 *p_longlongflag = longlongflag;
2205 if (p_size_tflag != NULL)
2206 *p_size_tflag = size_tflag;
2207 return f;
2208}
2209
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002210/* maximum number of characters required for output of %ld. 21 characters
2211 allows for 64-bit integers (in decimal) and an optional sign. */
2212#define MAX_LONG_CHARS 21
2213/* maximum number of characters required for output of %lld.
2214 We need at most ceil(log10(256)*SIZEOF_LONG_LONG) digits,
2215 plus 1 for the sign. 53/22 is an upper bound for log10(256). */
2216#define MAX_LONG_LONG_CHARS (2 + (SIZEOF_LONG_LONG*53-1) / 22)
2217
Walter Dörwaldd2034312007-05-18 16:29:38 +00002218PyObject *
2219PyUnicode_FromFormatV(const char *format, va_list vargs)
2220{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002221 va_list count;
2222 Py_ssize_t callcount = 0;
2223 PyObject **callresults = NULL;
2224 PyObject **callresult = NULL;
2225 Py_ssize_t n = 0;
2226 int width = 0;
2227 int precision = 0;
2228 int zeropad;
2229 const char* f;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002230 PyObject *string;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002231 /* used by sprintf */
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002232 char fmt[61]; /* should be enough for %0width.precisionlld */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002233 Py_UCS4 maxchar = 127; /* result is ASCII by default */
2234 Py_UCS4 argmaxchar;
2235 Py_ssize_t numbersize = 0;
2236 char *numberresults = NULL;
2237 char *numberresult = NULL;
2238 Py_ssize_t i;
2239 int kind;
2240 void *data;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002241
Victor Stinner4a2b7a12010-08-13 14:03:48 +00002242 Py_VA_COPY(count, vargs);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002243 /* step 1: count the number of %S/%R/%A/%s format specifications
2244 * (we call PyObject_Str()/PyObject_Repr()/PyObject_ASCII()/
2245 * PyUnicode_DecodeUTF8() for these objects once during step 3 and put the
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002246 * result in an array)
Georg Brandl7597add2011-10-05 16:36:47 +02002247 * also estimate a upper bound for all the number formats in the string,
2248 * numbers will be formatted in step 3 and be kept in a '\0'-separated
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002249 * buffer before putting everything together. */
Benjamin Peterson14339b62009-01-31 16:36:08 +00002250 for (f = format; *f; f++) {
2251 if (*f == '%') {
Victor Stinner96865452011-03-01 23:44:09 +00002252 int longlongflag;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002253 /* skip width or width.precision (eg. "1.2" of "%1.2f") */
2254 f = parse_format_flags(f, &width, NULL, NULL, &longlongflag, NULL);
2255 if (*f == 's' || *f=='S' || *f=='R' || *f=='A' || *f=='V')
2256 ++callcount;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002257
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002258 else if (*f == 'd' || *f=='u' || *f=='i' || *f=='x' || *f=='p') {
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002259#ifdef HAVE_LONG_LONG
2260 if (longlongflag) {
2261 if (width < MAX_LONG_LONG_CHARS)
2262 width = MAX_LONG_LONG_CHARS;
2263 }
2264 else
2265#endif
2266 /* MAX_LONG_CHARS is enough to hold a 64-bit integer,
2267 including sign. Decimal takes the most space. This
2268 isn't enough for octal. If a width is specified we
2269 need more (which we allocate later). */
2270 if (width < MAX_LONG_CHARS)
2271 width = MAX_LONG_CHARS;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002272
2273 /* account for the size + '\0' to separate numbers
2274 inside of the numberresults buffer */
2275 numbersize += (width + 1);
2276 }
2277 }
2278 else if ((unsigned char)*f > 127) {
2279 PyErr_Format(PyExc_ValueError,
2280 "PyUnicode_FromFormatV() expects an ASCII-encoded format "
2281 "string, got a non-ASCII byte: 0x%02x",
2282 (unsigned char)*f);
2283 return NULL;
2284 }
2285 }
2286 /* step 2: allocate memory for the results of
2287 * PyObject_Str()/PyObject_Repr()/PyUnicode_DecodeUTF8() calls */
2288 if (callcount) {
2289 callresults = PyObject_Malloc(sizeof(PyObject *) * callcount);
2290 if (!callresults) {
2291 PyErr_NoMemory();
2292 return NULL;
2293 }
2294 callresult = callresults;
2295 }
2296 /* step 2.5: allocate memory for the results of formating numbers */
2297 if (numbersize) {
2298 numberresults = PyObject_Malloc(numbersize);
2299 if (!numberresults) {
2300 PyErr_NoMemory();
2301 goto fail;
2302 }
2303 numberresult = numberresults;
2304 }
2305
2306 /* step 3: format numbers and figure out how large a buffer we need */
2307 for (f = format; *f; f++) {
2308 if (*f == '%') {
2309 const char* p;
2310 int longflag;
2311 int longlongflag;
2312 int size_tflag;
2313 int numprinted;
2314
2315 p = f;
2316 zeropad = (f[1] == '0');
2317 f = parse_format_flags(f, &width, &precision,
2318 &longflag, &longlongflag, &size_tflag);
2319 switch (*f) {
2320 case 'c':
2321 {
2322 Py_UCS4 ordinal = va_arg(count, int);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002323 maxchar = Py_MAX(maxchar, ordinal);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002324 n++;
2325 break;
2326 }
2327 case '%':
2328 n++;
2329 break;
2330 case 'i':
2331 case 'd':
2332 makefmt(fmt, longflag, longlongflag, size_tflag, zeropad,
2333 width, precision, *f);
2334 if (longflag)
2335 numprinted = sprintf(numberresult, fmt,
2336 va_arg(count, long));
2337#ifdef HAVE_LONG_LONG
2338 else if (longlongflag)
2339 numprinted = sprintf(numberresult, fmt,
2340 va_arg(count, PY_LONG_LONG));
2341#endif
2342 else if (size_tflag)
2343 numprinted = sprintf(numberresult, fmt,
2344 va_arg(count, Py_ssize_t));
2345 else
2346 numprinted = sprintf(numberresult, fmt,
2347 va_arg(count, int));
2348 n += numprinted;
2349 /* advance by +1 to skip over the '\0' */
2350 numberresult += (numprinted + 1);
2351 assert(*(numberresult - 1) == '\0');
2352 assert(*(numberresult - 2) != '\0');
2353 assert(numprinted >= 0);
2354 assert(numberresult <= numberresults + numbersize);
2355 break;
2356 case 'u':
2357 makefmt(fmt, longflag, longlongflag, size_tflag, zeropad,
2358 width, precision, 'u');
2359 if (longflag)
2360 numprinted = sprintf(numberresult, fmt,
2361 va_arg(count, unsigned long));
2362#ifdef HAVE_LONG_LONG
2363 else if (longlongflag)
2364 numprinted = sprintf(numberresult, fmt,
2365 va_arg(count, unsigned PY_LONG_LONG));
2366#endif
2367 else if (size_tflag)
2368 numprinted = sprintf(numberresult, fmt,
2369 va_arg(count, size_t));
2370 else
2371 numprinted = sprintf(numberresult, fmt,
2372 va_arg(count, unsigned int));
2373 n += numprinted;
2374 numberresult += (numprinted + 1);
2375 assert(*(numberresult - 1) == '\0');
2376 assert(*(numberresult - 2) != '\0');
2377 assert(numprinted >= 0);
2378 assert(numberresult <= numberresults + numbersize);
2379 break;
2380 case 'x':
2381 makefmt(fmt, 0, 0, 0, zeropad, width, precision, 'x');
2382 numprinted = sprintf(numberresult, fmt, va_arg(count, int));
2383 n += numprinted;
2384 numberresult += (numprinted + 1);
2385 assert(*(numberresult - 1) == '\0');
2386 assert(*(numberresult - 2) != '\0');
2387 assert(numprinted >= 0);
2388 assert(numberresult <= numberresults + numbersize);
2389 break;
2390 case 'p':
2391 numprinted = sprintf(numberresult, "%p", va_arg(count, void*));
2392 /* %p is ill-defined: ensure leading 0x. */
2393 if (numberresult[1] == 'X')
2394 numberresult[1] = 'x';
2395 else if (numberresult[1] != 'x') {
2396 memmove(numberresult + 2, numberresult,
2397 strlen(numberresult) + 1);
2398 numberresult[0] = '0';
2399 numberresult[1] = 'x';
2400 numprinted += 2;
2401 }
2402 n += numprinted;
2403 numberresult += (numprinted + 1);
2404 assert(*(numberresult - 1) == '\0');
2405 assert(*(numberresult - 2) != '\0');
2406 assert(numprinted >= 0);
2407 assert(numberresult <= numberresults + numbersize);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002408 break;
2409 case 's':
2410 {
2411 /* UTF-8 */
Georg Brandl780b2a62009-05-05 09:19:59 +00002412 const char *s = va_arg(count, const char*);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002413 PyObject *str = PyUnicode_DecodeUTF8(s, strlen(s), "replace");
2414 if (!str)
2415 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002416 /* since PyUnicode_DecodeUTF8 returns already flexible
2417 unicode objects, there is no need to call ready on them */
2418 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002419 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002420 n += PyUnicode_GET_LENGTH(str);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002421 /* Remember the str and switch to the next slot */
2422 *callresult++ = str;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002423 break;
2424 }
2425 case 'U':
2426 {
2427 PyObject *obj = va_arg(count, PyObject *);
Victor Stinner910337b2011-10-03 03:20:16 +02002428 assert(obj && _PyUnicode_CHECK(obj));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002429 if (PyUnicode_READY(obj) == -1)
2430 goto fail;
2431 argmaxchar = PyUnicode_MAX_CHAR_VALUE(obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002432 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002433 n += PyUnicode_GET_LENGTH(obj);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002434 break;
2435 }
2436 case 'V':
2437 {
2438 PyObject *obj = va_arg(count, PyObject *);
2439 const char *str = va_arg(count, const char *);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002440 PyObject *str_obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002441 assert(obj || str);
Victor Stinner910337b2011-10-03 03:20:16 +02002442 assert(!obj || _PyUnicode_CHECK(obj));
Victor Stinner2512a8b2011-03-01 22:46:52 +00002443 if (obj) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002444 if (PyUnicode_READY(obj) == -1)
2445 goto fail;
2446 argmaxchar = PyUnicode_MAX_CHAR_VALUE(obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002447 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002448 n += PyUnicode_GET_LENGTH(obj);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002449 *callresult++ = NULL;
2450 }
2451 else {
2452 str_obj = PyUnicode_DecodeUTF8(str, strlen(str), "replace");
2453 if (!str_obj)
2454 goto fail;
Victor Stinnere1335c72011-10-04 20:53:03 +02002455 if (PyUnicode_READY(str_obj)) {
2456 Py_DECREF(str_obj);
2457 goto fail;
2458 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002459 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str_obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002460 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002461 n += PyUnicode_GET_LENGTH(str_obj);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002462 *callresult++ = str_obj;
2463 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002464 break;
2465 }
2466 case 'S':
2467 {
2468 PyObject *obj = va_arg(count, PyObject *);
2469 PyObject *str;
2470 assert(obj);
2471 str = PyObject_Str(obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002472 if (!str || PyUnicode_READY(str) == -1)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002473 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002474 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002475 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002476 n += PyUnicode_GET_LENGTH(str);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002477 /* Remember the str and switch to the next slot */
2478 *callresult++ = str;
2479 break;
2480 }
2481 case 'R':
2482 {
2483 PyObject *obj = va_arg(count, PyObject *);
2484 PyObject *repr;
2485 assert(obj);
2486 repr = PyObject_Repr(obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002487 if (!repr || PyUnicode_READY(repr) == -1)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002488 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002489 argmaxchar = PyUnicode_MAX_CHAR_VALUE(repr);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002490 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002491 n += PyUnicode_GET_LENGTH(repr);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002492 /* Remember the repr and switch to the next slot */
2493 *callresult++ = repr;
2494 break;
2495 }
2496 case 'A':
2497 {
2498 PyObject *obj = va_arg(count, PyObject *);
2499 PyObject *ascii;
2500 assert(obj);
2501 ascii = PyObject_ASCII(obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002502 if (!ascii || PyUnicode_READY(ascii) == -1)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002503 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002504 argmaxchar = PyUnicode_MAX_CHAR_VALUE(ascii);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002505 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002506 n += PyUnicode_GET_LENGTH(ascii);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002507 /* Remember the repr and switch to the next slot */
2508 *callresult++ = ascii;
2509 break;
2510 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002511 default:
2512 /* if we stumble upon an unknown
2513 formatting code, copy the rest of
2514 the format string to the output
2515 string. (we cannot just skip the
2516 code, since there's no way to know
2517 what's in the argument list) */
2518 n += strlen(p);
2519 goto expand;
2520 }
2521 } else
2522 n++;
2523 }
Benjamin Peterson29060642009-01-31 22:14:21 +00002524 expand:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002525 /* step 4: fill the buffer */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002526 /* Since we've analyzed how much space we need,
Benjamin Peterson14339b62009-01-31 16:36:08 +00002527 we don't have to resize the string.
2528 There can be no errors beyond this point. */
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002529 string = PyUnicode_New(n, maxchar);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002530 if (!string)
2531 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002532 kind = PyUnicode_KIND(string);
2533 data = PyUnicode_DATA(string);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002534 callresult = callresults;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002535 numberresult = numberresults;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002536
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002537 for (i = 0, f = format; *f; f++) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00002538 if (*f == '%') {
Victor Stinner96865452011-03-01 23:44:09 +00002539 const char* p;
Victor Stinner96865452011-03-01 23:44:09 +00002540
2541 p = f;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002542 f = parse_format_flags(f, NULL, NULL, NULL, NULL, NULL);
2543 /* checking for == because the last argument could be a empty
2544 string, which causes i to point to end, the assert at the end of
2545 the loop */
2546 assert(i <= PyUnicode_GET_LENGTH(string));
Walter Dörwaldd2034312007-05-18 16:29:38 +00002547
Benjamin Peterson14339b62009-01-31 16:36:08 +00002548 switch (*f) {
2549 case 'c':
Victor Stinner5ed8b2c2011-02-21 21:13:44 +00002550 {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002551 const int ordinal = va_arg(vargs, int);
2552 PyUnicode_WRITE(kind, data, i++, ordinal);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002553 break;
Victor Stinner5ed8b2c2011-02-21 21:13:44 +00002554 }
Victor Stinner6d970f42011-03-02 00:04:25 +00002555 case 'i':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002556 case 'd':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002557 case 'u':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002558 case 'x':
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002559 case 'p':
2560 /* unused, since we already have the result */
2561 if (*f == 'p')
2562 (void) va_arg(vargs, void *);
2563 else
2564 (void) va_arg(vargs, int);
2565 /* extract the result from numberresults and append. */
2566 for (; *numberresult; ++i, ++numberresult)
2567 PyUnicode_WRITE(kind, data, i, *numberresult);
2568 /* skip over the separating '\0' */
2569 assert(*numberresult == '\0');
2570 numberresult++;
2571 assert(numberresult <= numberresults + numbersize);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002572 break;
2573 case 's':
2574 {
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002575 /* unused, since we already have the result */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002576 Py_ssize_t size;
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002577 (void) va_arg(vargs, char *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002578 size = PyUnicode_GET_LENGTH(*callresult);
2579 assert(PyUnicode_KIND(*callresult) <= PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002580 copy_characters(string, i, *callresult, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002581 i += size;
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002582 /* We're done with the unicode()/repr() => forget it */
2583 Py_DECREF(*callresult);
2584 /* switch to next unicode()/repr() result */
2585 ++callresult;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002586 break;
2587 }
2588 case 'U':
2589 {
2590 PyObject *obj = va_arg(vargs, PyObject *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002591 Py_ssize_t size;
2592 assert(PyUnicode_KIND(obj) <= PyUnicode_KIND(string));
2593 size = PyUnicode_GET_LENGTH(obj);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002594 copy_characters(string, i, obj, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002595 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002596 break;
2597 }
2598 case 'V':
2599 {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002600 Py_ssize_t size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002601 PyObject *obj = va_arg(vargs, PyObject *);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002602 va_arg(vargs, const char *);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002603 if (obj) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002604 size = PyUnicode_GET_LENGTH(obj);
2605 assert(PyUnicode_KIND(obj) <= PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002606 copy_characters(string, i, obj, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002607 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002608 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002609 size = PyUnicode_GET_LENGTH(*callresult);
2610 assert(PyUnicode_KIND(*callresult) <=
2611 PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002612 copy_characters(string, i, *callresult, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002613 i += size;
Victor Stinner2512a8b2011-03-01 22:46:52 +00002614 Py_DECREF(*callresult);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002615 }
Victor Stinner2512a8b2011-03-01 22:46:52 +00002616 ++callresult;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002617 break;
2618 }
2619 case 'S':
2620 case 'R':
Victor Stinner9a909002010-10-18 20:59:24 +00002621 case 'A':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002622 {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002623 Py_ssize_t size = PyUnicode_GET_LENGTH(*callresult);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002624 /* unused, since we already have the result */
2625 (void) va_arg(vargs, PyObject *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002626 assert(PyUnicode_KIND(*callresult) <= PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002627 copy_characters(string, i, *callresult, 0, size);
2628 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002629 /* We're done with the unicode()/repr() => forget it */
2630 Py_DECREF(*callresult);
2631 /* switch to next unicode()/repr() result */
2632 ++callresult;
2633 break;
2634 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002635 case '%':
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002636 PyUnicode_WRITE(kind, data, i++, '%');
Benjamin Peterson14339b62009-01-31 16:36:08 +00002637 break;
2638 default:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002639 for (; *p; ++p, ++i)
2640 PyUnicode_WRITE(kind, data, i, *p);
2641 assert(i == PyUnicode_GET_LENGTH(string));
Benjamin Peterson14339b62009-01-31 16:36:08 +00002642 goto end;
2643 }
Victor Stinner1205f272010-09-11 00:54:47 +00002644 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002645 else {
2646 assert(i < PyUnicode_GET_LENGTH(string));
2647 PyUnicode_WRITE(kind, data, i++, *f);
2648 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002649 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002650 assert(i == PyUnicode_GET_LENGTH(string));
Walter Dörwaldd2034312007-05-18 16:29:38 +00002651
Benjamin Peterson29060642009-01-31 22:14:21 +00002652 end:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002653 if (callresults)
2654 PyObject_Free(callresults);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002655 if (numberresults)
2656 PyObject_Free(numberresults);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002657 assert(_PyUnicode_CheckConsistency(string, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01002658 return string;
Benjamin Peterson29060642009-01-31 22:14:21 +00002659 fail:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002660 if (callresults) {
2661 PyObject **callresult2 = callresults;
2662 while (callresult2 < callresult) {
Victor Stinner2512a8b2011-03-01 22:46:52 +00002663 Py_XDECREF(*callresult2);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002664 ++callresult2;
2665 }
2666 PyObject_Free(callresults);
2667 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002668 if (numberresults)
2669 PyObject_Free(numberresults);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002670 return NULL;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002671}
2672
Walter Dörwaldd2034312007-05-18 16:29:38 +00002673PyObject *
2674PyUnicode_FromFormat(const char *format, ...)
2675{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002676 PyObject* ret;
2677 va_list vargs;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002678
2679#ifdef HAVE_STDARG_PROTOTYPES
Benjamin Peterson14339b62009-01-31 16:36:08 +00002680 va_start(vargs, format);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002681#else
Benjamin Peterson14339b62009-01-31 16:36:08 +00002682 va_start(vargs);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002683#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00002684 ret = PyUnicode_FromFormatV(format, vargs);
2685 va_end(vargs);
2686 return ret;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002687}
2688
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002689#ifdef HAVE_WCHAR_H
2690
Victor Stinner5593d8a2010-10-02 11:11:27 +00002691/* Helper function for PyUnicode_AsWideChar() and PyUnicode_AsWideCharString():
2692 convert a Unicode object to a wide character string.
2693
Victor Stinnerd88d9832011-09-06 02:00:05 +02002694 - If w is NULL: return the number of wide characters (including the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002695 character) required to convert the unicode object. Ignore size argument.
2696
Victor Stinnerd88d9832011-09-06 02:00:05 +02002697 - Otherwise: return the number of wide characters (excluding the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002698 character) written into w. Write at most size wide characters (including
Victor Stinnerd88d9832011-09-06 02:00:05 +02002699 the null character). */
Victor Stinner5593d8a2010-10-02 11:11:27 +00002700static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002701unicode_aswidechar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002702 wchar_t *w,
2703 Py_ssize_t size)
2704{
Victor Stinner5593d8a2010-10-02 11:11:27 +00002705 Py_ssize_t res;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002706 const wchar_t *wstr;
2707
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002708 wstr = PyUnicode_AsUnicodeAndSize(unicode, &res);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002709 if (wstr == NULL)
2710 return -1;
2711
Victor Stinner5593d8a2010-10-02 11:11:27 +00002712 if (w != NULL) {
Victor Stinner5593d8a2010-10-02 11:11:27 +00002713 if (size > res)
2714 size = res + 1;
2715 else
2716 res = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002717 Py_MEMCPY(w, wstr, size * sizeof(wchar_t));
Victor Stinner5593d8a2010-10-02 11:11:27 +00002718 return res;
2719 }
2720 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002721 return res + 1;
Victor Stinner137c34c2010-09-29 10:25:54 +00002722}
2723
2724Py_ssize_t
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002725PyUnicode_AsWideChar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002726 wchar_t *w,
2727 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002728{
2729 if (unicode == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002730 PyErr_BadInternalCall();
2731 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002732 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002733 return unicode_aswidechar(unicode, w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002734}
2735
Victor Stinner137c34c2010-09-29 10:25:54 +00002736wchar_t*
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00002737PyUnicode_AsWideCharString(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002738 Py_ssize_t *size)
2739{
2740 wchar_t* buffer;
2741 Py_ssize_t buflen;
2742
2743 if (unicode == NULL) {
2744 PyErr_BadInternalCall();
2745 return NULL;
2746 }
2747
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002748 buflen = unicode_aswidechar(unicode, NULL, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002749 if (buflen == -1)
2750 return NULL;
Victor Stinner5593d8a2010-10-02 11:11:27 +00002751 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < buflen) {
Victor Stinner137c34c2010-09-29 10:25:54 +00002752 PyErr_NoMemory();
2753 return NULL;
2754 }
2755
Victor Stinner137c34c2010-09-29 10:25:54 +00002756 buffer = PyMem_MALLOC(buflen * sizeof(wchar_t));
2757 if (buffer == NULL) {
2758 PyErr_NoMemory();
2759 return NULL;
2760 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002761 buflen = unicode_aswidechar(unicode, buffer, buflen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002762 if (buflen == -1)
2763 return NULL;
Victor Stinner5593d8a2010-10-02 11:11:27 +00002764 if (size != NULL)
2765 *size = buflen;
Victor Stinner137c34c2010-09-29 10:25:54 +00002766 return buffer;
2767}
2768
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002769#endif /* HAVE_WCHAR_H */
Guido van Rossumd57fd912000-03-10 22:53:23 +00002770
Alexander Belopolsky40018472011-02-26 01:02:56 +00002771PyObject *
2772PyUnicode_FromOrdinal(int ordinal)
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002773{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002774 PyObject *v;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002775 if (ordinal < 0 || ordinal > 0x10ffff) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002776 PyErr_SetString(PyExc_ValueError,
2777 "chr() arg not in range(0x110000)");
2778 return NULL;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002779 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00002780
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002781 if (ordinal < 256)
2782 return get_latin1_char(ordinal);
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002783
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002784 v = PyUnicode_New(1, ordinal);
2785 if (v == NULL)
2786 return NULL;
2787 PyUnicode_WRITE(PyUnicode_KIND(v), PyUnicode_DATA(v), 0, ordinal);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002788 assert(_PyUnicode_CheckConsistency(v, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002789 return v;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002790}
2791
Alexander Belopolsky40018472011-02-26 01:02:56 +00002792PyObject *
2793PyUnicode_FromObject(register PyObject *obj)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002794{
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002795 /* XXX Perhaps we should make this API an alias of
Benjamin Peterson29060642009-01-31 22:14:21 +00002796 PyObject_Str() instead ?! */
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002797 if (PyUnicode_CheckExact(obj)) {
Victor Stinnerd3a83d52011-10-01 03:09:33 +02002798 if (PyUnicode_READY(obj))
2799 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +00002800 Py_INCREF(obj);
2801 return obj;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002802 }
2803 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002804 /* For a Unicode subtype that's not a Unicode object,
2805 return a true Unicode object with the same data. */
Victor Stinner2219e0a2011-10-01 01:16:59 +02002806 return PyUnicode_Copy(obj);
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002807 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00002808 PyErr_Format(PyExc_TypeError,
2809 "Can't convert '%.100s' object to str implicitly",
Christian Heimes90aa7642007-12-19 02:45:37 +00002810 Py_TYPE(obj)->tp_name);
Guido van Rossum98297ee2007-11-06 21:34:58 +00002811 return NULL;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002812}
2813
Alexander Belopolsky40018472011-02-26 01:02:56 +00002814PyObject *
2815PyUnicode_FromEncodedObject(register PyObject *obj,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002816 const char *encoding,
2817 const char *errors)
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002818{
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002819 Py_buffer buffer;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002820 PyObject *v;
Tim Petersced69f82003-09-16 20:30:58 +00002821
Guido van Rossumd57fd912000-03-10 22:53:23 +00002822 if (obj == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002823 PyErr_BadInternalCall();
2824 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002825 }
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002826
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002827 /* Decoding bytes objects is the most common case and should be fast */
2828 if (PyBytes_Check(obj)) {
2829 if (PyBytes_GET_SIZE(obj) == 0) {
2830 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02002831 v = unicode_empty;
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002832 }
2833 else {
2834 v = PyUnicode_Decode(
2835 PyBytes_AS_STRING(obj), PyBytes_GET_SIZE(obj),
2836 encoding, errors);
2837 }
2838 return v;
2839 }
2840
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002841 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002842 PyErr_SetString(PyExc_TypeError,
2843 "decoding str is not supported");
2844 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002845 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002846
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002847 /* Retrieve a bytes buffer view through the PEP 3118 buffer interface */
2848 if (PyObject_GetBuffer(obj, &buffer, PyBUF_SIMPLE) < 0) {
2849 PyErr_Format(PyExc_TypeError,
2850 "coercing to str: need bytes, bytearray "
2851 "or buffer-like object, %.80s found",
2852 Py_TYPE(obj)->tp_name);
2853 return NULL;
Marc-André Lemburg6871f6a2001-09-20 12:53:16 +00002854 }
Tim Petersced69f82003-09-16 20:30:58 +00002855
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002856 if (buffer.len == 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002857 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02002858 v = unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002859 }
Tim Petersced69f82003-09-16 20:30:58 +00002860 else
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002861 v = PyUnicode_Decode((char*) buffer.buf, buffer.len, encoding, errors);
Marc-André Lemburgad7c98e2001-01-17 17:09:53 +00002862
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002863 PyBuffer_Release(&buffer);
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002864 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002865}
2866
Victor Stinner600d3be2010-06-10 12:00:55 +00002867/* Convert encoding to lower case and replace '_' with '-' in order to
Victor Stinner37296e82010-06-10 13:36:23 +00002868 catch e.g. UTF_8. Return 0 on error (encoding is longer than lower_len-1),
2869 1 on success. */
2870static int
2871normalize_encoding(const char *encoding,
2872 char *lower,
2873 size_t lower_len)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002874{
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002875 const char *e;
Victor Stinner600d3be2010-06-10 12:00:55 +00002876 char *l;
2877 char *l_end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002878
Benjamin Peterson7a6debe2011-10-15 09:25:28 -04002879 if (encoding == NULL) {
2880 strcpy(lower, "utf-8");
2881 return 1;
2882 }
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002883 e = encoding;
2884 l = lower;
Victor Stinner600d3be2010-06-10 12:00:55 +00002885 l_end = &lower[lower_len - 1];
Victor Stinner37296e82010-06-10 13:36:23 +00002886 while (*e) {
2887 if (l == l_end)
2888 return 0;
David Malcolm96960882010-11-05 17:23:41 +00002889 if (Py_ISUPPER(*e)) {
2890 *l++ = Py_TOLOWER(*e++);
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002891 }
2892 else if (*e == '_') {
2893 *l++ = '-';
2894 e++;
2895 }
2896 else {
2897 *l++ = *e++;
2898 }
2899 }
2900 *l = '\0';
Victor Stinner37296e82010-06-10 13:36:23 +00002901 return 1;
Victor Stinner600d3be2010-06-10 12:00:55 +00002902}
2903
Alexander Belopolsky40018472011-02-26 01:02:56 +00002904PyObject *
2905PyUnicode_Decode(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002906 Py_ssize_t size,
2907 const char *encoding,
2908 const char *errors)
Victor Stinner600d3be2010-06-10 12:00:55 +00002909{
2910 PyObject *buffer = NULL, *unicode;
2911 Py_buffer info;
2912 char lower[11]; /* Enough for any encoding shortcut */
2913
Fred Drakee4315f52000-05-09 19:53:39 +00002914 /* Shortcuts for common default encodings */
Victor Stinner37296e82010-06-10 13:36:23 +00002915 if (normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00002916 if ((strcmp(lower, "utf-8") == 0) ||
2917 (strcmp(lower, "utf8") == 0))
Victor Stinner37296e82010-06-10 13:36:23 +00002918 return PyUnicode_DecodeUTF8(s, size, errors);
2919 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00002920 (strcmp(lower, "latin1") == 0) ||
Victor Stinner37296e82010-06-10 13:36:23 +00002921 (strcmp(lower, "iso-8859-1") == 0))
2922 return PyUnicode_DecodeLatin1(s, size, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02002923#ifdef HAVE_MBCS
Victor Stinner37296e82010-06-10 13:36:23 +00002924 else if (strcmp(lower, "mbcs") == 0)
2925 return PyUnicode_DecodeMBCS(s, size, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00002926#endif
Victor Stinner37296e82010-06-10 13:36:23 +00002927 else if (strcmp(lower, "ascii") == 0)
2928 return PyUnicode_DecodeASCII(s, size, errors);
2929 else if (strcmp(lower, "utf-16") == 0)
2930 return PyUnicode_DecodeUTF16(s, size, errors, 0);
2931 else if (strcmp(lower, "utf-32") == 0)
2932 return PyUnicode_DecodeUTF32(s, size, errors, 0);
2933 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002934
2935 /* Decode via the codec registry */
Guido van Rossumbe801ac2007-10-08 03:32:34 +00002936 buffer = NULL;
Antoine Pitrouc3b39242009-01-03 16:59:18 +00002937 if (PyBuffer_FillInfo(&info, NULL, (void *)s, size, 1, PyBUF_FULL_RO) < 0)
Guido van Rossumbe801ac2007-10-08 03:32:34 +00002938 goto onError;
Antoine Pitrouee58fa42008-08-19 18:22:14 +00002939 buffer = PyMemoryView_FromBuffer(&info);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002940 if (buffer == NULL)
2941 goto onError;
2942 unicode = PyCodec_Decode(buffer, encoding, errors);
2943 if (unicode == NULL)
2944 goto onError;
2945 if (!PyUnicode_Check(unicode)) {
2946 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00002947 "decoder did not return a str object (type=%.400s)",
Christian Heimes90aa7642007-12-19 02:45:37 +00002948 Py_TYPE(unicode)->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002949 Py_DECREF(unicode);
2950 goto onError;
2951 }
2952 Py_DECREF(buffer);
Victor Stinner17efeed2011-10-04 20:05:46 +02002953#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02002954 if (_PyUnicode_READY_REPLACE(&unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002955 Py_DECREF(unicode);
2956 return NULL;
2957 }
Victor Stinner17efeed2011-10-04 20:05:46 +02002958#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002959 assert(_PyUnicode_CheckConsistency(unicode, 1));
Guido van Rossumd57fd912000-03-10 22:53:23 +00002960 return unicode;
Tim Petersced69f82003-09-16 20:30:58 +00002961
Benjamin Peterson29060642009-01-31 22:14:21 +00002962 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00002963 Py_XDECREF(buffer);
2964 return NULL;
2965}
2966
Alexander Belopolsky40018472011-02-26 01:02:56 +00002967PyObject *
2968PyUnicode_AsDecodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002969 const char *encoding,
2970 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002971{
2972 PyObject *v;
2973
2974 if (!PyUnicode_Check(unicode)) {
2975 PyErr_BadArgument();
2976 goto onError;
2977 }
2978
2979 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00002980 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002981
2982 /* Decode via the codec registry */
2983 v = PyCodec_Decode(unicode, encoding, errors);
2984 if (v == NULL)
2985 goto onError;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002986 assert(_PyUnicode_CheckConsistency(v, 1));
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002987 return v;
2988
Benjamin Peterson29060642009-01-31 22:14:21 +00002989 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002990 return NULL;
2991}
2992
Alexander Belopolsky40018472011-02-26 01:02:56 +00002993PyObject *
2994PyUnicode_AsDecodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002995 const char *encoding,
2996 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002997{
2998 PyObject *v;
2999
3000 if (!PyUnicode_Check(unicode)) {
3001 PyErr_BadArgument();
3002 goto onError;
3003 }
3004
3005 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003006 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003007
3008 /* Decode via the codec registry */
3009 v = PyCodec_Decode(unicode, encoding, errors);
3010 if (v == NULL)
3011 goto onError;
3012 if (!PyUnicode_Check(v)) {
3013 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00003014 "decoder did not return a str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003015 Py_TYPE(v)->tp_name);
3016 Py_DECREF(v);
3017 goto onError;
3018 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02003019 assert(_PyUnicode_CheckConsistency(v, 1));
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003020 return v;
3021
Benjamin Peterson29060642009-01-31 22:14:21 +00003022 onError:
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003023 return NULL;
3024}
3025
Alexander Belopolsky40018472011-02-26 01:02:56 +00003026PyObject *
3027PyUnicode_Encode(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003028 Py_ssize_t size,
3029 const char *encoding,
3030 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003031{
3032 PyObject *v, *unicode;
Tim Petersced69f82003-09-16 20:30:58 +00003033
Guido van Rossumd57fd912000-03-10 22:53:23 +00003034 unicode = PyUnicode_FromUnicode(s, size);
3035 if (unicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003036 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003037 v = PyUnicode_AsEncodedString(unicode, encoding, errors);
3038 Py_DECREF(unicode);
3039 return v;
3040}
3041
Alexander Belopolsky40018472011-02-26 01:02:56 +00003042PyObject *
3043PyUnicode_AsEncodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003044 const char *encoding,
3045 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003046{
3047 PyObject *v;
3048
3049 if (!PyUnicode_Check(unicode)) {
3050 PyErr_BadArgument();
3051 goto onError;
3052 }
3053
3054 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003055 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003056
3057 /* Encode via the codec registry */
3058 v = PyCodec_Encode(unicode, encoding, errors);
3059 if (v == NULL)
3060 goto onError;
3061 return v;
3062
Benjamin Peterson29060642009-01-31 22:14:21 +00003063 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003064 return NULL;
3065}
3066
Victor Stinnerad158722010-10-27 00:25:46 +00003067PyObject *
3068PyUnicode_EncodeFSDefault(PyObject *unicode)
Victor Stinnerae6265f2010-05-15 16:27:27 +00003069{
Victor Stinner99b95382011-07-04 14:23:54 +02003070#ifdef HAVE_MBCS
Victor Stinnerac931b12011-11-20 18:27:03 +01003071 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003072#elif defined(__APPLE__)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003073 return _PyUnicode_AsUTF8String(unicode, "surrogateescape");
Victor Stinnerad158722010-10-27 00:25:46 +00003074#else
Victor Stinner793b5312011-04-27 00:24:21 +02003075 PyInterpreterState *interp = PyThreadState_GET()->interp;
3076 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3077 cannot use it to encode and decode filenames before it is loaded. Load
3078 the Python codec requires to encode at least its own filename. Use the C
3079 version of the locale codec until the codec registry is initialized and
3080 the Python codec is loaded.
3081
3082 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3083 cannot only rely on it: check also interp->fscodec_initialized for
3084 subinterpreters. */
3085 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Victor Stinnerae6265f2010-05-15 16:27:27 +00003086 return PyUnicode_AsEncodedString(unicode,
3087 Py_FileSystemDefaultEncoding,
3088 "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00003089 }
3090 else {
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003091 /* locale encoding with surrogateescape */
3092 wchar_t *wchar;
3093 char *bytes;
3094 PyObject *bytes_obj;
Victor Stinner2f02a512010-11-08 22:43:46 +00003095 size_t error_pos;
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003096
3097 wchar = PyUnicode_AsWideCharString(unicode, NULL);
3098 if (wchar == NULL)
3099 return NULL;
Victor Stinner2f02a512010-11-08 22:43:46 +00003100 bytes = _Py_wchar2char(wchar, &error_pos);
3101 if (bytes == NULL) {
3102 if (error_pos != (size_t)-1) {
3103 char *errmsg = strerror(errno);
3104 PyObject *exc = NULL;
3105 if (errmsg == NULL)
3106 errmsg = "Py_wchar2char() failed";
3107 raise_encode_exception(&exc,
Martin v. Löwis12be46c2011-11-04 19:04:15 +01003108 "filesystemencoding", unicode,
Victor Stinner2f02a512010-11-08 22:43:46 +00003109 error_pos, error_pos+1,
3110 errmsg);
3111 Py_XDECREF(exc);
3112 }
3113 else
3114 PyErr_NoMemory();
3115 PyMem_Free(wchar);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003116 return NULL;
Victor Stinner2f02a512010-11-08 22:43:46 +00003117 }
3118 PyMem_Free(wchar);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003119
3120 bytes_obj = PyBytes_FromString(bytes);
3121 PyMem_Free(bytes);
3122 return bytes_obj;
Victor Stinnerc39211f2010-09-29 16:35:47 +00003123 }
Victor Stinnerad158722010-10-27 00:25:46 +00003124#endif
Victor Stinnerae6265f2010-05-15 16:27:27 +00003125}
3126
Alexander Belopolsky40018472011-02-26 01:02:56 +00003127PyObject *
3128PyUnicode_AsEncodedString(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003129 const char *encoding,
3130 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003131{
3132 PyObject *v;
Victor Stinner600d3be2010-06-10 12:00:55 +00003133 char lower[11]; /* Enough for any encoding shortcut */
Tim Petersced69f82003-09-16 20:30:58 +00003134
Guido van Rossumd57fd912000-03-10 22:53:23 +00003135 if (!PyUnicode_Check(unicode)) {
3136 PyErr_BadArgument();
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003137 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003138 }
Fred Drakee4315f52000-05-09 19:53:39 +00003139
Fred Drakee4315f52000-05-09 19:53:39 +00003140 /* Shortcuts for common default encodings */
Victor Stinner37296e82010-06-10 13:36:23 +00003141 if (normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003142 if ((strcmp(lower, "utf-8") == 0) ||
3143 (strcmp(lower, "utf8") == 0))
Victor Stinnera5c68c32011-03-02 01:03:14 +00003144 {
Victor Stinner2f283c22011-03-02 01:21:46 +00003145 if (errors == NULL || strcmp(errors, "strict") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003146 return _PyUnicode_AsUTF8String(unicode, NULL);
Victor Stinner2f283c22011-03-02 01:21:46 +00003147 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003148 return _PyUnicode_AsUTF8String(unicode, errors);
Victor Stinnera5c68c32011-03-02 01:03:14 +00003149 }
Victor Stinner37296e82010-06-10 13:36:23 +00003150 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003151 (strcmp(lower, "latin1") == 0) ||
Victor Stinner37296e82010-06-10 13:36:23 +00003152 (strcmp(lower, "iso-8859-1") == 0))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003153 return _PyUnicode_AsLatin1String(unicode, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02003154#ifdef HAVE_MBCS
Victor Stinnerac931b12011-11-20 18:27:03 +01003155 else if (strcmp(lower, "mbcs") == 0)
3156 return PyUnicode_EncodeCodePage(CP_ACP, unicode, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003157#endif
Victor Stinner37296e82010-06-10 13:36:23 +00003158 else if (strcmp(lower, "ascii") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003159 return _PyUnicode_AsASCIIString(unicode, errors);
Victor Stinner37296e82010-06-10 13:36:23 +00003160 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003161
3162 /* Encode via the codec registry */
3163 v = PyCodec_Encode(unicode, encoding, errors);
3164 if (v == NULL)
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003165 return NULL;
3166
3167 /* The normal path */
3168 if (PyBytes_Check(v))
3169 return v;
3170
3171 /* If the codec returns a buffer, raise a warning and convert to bytes */
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003172 if (PyByteArray_Check(v)) {
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003173 int error;
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003174 PyObject *b;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003175
3176 error = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
3177 "encoder %s returned bytearray instead of bytes",
3178 encoding);
3179 if (error) {
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003180 Py_DECREF(v);
3181 return NULL;
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003182 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003183
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003184 b = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(v), Py_SIZE(v));
3185 Py_DECREF(v);
3186 return b;
3187 }
3188
3189 PyErr_Format(PyExc_TypeError,
3190 "encoder did not return a bytes object (type=%.400s)",
3191 Py_TYPE(v)->tp_name);
3192 Py_DECREF(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003193 return NULL;
3194}
3195
Alexander Belopolsky40018472011-02-26 01:02:56 +00003196PyObject *
3197PyUnicode_AsEncodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003198 const char *encoding,
3199 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003200{
3201 PyObject *v;
3202
3203 if (!PyUnicode_Check(unicode)) {
3204 PyErr_BadArgument();
3205 goto onError;
3206 }
3207
3208 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003209 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003210
3211 /* Encode via the codec registry */
3212 v = PyCodec_Encode(unicode, encoding, errors);
3213 if (v == NULL)
3214 goto onError;
3215 if (!PyUnicode_Check(v)) {
3216 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00003217 "encoder did not return an str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003218 Py_TYPE(v)->tp_name);
3219 Py_DECREF(v);
3220 goto onError;
3221 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003222 return v;
Tim Petersced69f82003-09-16 20:30:58 +00003223
Benjamin Peterson29060642009-01-31 22:14:21 +00003224 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003225 return NULL;
3226}
3227
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003228PyObject*
Christian Heimes5894ba72007-11-04 11:43:14 +00003229PyUnicode_DecodeFSDefault(const char *s) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003230 Py_ssize_t size = (Py_ssize_t)strlen(s);
Christian Heimes5894ba72007-11-04 11:43:14 +00003231 return PyUnicode_DecodeFSDefaultAndSize(s, size);
3232}
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003233
Christian Heimes5894ba72007-11-04 11:43:14 +00003234PyObject*
3235PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
3236{
Victor Stinner99b95382011-07-04 14:23:54 +02003237#ifdef HAVE_MBCS
Victor Stinnerad158722010-10-27 00:25:46 +00003238 return PyUnicode_DecodeMBCS(s, size, NULL);
3239#elif defined(__APPLE__)
3240 return PyUnicode_DecodeUTF8(s, size, "surrogateescape");
3241#else
Victor Stinner793b5312011-04-27 00:24:21 +02003242 PyInterpreterState *interp = PyThreadState_GET()->interp;
3243 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3244 cannot use it to encode and decode filenames before it is loaded. Load
3245 the Python codec requires to encode at least its own filename. Use the C
3246 version of the locale codec until the codec registry is initialized and
3247 the Python codec is loaded.
3248
3249 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3250 cannot only rely on it: check also interp->fscodec_initialized for
3251 subinterpreters. */
3252 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003253 return PyUnicode_Decode(s, size,
3254 Py_FileSystemDefaultEncoding,
Victor Stinnerb9a20ad2010-04-30 16:37:52 +00003255 "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003256 }
3257 else {
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003258 /* locale encoding with surrogateescape */
3259 wchar_t *wchar;
3260 PyObject *unicode;
Victor Stinner168e1172010-10-16 23:16:16 +00003261 size_t len;
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003262
3263 if (s[size] != '\0' || size != strlen(s)) {
3264 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
3265 return NULL;
3266 }
3267
Victor Stinner168e1172010-10-16 23:16:16 +00003268 wchar = _Py_char2wchar(s, &len);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003269 if (wchar == NULL)
Victor Stinnerd5af0a52010-11-08 23:34:29 +00003270 return PyErr_NoMemory();
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003271
Victor Stinner168e1172010-10-16 23:16:16 +00003272 unicode = PyUnicode_FromWideChar(wchar, len);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003273 PyMem_Free(wchar);
3274 return unicode;
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003275 }
Victor Stinnerad158722010-10-27 00:25:46 +00003276#endif
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003277}
3278
Martin v. Löwis011e8422009-05-05 04:43:17 +00003279
3280int
3281PyUnicode_FSConverter(PyObject* arg, void* addr)
3282{
3283 PyObject *output = NULL;
3284 Py_ssize_t size;
3285 void *data;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003286 if (arg == NULL) {
3287 Py_DECREF(*(PyObject**)addr);
3288 return 1;
3289 }
Victor Stinnerdcb24032010-04-22 12:08:36 +00003290 if (PyBytes_Check(arg)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00003291 output = arg;
3292 Py_INCREF(output);
3293 }
3294 else {
3295 arg = PyUnicode_FromObject(arg);
3296 if (!arg)
3297 return 0;
Victor Stinnerae6265f2010-05-15 16:27:27 +00003298 output = PyUnicode_EncodeFSDefault(arg);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003299 Py_DECREF(arg);
3300 if (!output)
3301 return 0;
3302 if (!PyBytes_Check(output)) {
3303 Py_DECREF(output);
3304 PyErr_SetString(PyExc_TypeError, "encoder failed to return bytes");
3305 return 0;
3306 }
3307 }
Victor Stinner0ea2a462010-04-30 00:22:08 +00003308 size = PyBytes_GET_SIZE(output);
3309 data = PyBytes_AS_STRING(output);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003310 if (size != strlen(data)) {
Benjamin Peterson7a6b44a2011-08-18 13:51:47 -05003311 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
Martin v. Löwis011e8422009-05-05 04:43:17 +00003312 Py_DECREF(output);
3313 return 0;
3314 }
3315 *(PyObject**)addr = output;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003316 return Py_CLEANUP_SUPPORTED;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003317}
3318
3319
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003320int
3321PyUnicode_FSDecoder(PyObject* arg, void* addr)
3322{
3323 PyObject *output = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003324 if (arg == NULL) {
3325 Py_DECREF(*(PyObject**)addr);
3326 return 1;
3327 }
3328 if (PyUnicode_Check(arg)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003329 if (PyUnicode_READY(arg))
3330 return 0;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003331 output = arg;
3332 Py_INCREF(output);
3333 }
3334 else {
3335 arg = PyBytes_FromObject(arg);
3336 if (!arg)
3337 return 0;
3338 output = PyUnicode_DecodeFSDefaultAndSize(PyBytes_AS_STRING(arg),
3339 PyBytes_GET_SIZE(arg));
3340 Py_DECREF(arg);
3341 if (!output)
3342 return 0;
3343 if (!PyUnicode_Check(output)) {
3344 Py_DECREF(output);
3345 PyErr_SetString(PyExc_TypeError, "decoder failed to return unicode");
3346 return 0;
3347 }
3348 }
Victor Stinner065836e2011-10-27 01:56:33 +02003349 if (PyUnicode_READY(output) < 0) {
3350 Py_DECREF(output);
3351 return 0;
3352 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003353 if (findchar(PyUnicode_DATA(output), PyUnicode_KIND(output),
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02003354 PyUnicode_GET_LENGTH(output), 0, 1) >= 0) {
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003355 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
3356 Py_DECREF(output);
3357 return 0;
3358 }
3359 *(PyObject**)addr = output;
3360 return Py_CLEANUP_SUPPORTED;
3361}
3362
3363
Martin v. Löwis5b222132007-06-10 09:51:05 +00003364char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003365PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *psize)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003366{
Christian Heimesf3863112007-11-22 07:46:41 +00003367 PyObject *bytes;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003368
Neal Norwitze0a0a6e2007-08-25 01:04:21 +00003369 if (!PyUnicode_Check(unicode)) {
3370 PyErr_BadArgument();
3371 return NULL;
3372 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003373 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003374 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003375
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003376 if (PyUnicode_UTF8(unicode) == NULL) {
3377 assert(!PyUnicode_IS_COMPACT_ASCII(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003378 bytes = _PyUnicode_AsUTF8String(unicode, "strict");
3379 if (bytes == NULL)
3380 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003381 _PyUnicode_UTF8(unicode) = PyObject_MALLOC(PyBytes_GET_SIZE(bytes) + 1);
3382 if (_PyUnicode_UTF8(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003383 Py_DECREF(bytes);
3384 return NULL;
3385 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003386 _PyUnicode_UTF8_LENGTH(unicode) = PyBytes_GET_SIZE(bytes);
3387 Py_MEMCPY(_PyUnicode_UTF8(unicode),
3388 PyBytes_AS_STRING(bytes),
3389 _PyUnicode_UTF8_LENGTH(unicode) + 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003390 Py_DECREF(bytes);
3391 }
3392
3393 if (psize)
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003394 *psize = PyUnicode_UTF8_LENGTH(unicode);
3395 return PyUnicode_UTF8(unicode);
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003396}
3397
3398char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003399PyUnicode_AsUTF8(PyObject *unicode)
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003400{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003401 return PyUnicode_AsUTF8AndSize(unicode, NULL);
3402}
3403
3404#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +02003405static int unicode_as_unicode_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003406#endif
3407
3408
3409Py_UNICODE *
3410PyUnicode_AsUnicodeAndSize(PyObject *unicode, Py_ssize_t *size)
3411{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003412 const unsigned char *one_byte;
3413#if SIZEOF_WCHAR_T == 4
3414 const Py_UCS2 *two_bytes;
3415#else
3416 const Py_UCS4 *four_bytes;
3417 const Py_UCS4 *ucs4_end;
3418 Py_ssize_t num_surrogates;
3419#endif
3420 wchar_t *w;
3421 wchar_t *wchar_end;
3422
3423 if (!PyUnicode_Check(unicode)) {
3424 PyErr_BadArgument();
3425 return NULL;
3426 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003427 if (_PyUnicode_WSTR(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003428 /* Non-ASCII compact unicode object */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003429 assert(_PyUnicode_KIND(unicode) != 0);
3430 assert(PyUnicode_IS_READY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003431
3432#ifdef Py_DEBUG
3433 ++unicode_as_unicode_calls;
3434#endif
3435
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003436 if (PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003437#if SIZEOF_WCHAR_T == 2
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003438 four_bytes = PyUnicode_4BYTE_DATA(unicode);
3439 ucs4_end = four_bytes + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003440 num_surrogates = 0;
3441
3442 for (; four_bytes < ucs4_end; ++four_bytes) {
3443 if (*four_bytes > 0xFFFF)
3444 ++num_surrogates;
3445 }
3446
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003447 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(
3448 sizeof(wchar_t) * (_PyUnicode_LENGTH(unicode) + 1 + num_surrogates));
3449 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003450 PyErr_NoMemory();
3451 return NULL;
3452 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003453 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode) + num_surrogates;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003454
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003455 w = _PyUnicode_WSTR(unicode);
3456 wchar_end = w + _PyUnicode_WSTR_LENGTH(unicode);
3457 four_bytes = PyUnicode_4BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003458 for (; four_bytes < ucs4_end; ++four_bytes, ++w) {
3459 if (*four_bytes > 0xFFFF) {
3460 /* encode surrogate pair in this case */
3461 *w++ = 0xD800 | ((*four_bytes - 0x10000) >> 10);
3462 *w = 0xDC00 | ((*four_bytes - 0x10000) & 0x3FF);
3463 }
3464 else
3465 *w = *four_bytes;
3466
3467 if (w > wchar_end) {
3468 assert(0 && "Miscalculated string end");
3469 }
3470 }
3471 *w = 0;
3472#else
3473 /* sizeof(wchar_t) == 4 */
3474 Py_FatalError("Impossible unicode object state, wstr and str "
3475 "should share memory already.");
3476 return NULL;
3477#endif
3478 }
3479 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003480 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(sizeof(wchar_t) *
3481 (_PyUnicode_LENGTH(unicode) + 1));
3482 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003483 PyErr_NoMemory();
3484 return NULL;
3485 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003486 if (!PyUnicode_IS_COMPACT_ASCII(unicode))
3487 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode);
3488 w = _PyUnicode_WSTR(unicode);
3489 wchar_end = w + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003490
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003491 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND) {
3492 one_byte = PyUnicode_1BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003493 for (; w < wchar_end; ++one_byte, ++w)
3494 *w = *one_byte;
3495 /* null-terminate the wstr */
3496 *w = 0;
3497 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003498 else if (PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003499#if SIZEOF_WCHAR_T == 4
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003500 two_bytes = PyUnicode_2BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003501 for (; w < wchar_end; ++two_bytes, ++w)
3502 *w = *two_bytes;
3503 /* null-terminate the wstr */
3504 *w = 0;
3505#else
3506 /* sizeof(wchar_t) == 2 */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003507 PyObject_FREE(_PyUnicode_WSTR(unicode));
3508 _PyUnicode_WSTR(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003509 Py_FatalError("Impossible unicode object state, wstr "
3510 "and str should share memory already.");
3511 return NULL;
3512#endif
3513 }
3514 else {
3515 assert(0 && "This should never happen.");
3516 }
3517 }
3518 }
3519 if (size != NULL)
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003520 *size = PyUnicode_WSTR_LENGTH(unicode);
3521 return _PyUnicode_WSTR(unicode);
Martin v. Löwis5b222132007-06-10 09:51:05 +00003522}
3523
Alexander Belopolsky40018472011-02-26 01:02:56 +00003524Py_UNICODE *
3525PyUnicode_AsUnicode(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003526{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003527 return PyUnicode_AsUnicodeAndSize(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003528}
3529
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003530
Alexander Belopolsky40018472011-02-26 01:02:56 +00003531Py_ssize_t
3532PyUnicode_GetSize(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003533{
3534 if (!PyUnicode_Check(unicode)) {
3535 PyErr_BadArgument();
3536 goto onError;
3537 }
3538 return PyUnicode_GET_SIZE(unicode);
3539
Benjamin Peterson29060642009-01-31 22:14:21 +00003540 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003541 return -1;
3542}
3543
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003544Py_ssize_t
3545PyUnicode_GetLength(PyObject *unicode)
3546{
Victor Stinner5a706cf2011-10-02 00:36:53 +02003547 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003548 PyErr_BadArgument();
3549 return -1;
3550 }
3551
3552 return PyUnicode_GET_LENGTH(unicode);
3553}
3554
3555Py_UCS4
3556PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
3557{
Victor Stinner2fe5ced2011-10-02 00:25:40 +02003558 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
3559 PyErr_BadArgument();
3560 return (Py_UCS4)-1;
3561 }
3562 if (index < 0 || index >= _PyUnicode_LENGTH(unicode)) {
3563 PyErr_SetString(PyExc_IndexError, "string index out of range");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003564 return (Py_UCS4)-1;
3565 }
3566 return PyUnicode_READ_CHAR(unicode, index);
3567}
3568
3569int
3570PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 ch)
3571{
3572 if (!PyUnicode_Check(unicode) || !PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02003573 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003574 return -1;
3575 }
Victor Stinnercd9950f2011-10-02 00:34:53 +02003576 if (index < 0 || index >= _PyUnicode_LENGTH(unicode)) {
3577 PyErr_SetString(PyExc_IndexError, "string index out of range");
3578 return -1;
3579 }
3580 if (_PyUnicode_Dirty(unicode))
3581 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003582 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
3583 index, ch);
3584 return 0;
3585}
3586
Alexander Belopolsky40018472011-02-26 01:02:56 +00003587const char *
3588PyUnicode_GetDefaultEncoding(void)
Fred Drakee4315f52000-05-09 19:53:39 +00003589{
Victor Stinner42cb4622010-09-01 19:39:01 +00003590 return "utf-8";
Fred Drakee4315f52000-05-09 19:53:39 +00003591}
3592
Victor Stinner554f3f02010-06-16 23:33:54 +00003593/* create or adjust a UnicodeDecodeError */
3594static void
3595make_decode_exception(PyObject **exceptionObject,
3596 const char *encoding,
3597 const char *input, Py_ssize_t length,
3598 Py_ssize_t startpos, Py_ssize_t endpos,
3599 const char *reason)
3600{
3601 if (*exceptionObject == NULL) {
3602 *exceptionObject = PyUnicodeDecodeError_Create(
3603 encoding, input, length, startpos, endpos, reason);
3604 }
3605 else {
3606 if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
3607 goto onError;
3608 if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
3609 goto onError;
3610 if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
3611 goto onError;
3612 }
3613 return;
3614
3615onError:
3616 Py_DECREF(*exceptionObject);
3617 *exceptionObject = NULL;
3618}
3619
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003620/* error handling callback helper:
3621 build arguments, call the callback and check the arguments,
Fred Drakedb390c12005-10-28 14:39:47 +00003622 if no exception occurred, copy the replacement to the output
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003623 and adjust various state variables.
3624 return 0 on success, -1 on error
3625*/
3626
Alexander Belopolsky40018472011-02-26 01:02:56 +00003627static int
3628unicode_decode_call_errorhandler(const char *errors, PyObject **errorHandler,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003629 const char *encoding, const char *reason,
3630 const char **input, const char **inend, Py_ssize_t *startinpos,
3631 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003632 PyObject **output, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003633{
Benjamin Peterson142957c2008-07-04 19:55:29 +00003634 static char *argparse = "O!n;decoding error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003635
3636 PyObject *restuple = NULL;
3637 PyObject *repunicode = NULL;
Victor Stinner596a6c42011-11-09 00:02:18 +01003638 Py_ssize_t outsize;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003639 Py_ssize_t insize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003640 Py_ssize_t requiredsize;
3641 Py_ssize_t newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003642 PyObject *inputobj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003643 int res = -1;
3644
Victor Stinner596a6c42011-11-09 00:02:18 +01003645 if (_PyUnicode_KIND(*output) != PyUnicode_WCHAR_KIND)
3646 outsize = PyUnicode_GET_LENGTH(*output);
3647 else
3648 outsize = _PyUnicode_WSTR_LENGTH(*output);
3649
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003650 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003651 *errorHandler = PyCodec_LookupError(errors);
3652 if (*errorHandler == NULL)
3653 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003654 }
3655
Victor Stinner554f3f02010-06-16 23:33:54 +00003656 make_decode_exception(exceptionObject,
3657 encoding,
3658 *input, *inend - *input,
3659 *startinpos, *endinpos,
3660 reason);
3661 if (*exceptionObject == NULL)
3662 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003663
3664 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
3665 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003666 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003667 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00003668 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00003669 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003670 }
3671 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00003672 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003673 if (PyUnicode_READY(repunicode) < 0)
3674 goto onError;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003675
3676 /* Copy back the bytes variables, which might have been modified by the
3677 callback */
3678 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
3679 if (!inputobj)
3680 goto onError;
Christian Heimes72b710a2008-05-26 13:28:38 +00003681 if (!PyBytes_Check(inputobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003682 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
Walter Dörwalde78178e2007-07-30 13:31:40 +00003683 }
Christian Heimes72b710a2008-05-26 13:28:38 +00003684 *input = PyBytes_AS_STRING(inputobj);
3685 insize = PyBytes_GET_SIZE(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00003686 *inend = *input + insize;
Walter Dörwald36f938f2007-08-10 10:11:43 +00003687 /* we can DECREF safely, as the exception has another reference,
3688 so the object won't go away. */
3689 Py_DECREF(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00003690
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003691 if (newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00003692 newpos = insize+newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00003693 if (newpos<0 || newpos>insize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003694 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
3695 goto onError;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00003696 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003697
Victor Stinner596a6c42011-11-09 00:02:18 +01003698 if (_PyUnicode_KIND(*output) != PyUnicode_WCHAR_KIND) {
3699 /* need more space? (at least enough for what we
3700 have+the replacement+the rest of the string (starting
3701 at the new input position), so we won't have to check space
3702 when there are no errors in the rest of the string) */
3703 Py_ssize_t replen = PyUnicode_GET_LENGTH(repunicode);
3704 requiredsize = *outpos + replen + insize-newpos;
3705 if (requiredsize > outsize) {
3706 if (requiredsize<2*outsize)
3707 requiredsize = 2*outsize;
3708 if (unicode_resize(output, requiredsize) < 0)
3709 goto onError;
3710 }
3711 if (unicode_widen(output, PyUnicode_MAX_CHAR_VALUE(repunicode)) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00003712 goto onError;
Victor Stinner596a6c42011-11-09 00:02:18 +01003713 copy_characters(*output, *outpos, repunicode, 0, replen);
3714 *outpos += replen;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003715 }
Victor Stinner596a6c42011-11-09 00:02:18 +01003716 else {
3717 wchar_t *repwstr;
3718 Py_ssize_t repwlen;
3719 repwstr = PyUnicode_AsUnicodeAndSize(repunicode, &repwlen);
3720 if (repwstr == NULL)
3721 goto onError;
3722 /* need more space? (at least enough for what we
3723 have+the replacement+the rest of the string (starting
3724 at the new input position), so we won't have to check space
3725 when there are no errors in the rest of the string) */
3726 requiredsize = *outpos + repwlen + insize-newpos;
3727 if (requiredsize > outsize) {
3728 if (requiredsize < 2*outsize)
3729 requiredsize = 2*outsize;
3730 if (unicode_resize(output, requiredsize) < 0)
3731 goto onError;
3732 }
3733 wcsncpy(_PyUnicode_WSTR(*output) + *outpos, repwstr, repwlen);
3734 *outpos += repwlen;
3735 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003736 *endinpos = newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003737 *inptr = *input + newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003738
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003739 /* we made it! */
3740 res = 0;
3741
Benjamin Peterson29060642009-01-31 22:14:21 +00003742 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003743 Py_XDECREF(restuple);
3744 return res;
3745}
3746
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003747/* --- UTF-7 Codec -------------------------------------------------------- */
3748
Antoine Pitrou244651a2009-05-04 18:56:13 +00003749/* See RFC2152 for details. We encode conservatively and decode liberally. */
3750
3751/* Three simple macros defining base-64. */
3752
3753/* Is c a base-64 character? */
3754
3755#define IS_BASE64(c) \
3756 (((c) >= 'A' && (c) <= 'Z') || \
3757 ((c) >= 'a' && (c) <= 'z') || \
3758 ((c) >= '0' && (c) <= '9') || \
3759 (c) == '+' || (c) == '/')
3760
3761/* given that c is a base-64 character, what is its base-64 value? */
3762
3763#define FROM_BASE64(c) \
3764 (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' : \
3765 ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 : \
3766 ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 : \
3767 (c) == '+' ? 62 : 63)
3768
3769/* What is the base-64 character of the bottom 6 bits of n? */
3770
3771#define TO_BASE64(n) \
3772 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
3773
3774/* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
3775 * decoded as itself. We are permissive on decoding; the only ASCII
3776 * byte not decoding to itself is the + which begins a base64
3777 * string. */
3778
3779#define DECODE_DIRECT(c) \
3780 ((c) <= 127 && (c) != '+')
3781
3782/* The UTF-7 encoder treats ASCII characters differently according to
3783 * whether they are Set D, Set O, Whitespace, or special (i.e. none of
3784 * the above). See RFC2152. This array identifies these different
3785 * sets:
3786 * 0 : "Set D"
3787 * alphanumeric and '(),-./:?
3788 * 1 : "Set O"
3789 * !"#$%&*;<=>@[]^_`{|}
3790 * 2 : "whitespace"
3791 * ht nl cr sp
3792 * 3 : special (must be base64 encoded)
3793 * everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
3794 */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003795
Tim Petersced69f82003-09-16 20:30:58 +00003796static
Antoine Pitrou244651a2009-05-04 18:56:13 +00003797char utf7_category[128] = {
3798/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
3799 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
3800/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
3801 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
3802/* sp ! " # $ % & ' ( ) * + , - . / */
3803 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
3804/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
3805 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
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 [ \ ] ^ _ */
3809 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
3810/* ` a b c d e f g h i j k l m n o */
3811 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
3812/* p q r s t u v w x y z { | } ~ del */
3813 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003814};
3815
Antoine Pitrou244651a2009-05-04 18:56:13 +00003816/* ENCODE_DIRECT: this character should be encoded as itself. The
3817 * answer depends on whether we are encoding set O as itself, and also
3818 * on whether we are encoding whitespace as itself. RFC2152 makes it
3819 * clear that the answers to these questions vary between
3820 * applications, so this code needs to be flexible. */
Marc-André Lemburge115ec82005-10-19 22:33:31 +00003821
Antoine Pitrou244651a2009-05-04 18:56:13 +00003822#define ENCODE_DIRECT(c, directO, directWS) \
3823 ((c) < 128 && (c) > 0 && \
3824 ((utf7_category[(c)] == 0) || \
3825 (directWS && (utf7_category[(c)] == 2)) || \
3826 (directO && (utf7_category[(c)] == 1))))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003827
Alexander Belopolsky40018472011-02-26 01:02:56 +00003828PyObject *
3829PyUnicode_DecodeUTF7(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003830 Py_ssize_t size,
3831 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003832{
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003833 return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
3834}
3835
Antoine Pitrou244651a2009-05-04 18:56:13 +00003836/* The decoder. The only state we preserve is our read position,
3837 * i.e. how many characters we have consumed. So if we end in the
3838 * middle of a shift sequence we have to back off the read position
3839 * and the output to the beginning of the sequence, otherwise we lose
3840 * all the shift state (seen bits, number of bits seen, high
3841 * surrogate). */
3842
Alexander Belopolsky40018472011-02-26 01:02:56 +00003843PyObject *
3844PyUnicode_DecodeUTF7Stateful(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003845 Py_ssize_t size,
3846 const char *errors,
3847 Py_ssize_t *consumed)
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003848{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003849 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003850 Py_ssize_t startinpos;
3851 Py_ssize_t endinpos;
3852 Py_ssize_t outpos;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003853 const char *e;
Victor Stinner7931d9a2011-11-04 00:22:48 +01003854 PyObject *unicode;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003855 const char *errmsg = "";
3856 int inShift = 0;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003857 Py_ssize_t shiftOutStart;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003858 unsigned int base64bits = 0;
3859 unsigned long base64buffer = 0;
Victor Stinner24729f32011-11-10 20:31:37 +01003860 Py_UCS4 surrogate = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003861 PyObject *errorHandler = NULL;
3862 PyObject *exc = NULL;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003863
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003864 /* Start off assuming it's all ASCII. Widen later as necessary. */
3865 unicode = PyUnicode_New(size, 127);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003866 if (!unicode)
3867 return NULL;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003868 if (size == 0) {
3869 if (consumed)
3870 *consumed = 0;
Victor Stinner7931d9a2011-11-04 00:22:48 +01003871 return unicode;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003872 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003873
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003874 shiftOutStart = outpos = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003875 e = s + size;
3876
3877 while (s < e) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003878 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00003879 restart:
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00003880 ch = (unsigned char) *s;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003881
Antoine Pitrou244651a2009-05-04 18:56:13 +00003882 if (inShift) { /* in a base-64 section */
3883 if (IS_BASE64(ch)) { /* consume a base-64 character */
3884 base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
3885 base64bits += 6;
3886 s++;
3887 if (base64bits >= 16) {
3888 /* we have enough bits for a UTF-16 value */
Victor Stinner24729f32011-11-10 20:31:37 +01003889 Py_UCS4 outCh = (Py_UCS4)(base64buffer >> (base64bits-16));
Antoine Pitrou244651a2009-05-04 18:56:13 +00003890 base64bits -= 16;
3891 base64buffer &= (1 << base64bits) - 1; /* clear high bits */
3892 if (surrogate) {
3893 /* expecting a second surrogate */
3894 if (outCh >= 0xDC00 && outCh <= 0xDFFF) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003895 Py_UCS4 ch2 = (((surrogate & 0x3FF)<<10)
3896 | (outCh & 0x3FF)) + 0x10000;
3897 if (unicode_putchar(&unicode, &outpos, ch2) < 0)
3898 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003899 surrogate = 0;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01003900 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003901 }
3902 else {
Antoine Pitrou78edf752011-11-15 01:44:16 +01003903 if (unicode_putchar(&unicode, &outpos, surrogate) < 0)
3904 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003905 surrogate = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003906 }
3907 }
Antoine Pitrou5418ee02011-11-15 01:42:21 +01003908 if (outCh >= 0xD800 && outCh <= 0xDBFF) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00003909 /* first surrogate */
3910 surrogate = outCh;
3911 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003912 else {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003913 if (unicode_putchar(&unicode, &outpos, outCh) < 0)
3914 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003915 }
3916 }
3917 }
3918 else { /* now leaving a base-64 section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003919 inShift = 0;
3920 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003921 if (surrogate) {
Antoine Pitrou78edf752011-11-15 01:44:16 +01003922 if (unicode_putchar(&unicode, &outpos, surrogate) < 0)
3923 goto onError;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01003924 surrogate = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003925 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003926 if (base64bits > 0) { /* left-over bits */
3927 if (base64bits >= 6) {
3928 /* We've seen at least one base-64 character */
3929 errmsg = "partial character in shift sequence";
3930 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003931 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003932 else {
3933 /* Some bits remain; they should be zero */
3934 if (base64buffer != 0) {
3935 errmsg = "non-zero padding bits in shift sequence";
3936 goto utf7Error;
3937 }
3938 }
3939 }
3940 if (ch != '-') {
3941 /* '-' is absorbed; other terminating
3942 characters are preserved */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003943 if (unicode_putchar(&unicode, &outpos, ch) < 0)
3944 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003945 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003946 }
3947 }
3948 else if ( ch == '+' ) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003949 startinpos = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003950 s++; /* consume '+' */
3951 if (s < e && *s == '-') { /* '+-' encodes '+' */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003952 s++;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003953 if (unicode_putchar(&unicode, &outpos, '+') < 0)
3954 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003955 }
3956 else { /* begin base64-encoded section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003957 inShift = 1;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003958 shiftOutStart = outpos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003959 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003960 }
3961 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003962 else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003963 if (unicode_putchar(&unicode, &outpos, ch) < 0)
3964 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003965 s++;
3966 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003967 else {
3968 startinpos = s-starts;
3969 s++;
3970 errmsg = "unexpected special character";
3971 goto utf7Error;
3972 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003973 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003974utf7Error:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003975 endinpos = s-starts;
3976 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00003977 errors, &errorHandler,
3978 "utf7", errmsg,
3979 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003980 &unicode, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00003981 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003982 }
3983
Antoine Pitrou244651a2009-05-04 18:56:13 +00003984 /* end of string */
3985
3986 if (inShift && !consumed) { /* in shift sequence, no more to follow */
3987 /* if we're in an inconsistent state, that's an error */
3988 if (surrogate ||
3989 (base64bits >= 6) ||
3990 (base64bits > 0 && base64buffer != 0)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00003991 endinpos = size;
3992 if (unicode_decode_call_errorhandler(
3993 errors, &errorHandler,
3994 "utf7", "unterminated shift sequence",
3995 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003996 &unicode, &outpos))
Antoine Pitrou244651a2009-05-04 18:56:13 +00003997 goto onError;
3998 if (s < e)
3999 goto restart;
4000 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004001 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004002
4003 /* return state */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004004 if (consumed) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004005 if (inShift) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004006 outpos = shiftOutStart; /* back off output */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004007 *consumed = startinpos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004008 }
4009 else {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004010 *consumed = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004011 }
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004012 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004013
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004014 if (unicode_resize(&unicode, outpos) < 0)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004015 goto onError;
4016
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004017 Py_XDECREF(errorHandler);
4018 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02004019#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02004020 if (_PyUnicode_READY_REPLACE(&unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004021 Py_DECREF(unicode);
4022 return NULL;
4023 }
Victor Stinner17efeed2011-10-04 20:05:46 +02004024#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02004025 assert(_PyUnicode_CheckConsistency(unicode, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01004026 return unicode;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004027
Benjamin Peterson29060642009-01-31 22:14:21 +00004028 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004029 Py_XDECREF(errorHandler);
4030 Py_XDECREF(exc);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004031 Py_DECREF(unicode);
4032 return NULL;
4033}
4034
4035
Alexander Belopolsky40018472011-02-26 01:02:56 +00004036PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004037_PyUnicode_EncodeUTF7(PyObject *str,
4038 int base64SetO,
4039 int base64WhiteSpace,
4040 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004041{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004042 int kind;
4043 void *data;
4044 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004045 PyObject *v;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004046 Py_ssize_t allocated;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004047 int inShift = 0;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004048 Py_ssize_t i;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004049 unsigned int base64bits = 0;
4050 unsigned long base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004051 char * out;
4052 char * start;
4053
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004054 if (PyUnicode_READY(str) < 0)
4055 return NULL;
4056 kind = PyUnicode_KIND(str);
4057 data = PyUnicode_DATA(str);
4058 len = PyUnicode_GET_LENGTH(str);
4059
4060 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004061 return PyBytes_FromStringAndSize(NULL, 0);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004062
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004063 /* It might be possible to tighten this worst case */
4064 allocated = 8 * len;
4065 if (allocated / 8 != len)
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004066 return PyErr_NoMemory();
4067
Antoine Pitrou244651a2009-05-04 18:56:13 +00004068 v = PyBytes_FromStringAndSize(NULL, allocated);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004069 if (v == NULL)
4070 return NULL;
4071
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004072 start = out = PyBytes_AS_STRING(v);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004073 for (i = 0; i < len; ++i) {
Victor Stinner0e368262011-11-10 20:12:49 +01004074 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004075
Antoine Pitrou244651a2009-05-04 18:56:13 +00004076 if (inShift) {
4077 if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4078 /* shifting out */
4079 if (base64bits) { /* output remaining bits */
4080 *out++ = TO_BASE64(base64buffer << (6-base64bits));
4081 base64buffer = 0;
4082 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004083 }
4084 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004085 /* Characters not in the BASE64 set implicitly unshift the sequence
4086 so no '-' is required, except if the character is itself a '-' */
4087 if (IS_BASE64(ch) || ch == '-') {
4088 *out++ = '-';
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004089 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004090 *out++ = (char) ch;
4091 }
4092 else {
4093 goto encode_char;
Tim Petersced69f82003-09-16 20:30:58 +00004094 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004095 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004096 else { /* not in a shift sequence */
4097 if (ch == '+') {
4098 *out++ = '+';
4099 *out++ = '-';
4100 }
4101 else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4102 *out++ = (char) ch;
4103 }
4104 else {
4105 *out++ = '+';
4106 inShift = 1;
4107 goto encode_char;
4108 }
4109 }
4110 continue;
4111encode_char:
Antoine Pitrou244651a2009-05-04 18:56:13 +00004112 if (ch >= 0x10000) {
4113 /* code first surrogate */
4114 base64bits += 16;
4115 base64buffer = (base64buffer << 16) | 0xd800 | ((ch-0x10000) >> 10);
4116 while (base64bits >= 6) {
4117 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4118 base64bits -= 6;
4119 }
4120 /* prepare second surrogate */
4121 ch = 0xDC00 | ((ch-0x10000) & 0x3FF);
4122 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004123 base64bits += 16;
4124 base64buffer = (base64buffer << 16) | ch;
4125 while (base64bits >= 6) {
4126 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4127 base64bits -= 6;
4128 }
Hye-Shik Chang1bc09b72004-01-03 19:35:43 +00004129 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004130 if (base64bits)
4131 *out++= TO_BASE64(base64buffer << (6-base64bits) );
4132 if (inShift)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004133 *out++ = '-';
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004134 if (_PyBytes_Resize(&v, out - start) < 0)
4135 return NULL;
4136 return v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004137}
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004138PyObject *
4139PyUnicode_EncodeUTF7(const Py_UNICODE *s,
4140 Py_ssize_t size,
4141 int base64SetO,
4142 int base64WhiteSpace,
4143 const char *errors)
4144{
4145 PyObject *result;
4146 PyObject *tmp = PyUnicode_FromUnicode(s, size);
4147 if (tmp == NULL)
4148 return NULL;
Victor Stinner0e368262011-11-10 20:12:49 +01004149 result = _PyUnicode_EncodeUTF7(tmp, base64SetO,
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004150 base64WhiteSpace, errors);
4151 Py_DECREF(tmp);
4152 return result;
4153}
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004154
Antoine Pitrou244651a2009-05-04 18:56:13 +00004155#undef IS_BASE64
4156#undef FROM_BASE64
4157#undef TO_BASE64
4158#undef DECODE_DIRECT
4159#undef ENCODE_DIRECT
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004160
Guido van Rossumd57fd912000-03-10 22:53:23 +00004161/* --- UTF-8 Codec -------------------------------------------------------- */
4162
Tim Petersced69f82003-09-16 20:30:58 +00004163static
Guido van Rossumd57fd912000-03-10 22:53:23 +00004164char utf8_code_length[256] = {
Ezio Melotti57221d02010-07-01 07:32:02 +00004165 /* Map UTF-8 encoded prefix byte to sequence length. Zero means
4166 illegal prefix. See RFC 3629 for details */
4167 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 00-0F */
4168 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Victor Stinner4a2b7a12010-08-13 14:03:48 +00004169 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Guido van Rossumd57fd912000-03-10 22:53:23 +00004170 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
4171 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
4172 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
4173 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Ezio Melotti57221d02010-07-01 07:32:02 +00004174 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 70-7F */
4175 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 +00004176 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4177 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
Ezio Melotti57221d02010-07-01 07:32:02 +00004178 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* B0-BF */
4179 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* C0-C1 + C2-CF */
4180 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* D0-DF */
4181 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, /* E0-EF */
4182 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 +00004183};
4184
Alexander Belopolsky40018472011-02-26 01:02:56 +00004185PyObject *
4186PyUnicode_DecodeUTF8(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004187 Py_ssize_t size,
4188 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004189{
Walter Dörwald69652032004-09-07 20:24:22 +00004190 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
4191}
4192
Antoine Pitrouab868312009-01-10 15:40:25 +00004193/* Mask to check or force alignment of a pointer to C 'long' boundaries */
4194#define LONG_PTR_MASK (size_t) (SIZEOF_LONG - 1)
4195
4196/* Mask to quickly check whether a C 'long' contains a
4197 non-ASCII, UTF8-encoded char. */
4198#if (SIZEOF_LONG == 8)
4199# define ASCII_CHAR_MASK 0x8080808080808080L
4200#elif (SIZEOF_LONG == 4)
4201# define ASCII_CHAR_MASK 0x80808080L
4202#else
4203# error C 'long' size should be either 4 or 8!
4204#endif
4205
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004206/* Scans a UTF-8 string and returns the maximum character to be expected,
4207 the size of the decoded unicode string and if any major errors were
4208 encountered.
4209
4210 This function does check basic UTF-8 sanity, it does however NOT CHECK
4211 if the string contains surrogates, and if all continuation bytes are
4212 within the correct ranges, these checks are performed in
4213 PyUnicode_DecodeUTF8Stateful.
4214
4215 If it sets has_errors to 1, it means the value of unicode_size and max_char
4216 will be bogus and you should not rely on useful information in them.
4217 */
4218static Py_UCS4
4219utf8_max_char_size_and_has_errors(const char *s, Py_ssize_t string_size,
4220 Py_ssize_t *unicode_size, Py_ssize_t* consumed,
4221 int *has_errors)
4222{
4223 Py_ssize_t n;
4224 Py_ssize_t char_count = 0;
4225 Py_UCS4 max_char = 127, new_max;
4226 Py_UCS4 upper_bound;
4227 const unsigned char *p = (const unsigned char *)s;
4228 const unsigned char *end = p + string_size;
4229 const unsigned char *aligned_end = (const unsigned char *) ((size_t) end & ~LONG_PTR_MASK);
4230 int err = 0;
4231
4232 for (; p < end && !err; ++p, ++char_count) {
4233 /* Only check value if it's not a ASCII char... */
4234 if (*p < 0x80) {
4235 /* Fast path, see below in PyUnicode_DecodeUTF8Stateful for
4236 an explanation. */
4237 if (!((size_t) p & LONG_PTR_MASK)) {
4238 /* Help register allocation */
4239 register const unsigned char *_p = p;
4240 while (_p < aligned_end) {
4241 unsigned long value = *(unsigned long *) _p;
4242 if (value & ASCII_CHAR_MASK)
4243 break;
4244 _p += SIZEOF_LONG;
4245 char_count += SIZEOF_LONG;
4246 }
4247 p = _p;
4248 if (p == end)
4249 break;
4250 }
4251 }
4252 if (*p >= 0x80) {
4253 n = utf8_code_length[*p];
4254 new_max = max_char;
4255 switch (n) {
4256 /* invalid start byte */
4257 case 0:
4258 err = 1;
4259 break;
4260 case 2:
4261 /* Code points between 0x00FF and 0x07FF inclusive.
4262 Approximate the upper bound of the code point,
4263 if this flips over 255 we can be sure it will be more
4264 than 255 and the string will need 2 bytes per code coint,
4265 if it stays under or equal to 255, we can be sure 1 byte
4266 is enough.
4267 ((*p & 0b00011111) << 6) | 0b00111111 */
4268 upper_bound = ((*p & 0x1F) << 6) | 0x3F;
4269 if (max_char < upper_bound)
4270 new_max = upper_bound;
4271 /* Ensure we track at least that we left ASCII space. */
4272 if (new_max < 128)
4273 new_max = 128;
4274 break;
4275 case 3:
4276 /* Between 0x0FFF and 0xFFFF inclusive, so values are
4277 always > 255 and <= 65535 and will always need 2 bytes. */
4278 if (max_char < 65535)
4279 new_max = 65535;
4280 break;
4281 case 4:
4282 /* Code point will be above 0xFFFF for sure in this case. */
4283 new_max = 65537;
4284 break;
4285 /* Internal error, this should be caught by the first if */
4286 case 1:
4287 default:
4288 assert(0 && "Impossible case in utf8_max_char_and_size");
4289 err = 1;
4290 }
4291 /* Instead of number of overall bytes for this code point,
Georg Brandl7597add2011-10-05 16:36:47 +02004292 n contains the number of following bytes: */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004293 --n;
4294 /* Check if the follow up chars are all valid continuation bytes */
4295 if (n >= 1) {
4296 const unsigned char *cont;
4297 if ((p + n) >= end) {
4298 if (consumed == 0)
4299 /* incomplete data, non-incremental decoding */
4300 err = 1;
4301 break;
4302 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004303 for (cont = p + 1; cont <= (p + n); ++cont) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004304 if ((*cont & 0xc0) != 0x80) {
4305 err = 1;
4306 break;
4307 }
4308 }
4309 p += n;
4310 }
4311 else
4312 err = 1;
4313 max_char = new_max;
4314 }
4315 }
4316
4317 if (unicode_size)
4318 *unicode_size = char_count;
4319 if (has_errors)
4320 *has_errors = err;
4321 return max_char;
4322}
4323
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004324/* Similar to PyUnicode_WRITE but may attempt to widen and resize the string
4325 in case of errors. Implicit parameters: unicode, kind, data, has_errors,
4326 onError. Potential resizing overallocates, so the result needs to shrink
4327 at the end.
4328*/
4329#define WRITE_MAYBE_FAIL(index, value) \
4330 do { \
4331 if (has_errors) { \
4332 Py_ssize_t pos = index; \
4333 if (pos > PyUnicode_GET_LENGTH(unicode) && \
4334 unicode_resize(&unicode, pos + pos/8) < 0) \
4335 goto onError; \
4336 if (unicode_putchar(&unicode, &pos, value) < 0) \
4337 goto onError; \
4338 } \
4339 else \
4340 PyUnicode_WRITE(kind, data, index, value); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004341 } while (0)
4342
Alexander Belopolsky40018472011-02-26 01:02:56 +00004343PyObject *
4344PyUnicode_DecodeUTF8Stateful(const char *s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004345 Py_ssize_t size,
4346 const char *errors,
4347 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00004348{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004349 const char *starts = s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004350 int n;
Ezio Melotti57221d02010-07-01 07:32:02 +00004351 int k;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004352 Py_ssize_t startinpos;
4353 Py_ssize_t endinpos;
Antoine Pitrouab868312009-01-10 15:40:25 +00004354 const char *e, *aligned_end;
Victor Stinner7931d9a2011-11-04 00:22:48 +01004355 PyObject *unicode;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004356 const char *errmsg = "";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004357 PyObject *errorHandler = NULL;
4358 PyObject *exc = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004359 Py_UCS4 maxchar = 0;
4360 Py_ssize_t unicode_size;
4361 Py_ssize_t i;
4362 int kind;
4363 void *data;
4364 int has_errors;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004365
Walter Dörwald69652032004-09-07 20:24:22 +00004366 if (size == 0) {
4367 if (consumed)
4368 *consumed = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004369 return (PyObject *)PyUnicode_New(0, 0);
Walter Dörwald69652032004-09-07 20:24:22 +00004370 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004371 maxchar = utf8_max_char_size_and_has_errors(s, size, &unicode_size,
4372 consumed, &has_errors);
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004373 if (has_errors)
Victor Stinner62aa4d02011-11-09 00:03:45 +01004374 /* maxchar and size computation might be incorrect;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004375 code below widens and resizes as necessary. */
4376 unicode = PyUnicode_New(size, 127);
4377 else
Victor Stinner7931d9a2011-11-04 00:22:48 +01004378 unicode = PyUnicode_New(unicode_size, maxchar);
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004379 if (!unicode)
4380 return NULL;
4381 /* When the string is ASCII only, just use memcpy and return.
4382 unicode_size may be != size if there is an incomplete UTF-8
4383 sequence at the end of the ASCII block. */
4384 if (!has_errors && maxchar < 128 && size == unicode_size) {
4385 Py_MEMCPY(PyUnicode_1BYTE_DATA(unicode), s, unicode_size);
4386 return unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004387 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004388 kind = PyUnicode_KIND(unicode);
4389 data = PyUnicode_DATA(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004390 /* Unpack UTF-8 encoded data */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004391 i = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004392 e = s + size;
Antoine Pitrouab868312009-01-10 15:40:25 +00004393 aligned_end = (const char *) ((size_t) e & ~LONG_PTR_MASK);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004394
4395 while (s < e) {
Marc-André Lemburge12896e2000-07-07 17:51:08 +00004396 Py_UCS4 ch = (unsigned char)*s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004397
4398 if (ch < 0x80) {
Antoine Pitrouab868312009-01-10 15:40:25 +00004399 /* Fast path for runs of ASCII characters. Given that common UTF-8
4400 input will consist of an overwhelming majority of ASCII
4401 characters, we try to optimize for this case by checking
4402 as many characters as a C 'long' can contain.
4403 First, check if we can do an aligned read, as most CPUs have
4404 a penalty for unaligned reads.
4405 */
4406 if (!((size_t) s & LONG_PTR_MASK)) {
4407 /* Help register allocation */
4408 register const char *_s = s;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004409 register Py_ssize_t _i = i;
Antoine Pitrouab868312009-01-10 15:40:25 +00004410 while (_s < aligned_end) {
4411 /* Read a whole long at a time (either 4 or 8 bytes),
4412 and do a fast unrolled copy if it only contains ASCII
4413 characters. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004414 unsigned long value = *(unsigned long *) _s;
4415 if (value & ASCII_CHAR_MASK)
Antoine Pitrouab868312009-01-10 15:40:25 +00004416 break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004417 WRITE_MAYBE_FAIL(_i+0, _s[0]);
4418 WRITE_MAYBE_FAIL(_i+1, _s[1]);
4419 WRITE_MAYBE_FAIL(_i+2, _s[2]);
4420 WRITE_MAYBE_FAIL(_i+3, _s[3]);
Antoine Pitrouab868312009-01-10 15:40:25 +00004421#if (SIZEOF_LONG == 8)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004422 WRITE_MAYBE_FAIL(_i+4, _s[4]);
4423 WRITE_MAYBE_FAIL(_i+5, _s[5]);
4424 WRITE_MAYBE_FAIL(_i+6, _s[6]);
4425 WRITE_MAYBE_FAIL(_i+7, _s[7]);
Antoine Pitrouab868312009-01-10 15:40:25 +00004426#endif
4427 _s += SIZEOF_LONG;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004428 _i += SIZEOF_LONG;
Antoine Pitrouab868312009-01-10 15:40:25 +00004429 }
4430 s = _s;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004431 i = _i;
Antoine Pitrouab868312009-01-10 15:40:25 +00004432 if (s == e)
4433 break;
4434 ch = (unsigned char)*s;
4435 }
4436 }
4437
4438 if (ch < 0x80) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004439 WRITE_MAYBE_FAIL(i++, ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004440 s++;
4441 continue;
4442 }
4443
4444 n = utf8_code_length[ch];
4445
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004446 if (s + n > e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004447 if (consumed)
4448 break;
4449 else {
4450 errmsg = "unexpected end of data";
4451 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004452 endinpos = startinpos+1;
4453 for (k=1; (k < size-startinpos) && ((s[k]&0xC0) == 0x80); k++)
4454 endinpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00004455 goto utf8Error;
4456 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00004457 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004458
4459 switch (n) {
4460
4461 case 0:
Ezio Melotti57221d02010-07-01 07:32:02 +00004462 errmsg = "invalid start byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004463 startinpos = s-starts;
4464 endinpos = startinpos+1;
4465 goto utf8Error;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004466
4467 case 1:
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004468 errmsg = "internal error";
Benjamin Peterson29060642009-01-31 22:14:21 +00004469 startinpos = s-starts;
4470 endinpos = startinpos+1;
4471 goto utf8Error;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004472
4473 case 2:
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004474 if ((s[1] & 0xc0) != 0x80) {
Ezio Melotti57221d02010-07-01 07:32:02 +00004475 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004476 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004477 endinpos = startinpos + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00004478 goto utf8Error;
4479 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004480 ch = ((s[0] & 0x1f) << 6) + (s[1] & 0x3f);
Ezio Melotti57221d02010-07-01 07:32:02 +00004481 assert ((ch > 0x007F) && (ch <= 0x07FF));
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004482 WRITE_MAYBE_FAIL(i++, ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004483 break;
4484
4485 case 3:
Ezio Melotti9bf2b3a2010-07-03 04:52:19 +00004486 /* Decoding UTF-8 sequences in range \xed\xa0\x80-\xed\xbf\xbf
4487 will result in surrogates in range d800-dfff. Surrogates are
4488 not valid UTF-8 so they are rejected.
4489 See http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf
4490 (table 3-7) and http://www.rfc-editor.org/rfc/rfc3629.txt */
Tim Petersced69f82003-09-16 20:30:58 +00004491 if ((s[1] & 0xc0) != 0x80 ||
Ezio Melotti57221d02010-07-01 07:32:02 +00004492 (s[2] & 0xc0) != 0x80 ||
4493 ((unsigned char)s[0] == 0xE0 &&
4494 (unsigned char)s[1] < 0xA0) ||
4495 ((unsigned char)s[0] == 0xED &&
4496 (unsigned char)s[1] > 0x9F)) {
4497 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004498 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004499 endinpos = startinpos + 1;
4500
4501 /* if s[1] first two bits are 1 and 0, then the invalid
4502 continuation byte is s[2], so increment endinpos by 1,
4503 if not, s[1] is invalid and endinpos doesn't need to
4504 be incremented. */
4505 if ((s[1] & 0xC0) == 0x80)
4506 endinpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00004507 goto utf8Error;
4508 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004509 ch = ((s[0] & 0x0f) << 12) + ((s[1] & 0x3f) << 6) + (s[2] & 0x3f);
Ezio Melotti57221d02010-07-01 07:32:02 +00004510 assert ((ch > 0x07FF) && (ch <= 0xFFFF));
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004511 WRITE_MAYBE_FAIL(i++, ch);
Marc-André Lemburge12896e2000-07-07 17:51:08 +00004512 break;
4513
4514 case 4:
4515 if ((s[1] & 0xc0) != 0x80 ||
4516 (s[2] & 0xc0) != 0x80 ||
Ezio Melotti57221d02010-07-01 07:32:02 +00004517 (s[3] & 0xc0) != 0x80 ||
4518 ((unsigned char)s[0] == 0xF0 &&
4519 (unsigned char)s[1] < 0x90) ||
4520 ((unsigned char)s[0] == 0xF4 &&
4521 (unsigned char)s[1] > 0x8F)) {
4522 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004523 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004524 endinpos = startinpos + 1;
4525 if ((s[1] & 0xC0) == 0x80) {
4526 endinpos++;
4527 if ((s[2] & 0xC0) == 0x80)
4528 endinpos++;
4529 }
Benjamin Peterson29060642009-01-31 22:14:21 +00004530 goto utf8Error;
4531 }
Marc-André Lemburge12896e2000-07-07 17:51:08 +00004532 ch = ((s[0] & 0x7) << 18) + ((s[1] & 0x3f) << 12) +
Ezio Melotti57221d02010-07-01 07:32:02 +00004533 ((s[2] & 0x3f) << 6) + (s[3] & 0x3f);
4534 assert ((ch > 0xFFFF) && (ch <= 0x10ffff));
4535
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004536 WRITE_MAYBE_FAIL(i++, ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004537 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004538 }
4539 s += n;
Benjamin Peterson29060642009-01-31 22:14:21 +00004540 continue;
Tim Petersced69f82003-09-16 20:30:58 +00004541
Benjamin Peterson29060642009-01-31 22:14:21 +00004542 utf8Error:
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004543 if (!has_errors) {
4544 PyObject *tmp;
4545 Py_ssize_t k;
4546 /* We encountered some error that wasn't detected in the original scan,
4547 e.g. an encoded surrogate character. The original maxchar computation may
4548 have been incorrect, so redo it now. */
4549 for (k = 0, maxchar = 0; k < i; k++)
4550 maxchar = Py_MAX(maxchar, PyUnicode_READ(kind, data, k));
4551 tmp = PyUnicode_New(PyUnicode_GET_LENGTH(unicode), maxchar);
4552 if (tmp == NULL)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004553 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004554 PyUnicode_CopyCharacters(tmp, 0, unicode, 0, i);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004555 Py_DECREF(unicode);
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004556 unicode = tmp;
4557 has_errors = 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004558 }
Benjamin Peterson29060642009-01-31 22:14:21 +00004559 if (unicode_decode_call_errorhandler(
4560 errors, &errorHandler,
4561 "utf8", errmsg,
4562 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004563 &unicode, &i))
Benjamin Peterson29060642009-01-31 22:14:21 +00004564 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004565 /* Update data because unicode_decode_call_errorhandler might have
4566 re-created or resized the unicode object. */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004567 data = PyUnicode_DATA(unicode);
4568 kind = PyUnicode_KIND(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00004569 aligned_end = (const char *) ((size_t) e & ~LONG_PTR_MASK);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004570 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004571 /* Ensure the unicode_size calculation above was correct: */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004572 assert(has_errors || i == unicode_size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004573
Walter Dörwald69652032004-09-07 20:24:22 +00004574 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00004575 *consumed = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004576
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004577 /* Adjust length and ready string when it contained errors and
4578 is of the old resizable kind. */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004579 if (has_errors) {
Victor Stinner7931d9a2011-11-04 00:22:48 +01004580 if (PyUnicode_Resize(&unicode, i) < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004581 goto onError;
4582 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004583
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004584 Py_XDECREF(errorHandler);
4585 Py_XDECREF(exc);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02004586 assert(_PyUnicode_CheckConsistency(unicode, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01004587 return unicode;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004588
Benjamin Peterson29060642009-01-31 22:14:21 +00004589 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004590 Py_XDECREF(errorHandler);
4591 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004592 Py_DECREF(unicode);
4593 return NULL;
4594}
4595
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004596#undef WRITE_MAYBE_FAIL
Antoine Pitrouab868312009-01-10 15:40:25 +00004597
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004598#ifdef __APPLE__
4599
4600/* Simplified UTF-8 decoder using surrogateescape error handler,
4601 used to decode the command line arguments on Mac OS X. */
4602
4603wchar_t*
4604_Py_DecodeUTF8_surrogateescape(const char *s, Py_ssize_t size)
4605{
4606 int n;
4607 const char *e;
4608 wchar_t *unicode, *p;
4609
4610 /* Note: size will always be longer than the resulting Unicode
4611 character count */
4612 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < (size + 1)) {
4613 PyErr_NoMemory();
4614 return NULL;
4615 }
4616 unicode = PyMem_Malloc((size + 1) * sizeof(wchar_t));
4617 if (!unicode)
4618 return NULL;
4619
4620 /* Unpack UTF-8 encoded data */
4621 p = unicode;
4622 e = s + size;
4623 while (s < e) {
4624 Py_UCS4 ch = (unsigned char)*s;
4625
4626 if (ch < 0x80) {
4627 *p++ = (wchar_t)ch;
4628 s++;
4629 continue;
4630 }
4631
4632 n = utf8_code_length[ch];
4633 if (s + n > e) {
4634 goto surrogateescape;
4635 }
4636
4637 switch (n) {
4638 case 0:
4639 case 1:
4640 goto surrogateescape;
4641
4642 case 2:
4643 if ((s[1] & 0xc0) != 0x80)
4644 goto surrogateescape;
4645 ch = ((s[0] & 0x1f) << 6) + (s[1] & 0x3f);
4646 assert ((ch > 0x007F) && (ch <= 0x07FF));
4647 *p++ = (wchar_t)ch;
4648 break;
4649
4650 case 3:
4651 /* Decoding UTF-8 sequences in range \xed\xa0\x80-\xed\xbf\xbf
4652 will result in surrogates in range d800-dfff. Surrogates are
4653 not valid UTF-8 so they are rejected.
4654 See http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf
4655 (table 3-7) and http://www.rfc-editor.org/rfc/rfc3629.txt */
4656 if ((s[1] & 0xc0) != 0x80 ||
4657 (s[2] & 0xc0) != 0x80 ||
4658 ((unsigned char)s[0] == 0xE0 &&
4659 (unsigned char)s[1] < 0xA0) ||
4660 ((unsigned char)s[0] == 0xED &&
4661 (unsigned char)s[1] > 0x9F)) {
4662
4663 goto surrogateescape;
4664 }
4665 ch = ((s[0] & 0x0f) << 12) + ((s[1] & 0x3f) << 6) + (s[2] & 0x3f);
4666 assert ((ch > 0x07FF) && (ch <= 0xFFFF));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004667 *p++ = (wchar_t)ch;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004668 break;
4669
4670 case 4:
4671 if ((s[1] & 0xc0) != 0x80 ||
4672 (s[2] & 0xc0) != 0x80 ||
4673 (s[3] & 0xc0) != 0x80 ||
4674 ((unsigned char)s[0] == 0xF0 &&
4675 (unsigned char)s[1] < 0x90) ||
4676 ((unsigned char)s[0] == 0xF4 &&
4677 (unsigned char)s[1] > 0x8F)) {
4678 goto surrogateescape;
4679 }
4680 ch = ((s[0] & 0x7) << 18) + ((s[1] & 0x3f) << 12) +
4681 ((s[2] & 0x3f) << 6) + (s[3] & 0x3f);
4682 assert ((ch > 0xFFFF) && (ch <= 0x10ffff));
4683
4684#if SIZEOF_WCHAR_T == 4
4685 *p++ = (wchar_t)ch;
4686#else
4687 /* compute and append the two surrogates: */
4688
4689 /* translate from 10000..10FFFF to 0..FFFF */
4690 ch -= 0x10000;
4691
4692 /* high surrogate = top 10 bits added to D800 */
4693 *p++ = (wchar_t)(0xD800 + (ch >> 10));
4694
4695 /* low surrogate = bottom 10 bits added to DC00 */
4696 *p++ = (wchar_t)(0xDC00 + (ch & 0x03FF));
4697#endif
4698 break;
4699 }
4700 s += n;
4701 continue;
4702
4703 surrogateescape:
4704 *p++ = 0xDC00 + ch;
4705 s++;
4706 }
4707 *p = L'\0';
4708 return unicode;
4709}
4710
4711#endif /* __APPLE__ */
Antoine Pitrouab868312009-01-10 15:40:25 +00004712
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004713/* Primary internal function which creates utf8 encoded bytes objects.
4714
4715 Allocation strategy: if the string is short, convert into a stack buffer
Tim Peters602f7402002-04-27 18:03:26 +00004716 and allocate exactly as much space needed at the end. Else allocate the
4717 maximum possible needed (4 result bytes per Unicode character), and return
4718 the excess memory at the end.
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004719*/
Tim Peters7e3d9612002-04-21 03:26:37 +00004720PyObject *
Victor Stinner7931d9a2011-11-04 00:22:48 +01004721_PyUnicode_AsUTF8String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004722{
Tim Peters602f7402002-04-27 18:03:26 +00004723#define MAX_SHORT_UNICHARS 300 /* largest size we'll do on the stack */
Tim Peters0eca65c2002-04-21 17:28:06 +00004724
Guido van Rossum98297ee2007-11-06 21:34:58 +00004725 Py_ssize_t i; /* index into s of next input byte */
4726 PyObject *result; /* result string object */
4727 char *p; /* next free byte in output buffer */
4728 Py_ssize_t nallocated; /* number of result bytes allocated */
4729 Py_ssize_t nneeded; /* number of result bytes needed */
Tim Peters602f7402002-04-27 18:03:26 +00004730 char stackbuf[MAX_SHORT_UNICHARS * 4];
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004731 PyObject *errorHandler = NULL;
4732 PyObject *exc = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004733 int kind;
4734 void *data;
4735 Py_ssize_t size;
Antoine Pitrou31b92a52011-11-12 18:35:19 +01004736 PyObject *rep = NULL;
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00004737
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004738 if (!PyUnicode_Check(unicode)) {
4739 PyErr_BadArgument();
4740 return NULL;
4741 }
4742
4743 if (PyUnicode_READY(unicode) == -1)
4744 return NULL;
4745
Victor Stinnere90fe6a2011-10-01 16:48:13 +02004746 if (PyUnicode_UTF8(unicode))
4747 return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode),
4748 PyUnicode_UTF8_LENGTH(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004749
4750 kind = PyUnicode_KIND(unicode);
4751 data = PyUnicode_DATA(unicode);
4752 size = PyUnicode_GET_LENGTH(unicode);
4753
Tim Peters602f7402002-04-27 18:03:26 +00004754 assert(size >= 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004755
Tim Peters602f7402002-04-27 18:03:26 +00004756 if (size <= MAX_SHORT_UNICHARS) {
4757 /* Write into the stack buffer; nallocated can't overflow.
4758 * At the end, we'll allocate exactly as much heap space as it
4759 * turns out we need.
4760 */
4761 nallocated = Py_SAFE_DOWNCAST(sizeof(stackbuf), size_t, int);
Guido van Rossum98297ee2007-11-06 21:34:58 +00004762 result = NULL; /* will allocate after we're done */
Tim Peters602f7402002-04-27 18:03:26 +00004763 p = stackbuf;
4764 }
4765 else {
4766 /* Overallocate on the heap, and give the excess back at the end. */
4767 nallocated = size * 4;
4768 if (nallocated / 4 != size) /* overflow! */
4769 return PyErr_NoMemory();
Christian Heimes72b710a2008-05-26 13:28:38 +00004770 result = PyBytes_FromStringAndSize(NULL, nallocated);
Guido van Rossum98297ee2007-11-06 21:34:58 +00004771 if (result == NULL)
Tim Peters602f7402002-04-27 18:03:26 +00004772 return NULL;
Christian Heimes72b710a2008-05-26 13:28:38 +00004773 p = PyBytes_AS_STRING(result);
Tim Peters602f7402002-04-27 18:03:26 +00004774 }
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004775
Tim Peters602f7402002-04-27 18:03:26 +00004776 for (i = 0; i < size;) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004777 Py_UCS4 ch = PyUnicode_READ(kind, data, i++);
Marc-André Lemburg3688a882002-02-06 18:09:02 +00004778
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004779 if (ch < 0x80)
Tim Peters602f7402002-04-27 18:03:26 +00004780 /* Encode ASCII */
Guido van Rossumd57fd912000-03-10 22:53:23 +00004781 *p++ = (char) ch;
Marc-André Lemburg3688a882002-02-06 18:09:02 +00004782
Guido van Rossumd57fd912000-03-10 22:53:23 +00004783 else if (ch < 0x0800) {
Tim Peters602f7402002-04-27 18:03:26 +00004784 /* Encode Latin-1 */
Marc-André Lemburgdc724d62002-02-06 18:20:19 +00004785 *p++ = (char)(0xc0 | (ch >> 6));
4786 *p++ = (char)(0x80 | (ch & 0x3f));
Victor Stinner31be90b2010-04-22 19:38:16 +00004787 } else if (0xD800 <= ch && ch <= 0xDFFF) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004788 Py_ssize_t newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004789 Py_ssize_t repsize, k, startpos;
4790 startpos = i-1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004791 rep = unicode_encode_call_errorhandler(
4792 errors, &errorHandler, "utf-8", "surrogates not allowed",
Victor Stinner7931d9a2011-11-04 00:22:48 +01004793 unicode, &exc, startpos, startpos+1, &newpos);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004794 if (!rep)
4795 goto error;
Victor Stinner31be90b2010-04-22 19:38:16 +00004796
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004797 if (PyBytes_Check(rep))
4798 repsize = PyBytes_GET_SIZE(rep);
4799 else
Victor Stinner9e30aa52011-11-21 02:49:52 +01004800 repsize = PyUnicode_GET_LENGTH(rep);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004801
4802 if (repsize > 4) {
4803 Py_ssize_t offset;
4804
4805 if (result == NULL)
4806 offset = p - stackbuf;
Victor Stinner31be90b2010-04-22 19:38:16 +00004807 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004808 offset = p - PyBytes_AS_STRING(result);
Victor Stinner31be90b2010-04-22 19:38:16 +00004809
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004810 if (nallocated > PY_SSIZE_T_MAX - repsize + 4) {
4811 /* integer overflow */
4812 PyErr_NoMemory();
4813 goto error;
4814 }
4815 nallocated += repsize - 4;
4816 if (result != NULL) {
4817 if (_PyBytes_Resize(&result, nallocated) < 0)
4818 goto error;
4819 } else {
4820 result = PyBytes_FromStringAndSize(NULL, nallocated);
Victor Stinner31be90b2010-04-22 19:38:16 +00004821 if (result == NULL)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004822 goto error;
4823 Py_MEMCPY(PyBytes_AS_STRING(result), stackbuf, offset);
4824 }
4825 p = PyBytes_AS_STRING(result) + offset;
4826 }
Victor Stinner31be90b2010-04-22 19:38:16 +00004827
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004828 if (PyBytes_Check(rep)) {
4829 char *prep = PyBytes_AS_STRING(rep);
4830 for(k = repsize; k > 0; k--)
4831 *p++ = *prep++;
4832 } else /* rep is unicode */ {
Victor Stinnera98b28c2011-11-10 20:21:49 +01004833 enum PyUnicode_Kind repkind;
4834 void *repdata;
4835
Antoine Pitrou31b92a52011-11-12 18:35:19 +01004836 if (PyUnicode_READY(rep) < 0)
Victor Stinnera98b28c2011-11-10 20:21:49 +01004837 goto error;
Victor Stinnera98b28c2011-11-10 20:21:49 +01004838 repkind = PyUnicode_KIND(rep);
4839 repdata = PyUnicode_DATA(rep);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004840
4841 for(k=0; k<repsize; k++) {
Victor Stinnera98b28c2011-11-10 20:21:49 +01004842 Py_UCS4 c = PyUnicode_READ(repkind, repdata, k);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004843 if (0x80 <= c) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01004844 raise_encode_exception(&exc, "utf-8",
Victor Stinner7931d9a2011-11-04 00:22:48 +01004845 unicode,
Martin v. Löwis9e816682011-11-02 12:45:42 +01004846 i-1, i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004847 "surrogates not allowed");
Victor Stinner31be90b2010-04-22 19:38:16 +00004848 goto error;
4849 }
Victor Stinnera98b28c2011-11-10 20:21:49 +01004850 *p++ = (char)c;
Victor Stinner31be90b2010-04-22 19:38:16 +00004851 }
Victor Stinner31be90b2010-04-22 19:38:16 +00004852 }
Antoine Pitrou31b92a52011-11-12 18:35:19 +01004853 Py_CLEAR(rep);
Victor Stinner31be90b2010-04-22 19:38:16 +00004854 } else if (ch < 0x10000) {
4855 *p++ = (char)(0xe0 | (ch >> 12));
4856 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
4857 *p++ = (char)(0x80 | (ch & 0x3f));
4858 } else /* ch >= 0x10000 */ {
Tim Peters602f7402002-04-27 18:03:26 +00004859 /* Encode UCS4 Unicode ordinals */
4860 *p++ = (char)(0xf0 | (ch >> 18));
4861 *p++ = (char)(0x80 | ((ch >> 12) & 0x3f));
4862 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
4863 *p++ = (char)(0x80 | (ch & 0x3f));
4864 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004865 }
Tim Peters0eca65c2002-04-21 17:28:06 +00004866
Guido van Rossum98297ee2007-11-06 21:34:58 +00004867 if (result == NULL) {
Tim Peters602f7402002-04-27 18:03:26 +00004868 /* This was stack allocated. */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004869 nneeded = p - stackbuf;
Tim Peters602f7402002-04-27 18:03:26 +00004870 assert(nneeded <= nallocated);
Christian Heimes72b710a2008-05-26 13:28:38 +00004871 result = PyBytes_FromStringAndSize(stackbuf, nneeded);
Tim Peters602f7402002-04-27 18:03:26 +00004872 }
4873 else {
Christian Heimesf3863112007-11-22 07:46:41 +00004874 /* Cut back to size actually needed. */
Christian Heimes72b710a2008-05-26 13:28:38 +00004875 nneeded = p - PyBytes_AS_STRING(result);
Tim Peters602f7402002-04-27 18:03:26 +00004876 assert(nneeded <= nallocated);
Christian Heimes72b710a2008-05-26 13:28:38 +00004877 _PyBytes_Resize(&result, nneeded);
Tim Peters602f7402002-04-27 18:03:26 +00004878 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004879
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004880 Py_XDECREF(errorHandler);
4881 Py_XDECREF(exc);
Guido van Rossum98297ee2007-11-06 21:34:58 +00004882 return result;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004883 error:
Antoine Pitrou31b92a52011-11-12 18:35:19 +01004884 Py_XDECREF(rep);
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004885 Py_XDECREF(errorHandler);
4886 Py_XDECREF(exc);
4887 Py_XDECREF(result);
4888 return NULL;
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004889
Tim Peters602f7402002-04-27 18:03:26 +00004890#undef MAX_SHORT_UNICHARS
Guido van Rossumd57fd912000-03-10 22:53:23 +00004891}
4892
Alexander Belopolsky40018472011-02-26 01:02:56 +00004893PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004894PyUnicode_EncodeUTF8(const Py_UNICODE *s,
4895 Py_ssize_t size,
4896 const char *errors)
4897{
4898 PyObject *v, *unicode;
4899
4900 unicode = PyUnicode_FromUnicode(s, size);
4901 if (unicode == NULL)
4902 return NULL;
4903 v = _PyUnicode_AsUTF8String(unicode, errors);
4904 Py_DECREF(unicode);
4905 return v;
4906}
4907
4908PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00004909PyUnicode_AsUTF8String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004910{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004911 return _PyUnicode_AsUTF8String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004912}
4913
Walter Dörwald41980ca2007-08-16 21:55:45 +00004914/* --- UTF-32 Codec ------------------------------------------------------- */
4915
4916PyObject *
4917PyUnicode_DecodeUTF32(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004918 Py_ssize_t size,
4919 const char *errors,
4920 int *byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004921{
4922 return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
4923}
4924
4925PyObject *
4926PyUnicode_DecodeUTF32Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004927 Py_ssize_t size,
4928 const char *errors,
4929 int *byteorder,
4930 Py_ssize_t *consumed)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004931{
4932 const char *starts = s;
4933 Py_ssize_t startinpos;
4934 Py_ssize_t endinpos;
4935 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01004936 PyObject *unicode;
Mark Dickinson7db923c2010-06-12 09:10:14 +00004937 const unsigned char *q, *e;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004938 int bo = 0; /* assume native ordering by default */
4939 const char *errmsg = "";
Walter Dörwald41980ca2007-08-16 21:55:45 +00004940 /* Offsets from q for retrieving bytes in the right order. */
4941#ifdef BYTEORDER_IS_LITTLE_ENDIAN
4942 int iorder[] = {0, 1, 2, 3};
4943#else
4944 int iorder[] = {3, 2, 1, 0};
4945#endif
4946 PyObject *errorHandler = NULL;
4947 PyObject *exc = NULL;
Victor Stinner313a1202010-06-11 23:56:51 +00004948
Walter Dörwald41980ca2007-08-16 21:55:45 +00004949 q = (unsigned char *)s;
4950 e = q + size;
4951
4952 if (byteorder)
4953 bo = *byteorder;
4954
4955 /* Check for BOM marks (U+FEFF) in the input and adjust current
4956 byte order setting accordingly. In native mode, the leading BOM
4957 mark is skipped, in all other modes, it is copied to the output
4958 stream as-is (giving a ZWNBSP character). */
4959 if (bo == 0) {
4960 if (size >= 4) {
4961 const Py_UCS4 bom = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
Benjamin Peterson29060642009-01-31 22:14:21 +00004962 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00004963#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Benjamin Peterson29060642009-01-31 22:14:21 +00004964 if (bom == 0x0000FEFF) {
4965 q += 4;
4966 bo = -1;
4967 }
4968 else if (bom == 0xFFFE0000) {
4969 q += 4;
4970 bo = 1;
4971 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004972#else
Benjamin Peterson29060642009-01-31 22:14:21 +00004973 if (bom == 0x0000FEFF) {
4974 q += 4;
4975 bo = 1;
4976 }
4977 else if (bom == 0xFFFE0000) {
4978 q += 4;
4979 bo = -1;
4980 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004981#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00004982 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004983 }
4984
4985 if (bo == -1) {
4986 /* force LE */
4987 iorder[0] = 0;
4988 iorder[1] = 1;
4989 iorder[2] = 2;
4990 iorder[3] = 3;
4991 }
4992 else if (bo == 1) {
4993 /* force BE */
4994 iorder[0] = 3;
4995 iorder[1] = 2;
4996 iorder[2] = 1;
4997 iorder[3] = 0;
4998 }
4999
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005000 /* This might be one to much, because of a BOM */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005001 unicode = PyUnicode_New((size+3)/4, 127);
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005002 if (!unicode)
5003 return NULL;
5004 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01005005 return unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005006 outpos = 0;
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005007
Walter Dörwald41980ca2007-08-16 21:55:45 +00005008 while (q < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005009 Py_UCS4 ch;
5010 /* remaining bytes at the end? (size should be divisible by 4) */
5011 if (e-q<4) {
5012 if (consumed)
5013 break;
5014 errmsg = "truncated data";
5015 startinpos = ((const char *)q)-starts;
5016 endinpos = ((const char *)e)-starts;
5017 goto utf32Error;
5018 /* The remaining input chars are ignored if the callback
5019 chooses to skip the input */
5020 }
5021 ch = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
5022 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00005023
Benjamin Peterson29060642009-01-31 22:14:21 +00005024 if (ch >= 0x110000)
5025 {
5026 errmsg = "codepoint not in range(0x110000)";
5027 startinpos = ((const char *)q)-starts;
5028 endinpos = startinpos+4;
5029 goto utf32Error;
5030 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005031 if (unicode_putchar(&unicode, &outpos, ch) < 0)
5032 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005033 q += 4;
5034 continue;
5035 utf32Error:
Benjamin Peterson29060642009-01-31 22:14:21 +00005036 if (unicode_decode_call_errorhandler(
5037 errors, &errorHandler,
5038 "utf32", errmsg,
5039 &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005040 &unicode, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00005041 goto onError;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005042 }
5043
5044 if (byteorder)
5045 *byteorder = bo;
5046
5047 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005048 *consumed = (const char *)q-starts;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005049
5050 /* Adjust length */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005051 if (PyUnicode_Resize(&unicode, outpos) < 0)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005052 goto onError;
5053
5054 Py_XDECREF(errorHandler);
5055 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02005056#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02005057 if (_PyUnicode_READY_REPLACE(&unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005058 Py_DECREF(unicode);
5059 return NULL;
5060 }
Victor Stinner17efeed2011-10-04 20:05:46 +02005061#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02005062 assert(_PyUnicode_CheckConsistency(unicode, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01005063 return unicode;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005064
Benjamin Peterson29060642009-01-31 22:14:21 +00005065 onError:
Walter Dörwald41980ca2007-08-16 21:55:45 +00005066 Py_DECREF(unicode);
5067 Py_XDECREF(errorHandler);
5068 Py_XDECREF(exc);
5069 return NULL;
5070}
5071
5072PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005073_PyUnicode_EncodeUTF32(PyObject *str,
5074 const char *errors,
5075 int byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005076{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005077 int kind;
5078 void *data;
5079 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005080 PyObject *v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005081 unsigned char *p;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005082 Py_ssize_t nsize, bytesize, i;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005083 /* Offsets from p for storing byte pairs in the right order. */
5084#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5085 int iorder[] = {0, 1, 2, 3};
5086#else
5087 int iorder[] = {3, 2, 1, 0};
5088#endif
5089
Benjamin Peterson29060642009-01-31 22:14:21 +00005090#define STORECHAR(CH) \
5091 do { \
5092 p[iorder[3]] = ((CH) >> 24) & 0xff; \
5093 p[iorder[2]] = ((CH) >> 16) & 0xff; \
5094 p[iorder[1]] = ((CH) >> 8) & 0xff; \
5095 p[iorder[0]] = (CH) & 0xff; \
5096 p += 4; \
Walter Dörwald41980ca2007-08-16 21:55:45 +00005097 } while(0)
5098
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005099 if (!PyUnicode_Check(str)) {
5100 PyErr_BadArgument();
5101 return NULL;
5102 }
5103 if (PyUnicode_READY(str) < 0)
5104 return NULL;
5105 kind = PyUnicode_KIND(str);
5106 data = PyUnicode_DATA(str);
5107 len = PyUnicode_GET_LENGTH(str);
5108
5109 nsize = len + (byteorder == 0);
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005110 bytesize = nsize * 4;
5111 if (bytesize / 4 != nsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005112 return PyErr_NoMemory();
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005113 v = PyBytes_FromStringAndSize(NULL, bytesize);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005114 if (v == NULL)
5115 return NULL;
5116
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005117 p = (unsigned char *)PyBytes_AS_STRING(v);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005118 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005119 STORECHAR(0xFEFF);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005120 if (len == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005121 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005122
5123 if (byteorder == -1) {
5124 /* force LE */
5125 iorder[0] = 0;
5126 iorder[1] = 1;
5127 iorder[2] = 2;
5128 iorder[3] = 3;
5129 }
5130 else if (byteorder == 1) {
5131 /* force BE */
5132 iorder[0] = 3;
5133 iorder[1] = 2;
5134 iorder[2] = 1;
5135 iorder[3] = 0;
5136 }
5137
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005138 for (i = 0; i < len; i++)
5139 STORECHAR(PyUnicode_READ(kind, data, i));
Guido van Rossum98297ee2007-11-06 21:34:58 +00005140
5141 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005142 return v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005143#undef STORECHAR
5144}
5145
Alexander Belopolsky40018472011-02-26 01:02:56 +00005146PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005147PyUnicode_EncodeUTF32(const Py_UNICODE *s,
5148 Py_ssize_t size,
5149 const char *errors,
5150 int byteorder)
5151{
5152 PyObject *result;
5153 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5154 if (tmp == NULL)
5155 return NULL;
5156 result = _PyUnicode_EncodeUTF32(tmp, errors, byteorder);
5157 Py_DECREF(tmp);
5158 return result;
5159}
5160
5161PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005162PyUnicode_AsUTF32String(PyObject *unicode)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005163{
Victor Stinnerb960b342011-11-20 19:12:52 +01005164 return _PyUnicode_EncodeUTF32(unicode, NULL, 0);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005165}
5166
Guido van Rossumd57fd912000-03-10 22:53:23 +00005167/* --- UTF-16 Codec ------------------------------------------------------- */
5168
Tim Peters772747b2001-08-09 22:21:55 +00005169PyObject *
5170PyUnicode_DecodeUTF16(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005171 Py_ssize_t size,
5172 const char *errors,
5173 int *byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005174{
Walter Dörwald69652032004-09-07 20:24:22 +00005175 return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
5176}
5177
Antoine Pitrouab868312009-01-10 15:40:25 +00005178/* Two masks for fast checking of whether a C 'long' may contain
5179 UTF16-encoded surrogate characters. This is an efficient heuristic,
5180 assuming that non-surrogate characters with a code point >= 0x8000 are
5181 rare in most input.
5182 FAST_CHAR_MASK is used when the input is in native byte ordering,
5183 SWAPPED_FAST_CHAR_MASK when the input is in byteswapped ordering.
Benjamin Peterson29060642009-01-31 22:14:21 +00005184*/
Antoine Pitrouab868312009-01-10 15:40:25 +00005185#if (SIZEOF_LONG == 8)
5186# define FAST_CHAR_MASK 0x8000800080008000L
5187# define SWAPPED_FAST_CHAR_MASK 0x0080008000800080L
5188#elif (SIZEOF_LONG == 4)
5189# define FAST_CHAR_MASK 0x80008000L
5190# define SWAPPED_FAST_CHAR_MASK 0x00800080L
5191#else
5192# error C 'long' size should be either 4 or 8!
5193#endif
5194
Walter Dörwald69652032004-09-07 20:24:22 +00005195PyObject *
5196PyUnicode_DecodeUTF16Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005197 Py_ssize_t size,
5198 const char *errors,
5199 int *byteorder,
5200 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00005201{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005202 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005203 Py_ssize_t startinpos;
5204 Py_ssize_t endinpos;
5205 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01005206 PyObject *unicode;
Antoine Pitrouab868312009-01-10 15:40:25 +00005207 const unsigned char *q, *e, *aligned_end;
Tim Peters772747b2001-08-09 22:21:55 +00005208 int bo = 0; /* assume native ordering by default */
Antoine Pitrouab868312009-01-10 15:40:25 +00005209 int native_ordering = 0;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00005210 const char *errmsg = "";
Tim Peters772747b2001-08-09 22:21:55 +00005211 /* Offsets from q for retrieving byte pairs in the right order. */
5212#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5213 int ihi = 1, ilo = 0;
5214#else
5215 int ihi = 0, ilo = 1;
5216#endif
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005217 PyObject *errorHandler = NULL;
5218 PyObject *exc = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005219
5220 /* Note: size will always be longer than the resulting Unicode
5221 character count */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005222 unicode = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005223 if (!unicode)
5224 return NULL;
5225 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01005226 return unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005227 outpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005228
Tim Peters772747b2001-08-09 22:21:55 +00005229 q = (unsigned char *)s;
Antoine Pitrouab868312009-01-10 15:40:25 +00005230 e = q + size - 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005231
5232 if (byteorder)
Tim Peters772747b2001-08-09 22:21:55 +00005233 bo = *byteorder;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005234
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005235 /* Check for BOM marks (U+FEFF) in the input and adjust current
5236 byte order setting accordingly. In native mode, the leading BOM
5237 mark is skipped, in all other modes, it is copied to the output
5238 stream as-is (giving a ZWNBSP character). */
5239 if (bo == 0) {
Walter Dörwald69652032004-09-07 20:24:22 +00005240 if (size >= 2) {
Victor Stinner24729f32011-11-10 20:31:37 +01005241 const Py_UCS4 bom = (q[ihi] << 8) | q[ilo];
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005242#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Benjamin Peterson29060642009-01-31 22:14:21 +00005243 if (bom == 0xFEFF) {
5244 q += 2;
5245 bo = -1;
5246 }
5247 else if (bom == 0xFFFE) {
5248 q += 2;
5249 bo = 1;
5250 }
Tim Petersced69f82003-09-16 20:30:58 +00005251#else
Benjamin Peterson29060642009-01-31 22:14:21 +00005252 if (bom == 0xFEFF) {
5253 q += 2;
5254 bo = 1;
5255 }
5256 else if (bom == 0xFFFE) {
5257 q += 2;
5258 bo = -1;
5259 }
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005260#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00005261 }
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005262 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005263
Tim Peters772747b2001-08-09 22:21:55 +00005264 if (bo == -1) {
5265 /* force LE */
5266 ihi = 1;
5267 ilo = 0;
5268 }
5269 else if (bo == 1) {
5270 /* force BE */
5271 ihi = 0;
5272 ilo = 1;
5273 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005274#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5275 native_ordering = ilo < ihi;
5276#else
5277 native_ordering = ilo > ihi;
5278#endif
Tim Peters772747b2001-08-09 22:21:55 +00005279
Antoine Pitrouab868312009-01-10 15:40:25 +00005280 aligned_end = (const unsigned char *) ((size_t) e & ~LONG_PTR_MASK);
Tim Peters772747b2001-08-09 22:21:55 +00005281 while (q < e) {
Victor Stinner24729f32011-11-10 20:31:37 +01005282 Py_UCS4 ch;
Antoine Pitrouab868312009-01-10 15:40:25 +00005283 /* First check for possible aligned read of a C 'long'. Unaligned
5284 reads are more expensive, better to defer to another iteration. */
5285 if (!((size_t) q & LONG_PTR_MASK)) {
5286 /* Fast path for runs of non-surrogate chars. */
5287 register const unsigned char *_q = q;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005288 int kind = PyUnicode_KIND(unicode);
5289 void *data = PyUnicode_DATA(unicode);
5290 while (_q < aligned_end) {
5291 unsigned long block = * (unsigned long *) _q;
5292 unsigned short *pblock = (unsigned short*)&block;
5293 Py_UCS4 maxch;
5294 if (native_ordering) {
5295 /* Can use buffer directly */
5296 if (block & FAST_CHAR_MASK)
Antoine Pitrouab868312009-01-10 15:40:25 +00005297 break;
Antoine Pitrouab868312009-01-10 15:40:25 +00005298 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005299 else {
5300 /* Need to byte-swap */
5301 unsigned char *_p = (unsigned char*)pblock;
5302 if (block & SWAPPED_FAST_CHAR_MASK)
Antoine Pitrouab868312009-01-10 15:40:25 +00005303 break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005304 _p[0] = _q[1];
5305 _p[1] = _q[0];
5306 _p[2] = _q[3];
5307 _p[3] = _q[2];
Antoine Pitrouab868312009-01-10 15:40:25 +00005308#if (SIZEOF_LONG == 8)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005309 _p[4] = _q[5];
5310 _p[5] = _q[4];
5311 _p[6] = _q[7];
5312 _p[7] = _q[6];
Antoine Pitrouab868312009-01-10 15:40:25 +00005313#endif
Antoine Pitrouab868312009-01-10 15:40:25 +00005314 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005315 maxch = Py_MAX(pblock[0], pblock[1]);
5316#if SIZEOF_LONG == 8
5317 maxch = Py_MAX(maxch, Py_MAX(pblock[2], pblock[3]));
5318#endif
5319 if (maxch > PyUnicode_MAX_CHAR_VALUE(unicode)) {
5320 if (unicode_widen(&unicode, maxch) < 0)
5321 goto onError;
5322 kind = PyUnicode_KIND(unicode);
5323 data = PyUnicode_DATA(unicode);
5324 }
5325 PyUnicode_WRITE(kind, data, outpos++, pblock[0]);
5326 PyUnicode_WRITE(kind, data, outpos++, pblock[1]);
5327#if SIZEOF_LONG == 8
5328 PyUnicode_WRITE(kind, data, outpos++, pblock[2]);
5329 PyUnicode_WRITE(kind, data, outpos++, pblock[3]);
5330#endif
5331 _q += SIZEOF_LONG;
Antoine Pitrouab868312009-01-10 15:40:25 +00005332 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005333 q = _q;
5334 if (q >= e)
5335 break;
5336 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005337 ch = (q[ihi] << 8) | q[ilo];
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005338
Benjamin Peterson14339b62009-01-31 16:36:08 +00005339 q += 2;
Benjamin Peterson29060642009-01-31 22:14:21 +00005340
5341 if (ch < 0xD800 || ch > 0xDFFF) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005342 if (unicode_putchar(&unicode, &outpos, ch) < 0)
5343 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005344 continue;
5345 }
5346
5347 /* UTF-16 code pair: */
5348 if (q > e) {
5349 errmsg = "unexpected end of data";
5350 startinpos = (((const char *)q) - 2) - starts;
5351 endinpos = ((const char *)e) + 1 - starts;
5352 goto utf16Error;
5353 }
Victor Stinner2e9cfad2011-11-20 18:40:27 +01005354 if (Py_UNICODE_IS_HIGH_SURROGATE(ch)) {
5355 Py_UCS4 ch2 = (q[ihi] << 8) | q[ilo];
Benjamin Peterson29060642009-01-31 22:14:21 +00005356 q += 2;
Victor Stinner2e9cfad2011-11-20 18:40:27 +01005357 if (Py_UNICODE_IS_LOW_SURROGATE(ch2)) {
Victor Stinner62aa4d02011-11-09 00:03:45 +01005358 if (unicode_putchar(&unicode, &outpos,
Victor Stinner2e9cfad2011-11-20 18:40:27 +01005359 Py_UNICODE_JOIN_SURROGATES(ch, ch2)) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005360 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005361 continue;
5362 }
5363 else {
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005364 errmsg = "illegal UTF-16 surrogate";
Benjamin Peterson29060642009-01-31 22:14:21 +00005365 startinpos = (((const char *)q)-4)-starts;
5366 endinpos = startinpos+2;
5367 goto utf16Error;
5368 }
5369
Benjamin Peterson14339b62009-01-31 16:36:08 +00005370 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005371 errmsg = "illegal encoding";
5372 startinpos = (((const char *)q)-2)-starts;
5373 endinpos = startinpos+2;
5374 /* Fall through to report the error */
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005375
Benjamin Peterson29060642009-01-31 22:14:21 +00005376 utf16Error:
Benjamin Peterson29060642009-01-31 22:14:21 +00005377 if (unicode_decode_call_errorhandler(
Antoine Pitrouab868312009-01-10 15:40:25 +00005378 errors,
5379 &errorHandler,
5380 "utf16", errmsg,
5381 &starts,
5382 (const char **)&e,
5383 &startinpos,
5384 &endinpos,
5385 &exc,
5386 (const char **)&q,
5387 &unicode,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005388 &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00005389 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005390 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005391 /* remaining byte at the end? (size should be even) */
5392 if (e == q) {
5393 if (!consumed) {
5394 errmsg = "truncated data";
5395 startinpos = ((const char *)q) - starts;
5396 endinpos = ((const char *)e) + 1 - starts;
Antoine Pitrouab868312009-01-10 15:40:25 +00005397 if (unicode_decode_call_errorhandler(
5398 errors,
5399 &errorHandler,
5400 "utf16", errmsg,
5401 &starts,
5402 (const char **)&e,
5403 &startinpos,
5404 &endinpos,
5405 &exc,
5406 (const char **)&q,
5407 &unicode,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005408 &outpos))
Antoine Pitrouab868312009-01-10 15:40:25 +00005409 goto onError;
5410 /* The remaining input chars are ignored if the callback
5411 chooses to skip the input */
5412 }
5413 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005414
5415 if (byteorder)
5416 *byteorder = bo;
5417
Walter Dörwald69652032004-09-07 20:24:22 +00005418 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005419 *consumed = (const char *)q-starts;
Walter Dörwald69652032004-09-07 20:24:22 +00005420
Guido van Rossumd57fd912000-03-10 22:53:23 +00005421 /* Adjust length */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005422 if (PyUnicode_Resize(&unicode, outpos) < 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005423 goto onError;
5424
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005425 Py_XDECREF(errorHandler);
5426 Py_XDECREF(exc);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02005427 assert(_PyUnicode_CheckConsistency(unicode, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01005428 return unicode;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005429
Benjamin Peterson29060642009-01-31 22:14:21 +00005430 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00005431 Py_DECREF(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005432 Py_XDECREF(errorHandler);
5433 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005434 return NULL;
5435}
5436
Antoine Pitrouab868312009-01-10 15:40:25 +00005437#undef FAST_CHAR_MASK
5438#undef SWAPPED_FAST_CHAR_MASK
5439
Tim Peters772747b2001-08-09 22:21:55 +00005440PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005441_PyUnicode_EncodeUTF16(PyObject *str,
5442 const char *errors,
5443 int byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005444{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005445 int kind;
5446 void *data;
5447 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005448 PyObject *v;
Tim Peters772747b2001-08-09 22:21:55 +00005449 unsigned char *p;
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005450 Py_ssize_t nsize, bytesize;
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005451 Py_ssize_t i, pairs;
Tim Peters772747b2001-08-09 22:21:55 +00005452 /* Offsets from p for storing byte pairs in the right order. */
5453#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5454 int ihi = 1, ilo = 0;
5455#else
5456 int ihi = 0, ilo = 1;
5457#endif
5458
Benjamin Peterson29060642009-01-31 22:14:21 +00005459#define STORECHAR(CH) \
5460 do { \
5461 p[ihi] = ((CH) >> 8) & 0xff; \
5462 p[ilo] = (CH) & 0xff; \
5463 p += 2; \
Tim Peters772747b2001-08-09 22:21:55 +00005464 } while(0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005465
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005466 if (!PyUnicode_Check(str)) {
5467 PyErr_BadArgument();
5468 return NULL;
5469 }
5470 if (PyUnicode_READY(str) < 0)
5471 return NULL;
5472 kind = PyUnicode_KIND(str);
5473 data = PyUnicode_DATA(str);
5474 len = PyUnicode_GET_LENGTH(str);
Victor Stinner0e368262011-11-10 20:12:49 +01005475
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005476 pairs = 0;
5477 if (kind == PyUnicode_4BYTE_KIND)
5478 for (i = 0; i < len; i++)
5479 if (PyUnicode_READ(kind, data, i) >= 0x10000)
5480 pairs++;
5481 /* 2 * (len + pairs + (byteorder == 0)) */
5482 if (len > PY_SSIZE_T_MAX - pairs - (byteorder == 0))
Benjamin Peterson29060642009-01-31 22:14:21 +00005483 return PyErr_NoMemory();
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005484 nsize = len + pairs + (byteorder == 0);
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005485 bytesize = nsize * 2;
5486 if (bytesize / 2 != nsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005487 return PyErr_NoMemory();
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005488 v = PyBytes_FromStringAndSize(NULL, bytesize);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005489 if (v == NULL)
5490 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005491
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005492 p = (unsigned char *)PyBytes_AS_STRING(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005493 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005494 STORECHAR(0xFEFF);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005495 if (len == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005496 goto done;
Tim Peters772747b2001-08-09 22:21:55 +00005497
5498 if (byteorder == -1) {
5499 /* force LE */
5500 ihi = 1;
5501 ilo = 0;
5502 }
5503 else if (byteorder == 1) {
5504 /* force BE */
5505 ihi = 0;
5506 ilo = 1;
5507 }
5508
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005509 for (i = 0; i < len; i++) {
5510 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
5511 Py_UCS4 ch2 = 0;
Benjamin Peterson29060642009-01-31 22:14:21 +00005512 if (ch >= 0x10000) {
5513 ch2 = 0xDC00 | ((ch-0x10000) & 0x3FF);
5514 ch = 0xD800 | ((ch-0x10000) >> 10);
5515 }
Tim Peters772747b2001-08-09 22:21:55 +00005516 STORECHAR(ch);
5517 if (ch2)
5518 STORECHAR(ch2);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005519 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005520
5521 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005522 return v;
Tim Peters772747b2001-08-09 22:21:55 +00005523#undef STORECHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00005524}
5525
Alexander Belopolsky40018472011-02-26 01:02:56 +00005526PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005527PyUnicode_EncodeUTF16(const Py_UNICODE *s,
5528 Py_ssize_t size,
5529 const char *errors,
5530 int byteorder)
5531{
5532 PyObject *result;
5533 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5534 if (tmp == NULL)
5535 return NULL;
5536 result = _PyUnicode_EncodeUTF16(tmp, errors, byteorder);
5537 Py_DECREF(tmp);
5538 return result;
5539}
5540
5541PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005542PyUnicode_AsUTF16String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005543{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005544 return _PyUnicode_EncodeUTF16(unicode, NULL, 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005545}
5546
5547/* --- Unicode Escape Codec ----------------------------------------------- */
5548
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005549/* Helper function for PyUnicode_DecodeUnicodeEscape, determines
5550 if all the escapes in the string make it still a valid ASCII string.
5551 Returns -1 if any escapes were found which cause the string to
5552 pop out of ASCII range. Otherwise returns the length of the
5553 required buffer to hold the string.
5554 */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02005555static Py_ssize_t
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005556length_of_escaped_ascii_string(const char *s, Py_ssize_t size)
5557{
5558 const unsigned char *p = (const unsigned char *)s;
5559 const unsigned char *end = p + size;
5560 Py_ssize_t length = 0;
5561
5562 if (size < 0)
5563 return -1;
5564
5565 for (; p < end; ++p) {
5566 if (*p > 127) {
5567 /* Non-ASCII */
5568 return -1;
5569 }
5570 else if (*p != '\\') {
5571 /* Normal character */
5572 ++length;
5573 }
5574 else {
5575 /* Backslash-escape, check next char */
5576 ++p;
5577 /* Escape sequence reaches till end of string or
5578 non-ASCII follow-up. */
5579 if (p >= end || *p > 127)
5580 return -1;
5581 switch (*p) {
5582 case '\n':
5583 /* backslash + \n result in zero characters */
5584 break;
5585 case '\\': case '\'': case '\"':
5586 case 'b': case 'f': case 't':
5587 case 'n': case 'r': case 'v': case 'a':
5588 ++length;
5589 break;
5590 case '0': case '1': case '2': case '3':
5591 case '4': case '5': case '6': case '7':
5592 case 'x': case 'u': case 'U': case 'N':
5593 /* these do not guarantee ASCII characters */
5594 return -1;
5595 default:
5596 /* count the backslash + the other character */
5597 length += 2;
5598 }
5599 }
5600 }
5601 return length;
5602}
5603
Fredrik Lundh06d12682001-01-24 07:59:11 +00005604static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
Marc-André Lemburg0f774e32000-06-28 16:43:35 +00005605
Alexander Belopolsky40018472011-02-26 01:02:56 +00005606PyObject *
5607PyUnicode_DecodeUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005608 Py_ssize_t size,
Victor Stinnerc17f5402011-09-29 00:16:58 +02005609 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005610{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005611 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005612 Py_ssize_t startinpos;
5613 Py_ssize_t endinpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005614 int j;
Victor Stinner7931d9a2011-11-04 00:22:48 +01005615 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005616 const char *end;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005617 char* message;
5618 Py_UCS4 chr = 0xffffffff; /* in case 'getcode' messes up */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005619 PyObject *errorHandler = NULL;
5620 PyObject *exc = NULL;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005621 Py_ssize_t len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005622 Py_ssize_t i;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005623
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005624 len = length_of_escaped_ascii_string(s, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005625
5626 /* After length_of_escaped_ascii_string() there are two alternatives,
5627 either the string is pure ASCII with named escapes like \n, etc.
5628 and we determined it's exact size (common case)
5629 or it contains \x, \u, ... escape sequences. then we create a
5630 legacy wchar string and resize it at the end of this function. */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005631 if (len >= 0) {
5632 v = PyUnicode_New(len, 127);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005633 if (!v)
5634 goto onError;
5635 assert(PyUnicode_KIND(v) == PyUnicode_1BYTE_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005636 }
5637 else {
5638 /* Escaped strings will always be longer than the resulting
5639 Unicode string, so we start with size here and then reduce the
5640 length after conversion to the true value.
5641 (but if the error callback returns a long replacement string
5642 we'll have to allocate more space) */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005643 v = PyUnicode_New(size, 127);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005644 if (!v)
5645 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005646 len = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005647 }
5648
Guido van Rossumd57fd912000-03-10 22:53:23 +00005649 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01005650 return v;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005651 i = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005652 end = s + size;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005653
Guido van Rossumd57fd912000-03-10 22:53:23 +00005654 while (s < end) {
5655 unsigned char c;
Victor Stinner24729f32011-11-10 20:31:37 +01005656 Py_UCS4 x;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005657 int digits;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005658
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005659 /* The only case in which i == ascii_length is a backslash
5660 followed by a newline. */
5661 assert(i <= len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005662
Guido van Rossumd57fd912000-03-10 22:53:23 +00005663 /* Non-escape characters are interpreted as Unicode ordinals */
5664 if (*s != '\\') {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005665 if (unicode_putchar(&v, &i, (unsigned char) *s++) < 0)
5666 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005667 continue;
5668 }
5669
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005670 startinpos = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005671 /* \ - Escapes */
5672 s++;
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005673 c = *s++;
5674 if (s > end)
5675 c = '\0'; /* Invalid after \ */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005676
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005677 /* The only case in which i == ascii_length is a backslash
5678 followed by a newline. */
5679 assert(i < len || (i == len && c == '\n'));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005680
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005681 switch (c) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005682
Benjamin Peterson29060642009-01-31 22:14:21 +00005683 /* \x escapes */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005684#define WRITECHAR(ch) \
5685 do { \
5686 if (unicode_putchar(&v, &i, ch) < 0) \
5687 goto onError; \
5688 }while(0)
5689
Guido van Rossumd57fd912000-03-10 22:53:23 +00005690 case '\n': break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005691 case '\\': WRITECHAR('\\'); break;
5692 case '\'': WRITECHAR('\''); break;
5693 case '\"': WRITECHAR('\"'); break;
5694 case 'b': WRITECHAR('\b'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005695 /* FF */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005696 case 'f': WRITECHAR('\014'); break;
5697 case 't': WRITECHAR('\t'); break;
5698 case 'n': WRITECHAR('\n'); break;
5699 case 'r': WRITECHAR('\r'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005700 /* VT */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005701 case 'v': WRITECHAR('\013'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005702 /* BEL, not classic C */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005703 case 'a': WRITECHAR('\007'); break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005704
Benjamin Peterson29060642009-01-31 22:14:21 +00005705 /* \OOO (octal) escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005706 case '0': case '1': case '2': case '3':
5707 case '4': case '5': case '6': case '7':
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005708 x = s[-1] - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005709 if (s < end && '0' <= *s && *s <= '7') {
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005710 x = (x<<3) + *s++ - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005711 if (s < end && '0' <= *s && *s <= '7')
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005712 x = (x<<3) + *s++ - '0';
Guido van Rossumd57fd912000-03-10 22:53:23 +00005713 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005714 WRITECHAR(x);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005715 break;
5716
Benjamin Peterson29060642009-01-31 22:14:21 +00005717 /* hex escapes */
5718 /* \xXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005719 case 'x':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005720 digits = 2;
5721 message = "truncated \\xXX escape";
5722 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005723
Benjamin Peterson29060642009-01-31 22:14:21 +00005724 /* \uXXXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005725 case 'u':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005726 digits = 4;
5727 message = "truncated \\uXXXX escape";
5728 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005729
Benjamin Peterson29060642009-01-31 22:14:21 +00005730 /* \UXXXXXXXX */
Fredrik Lundhdf846752000-09-03 11:29:49 +00005731 case 'U':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005732 digits = 8;
5733 message = "truncated \\UXXXXXXXX escape";
5734 hexescape:
5735 chr = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005736 if (s+digits>end) {
5737 endinpos = size;
5738 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005739 errors, &errorHandler,
5740 "unicodeescape", "end of string in escape sequence",
5741 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005742 &v, &i))
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005743 goto onError;
5744 goto nextByte;
5745 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005746 for (j = 0; j < digits; ++j) {
5747 c = (unsigned char) s[j];
David Malcolm96960882010-11-05 17:23:41 +00005748 if (!Py_ISXDIGIT(c)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005749 endinpos = (s+j+1)-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005750 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005751 errors, &errorHandler,
5752 "unicodeescape", message,
5753 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005754 &v, &i))
Fredrik Lundhdf846752000-09-03 11:29:49 +00005755 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005756 len = PyUnicode_GET_LENGTH(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005757 goto nextByte;
Fredrik Lundhdf846752000-09-03 11:29:49 +00005758 }
5759 chr = (chr<<4) & ~0xF;
5760 if (c >= '0' && c <= '9')
5761 chr += c - '0';
5762 else if (c >= 'a' && c <= 'f')
5763 chr += 10 + c - 'a';
5764 else
5765 chr += 10 + c - 'A';
5766 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005767 s += j;
Jeremy Hylton504de6b2003-10-06 05:08:26 +00005768 if (chr == 0xffffffff && PyErr_Occurred())
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005769 /* _decoding_error will have already written into the
5770 target buffer. */
5771 break;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005772 store:
Fredrik Lundhdf846752000-09-03 11:29:49 +00005773 /* when we get here, chr is a 32-bit unicode character */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005774 if (chr <= 0x10ffff) {
5775 WRITECHAR(chr);
Fredrik Lundhdf846752000-09-03 11:29:49 +00005776 } else {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005777 endinpos = s-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005778 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005779 errors, &errorHandler,
5780 "unicodeescape", "illegal Unicode character",
5781 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005782 &v, &i))
Fredrik Lundhdf846752000-09-03 11:29:49 +00005783 goto onError;
5784 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00005785 break;
5786
Benjamin Peterson29060642009-01-31 22:14:21 +00005787 /* \N{name} */
Fredrik Lundhccc74732001-02-18 22:13:49 +00005788 case 'N':
5789 message = "malformed \\N character escape";
5790 if (ucnhash_CAPI == NULL) {
5791 /* load the unicode data module */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005792 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
5793 PyUnicodeData_CAPSULE_NAME, 1);
Fredrik Lundhccc74732001-02-18 22:13:49 +00005794 if (ucnhash_CAPI == NULL)
5795 goto ucnhashError;
5796 }
5797 if (*s == '{') {
5798 const char *start = s+1;
5799 /* look for the closing brace */
5800 while (*s != '}' && s < end)
5801 s++;
5802 if (s > start && s < end && *s == '}') {
5803 /* found a name. look it up in the unicode database */
5804 message = "unknown Unicode character name";
5805 s++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005806 if (ucnhash_CAPI->getcode(NULL, start, (int)(s-start-1),
Ezio Melotti931b8aa2011-10-21 21:57:36 +03005807 &chr, 0))
Fredrik Lundhccc74732001-02-18 22:13:49 +00005808 goto store;
5809 }
5810 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005811 endinpos = s-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005812 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005813 errors, &errorHandler,
5814 "unicodeescape", message,
5815 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005816 &v, &i))
Fredrik Lundhccc74732001-02-18 22:13:49 +00005817 goto onError;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005818 break;
5819
5820 default:
Walter Dörwald8c077222002-03-25 11:16:18 +00005821 if (s > end) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005822 message = "\\ at end of string";
5823 s--;
5824 endinpos = s-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005825 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005826 errors, &errorHandler,
5827 "unicodeescape", message,
5828 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005829 &v, &i))
Walter Dörwald8c077222002-03-25 11:16:18 +00005830 goto onError;
5831 }
5832 else {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005833 WRITECHAR('\\');
5834 WRITECHAR(s[-1]);
Walter Dörwald8c077222002-03-25 11:16:18 +00005835 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00005836 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005837 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005838 nextByte:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005839 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005840 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005841#undef WRITECHAR
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005842
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005843 if (PyUnicode_Resize(&v, i) < 0)
5844 goto onError;
Walter Dörwaldd4ade082003-08-15 15:00:26 +00005845 Py_XDECREF(errorHandler);
5846 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02005847#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02005848 if (_PyUnicode_READY_REPLACE(&v)) {
5849 Py_DECREF(v);
5850 return NULL;
5851 }
Victor Stinner17efeed2011-10-04 20:05:46 +02005852#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02005853 assert(_PyUnicode_CheckConsistency(v, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01005854 return v;
Walter Dörwald8c077222002-03-25 11:16:18 +00005855
Benjamin Peterson29060642009-01-31 22:14:21 +00005856 ucnhashError:
Fredrik Lundh06d12682001-01-24 07:59:11 +00005857 PyErr_SetString(
5858 PyExc_UnicodeError,
5859 "\\N escapes not supported (can't load unicodedata module)"
5860 );
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00005861 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005862 Py_XDECREF(errorHandler);
5863 Py_XDECREF(exc);
Fredrik Lundhf6056062001-01-20 11:15:25 +00005864 return NULL;
5865
Benjamin Peterson29060642009-01-31 22:14:21 +00005866 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00005867 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005868 Py_XDECREF(errorHandler);
5869 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005870 return NULL;
5871}
5872
5873/* Return a Unicode-Escape string version of the Unicode object.
5874
5875 If quotes is true, the string is enclosed in u"" or u'' quotes as
5876 appropriate.
5877
5878*/
5879
Alexander Belopolsky40018472011-02-26 01:02:56 +00005880PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005881PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005882{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005883 Py_ssize_t i, len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005884 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005885 char *p;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005886 int kind;
5887 void *data;
5888 Py_ssize_t expandsize = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005889
Thomas Wouters89f507f2006-12-13 04:49:30 +00005890 /* Initial allocation is based on the longest-possible unichr
5891 escape.
5892
5893 In wide (UTF-32) builds '\U00xxxxxx' is 10 chars per source
5894 unichr, so in this case it's the longest unichr escape. In
5895 narrow (UTF-16) builds this is five chars per source unichr
5896 since there are two unichrs in the surrogate pair, so in narrow
5897 (UTF-16) builds it's not the longest unichr escape.
5898
5899 In wide or narrow builds '\uxxxx' is 6 chars per source unichr,
5900 so in the narrow (UTF-16) build case it's the longest unichr
5901 escape.
5902 */
5903
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005904 if (!PyUnicode_Check(unicode)) {
5905 PyErr_BadArgument();
5906 return NULL;
5907 }
5908 if (PyUnicode_READY(unicode) < 0)
5909 return NULL;
5910 len = PyUnicode_GET_LENGTH(unicode);
5911 kind = PyUnicode_KIND(unicode);
5912 data = PyUnicode_DATA(unicode);
5913 switch(kind) {
5914 case PyUnicode_1BYTE_KIND: expandsize = 4; break;
5915 case PyUnicode_2BYTE_KIND: expandsize = 6; break;
5916 case PyUnicode_4BYTE_KIND: expandsize = 10; break;
5917 }
5918
5919 if (len == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005920 return PyBytes_FromStringAndSize(NULL, 0);
5921
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005922 if (len > (PY_SSIZE_T_MAX - 2 - 1) / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005923 return PyErr_NoMemory();
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005924
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005925 repr = PyBytes_FromStringAndSize(NULL,
Benjamin Peterson29060642009-01-31 22:14:21 +00005926 2
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005927 + expandsize*len
Benjamin Peterson29060642009-01-31 22:14:21 +00005928 + 1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005929 if (repr == NULL)
5930 return NULL;
5931
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005932 p = PyBytes_AS_STRING(repr);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005933
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005934 for (i = 0; i < len; i++) {
Victor Stinner3326cb62011-11-10 20:15:25 +01005935 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005936
Walter Dörwald79e913e2007-05-12 11:08:06 +00005937 /* Escape backslashes */
5938 if (ch == '\\') {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005939 *p++ = '\\';
5940 *p++ = (char) ch;
Walter Dörwald79e913e2007-05-12 11:08:06 +00005941 continue;
Tim Petersced69f82003-09-16 20:30:58 +00005942 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005943
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005944 /* Map 21-bit characters to '\U00xxxxxx' */
5945 else if (ch >= 0x10000) {
5946 *p++ = '\\';
5947 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005948 *p++ = Py_hexdigits[(ch >> 28) & 0x0000000F];
5949 *p++ = Py_hexdigits[(ch >> 24) & 0x0000000F];
5950 *p++ = Py_hexdigits[(ch >> 20) & 0x0000000F];
5951 *p++ = Py_hexdigits[(ch >> 16) & 0x0000000F];
5952 *p++ = Py_hexdigits[(ch >> 12) & 0x0000000F];
5953 *p++ = Py_hexdigits[(ch >> 8) & 0x0000000F];
5954 *p++ = Py_hexdigits[(ch >> 4) & 0x0000000F];
5955 *p++ = Py_hexdigits[ch & 0x0000000F];
Benjamin Peterson29060642009-01-31 22:14:21 +00005956 continue;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005957 }
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005958
Guido van Rossumd57fd912000-03-10 22:53:23 +00005959 /* Map 16-bit characters to '\uxxxx' */
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005960 if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005961 *p++ = '\\';
5962 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005963 *p++ = Py_hexdigits[(ch >> 12) & 0x000F];
5964 *p++ = Py_hexdigits[(ch >> 8) & 0x000F];
5965 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
5966 *p++ = Py_hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00005967 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005968
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005969 /* Map special whitespace to '\t', \n', '\r' */
5970 else if (ch == '\t') {
5971 *p++ = '\\';
5972 *p++ = 't';
5973 }
5974 else if (ch == '\n') {
5975 *p++ = '\\';
5976 *p++ = 'n';
5977 }
5978 else if (ch == '\r') {
5979 *p++ = '\\';
5980 *p++ = 'r';
5981 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005982
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005983 /* Map non-printable US ASCII to '\xhh' */
Marc-André Lemburg11326de2001-11-28 12:56:20 +00005984 else if (ch < ' ' || ch >= 0x7F) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005985 *p++ = '\\';
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005986 *p++ = 'x';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005987 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
5988 *p++ = Py_hexdigits[ch & 0x000F];
Tim Petersced69f82003-09-16 20:30:58 +00005989 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005990
Guido van Rossumd57fd912000-03-10 22:53:23 +00005991 /* Copy everything else as-is */
5992 else
5993 *p++ = (char) ch;
5994 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005995
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005996 assert(p - PyBytes_AS_STRING(repr) > 0);
5997 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0)
5998 return NULL;
5999 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006000}
6001
Alexander Belopolsky40018472011-02-26 01:02:56 +00006002PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006003PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
6004 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006005{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006006 PyObject *result;
6007 PyObject *tmp = PyUnicode_FromUnicode(s, size);
6008 if (tmp == NULL)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006009 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006010 result = PyUnicode_AsUnicodeEscapeString(tmp);
6011 Py_DECREF(tmp);
6012 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006013}
6014
6015/* --- Raw Unicode Escape Codec ------------------------------------------- */
6016
Alexander Belopolsky40018472011-02-26 01:02:56 +00006017PyObject *
6018PyUnicode_DecodeRawUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006019 Py_ssize_t size,
6020 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006021{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006022 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006023 Py_ssize_t startinpos;
6024 Py_ssize_t endinpos;
6025 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01006026 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006027 const char *end;
6028 const char *bs;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006029 PyObject *errorHandler = NULL;
6030 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006031
Guido van Rossumd57fd912000-03-10 22:53:23 +00006032 /* Escaped strings will always be longer than the resulting
6033 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006034 length after conversion to the true value. (But decoding error
6035 handler might have to resize the string) */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006036 v = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006037 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006038 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006039 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01006040 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006041 outpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006042 end = s + size;
6043 while (s < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006044 unsigned char c;
6045 Py_UCS4 x;
6046 int i;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006047 int count;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006048
Benjamin Peterson29060642009-01-31 22:14:21 +00006049 /* Non-escape characters are interpreted as Unicode ordinals */
6050 if (*s != '\\') {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006051 if (unicode_putchar(&v, &outpos, (unsigned char)*s++) < 0)
6052 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00006053 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006054 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006055 startinpos = s-starts;
6056
6057 /* \u-escapes are only interpreted iff the number of leading
6058 backslashes if odd */
6059 bs = s;
6060 for (;s < end;) {
6061 if (*s != '\\')
6062 break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006063 if (unicode_putchar(&v, &outpos, (unsigned char)*s++) < 0)
6064 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00006065 }
6066 if (((s - bs) & 1) == 0 ||
6067 s >= end ||
6068 (*s != 'u' && *s != 'U')) {
6069 continue;
6070 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006071 outpos--;
Benjamin Peterson29060642009-01-31 22:14:21 +00006072 count = *s=='u' ? 4 : 8;
6073 s++;
6074
6075 /* \uXXXX with 4 hex digits, \Uxxxxxxxx with 8 */
Benjamin Peterson29060642009-01-31 22:14:21 +00006076 for (x = 0, i = 0; i < count; ++i, ++s) {
6077 c = (unsigned char)*s;
David Malcolm96960882010-11-05 17:23:41 +00006078 if (!Py_ISXDIGIT(c)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006079 endinpos = s-starts;
6080 if (unicode_decode_call_errorhandler(
6081 errors, &errorHandler,
6082 "rawunicodeescape", "truncated \\uXXXX",
6083 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006084 &v, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00006085 goto onError;
6086 goto nextByte;
6087 }
6088 x = (x<<4) & ~0xF;
6089 if (c >= '0' && c <= '9')
6090 x += c - '0';
6091 else if (c >= 'a' && c <= 'f')
6092 x += 10 + c - 'a';
6093 else
6094 x += 10 + c - 'A';
6095 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006096 if (x <= 0x10ffff) {
6097 if (unicode_putchar(&v, &outpos, x) < 0)
6098 goto onError;
Christian Heimesfe337bf2008-03-23 21:54:12 +00006099 } else {
6100 endinpos = s-starts;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006101 if (unicode_decode_call_errorhandler(
6102 errors, &errorHandler,
6103 "rawunicodeescape", "\\Uxxxxxxxx out of range",
Benjamin Peterson29060642009-01-31 22:14:21 +00006104 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006105 &v, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00006106 goto onError;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006107 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006108 nextByte:
6109 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006110 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006111 if (PyUnicode_Resize(&v, outpos) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006112 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006113 Py_XDECREF(errorHandler);
6114 Py_XDECREF(exc);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02006115 assert(_PyUnicode_CheckConsistency(v, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01006116 return v;
Tim Petersced69f82003-09-16 20:30:58 +00006117
Benjamin Peterson29060642009-01-31 22:14:21 +00006118 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00006119 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006120 Py_XDECREF(errorHandler);
6121 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006122 return NULL;
6123}
6124
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006125
Alexander Belopolsky40018472011-02-26 01:02:56 +00006126PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006127PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006128{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006129 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006130 char *p;
6131 char *q;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006132 Py_ssize_t expandsize, pos;
6133 int kind;
6134 void *data;
6135 Py_ssize_t len;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006136
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006137 if (!PyUnicode_Check(unicode)) {
6138 PyErr_BadArgument();
6139 return NULL;
6140 }
6141 if (PyUnicode_READY(unicode) < 0)
6142 return NULL;
6143 kind = PyUnicode_KIND(unicode);
6144 data = PyUnicode_DATA(unicode);
6145 len = PyUnicode_GET_LENGTH(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006146
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006147 switch(kind) {
6148 case PyUnicode_1BYTE_KIND: expandsize = 4; break;
6149 case PyUnicode_2BYTE_KIND: expandsize = 6; break;
6150 case PyUnicode_4BYTE_KIND: expandsize = 10; break;
6151 }
Victor Stinner0e368262011-11-10 20:12:49 +01006152
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006153 if (len > PY_SSIZE_T_MAX / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00006154 return PyErr_NoMemory();
Benjamin Peterson14339b62009-01-31 16:36:08 +00006155
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006156 repr = PyBytes_FromStringAndSize(NULL, expandsize * len);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006157 if (repr == NULL)
6158 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006159 if (len == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006160 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006161
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006162 p = q = PyBytes_AS_STRING(repr);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006163 for (pos = 0; pos < len; pos++) {
6164 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Benjamin Peterson29060642009-01-31 22:14:21 +00006165 /* Map 32-bit characters to '\Uxxxxxxxx' */
6166 if (ch >= 0x10000) {
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006167 *p++ = '\\';
6168 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006169 *p++ = Py_hexdigits[(ch >> 28) & 0xf];
6170 *p++ = Py_hexdigits[(ch >> 24) & 0xf];
6171 *p++ = Py_hexdigits[(ch >> 20) & 0xf];
6172 *p++ = Py_hexdigits[(ch >> 16) & 0xf];
6173 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6174 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6175 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6176 *p++ = Py_hexdigits[ch & 15];
Tim Petersced69f82003-09-16 20:30:58 +00006177 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006178 /* Map 16-bit characters to '\uxxxx' */
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006179 else if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006180 *p++ = '\\';
6181 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006182 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6183 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6184 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6185 *p++ = Py_hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006186 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006187 /* Copy everything else as-is */
6188 else
Guido van Rossumd57fd912000-03-10 22:53:23 +00006189 *p++ = (char) ch;
6190 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00006191
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006192 assert(p > q);
6193 if (_PyBytes_Resize(&repr, p - q) < 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006194 return NULL;
6195 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006196}
6197
Alexander Belopolsky40018472011-02-26 01:02:56 +00006198PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006199PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
6200 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006201{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006202 PyObject *result;
6203 PyObject *tmp = PyUnicode_FromUnicode(s, size);
6204 if (tmp == NULL)
Walter Dörwald711005d2007-05-12 12:03:26 +00006205 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006206 result = PyUnicode_AsRawUnicodeEscapeString(tmp);
6207 Py_DECREF(tmp);
6208 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006209}
6210
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006211/* --- Unicode Internal Codec ------------------------------------------- */
6212
Alexander Belopolsky40018472011-02-26 01:02:56 +00006213PyObject *
6214_PyUnicode_DecodeUnicodeInternal(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006215 Py_ssize_t size,
6216 const char *errors)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006217{
6218 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006219 Py_ssize_t startinpos;
6220 Py_ssize_t endinpos;
6221 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01006222 PyObject *v;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006223 const char *end;
6224 const char *reason;
6225 PyObject *errorHandler = NULL;
6226 PyObject *exc = NULL;
6227
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006228 if (PyErr_WarnEx(PyExc_DeprecationWarning,
Ezio Melotti11060a42011-11-16 09:39:10 +02006229 "unicode_internal codec has been deprecated",
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006230 1))
6231 return NULL;
6232
Thomas Wouters89f507f2006-12-13 04:49:30 +00006233 /* XXX overflow detection missing */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006234 v = PyUnicode_New((size+Py_UNICODE_SIZE-1)/ Py_UNICODE_SIZE, 127);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006235 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006236 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006237 if (PyUnicode_GET_LENGTH(v) == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01006238 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006239 outpos = 0;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006240 end = s + size;
6241
6242 while (s < end) {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006243 Py_UNICODE uch;
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006244 Py_UCS4 ch;
6245 /* We copy the raw representation one byte at a time because the
6246 pointer may be unaligned (see test_codeccallbacks). */
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006247 ((char *) &uch)[0] = s[0];
6248 ((char *) &uch)[1] = s[1];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006249#ifdef Py_UNICODE_WIDE
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006250 ((char *) &uch)[2] = s[2];
6251 ((char *) &uch)[3] = s[3];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006252#endif
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006253 ch = uch;
6254
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006255 /* We have to sanity check the raw data, otherwise doom looms for
6256 some malformed UCS-4 data. */
6257 if (
Benjamin Peterson29060642009-01-31 22:14:21 +00006258#ifdef Py_UNICODE_WIDE
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006259 ch > 0x10ffff ||
Benjamin Peterson29060642009-01-31 22:14:21 +00006260#endif
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006261 end-s < Py_UNICODE_SIZE
6262 )
Benjamin Peterson29060642009-01-31 22:14:21 +00006263 {
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006264 startinpos = s - starts;
6265 if (end-s < Py_UNICODE_SIZE) {
6266 endinpos = end-starts;
6267 reason = "truncated input";
6268 }
6269 else {
6270 endinpos = s - starts + Py_UNICODE_SIZE;
6271 reason = "illegal code point (> 0x10FFFF)";
6272 }
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006273 if (unicode_decode_call_errorhandler(
6274 errors, &errorHandler,
6275 "unicode_internal", reason,
Walter Dörwalde78178e2007-07-30 13:31:40 +00006276 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006277 &v, &outpos))
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006278 goto onError;
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006279 continue;
6280 }
6281
6282 s += Py_UNICODE_SIZE;
6283#ifndef Py_UNICODE_WIDE
6284 if (ch >= 0xD800 && ch <= 0xDBFF && s < end)
6285 {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006286 Py_UNICODE uch2;
6287 ((char *) &uch2)[0] = s[0];
6288 ((char *) &uch2)[1] = s[1];
6289 if (uch2 >= 0xDC00 && uch2 <= 0xDFFF)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006290 {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006291 ch = (((uch & 0x3FF)<<10) | (uch2 & 0x3FF)) + 0x10000;
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006292 s += Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006293 }
6294 }
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006295#endif
6296
6297 if (unicode_putchar(&v, &outpos, ch) < 0)
6298 goto onError;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006299 }
6300
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006301 if (PyUnicode_Resize(&v, outpos) < 0)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006302 goto onError;
6303 Py_XDECREF(errorHandler);
6304 Py_XDECREF(exc);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02006305 assert(_PyUnicode_CheckConsistency(v, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01006306 return v;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006307
Benjamin Peterson29060642009-01-31 22:14:21 +00006308 onError:
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006309 Py_XDECREF(v);
6310 Py_XDECREF(errorHandler);
6311 Py_XDECREF(exc);
6312 return NULL;
6313}
6314
Guido van Rossumd57fd912000-03-10 22:53:23 +00006315/* --- Latin-1 Codec ------------------------------------------------------ */
6316
Alexander Belopolsky40018472011-02-26 01:02:56 +00006317PyObject *
6318PyUnicode_DecodeLatin1(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006319 Py_ssize_t size,
6320 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006321{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006322 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Victor Stinnere57b1c02011-09-28 22:20:48 +02006323 return _PyUnicode_FromUCS1((unsigned char*)s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006324}
6325
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006326/* create or adjust a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006327static void
6328make_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006329 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006330 PyObject *unicode,
6331 Py_ssize_t startpos, Py_ssize_t endpos,
6332 const char *reason)
6333{
6334 if (*exceptionObject == NULL) {
6335 *exceptionObject = PyObject_CallFunction(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006336 PyExc_UnicodeEncodeError, "sOnns",
Martin v. Löwis9e816682011-11-02 12:45:42 +01006337 encoding, unicode, startpos, endpos, reason);
6338 }
6339 else {
6340 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
6341 goto onError;
6342 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
6343 goto onError;
6344 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
6345 goto onError;
6346 return;
6347 onError:
6348 Py_DECREF(*exceptionObject);
6349 *exceptionObject = NULL;
6350 }
6351}
6352
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006353/* raises a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006354static void
6355raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006356 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006357 PyObject *unicode,
6358 Py_ssize_t startpos, Py_ssize_t endpos,
6359 const char *reason)
6360{
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006361 make_encode_exception(exceptionObject,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006362 encoding, unicode, startpos, endpos, reason);
6363 if (*exceptionObject != NULL)
6364 PyCodec_StrictErrors(*exceptionObject);
6365}
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006366
6367/* error handling callback helper:
6368 build arguments, call the callback and check the arguments,
6369 put the result into newpos and return the replacement string, which
6370 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006371static PyObject *
6372unicode_encode_call_errorhandler(const char *errors,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006373 PyObject **errorHandler,
6374 const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006375 PyObject *unicode, PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006376 Py_ssize_t startpos, Py_ssize_t endpos,
6377 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006378{
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006379 static char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006380 Py_ssize_t len;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006381 PyObject *restuple;
6382 PyObject *resunicode;
6383
6384 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006385 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006386 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006387 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006388 }
6389
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006390 if (PyUnicode_READY(unicode) < 0)
6391 return NULL;
6392 len = PyUnicode_GET_LENGTH(unicode);
6393
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006394 make_encode_exception(exceptionObject,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006395 encoding, unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006396 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006397 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006398
6399 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00006400 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006401 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006402 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006403 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006404 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00006405 Py_DECREF(restuple);
6406 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006407 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006408 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00006409 &resunicode, newpos)) {
6410 Py_DECREF(restuple);
6411 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006412 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006413 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
6414 PyErr_SetString(PyExc_TypeError, &argparse[3]);
6415 Py_DECREF(restuple);
6416 return NULL;
6417 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006418 if (*newpos<0)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006419 *newpos = len + *newpos;
6420 if (*newpos<0 || *newpos>len) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006421 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
6422 Py_DECREF(restuple);
6423 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00006424 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006425 Py_INCREF(resunicode);
6426 Py_DECREF(restuple);
6427 return resunicode;
6428}
6429
Alexander Belopolsky40018472011-02-26 01:02:56 +00006430static PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006431unicode_encode_ucs1(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006432 const char *errors,
Victor Stinnerfcd96532011-11-04 00:28:50 +01006433 unsigned int limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006434{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006435 /* input state */
6436 Py_ssize_t pos=0, size;
6437 int kind;
6438 void *data;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006439 /* output object */
6440 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006441 /* pointer into the output */
6442 char *str;
6443 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00006444 Py_ssize_t ressize;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006445 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
6446 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006447 PyObject *errorHandler = NULL;
6448 PyObject *exc = NULL;
6449 /* the following variable is used for caching string comparisons
6450 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
6451 int known_errorHandler = -1;
6452
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006453 if (PyUnicode_READY(unicode) < 0)
6454 return NULL;
6455 size = PyUnicode_GET_LENGTH(unicode);
6456 kind = PyUnicode_KIND(unicode);
6457 data = PyUnicode_DATA(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006458 /* allocate enough for a simple encoding without
6459 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00006460 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00006461 return PyBytes_FromStringAndSize(NULL, 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006462 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006463 if (res == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00006464 return NULL;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006465 str = PyBytes_AS_STRING(res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006466 ressize = size;
6467
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006468 while (pos < size) {
6469 Py_UCS4 c = PyUnicode_READ(kind, data, pos);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006470
Benjamin Peterson29060642009-01-31 22:14:21 +00006471 /* can we encode this? */
6472 if (c<limit) {
6473 /* no overflow check, because we know that the space is enough */
6474 *str++ = (char)c;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006475 ++pos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006476 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006477 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006478 Py_ssize_t requiredsize;
6479 PyObject *repunicode;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006480 Py_ssize_t repsize, newpos, respos, i;
Benjamin Peterson29060642009-01-31 22:14:21 +00006481 /* startpos for collecting unencodable chars */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006482 Py_ssize_t collstart = pos;
6483 Py_ssize_t collend = pos;
Benjamin Peterson29060642009-01-31 22:14:21 +00006484 /* find all unecodable characters */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006485 while ((collend < size) && (PyUnicode_READ(kind, data, collend)>=limit))
Benjamin Peterson29060642009-01-31 22:14:21 +00006486 ++collend;
6487 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
6488 if (known_errorHandler==-1) {
6489 if ((errors==NULL) || (!strcmp(errors, "strict")))
6490 known_errorHandler = 1;
6491 else if (!strcmp(errors, "replace"))
6492 known_errorHandler = 2;
6493 else if (!strcmp(errors, "ignore"))
6494 known_errorHandler = 3;
6495 else if (!strcmp(errors, "xmlcharrefreplace"))
6496 known_errorHandler = 4;
6497 else
6498 known_errorHandler = 0;
6499 }
6500 switch (known_errorHandler) {
6501 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006502 raise_encode_exception(&exc, encoding, unicode, collstart, collend, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006503 goto onError;
6504 case 2: /* replace */
6505 while (collstart++<collend)
6506 *str++ = '?'; /* fall through */
6507 case 3: /* ignore */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006508 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006509 break;
6510 case 4: /* xmlcharrefreplace */
6511 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006512 /* determine replacement size */
6513 for (i = collstart, repsize = 0; i < collend; ++i) {
6514 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
6515 if (ch < 10)
Benjamin Peterson29060642009-01-31 22:14:21 +00006516 repsize += 2+1+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006517 else if (ch < 100)
Benjamin Peterson29060642009-01-31 22:14:21 +00006518 repsize += 2+2+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006519 else if (ch < 1000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006520 repsize += 2+3+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006521 else if (ch < 10000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006522 repsize += 2+4+1;
Hye-Shik Chang40e95092003-12-22 01:31:13 +00006523#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00006524 else
6525 repsize += 2+5+1;
Hye-Shik Chang40e95092003-12-22 01:31:13 +00006526#else
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006527 else if (ch < 100000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006528 repsize += 2+5+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006529 else if (ch < 1000000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006530 repsize += 2+6+1;
6531 else
6532 repsize += 2+7+1;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00006533#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00006534 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006535 requiredsize = respos+repsize+(size-collend);
Benjamin Peterson29060642009-01-31 22:14:21 +00006536 if (requiredsize > ressize) {
6537 if (requiredsize<2*ressize)
6538 requiredsize = 2*ressize;
6539 if (_PyBytes_Resize(&res, requiredsize))
6540 goto onError;
6541 str = PyBytes_AS_STRING(res) + respos;
6542 ressize = requiredsize;
6543 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006544 /* generate replacement */
6545 for (i = collstart; i < collend; ++i) {
6546 str += sprintf(str, "&#%d;", PyUnicode_READ(kind, data, i));
Benjamin Peterson29060642009-01-31 22:14:21 +00006547 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006548 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006549 break;
6550 default:
6551 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006552 encoding, reason, unicode, &exc,
6553 collstart, collend, &newpos);
6554 if (repunicode == NULL || (PyUnicode_Check(repunicode) &&
6555 PyUnicode_READY(repunicode) < 0))
Benjamin Peterson29060642009-01-31 22:14:21 +00006556 goto onError;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006557 if (PyBytes_Check(repunicode)) {
6558 /* Directly copy bytes result to output. */
6559 repsize = PyBytes_Size(repunicode);
6560 if (repsize > 1) {
6561 /* Make room for all additional bytes. */
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006562 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006563 if (_PyBytes_Resize(&res, ressize+repsize-1)) {
6564 Py_DECREF(repunicode);
6565 goto onError;
6566 }
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006567 str = PyBytes_AS_STRING(res) + respos;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006568 ressize += repsize-1;
6569 }
6570 memcpy(str, PyBytes_AsString(repunicode), repsize);
6571 str += repsize;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006572 pos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006573 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006574 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006575 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006576 /* need more space? (at least enough for what we
6577 have+the replacement+the rest of the string, so
6578 we won't have to check space for encodable characters) */
6579 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006580 repsize = PyUnicode_GET_LENGTH(repunicode);
6581 requiredsize = respos+repsize+(size-collend);
Benjamin Peterson29060642009-01-31 22:14:21 +00006582 if (requiredsize > ressize) {
6583 if (requiredsize<2*ressize)
6584 requiredsize = 2*ressize;
6585 if (_PyBytes_Resize(&res, requiredsize)) {
6586 Py_DECREF(repunicode);
6587 goto onError;
6588 }
6589 str = PyBytes_AS_STRING(res) + respos;
6590 ressize = requiredsize;
6591 }
6592 /* check if there is anything unencodable in the replacement
6593 and copy it to the output */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006594 for (i = 0; repsize-->0; ++i, ++str) {
6595 c = PyUnicode_READ_CHAR(repunicode, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00006596 if (c >= limit) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006597 raise_encode_exception(&exc, encoding, unicode,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006598 pos, pos+1, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006599 Py_DECREF(repunicode);
6600 goto onError;
6601 }
6602 *str = (char)c;
6603 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006604 pos = newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006605 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006606 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00006607 }
6608 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006609 /* Resize if we allocated to much */
6610 size = str - PyBytes_AS_STRING(res);
6611 if (size < ressize) { /* If this falls res will be NULL */
Alexandre Vassalottibad1b922008-12-27 09:49:09 +00006612 assert(size >= 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006613 if (_PyBytes_Resize(&res, size) < 0)
6614 goto onError;
6615 }
6616
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006617 Py_XDECREF(errorHandler);
6618 Py_XDECREF(exc);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006619 return res;
6620
6621 onError:
6622 Py_XDECREF(res);
6623 Py_XDECREF(errorHandler);
6624 Py_XDECREF(exc);
6625 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006626}
6627
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006628/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006629PyObject *
6630PyUnicode_EncodeLatin1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006631 Py_ssize_t size,
6632 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006633{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006634 PyObject *result;
6635 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6636 if (unicode == NULL)
6637 return NULL;
6638 result = unicode_encode_ucs1(unicode, errors, 256);
6639 Py_DECREF(unicode);
6640 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006641}
6642
Alexander Belopolsky40018472011-02-26 01:02:56 +00006643PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006644_PyUnicode_AsLatin1String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006645{
6646 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006647 PyErr_BadArgument();
6648 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006649 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006650 if (PyUnicode_READY(unicode) == -1)
6651 return NULL;
6652 /* Fast path: if it is a one-byte string, construct
6653 bytes object directly. */
6654 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND)
6655 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6656 PyUnicode_GET_LENGTH(unicode));
6657 /* Non-Latin-1 characters present. Defer to above function to
6658 raise the exception. */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006659 return unicode_encode_ucs1(unicode, errors, 256);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006660}
6661
6662PyObject*
6663PyUnicode_AsLatin1String(PyObject *unicode)
6664{
6665 return _PyUnicode_AsLatin1String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006666}
6667
6668/* --- 7-bit ASCII Codec -------------------------------------------------- */
6669
Alexander Belopolsky40018472011-02-26 01:02:56 +00006670PyObject *
6671PyUnicode_DecodeASCII(const char *s,
6672 Py_ssize_t size,
6673 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006674{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006675 const char *starts = s;
Victor Stinner7931d9a2011-11-04 00:22:48 +01006676 PyObject *v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006677 int kind;
6678 void *data;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006679 Py_ssize_t startinpos;
6680 Py_ssize_t endinpos;
6681 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006682 const char *e;
Victor Stinner702c7342011-10-05 13:50:52 +02006683 int has_error;
6684 const unsigned char *p = (const unsigned char *)s;
6685 const unsigned char *end = p + size;
6686 const unsigned char *aligned_end = (const unsigned char *) ((size_t) end & ~LONG_PTR_MASK);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006687 PyObject *errorHandler = NULL;
6688 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006689
Guido van Rossumd57fd912000-03-10 22:53:23 +00006690 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Victor Stinner702c7342011-10-05 13:50:52 +02006691 if (size == 1 && (unsigned char)s[0] < 128)
6692 return get_latin1_char((unsigned char)s[0]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006693
Victor Stinner702c7342011-10-05 13:50:52 +02006694 has_error = 0;
6695 while (p < end && !has_error) {
6696 /* Fast path, see below in PyUnicode_DecodeUTF8Stateful for
6697 an explanation. */
6698 if (!((size_t) p & LONG_PTR_MASK)) {
6699 /* Help register allocation */
6700 register const unsigned char *_p = p;
6701 while (_p < aligned_end) {
6702 unsigned long value = *(unsigned long *) _p;
6703 if (value & ASCII_CHAR_MASK) {
6704 has_error = 1;
6705 break;
6706 }
6707 _p += SIZEOF_LONG;
6708 }
6709 if (_p == end)
6710 break;
6711 if (has_error)
6712 break;
6713 p = _p;
6714 }
6715 if (*p & 0x80) {
6716 has_error = 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006717 break;
Victor Stinner702c7342011-10-05 13:50:52 +02006718 }
6719 else {
6720 ++p;
6721 }
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00006722 }
Victor Stinner702c7342011-10-05 13:50:52 +02006723 if (!has_error)
6724 return unicode_fromascii((const unsigned char *)s, size);
Tim Petersced69f82003-09-16 20:30:58 +00006725
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006726 v = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006727 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006728 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006729 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01006730 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006731 kind = PyUnicode_KIND(v);
6732 data = PyUnicode_DATA(v);
6733 outpos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006734 e = s + size;
6735 while (s < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006736 register unsigned char c = (unsigned char)*s;
6737 if (c < 128) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006738 PyUnicode_WRITE(kind, data, outpos++, c);
Benjamin Peterson29060642009-01-31 22:14:21 +00006739 ++s;
6740 }
6741 else {
6742 startinpos = s-starts;
6743 endinpos = startinpos + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00006744 if (unicode_decode_call_errorhandler(
6745 errors, &errorHandler,
6746 "ascii", "ordinal not in range(128)",
6747 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006748 &v, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00006749 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006750 kind = PyUnicode_KIND(v);
6751 data = PyUnicode_DATA(v);
Benjamin Peterson29060642009-01-31 22:14:21 +00006752 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006753 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006754 if (PyUnicode_Resize(&v, outpos) < 0)
6755 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006756 Py_XDECREF(errorHandler);
6757 Py_XDECREF(exc);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02006758 assert(_PyUnicode_CheckConsistency(v, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01006759 return v;
Tim Petersced69f82003-09-16 20:30:58 +00006760
Benjamin Peterson29060642009-01-31 22:14:21 +00006761 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00006762 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006763 Py_XDECREF(errorHandler);
6764 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006765 return NULL;
6766}
6767
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006768/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006769PyObject *
6770PyUnicode_EncodeASCII(const Py_UNICODE *p,
6771 Py_ssize_t size,
6772 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006773{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006774 PyObject *result;
6775 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6776 if (unicode == NULL)
6777 return NULL;
6778 result = unicode_encode_ucs1(unicode, errors, 128);
6779 Py_DECREF(unicode);
6780 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006781}
6782
Alexander Belopolsky40018472011-02-26 01:02:56 +00006783PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006784_PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006785{
6786 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006787 PyErr_BadArgument();
6788 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006789 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006790 if (PyUnicode_READY(unicode) == -1)
6791 return NULL;
6792 /* Fast path: if it is an ASCII-only string, construct bytes object
6793 directly. Else defer to above function to raise the exception. */
6794 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
6795 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6796 PyUnicode_GET_LENGTH(unicode));
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006797 return unicode_encode_ucs1(unicode, errors, 128);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006798}
6799
6800PyObject *
6801PyUnicode_AsASCIIString(PyObject *unicode)
6802{
6803 return _PyUnicode_AsASCIIString(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006804}
6805
Victor Stinner99b95382011-07-04 14:23:54 +02006806#ifdef HAVE_MBCS
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006807
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006808/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006809
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00006810#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006811#define NEED_RETRY
6812#endif
6813
Victor Stinner3a50e702011-10-18 21:21:00 +02006814#ifndef WC_ERR_INVALID_CHARS
6815# define WC_ERR_INVALID_CHARS 0x0080
6816#endif
6817
6818static char*
6819code_page_name(UINT code_page, PyObject **obj)
6820{
6821 *obj = NULL;
6822 if (code_page == CP_ACP)
6823 return "mbcs";
6824 if (code_page == CP_UTF7)
6825 return "CP_UTF7";
6826 if (code_page == CP_UTF8)
6827 return "CP_UTF8";
6828
6829 *obj = PyBytes_FromFormat("cp%u", code_page);
6830 if (*obj == NULL)
6831 return NULL;
6832 return PyBytes_AS_STRING(*obj);
6833}
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006834
Alexander Belopolsky40018472011-02-26 01:02:56 +00006835static int
Victor Stinner3a50e702011-10-18 21:21:00 +02006836is_dbcs_lead_byte(UINT code_page, const char *s, int offset)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006837{
6838 const char *curr = s + offset;
Victor Stinner3a50e702011-10-18 21:21:00 +02006839 const char *prev;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006840
Victor Stinner3a50e702011-10-18 21:21:00 +02006841 if (!IsDBCSLeadByteEx(code_page, *curr))
6842 return 0;
6843
6844 prev = CharPrevExA(code_page, s, curr, 0);
6845 if (prev == curr)
6846 return 1;
6847 /* FIXME: This code is limited to "true" double-byte encodings,
6848 as it assumes an incomplete character consists of a single
6849 byte. */
6850 if (curr - prev == 2)
6851 return 1;
6852 if (!IsDBCSLeadByteEx(code_page, *prev))
6853 return 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006854 return 0;
6855}
6856
Victor Stinner3a50e702011-10-18 21:21:00 +02006857static DWORD
6858decode_code_page_flags(UINT code_page)
6859{
6860 if (code_page == CP_UTF7) {
6861 /* The CP_UTF7 decoder only supports flags=0 */
6862 return 0;
6863 }
6864 else
6865 return MB_ERR_INVALID_CHARS;
6866}
6867
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006868/*
Victor Stinner3a50e702011-10-18 21:21:00 +02006869 * Decode a byte string from a Windows code page into unicode object in strict
6870 * mode.
6871 *
6872 * Returns consumed size if succeed, returns -2 on decode error, or raise a
6873 * WindowsError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006874 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006875static int
Victor Stinner3a50e702011-10-18 21:21:00 +02006876decode_code_page_strict(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01006877 PyObject **v,
Victor Stinner3a50e702011-10-18 21:21:00 +02006878 const char *in,
6879 int insize)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006880{
Victor Stinner3a50e702011-10-18 21:21:00 +02006881 const DWORD flags = decode_code_page_flags(code_page);
Victor Stinner24729f32011-11-10 20:31:37 +01006882 wchar_t *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02006883 DWORD outsize;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006884
6885 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02006886 assert(insize > 0);
6887 outsize = MultiByteToWideChar(code_page, flags, in, insize, NULL, 0);
6888 if (outsize <= 0)
6889 goto error;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006890
6891 if (*v == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006892 /* Create unicode object */
Victor Stinner76a31a62011-11-04 00:05:13 +01006893 *v = (PyObject*)_PyUnicode_New(outsize);
Benjamin Peterson29060642009-01-31 22:14:21 +00006894 if (*v == NULL)
6895 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02006896 out = PyUnicode_AS_UNICODE(*v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006897 }
6898 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006899 /* Extend unicode object */
Victor Stinner3a50e702011-10-18 21:21:00 +02006900 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
Victor Stinner76a31a62011-11-04 00:05:13 +01006901 if (PyUnicode_Resize(v, n + outsize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006902 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02006903 out = PyUnicode_AS_UNICODE(*v) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006904 }
6905
6906 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02006907 outsize = MultiByteToWideChar(code_page, flags, in, insize, out, outsize);
6908 if (outsize <= 0)
6909 goto error;
6910 return insize;
Victor Stinner554f3f02010-06-16 23:33:54 +00006911
Victor Stinner3a50e702011-10-18 21:21:00 +02006912error:
6913 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
6914 return -2;
6915 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00006916 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006917}
6918
Victor Stinner3a50e702011-10-18 21:21:00 +02006919/*
6920 * Decode a byte string from a code page into unicode object with an error
6921 * handler.
6922 *
6923 * Returns consumed size if succeed, or raise a WindowsError or
6924 * UnicodeDecodeError exception and returns -1 on error.
6925 */
6926static int
6927decode_code_page_errors(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01006928 PyObject **v,
6929 const char *in, const int size,
Victor Stinner3a50e702011-10-18 21:21:00 +02006930 const char *errors)
6931{
6932 const char *startin = in;
6933 const char *endin = in + size;
6934 const DWORD flags = decode_code_page_flags(code_page);
6935 /* Ideally, we should get reason from FormatMessage. This is the Windows
6936 2000 English version of the message. */
6937 const char *reason = "No mapping for the Unicode character exists "
6938 "in the target code page.";
6939 /* each step cannot decode more than 1 character, but a character can be
6940 represented as a surrogate pair */
6941 wchar_t buffer[2], *startout, *out;
6942 int insize, outsize;
6943 PyObject *errorHandler = NULL;
6944 PyObject *exc = NULL;
6945 PyObject *encoding_obj = NULL;
6946 char *encoding;
6947 DWORD err;
6948 int ret = -1;
6949
6950 assert(size > 0);
6951
6952 encoding = code_page_name(code_page, &encoding_obj);
6953 if (encoding == NULL)
6954 return -1;
6955
6956 if (errors == NULL || strcmp(errors, "strict") == 0) {
6957 /* The last error was ERROR_NO_UNICODE_TRANSLATION, then we raise a
6958 UnicodeDecodeError. */
6959 make_decode_exception(&exc, encoding, in, size, 0, 0, reason);
6960 if (exc != NULL) {
6961 PyCodec_StrictErrors(exc);
6962 Py_CLEAR(exc);
6963 }
6964 goto error;
6965 }
6966
6967 if (*v == NULL) {
6968 /* Create unicode object */
6969 if (size > PY_SSIZE_T_MAX / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
6970 PyErr_NoMemory();
6971 goto error;
6972 }
Victor Stinner76a31a62011-11-04 00:05:13 +01006973 *v = (PyObject*)_PyUnicode_New(size * Py_ARRAY_LENGTH(buffer));
Victor Stinner3a50e702011-10-18 21:21:00 +02006974 if (*v == NULL)
6975 goto error;
6976 startout = PyUnicode_AS_UNICODE(*v);
6977 }
6978 else {
6979 /* Extend unicode object */
6980 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
6981 if (size > (PY_SSIZE_T_MAX - n) / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
6982 PyErr_NoMemory();
6983 goto error;
6984 }
Victor Stinner76a31a62011-11-04 00:05:13 +01006985 if (PyUnicode_Resize(v, n + size * Py_ARRAY_LENGTH(buffer)) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02006986 goto error;
6987 startout = PyUnicode_AS_UNICODE(*v) + n;
6988 }
6989
6990 /* Decode the byte string character per character */
6991 out = startout;
6992 while (in < endin)
6993 {
6994 /* Decode a character */
6995 insize = 1;
6996 do
6997 {
6998 outsize = MultiByteToWideChar(code_page, flags,
6999 in, insize,
7000 buffer, Py_ARRAY_LENGTH(buffer));
7001 if (outsize > 0)
7002 break;
7003 err = GetLastError();
7004 if (err != ERROR_NO_UNICODE_TRANSLATION
7005 && err != ERROR_INSUFFICIENT_BUFFER)
7006 {
7007 PyErr_SetFromWindowsErr(0);
7008 goto error;
7009 }
7010 insize++;
7011 }
7012 /* 4=maximum length of a UTF-8 sequence */
7013 while (insize <= 4 && (in + insize) <= endin);
7014
7015 if (outsize <= 0) {
7016 Py_ssize_t startinpos, endinpos, outpos;
7017
7018 startinpos = in - startin;
7019 endinpos = startinpos + 1;
7020 outpos = out - PyUnicode_AS_UNICODE(*v);
7021 if (unicode_decode_call_errorhandler(
7022 errors, &errorHandler,
7023 encoding, reason,
7024 &startin, &endin, &startinpos, &endinpos, &exc, &in,
Victor Stinner596a6c42011-11-09 00:02:18 +01007025 v, &outpos))
Victor Stinner3a50e702011-10-18 21:21:00 +02007026 {
7027 goto error;
7028 }
Victor Stinner596a6c42011-11-09 00:02:18 +01007029 out = PyUnicode_AS_UNICODE(*v) + outpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007030 }
7031 else {
7032 in += insize;
7033 memcpy(out, buffer, outsize * sizeof(wchar_t));
7034 out += outsize;
7035 }
7036 }
7037
7038 /* write a NUL character at the end */
7039 *out = 0;
7040
7041 /* Extend unicode object */
7042 outsize = out - startout;
7043 assert(outsize <= PyUnicode_WSTR_LENGTH(*v));
Victor Stinner76a31a62011-11-04 00:05:13 +01007044 if (PyUnicode_Resize(v, outsize) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007045 goto error;
Victor Stinner76a31a62011-11-04 00:05:13 +01007046 ret = size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007047
7048error:
7049 Py_XDECREF(encoding_obj);
7050 Py_XDECREF(errorHandler);
7051 Py_XDECREF(exc);
7052 return ret;
7053}
7054
Victor Stinner3a50e702011-10-18 21:21:00 +02007055static PyObject *
7056decode_code_page_stateful(int code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007057 const char *s, Py_ssize_t size,
7058 const char *errors, Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007059{
Victor Stinner76a31a62011-11-04 00:05:13 +01007060 PyObject *v = NULL;
7061 int chunk_size, final, converted, done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007062
Victor Stinner3a50e702011-10-18 21:21:00 +02007063 if (code_page < 0) {
7064 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7065 return NULL;
7066 }
7067
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007068 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00007069 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007070
Victor Stinner76a31a62011-11-04 00:05:13 +01007071 do
7072 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007073#ifdef NEED_RETRY
Victor Stinner76a31a62011-11-04 00:05:13 +01007074 if (size > INT_MAX) {
7075 chunk_size = INT_MAX;
7076 final = 0;
7077 done = 0;
7078 }
7079 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007080#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007081 {
7082 chunk_size = (int)size;
7083 final = (consumed == NULL);
7084 done = 1;
7085 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007086
Victor Stinner76a31a62011-11-04 00:05:13 +01007087 /* Skip trailing lead-byte unless 'final' is set */
7088 if (!final && is_dbcs_lead_byte(code_page, s, chunk_size - 1))
7089 --chunk_size;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007090
Victor Stinner76a31a62011-11-04 00:05:13 +01007091 if (chunk_size == 0 && done) {
7092 if (v != NULL)
7093 break;
7094 Py_INCREF(unicode_empty);
7095 return unicode_empty;
7096 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007097
Victor Stinner76a31a62011-11-04 00:05:13 +01007098
7099 converted = decode_code_page_strict(code_page, &v,
7100 s, chunk_size);
7101 if (converted == -2)
7102 converted = decode_code_page_errors(code_page, &v,
7103 s, chunk_size,
7104 errors);
7105 assert(converted != 0);
7106
7107 if (converted < 0) {
7108 Py_XDECREF(v);
7109 return NULL;
7110 }
7111
7112 if (consumed)
7113 *consumed += converted;
7114
7115 s += converted;
7116 size -= converted;
7117 } while (!done);
Victor Stinner3a50e702011-10-18 21:21:00 +02007118
Victor Stinner17efeed2011-10-04 20:05:46 +02007119#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02007120 if (_PyUnicode_READY_REPLACE(&v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007121 Py_DECREF(v);
7122 return NULL;
7123 }
Victor Stinner17efeed2011-10-04 20:05:46 +02007124#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02007125 assert(_PyUnicode_CheckConsistency(v, 1));
Victor Stinner76a31a62011-11-04 00:05:13 +01007126 return v;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007127}
7128
Alexander Belopolsky40018472011-02-26 01:02:56 +00007129PyObject *
Victor Stinner3a50e702011-10-18 21:21:00 +02007130PyUnicode_DecodeCodePageStateful(int code_page,
7131 const char *s,
7132 Py_ssize_t size,
7133 const char *errors,
7134 Py_ssize_t *consumed)
7135{
7136 return decode_code_page_stateful(code_page, s, size, errors, consumed);
7137}
7138
7139PyObject *
7140PyUnicode_DecodeMBCSStateful(const char *s,
7141 Py_ssize_t size,
7142 const char *errors,
7143 Py_ssize_t *consumed)
7144{
7145 return decode_code_page_stateful(CP_ACP, s, size, errors, consumed);
7146}
7147
7148PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00007149PyUnicode_DecodeMBCS(const char *s,
7150 Py_ssize_t size,
7151 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007152{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007153 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
7154}
7155
Victor Stinner3a50e702011-10-18 21:21:00 +02007156static DWORD
7157encode_code_page_flags(UINT code_page, const char *errors)
7158{
7159 if (code_page == CP_UTF8) {
7160 if (winver.dwMajorVersion >= 6)
7161 /* CP_UTF8 supports WC_ERR_INVALID_CHARS on Windows Vista
7162 and later */
7163 return WC_ERR_INVALID_CHARS;
7164 else
7165 /* CP_UTF8 only supports flags=0 on Windows older than Vista */
7166 return 0;
7167 }
7168 else if (code_page == CP_UTF7) {
7169 /* CP_UTF7 only supports flags=0 */
7170 return 0;
7171 }
7172 else {
7173 if (errors != NULL && strcmp(errors, "replace") == 0)
7174 return 0;
7175 else
7176 return WC_NO_BEST_FIT_CHARS;
7177 }
7178}
7179
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007180/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007181 * Encode a Unicode string to a Windows code page into a byte string in strict
7182 * mode.
7183 *
7184 * Returns consumed characters if succeed, returns -2 on encode error, or raise
7185 * a WindowsError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007186 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007187static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007188encode_code_page_strict(UINT code_page, PyObject **outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007189 PyObject *unicode, Py_ssize_t offset, int len,
Victor Stinner3a50e702011-10-18 21:21:00 +02007190 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007191{
Victor Stinner554f3f02010-06-16 23:33:54 +00007192 BOOL usedDefaultChar = FALSE;
Victor Stinner3a50e702011-10-18 21:21:00 +02007193 BOOL *pusedDefaultChar = &usedDefaultChar;
7194 int outsize;
Victor Stinner554f3f02010-06-16 23:33:54 +00007195 PyObject *exc = NULL;
Victor Stinner24729f32011-11-10 20:31:37 +01007196 wchar_t *p;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007197 Py_ssize_t size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007198 const DWORD flags = encode_code_page_flags(code_page, NULL);
7199 char *out;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007200 /* Create a substring so that we can get the UTF-16 representation
7201 of just the slice under consideration. */
7202 PyObject *substring;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007203
Martin v. Löwis3d325192011-11-04 18:23:06 +01007204 assert(len > 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007205
Victor Stinner3a50e702011-10-18 21:21:00 +02007206 if (code_page != CP_UTF8 && code_page != CP_UTF7)
Victor Stinner554f3f02010-06-16 23:33:54 +00007207 pusedDefaultChar = &usedDefaultChar;
Victor Stinner3a50e702011-10-18 21:21:00 +02007208 else
Victor Stinner554f3f02010-06-16 23:33:54 +00007209 pusedDefaultChar = NULL;
Victor Stinner554f3f02010-06-16 23:33:54 +00007210
Victor Stinner2fc507f2011-11-04 20:06:39 +01007211 substring = PyUnicode_Substring(unicode, offset, offset+len);
7212 if (substring == NULL)
7213 return -1;
7214 p = PyUnicode_AsUnicodeAndSize(substring, &size);
7215 if (p == NULL) {
7216 Py_DECREF(substring);
7217 return -1;
7218 }
Martin v. Löwis3d325192011-11-04 18:23:06 +01007219
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007220 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007221 outsize = WideCharToMultiByte(code_page, flags,
7222 p, size,
7223 NULL, 0,
7224 NULL, pusedDefaultChar);
7225 if (outsize <= 0)
7226 goto error;
7227 /* If we used a default char, then we failed! */
Victor Stinner2fc507f2011-11-04 20:06:39 +01007228 if (pusedDefaultChar && *pusedDefaultChar) {
7229 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007230 return -2;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007231 }
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007232
Victor Stinner3a50e702011-10-18 21:21:00 +02007233 if (*outbytes == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007234 /* Create string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007235 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007236 if (*outbytes == NULL) {
7237 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007238 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007239 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007240 out = PyBytes_AS_STRING(*outbytes);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007241 }
7242 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007243 /* Extend string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007244 const Py_ssize_t n = PyBytes_Size(*outbytes);
7245 if (outsize > PY_SSIZE_T_MAX - n) {
7246 PyErr_NoMemory();
Victor Stinner2fc507f2011-11-04 20:06:39 +01007247 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007248 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007249 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007250 if (_PyBytes_Resize(outbytes, n + outsize) < 0) {
7251 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007252 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007253 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007254 out = PyBytes_AS_STRING(*outbytes) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007255 }
7256
7257 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007258 outsize = WideCharToMultiByte(code_page, flags,
7259 p, size,
7260 out, outsize,
7261 NULL, pusedDefaultChar);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007262 Py_CLEAR(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007263 if (outsize <= 0)
7264 goto error;
7265 if (pusedDefaultChar && *pusedDefaultChar)
7266 return -2;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007267 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00007268
Victor Stinner3a50e702011-10-18 21:21:00 +02007269error:
Victor Stinner2fc507f2011-11-04 20:06:39 +01007270 Py_XDECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007271 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7272 return -2;
7273 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007274 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007275}
7276
Victor Stinner3a50e702011-10-18 21:21:00 +02007277/*
7278 * Encode a Unicode string to a Windows code page into a byte string using a
7279 * error handler.
7280 *
7281 * Returns consumed characters if succeed, or raise a WindowsError and returns
7282 * -1 on other error.
7283 */
7284static int
7285encode_code_page_errors(UINT code_page, PyObject **outbytes,
Victor Stinner7581cef2011-11-03 22:32:33 +01007286 PyObject *unicode, Py_ssize_t unicode_offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007287 Py_ssize_t insize, const char* errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007288{
Victor Stinner3a50e702011-10-18 21:21:00 +02007289 const DWORD flags = encode_code_page_flags(code_page, errors);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007290 Py_ssize_t pos = unicode_offset;
7291 Py_ssize_t endin = unicode_offset + insize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007292 /* Ideally, we should get reason from FormatMessage. This is the Windows
7293 2000 English version of the message. */
7294 const char *reason = "invalid character";
7295 /* 4=maximum length of a UTF-8 sequence */
7296 char buffer[4];
7297 BOOL usedDefaultChar = FALSE, *pusedDefaultChar;
7298 Py_ssize_t outsize;
7299 char *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007300 PyObject *errorHandler = NULL;
7301 PyObject *exc = NULL;
7302 PyObject *encoding_obj = NULL;
7303 char *encoding;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007304 Py_ssize_t newpos, newoutsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007305 PyObject *rep;
7306 int ret = -1;
7307
7308 assert(insize > 0);
7309
7310 encoding = code_page_name(code_page, &encoding_obj);
7311 if (encoding == NULL)
7312 return -1;
7313
7314 if (errors == NULL || strcmp(errors, "strict") == 0) {
7315 /* The last error was ERROR_NO_UNICODE_TRANSLATION,
7316 then we raise a UnicodeEncodeError. */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007317 make_encode_exception(&exc, encoding, unicode, 0, 0, reason);
Victor Stinner3a50e702011-10-18 21:21:00 +02007318 if (exc != NULL) {
7319 PyCodec_StrictErrors(exc);
7320 Py_DECREF(exc);
7321 }
7322 Py_XDECREF(encoding_obj);
7323 return -1;
7324 }
7325
7326 if (code_page != CP_UTF8 && code_page != CP_UTF7)
7327 pusedDefaultChar = &usedDefaultChar;
7328 else
7329 pusedDefaultChar = NULL;
7330
7331 if (Py_ARRAY_LENGTH(buffer) > PY_SSIZE_T_MAX / insize) {
7332 PyErr_NoMemory();
7333 goto error;
7334 }
7335 outsize = insize * Py_ARRAY_LENGTH(buffer);
7336
7337 if (*outbytes == NULL) {
7338 /* Create string object */
7339 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
7340 if (*outbytes == NULL)
7341 goto error;
7342 out = PyBytes_AS_STRING(*outbytes);
7343 }
7344 else {
7345 /* Extend string object */
7346 Py_ssize_t n = PyBytes_Size(*outbytes);
7347 if (n > PY_SSIZE_T_MAX - outsize) {
7348 PyErr_NoMemory();
7349 goto error;
7350 }
7351 if (_PyBytes_Resize(outbytes, n + outsize) < 0)
7352 goto error;
7353 out = PyBytes_AS_STRING(*outbytes) + n;
7354 }
7355
7356 /* Encode the string character per character */
Martin v. Löwis3d325192011-11-04 18:23:06 +01007357 while (pos < endin)
Victor Stinner3a50e702011-10-18 21:21:00 +02007358 {
Victor Stinner2fc507f2011-11-04 20:06:39 +01007359 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, pos);
7360 wchar_t chars[2];
7361 int charsize;
7362 if (ch < 0x10000) {
7363 chars[0] = (wchar_t)ch;
7364 charsize = 1;
7365 }
7366 else {
7367 ch -= 0x10000;
7368 chars[0] = 0xd800 + (ch >> 10);
7369 chars[1] = 0xdc00 + (ch & 0x3ff);
7370 charsize = 2;
7371 }
7372
Victor Stinner3a50e702011-10-18 21:21:00 +02007373 outsize = WideCharToMultiByte(code_page, flags,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007374 chars, charsize,
Victor Stinner3a50e702011-10-18 21:21:00 +02007375 buffer, Py_ARRAY_LENGTH(buffer),
7376 NULL, pusedDefaultChar);
7377 if (outsize > 0) {
7378 if (pusedDefaultChar == NULL || !(*pusedDefaultChar))
7379 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007380 pos++;
Victor Stinner3a50e702011-10-18 21:21:00 +02007381 memcpy(out, buffer, outsize);
7382 out += outsize;
7383 continue;
7384 }
7385 }
7386 else if (GetLastError() != ERROR_NO_UNICODE_TRANSLATION) {
7387 PyErr_SetFromWindowsErr(0);
7388 goto error;
7389 }
7390
Victor Stinner3a50e702011-10-18 21:21:00 +02007391 rep = unicode_encode_call_errorhandler(
7392 errors, &errorHandler, encoding, reason,
Victor Stinner7581cef2011-11-03 22:32:33 +01007393 unicode, &exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007394 pos, pos + 1, &newpos);
Victor Stinner3a50e702011-10-18 21:21:00 +02007395 if (rep == NULL)
7396 goto error;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007397 pos = newpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007398
7399 if (PyBytes_Check(rep)) {
7400 outsize = PyBytes_GET_SIZE(rep);
7401 if (outsize != 1) {
7402 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7403 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7404 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7405 Py_DECREF(rep);
7406 goto error;
7407 }
7408 out = PyBytes_AS_STRING(*outbytes) + offset;
7409 }
7410 memcpy(out, PyBytes_AS_STRING(rep), outsize);
7411 out += outsize;
7412 }
7413 else {
7414 Py_ssize_t i;
7415 enum PyUnicode_Kind kind;
7416 void *data;
7417
7418 if (PyUnicode_READY(rep) < 0) {
7419 Py_DECREF(rep);
7420 goto error;
7421 }
7422
7423 outsize = PyUnicode_GET_LENGTH(rep);
7424 if (outsize != 1) {
7425 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7426 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7427 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7428 Py_DECREF(rep);
7429 goto error;
7430 }
7431 out = PyBytes_AS_STRING(*outbytes) + offset;
7432 }
7433 kind = PyUnicode_KIND(rep);
7434 data = PyUnicode_DATA(rep);
7435 for (i=0; i < outsize; i++) {
7436 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7437 if (ch > 127) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007438 raise_encode_exception(&exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007439 encoding, unicode,
7440 pos, pos + 1,
Victor Stinner3a50e702011-10-18 21:21:00 +02007441 "unable to encode error handler result to ASCII");
7442 Py_DECREF(rep);
7443 goto error;
7444 }
7445 *out = (unsigned char)ch;
7446 out++;
7447 }
7448 }
7449 Py_DECREF(rep);
7450 }
7451 /* write a NUL byte */
7452 *out = 0;
7453 outsize = out - PyBytes_AS_STRING(*outbytes);
7454 assert(outsize <= PyBytes_GET_SIZE(*outbytes));
7455 if (_PyBytes_Resize(outbytes, outsize) < 0)
7456 goto error;
7457 ret = 0;
7458
7459error:
7460 Py_XDECREF(encoding_obj);
7461 Py_XDECREF(errorHandler);
7462 Py_XDECREF(exc);
7463 return ret;
7464}
7465
Victor Stinner3a50e702011-10-18 21:21:00 +02007466static PyObject *
7467encode_code_page(int code_page,
Victor Stinner7581cef2011-11-03 22:32:33 +01007468 PyObject *unicode,
Victor Stinner3a50e702011-10-18 21:21:00 +02007469 const char *errors)
7470{
Martin v. Löwis3d325192011-11-04 18:23:06 +01007471 Py_ssize_t len;
Victor Stinner3a50e702011-10-18 21:21:00 +02007472 PyObject *outbytes = NULL;
Victor Stinner7581cef2011-11-03 22:32:33 +01007473 Py_ssize_t offset;
Victor Stinner76a31a62011-11-04 00:05:13 +01007474 int chunk_len, ret, done;
Victor Stinner7581cef2011-11-03 22:32:33 +01007475
Victor Stinner2fc507f2011-11-04 20:06:39 +01007476 if (PyUnicode_READY(unicode) < 0)
7477 return NULL;
7478 len = PyUnicode_GET_LENGTH(unicode);
Guido van Rossum03e29f12000-05-04 15:52:20 +00007479
Victor Stinner3a50e702011-10-18 21:21:00 +02007480 if (code_page < 0) {
7481 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7482 return NULL;
7483 }
7484
Martin v. Löwis3d325192011-11-04 18:23:06 +01007485 if (len == 0)
Victor Stinner76a31a62011-11-04 00:05:13 +01007486 return PyBytes_FromStringAndSize(NULL, 0);
7487
Victor Stinner7581cef2011-11-03 22:32:33 +01007488 offset = 0;
7489 do
7490 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007491#ifdef NEED_RETRY
Victor Stinner2fc507f2011-11-04 20:06:39 +01007492 /* UTF-16 encoding may double the size, so use only INT_MAX/2
Martin v. Löwis3d325192011-11-04 18:23:06 +01007493 chunks. */
7494 if (len > INT_MAX/2) {
7495 chunk_len = INT_MAX/2;
Victor Stinner76a31a62011-11-04 00:05:13 +01007496 done = 0;
7497 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007498 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007499#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007500 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007501 chunk_len = (int)len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007502 done = 1;
7503 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007504
Victor Stinner76a31a62011-11-04 00:05:13 +01007505 ret = encode_code_page_strict(code_page, &outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007506 unicode, offset, chunk_len,
Victor Stinner76a31a62011-11-04 00:05:13 +01007507 errors);
7508 if (ret == -2)
7509 ret = encode_code_page_errors(code_page, &outbytes,
7510 unicode, offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007511 chunk_len, errors);
Victor Stinner7581cef2011-11-03 22:32:33 +01007512 if (ret < 0) {
7513 Py_XDECREF(outbytes);
7514 return NULL;
7515 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007516
Victor Stinner7581cef2011-11-03 22:32:33 +01007517 offset += chunk_len;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007518 len -= chunk_len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007519 } while (!done);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007520
Victor Stinner3a50e702011-10-18 21:21:00 +02007521 return outbytes;
7522}
7523
7524PyObject *
7525PyUnicode_EncodeMBCS(const Py_UNICODE *p,
7526 Py_ssize_t size,
7527 const char *errors)
7528{
Victor Stinner7581cef2011-11-03 22:32:33 +01007529 PyObject *unicode, *res;
7530 unicode = PyUnicode_FromUnicode(p, size);
7531 if (unicode == NULL)
7532 return NULL;
7533 res = encode_code_page(CP_ACP, unicode, errors);
7534 Py_DECREF(unicode);
7535 return res;
Victor Stinner3a50e702011-10-18 21:21:00 +02007536}
7537
7538PyObject *
7539PyUnicode_EncodeCodePage(int code_page,
7540 PyObject *unicode,
7541 const char *errors)
7542{
Victor Stinner7581cef2011-11-03 22:32:33 +01007543 return encode_code_page(code_page, unicode, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007544}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007545
Alexander Belopolsky40018472011-02-26 01:02:56 +00007546PyObject *
7547PyUnicode_AsMBCSString(PyObject *unicode)
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007548{
7549 if (!PyUnicode_Check(unicode)) {
7550 PyErr_BadArgument();
7551 return NULL;
7552 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007553 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007554}
7555
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007556#undef NEED_RETRY
7557
Victor Stinner99b95382011-07-04 14:23:54 +02007558#endif /* HAVE_MBCS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007559
Guido van Rossumd57fd912000-03-10 22:53:23 +00007560/* --- Character Mapping Codec -------------------------------------------- */
7561
Alexander Belopolsky40018472011-02-26 01:02:56 +00007562PyObject *
7563PyUnicode_DecodeCharmap(const char *s,
7564 Py_ssize_t size,
7565 PyObject *mapping,
7566 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007567{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007568 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007569 Py_ssize_t startinpos;
7570 Py_ssize_t endinpos;
7571 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007572 const char *e;
Victor Stinner7931d9a2011-11-04 00:22:48 +01007573 PyObject *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007574 Py_ssize_t extrachars = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007575 PyObject *errorHandler = NULL;
7576 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00007577
Guido van Rossumd57fd912000-03-10 22:53:23 +00007578 /* Default to Latin-1 */
7579 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007580 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007581
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007582 v = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007583 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007584 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007585 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01007586 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007587 outpos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007588 e = s + size;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007589 if (PyUnicode_CheckExact(mapping)) {
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007590 Py_ssize_t maplen;
7591 enum PyUnicode_Kind kind;
7592 void *data;
7593 Py_UCS4 x;
7594
7595 if (PyUnicode_READY(mapping) < 0)
7596 return NULL;
7597
7598 maplen = PyUnicode_GET_LENGTH(mapping);
7599 data = PyUnicode_DATA(mapping);
7600 kind = PyUnicode_KIND(mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00007601 while (s < e) {
7602 unsigned char ch = *s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007603
Benjamin Peterson29060642009-01-31 22:14:21 +00007604 if (ch < maplen)
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007605 x = PyUnicode_READ(kind, data, ch);
7606 else
7607 x = 0xfffe; /* invalid value */
Guido van Rossumd57fd912000-03-10 22:53:23 +00007608
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007609 if (x == 0xfffe)
7610 {
Benjamin Peterson29060642009-01-31 22:14:21 +00007611 /* undefined mapping */
Benjamin Peterson29060642009-01-31 22:14:21 +00007612 startinpos = s-starts;
7613 endinpos = startinpos+1;
7614 if (unicode_decode_call_errorhandler(
7615 errors, &errorHandler,
7616 "charmap", "character maps to <undefined>",
7617 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007618 &v, &outpos)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007619 goto onError;
7620 }
7621 continue;
7622 }
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007623
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007624 if (unicode_putchar(&v, &outpos, x) < 0)
7625 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00007626 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007627 }
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007628 }
7629 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007630 while (s < e) {
7631 unsigned char ch = *s;
7632 PyObject *w, *x;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007633
Benjamin Peterson29060642009-01-31 22:14:21 +00007634 /* Get mapping (char ordinal -> integer, Unicode char or None) */
7635 w = PyLong_FromLong((long)ch);
7636 if (w == NULL)
7637 goto onError;
7638 x = PyObject_GetItem(mapping, w);
7639 Py_DECREF(w);
7640 if (x == NULL) {
7641 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7642 /* No mapping found means: mapping is undefined. */
7643 PyErr_Clear();
7644 x = Py_None;
7645 Py_INCREF(x);
7646 } else
7647 goto onError;
7648 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007649
Benjamin Peterson29060642009-01-31 22:14:21 +00007650 /* Apply mapping */
7651 if (PyLong_Check(x)) {
7652 long value = PyLong_AS_LONG(x);
7653 if (value < 0 || value > 65535) {
7654 PyErr_SetString(PyExc_TypeError,
7655 "character mapping must be in range(65536)");
7656 Py_DECREF(x);
7657 goto onError;
7658 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007659 if (unicode_putchar(&v, &outpos, value) < 0)
7660 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00007661 }
7662 else if (x == Py_None) {
7663 /* undefined mapping */
Benjamin Peterson29060642009-01-31 22:14:21 +00007664 startinpos = s-starts;
7665 endinpos = startinpos+1;
7666 if (unicode_decode_call_errorhandler(
7667 errors, &errorHandler,
7668 "charmap", "character maps to <undefined>",
7669 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007670 &v, &outpos)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007671 Py_DECREF(x);
7672 goto onError;
7673 }
7674 Py_DECREF(x);
7675 continue;
7676 }
7677 else if (PyUnicode_Check(x)) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007678 Py_ssize_t targetsize;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007679
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007680 if (PyUnicode_READY(x) < 0)
7681 goto onError;
7682 targetsize = PyUnicode_GET_LENGTH(x);
7683
7684 if (targetsize == 1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007685 /* 1-1 mapping */
Victor Stinner62aa4d02011-11-09 00:03:45 +01007686 if (unicode_putchar(&v, &outpos,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007687 PyUnicode_READ_CHAR(x, 0)) < 0)
7688 goto onError;
7689 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007690 else if (targetsize > 1) {
7691 /* 1-n mapping */
7692 if (targetsize > extrachars) {
7693 /* resize first */
Benjamin Peterson29060642009-01-31 22:14:21 +00007694 Py_ssize_t needed = (targetsize - extrachars) + \
7695 (targetsize << 2);
7696 extrachars += needed;
7697 /* XXX overflow detection missing */
Victor Stinner7931d9a2011-11-04 00:22:48 +01007698 if (PyUnicode_Resize(&v,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007699 PyUnicode_GET_LENGTH(v) + needed) < 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007700 Py_DECREF(x);
7701 goto onError;
7702 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007703 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007704 if (unicode_widen(&v, PyUnicode_MAX_CHAR_VALUE(x)) < 0)
7705 goto onError;
7706 PyUnicode_CopyCharacters(v, outpos, x, 0, targetsize);
7707 outpos += targetsize;
Benjamin Peterson29060642009-01-31 22:14:21 +00007708 extrachars -= targetsize;
7709 }
7710 /* 1-0 mapping: skip the character */
7711 }
7712 else {
7713 /* wrong return value */
7714 PyErr_SetString(PyExc_TypeError,
7715 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00007716 Py_DECREF(x);
7717 goto onError;
7718 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007719 Py_DECREF(x);
7720 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007721 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00007722 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007723 if (PyUnicode_Resize(&v, outpos) < 0)
Antoine Pitroua8f63c02011-11-08 18:37:16 +01007724 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007725 Py_XDECREF(errorHandler);
7726 Py_XDECREF(exc);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02007727 assert(_PyUnicode_CheckConsistency(v, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01007728 return v;
Tim Petersced69f82003-09-16 20:30:58 +00007729
Benjamin Peterson29060642009-01-31 22:14:21 +00007730 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007731 Py_XDECREF(errorHandler);
7732 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007733 Py_XDECREF(v);
7734 return NULL;
7735}
7736
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007737/* Charmap encoding: the lookup table */
7738
Alexander Belopolsky40018472011-02-26 01:02:56 +00007739struct encoding_map {
Benjamin Peterson29060642009-01-31 22:14:21 +00007740 PyObject_HEAD
7741 unsigned char level1[32];
7742 int count2, count3;
7743 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007744};
7745
7746static PyObject*
7747encoding_map_size(PyObject *obj, PyObject* args)
7748{
7749 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007750 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00007751 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007752}
7753
7754static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007755 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00007756 PyDoc_STR("Return the size (in bytes) of this object") },
7757 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007758};
7759
7760static void
7761encoding_map_dealloc(PyObject* o)
7762{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007763 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007764}
7765
7766static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007767 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007768 "EncodingMap", /*tp_name*/
7769 sizeof(struct encoding_map), /*tp_basicsize*/
7770 0, /*tp_itemsize*/
7771 /* methods */
7772 encoding_map_dealloc, /*tp_dealloc*/
7773 0, /*tp_print*/
7774 0, /*tp_getattr*/
7775 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00007776 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00007777 0, /*tp_repr*/
7778 0, /*tp_as_number*/
7779 0, /*tp_as_sequence*/
7780 0, /*tp_as_mapping*/
7781 0, /*tp_hash*/
7782 0, /*tp_call*/
7783 0, /*tp_str*/
7784 0, /*tp_getattro*/
7785 0, /*tp_setattro*/
7786 0, /*tp_as_buffer*/
7787 Py_TPFLAGS_DEFAULT, /*tp_flags*/
7788 0, /*tp_doc*/
7789 0, /*tp_traverse*/
7790 0, /*tp_clear*/
7791 0, /*tp_richcompare*/
7792 0, /*tp_weaklistoffset*/
7793 0, /*tp_iter*/
7794 0, /*tp_iternext*/
7795 encoding_map_methods, /*tp_methods*/
7796 0, /*tp_members*/
7797 0, /*tp_getset*/
7798 0, /*tp_base*/
7799 0, /*tp_dict*/
7800 0, /*tp_descr_get*/
7801 0, /*tp_descr_set*/
7802 0, /*tp_dictoffset*/
7803 0, /*tp_init*/
7804 0, /*tp_alloc*/
7805 0, /*tp_new*/
7806 0, /*tp_free*/
7807 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007808};
7809
7810PyObject*
7811PyUnicode_BuildEncodingMap(PyObject* string)
7812{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007813 PyObject *result;
7814 struct encoding_map *mresult;
7815 int i;
7816 int need_dict = 0;
7817 unsigned char level1[32];
7818 unsigned char level2[512];
7819 unsigned char *mlevel1, *mlevel2, *mlevel3;
7820 int count2 = 0, count3 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007821 int kind;
7822 void *data;
7823 Py_UCS4 ch;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007824
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007825 if (!PyUnicode_Check(string) || PyUnicode_GET_LENGTH(string) != 256) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007826 PyErr_BadArgument();
7827 return NULL;
7828 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007829 kind = PyUnicode_KIND(string);
7830 data = PyUnicode_DATA(string);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007831 memset(level1, 0xFF, sizeof level1);
7832 memset(level2, 0xFF, sizeof level2);
7833
7834 /* If there isn't a one-to-one mapping of NULL to \0,
7835 or if there are non-BMP characters, we need to use
7836 a mapping dictionary. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007837 if (PyUnicode_READ(kind, data, 0) != 0)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007838 need_dict = 1;
7839 for (i = 1; i < 256; i++) {
7840 int l1, l2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007841 ch = PyUnicode_READ(kind, data, i);
7842 if (ch == 0 || ch > 0xFFFF) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007843 need_dict = 1;
7844 break;
7845 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007846 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007847 /* unmapped character */
7848 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007849 l1 = ch >> 11;
7850 l2 = ch >> 7;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007851 if (level1[l1] == 0xFF)
7852 level1[l1] = count2++;
7853 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00007854 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007855 }
7856
7857 if (count2 >= 0xFF || count3 >= 0xFF)
7858 need_dict = 1;
7859
7860 if (need_dict) {
7861 PyObject *result = PyDict_New();
7862 PyObject *key, *value;
7863 if (!result)
7864 return NULL;
7865 for (i = 0; i < 256; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007866 key = PyLong_FromLong(PyUnicode_READ(kind, data, i));
Christian Heimes217cfd12007-12-02 14:31:20 +00007867 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007868 if (!key || !value)
7869 goto failed1;
7870 if (PyDict_SetItem(result, key, value) == -1)
7871 goto failed1;
7872 Py_DECREF(key);
7873 Py_DECREF(value);
7874 }
7875 return result;
7876 failed1:
7877 Py_XDECREF(key);
7878 Py_XDECREF(value);
7879 Py_DECREF(result);
7880 return NULL;
7881 }
7882
7883 /* Create a three-level trie */
7884 result = PyObject_MALLOC(sizeof(struct encoding_map) +
7885 16*count2 + 128*count3 - 1);
7886 if (!result)
7887 return PyErr_NoMemory();
7888 PyObject_Init(result, &EncodingMapType);
7889 mresult = (struct encoding_map*)result;
7890 mresult->count2 = count2;
7891 mresult->count3 = count3;
7892 mlevel1 = mresult->level1;
7893 mlevel2 = mresult->level23;
7894 mlevel3 = mresult->level23 + 16*count2;
7895 memcpy(mlevel1, level1, 32);
7896 memset(mlevel2, 0xFF, 16*count2);
7897 memset(mlevel3, 0, 128*count3);
7898 count3 = 0;
7899 for (i = 1; i < 256; i++) {
7900 int o1, o2, o3, i2, i3;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007901 if (PyUnicode_READ(kind, data, i) == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007902 /* unmapped character */
7903 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007904 o1 = PyUnicode_READ(kind, data, i)>>11;
7905 o2 = (PyUnicode_READ(kind, data, i)>>7) & 0xF;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007906 i2 = 16*mlevel1[o1] + o2;
7907 if (mlevel2[i2] == 0xFF)
7908 mlevel2[i2] = count3++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007909 o3 = PyUnicode_READ(kind, data, i) & 0x7F;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007910 i3 = 128*mlevel2[i2] + o3;
7911 mlevel3[i3] = i;
7912 }
7913 return result;
7914}
7915
7916static int
Victor Stinner22168992011-11-20 17:09:18 +01007917encoding_map_lookup(Py_UCS4 c, PyObject *mapping)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007918{
7919 struct encoding_map *map = (struct encoding_map*)mapping;
7920 int l1 = c>>11;
7921 int l2 = (c>>7) & 0xF;
7922 int l3 = c & 0x7F;
7923 int i;
7924
Victor Stinner22168992011-11-20 17:09:18 +01007925 if (c > 0xFFFF)
Benjamin Peterson29060642009-01-31 22:14:21 +00007926 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007927 if (c == 0)
7928 return 0;
7929 /* level 1*/
7930 i = map->level1[l1];
7931 if (i == 0xFF) {
7932 return -1;
7933 }
7934 /* level 2*/
7935 i = map->level23[16*i+l2];
7936 if (i == 0xFF) {
7937 return -1;
7938 }
7939 /* level 3 */
7940 i = map->level23[16*map->count2 + 128*i + l3];
7941 if (i == 0) {
7942 return -1;
7943 }
7944 return i;
7945}
7946
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007947/* Lookup the character ch in the mapping. If the character
7948 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00007949 error occurred). */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007950static PyObject *
Victor Stinner22168992011-11-20 17:09:18 +01007951charmapencode_lookup(Py_UCS4 c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007952{
Christian Heimes217cfd12007-12-02 14:31:20 +00007953 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007954 PyObject *x;
7955
7956 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007957 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007958 x = PyObject_GetItem(mapping, w);
7959 Py_DECREF(w);
7960 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007961 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7962 /* No mapping found means: mapping is undefined. */
7963 PyErr_Clear();
7964 x = Py_None;
7965 Py_INCREF(x);
7966 return x;
7967 } else
7968 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007969 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00007970 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00007971 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00007972 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007973 long value = PyLong_AS_LONG(x);
7974 if (value < 0 || value > 255) {
7975 PyErr_SetString(PyExc_TypeError,
7976 "character mapping must be in range(256)");
7977 Py_DECREF(x);
7978 return NULL;
7979 }
7980 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007981 }
Christian Heimes72b710a2008-05-26 13:28:38 +00007982 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00007983 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007984 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007985 /* wrong return value */
7986 PyErr_Format(PyExc_TypeError,
7987 "character mapping must return integer, bytes or None, not %.400s",
7988 x->ob_type->tp_name);
7989 Py_DECREF(x);
7990 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007991 }
7992}
7993
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007994static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00007995charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007996{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007997 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
7998 /* exponentially overallocate to minimize reallocations */
7999 if (requiredsize < 2*outsize)
8000 requiredsize = 2*outsize;
8001 if (_PyBytes_Resize(outobj, requiredsize))
8002 return -1;
8003 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008004}
8005
Benjamin Peterson14339b62009-01-31 16:36:08 +00008006typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00008007 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Alexander Belopolsky40018472011-02-26 01:02:56 +00008008} charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008009/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00008010 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008011 space is available. Return a new reference to the object that
8012 was put in the output buffer, or Py_None, if the mapping was undefined
8013 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00008014 reallocation error occurred. The caller must decref the result */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008015static charmapencode_result
Victor Stinner22168992011-11-20 17:09:18 +01008016charmapencode_output(Py_UCS4 c, PyObject *mapping,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008017 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008018{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008019 PyObject *rep;
8020 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00008021 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008022
Christian Heimes90aa7642007-12-19 02:45:37 +00008023 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008024 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008025 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008026 if (res == -1)
8027 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00008028 if (outsize<requiredsize)
8029 if (charmapencode_resize(outobj, outpos, requiredsize))
8030 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00008031 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008032 outstart[(*outpos)++] = (char)res;
8033 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008034 }
8035
8036 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008037 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008038 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008039 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008040 Py_DECREF(rep);
8041 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008042 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008043 if (PyLong_Check(rep)) {
8044 Py_ssize_t requiredsize = *outpos+1;
8045 if (outsize<requiredsize)
8046 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8047 Py_DECREF(rep);
8048 return enc_EXCEPTION;
8049 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008050 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008051 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008052 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008053 else {
8054 const char *repchars = PyBytes_AS_STRING(rep);
8055 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
8056 Py_ssize_t requiredsize = *outpos+repsize;
8057 if (outsize<requiredsize)
8058 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8059 Py_DECREF(rep);
8060 return enc_EXCEPTION;
8061 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008062 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008063 memcpy(outstart + *outpos, repchars, repsize);
8064 *outpos += repsize;
8065 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008066 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008067 Py_DECREF(rep);
8068 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008069}
8070
8071/* handle an error in PyUnicode_EncodeCharmap
8072 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008073static int
8074charmap_encoding_error(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008075 PyObject *unicode, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008076 PyObject **exceptionObject,
Walter Dörwalde5402fb2003-08-14 20:25:29 +00008077 int *known_errorHandler, PyObject **errorHandler, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00008078 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008079{
8080 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008081 Py_ssize_t size, repsize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008082 Py_ssize_t newpos;
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008083 enum PyUnicode_Kind kind;
8084 void *data;
8085 Py_ssize_t index;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008086 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008087 Py_ssize_t collstartpos = *inpos;
8088 Py_ssize_t collendpos = *inpos+1;
8089 Py_ssize_t collpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008090 char *encoding = "charmap";
8091 char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008092 charmapencode_result x;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008093 Py_UCS4 ch;
Brian Curtin2787ea42011-11-02 15:09:37 -05008094 int val;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008095
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008096 if (PyUnicode_READY(unicode) < 0)
8097 return -1;
8098 size = PyUnicode_GET_LENGTH(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008099 /* find all unencodable characters */
8100 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008101 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00008102 if (Py_TYPE(mapping) == &EncodingMapType) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008103 ch = PyUnicode_READ_CHAR(unicode, collendpos);
Brian Curtin2787ea42011-11-02 15:09:37 -05008104 val = encoding_map_lookup(ch, mapping);
8105 if (val != -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008106 break;
8107 ++collendpos;
8108 continue;
8109 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008110
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008111 ch = PyUnicode_READ_CHAR(unicode, collendpos);
8112 rep = charmapencode_lookup(ch, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008113 if (rep==NULL)
8114 return -1;
8115 else if (rep!=Py_None) {
8116 Py_DECREF(rep);
8117 break;
8118 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008119 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00008120 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008121 }
8122 /* cache callback name lookup
8123 * (if not done yet, i.e. it's the first error) */
8124 if (*known_errorHandler==-1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008125 if ((errors==NULL) || (!strcmp(errors, "strict")))
8126 *known_errorHandler = 1;
8127 else if (!strcmp(errors, "replace"))
8128 *known_errorHandler = 2;
8129 else if (!strcmp(errors, "ignore"))
8130 *known_errorHandler = 3;
8131 else if (!strcmp(errors, "xmlcharrefreplace"))
8132 *known_errorHandler = 4;
8133 else
8134 *known_errorHandler = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008135 }
8136 switch (*known_errorHandler) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008137 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008138 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008139 return -1;
8140 case 2: /* replace */
8141 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008142 x = charmapencode_output('?', mapping, res, respos);
8143 if (x==enc_EXCEPTION) {
8144 return -1;
8145 }
8146 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008147 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008148 return -1;
8149 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008150 }
8151 /* fall through */
8152 case 3: /* ignore */
8153 *inpos = collendpos;
8154 break;
8155 case 4: /* xmlcharrefreplace */
8156 /* generate replacement (temporarily (mis)uses p) */
8157 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008158 char buffer[2+29+1+1];
8159 char *cp;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008160 sprintf(buffer, "&#%d;", (int)PyUnicode_READ_CHAR(unicode, collpos));
Benjamin Peterson29060642009-01-31 22:14:21 +00008161 for (cp = buffer; *cp; ++cp) {
8162 x = charmapencode_output(*cp, mapping, res, respos);
8163 if (x==enc_EXCEPTION)
8164 return -1;
8165 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008166 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008167 return -1;
8168 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008169 }
8170 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008171 *inpos = collendpos;
8172 break;
8173 default:
8174 repunicode = unicode_encode_call_errorhandler(errors, errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008175 encoding, reason, unicode, exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00008176 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008177 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008178 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00008179 if (PyBytes_Check(repunicode)) {
8180 /* Directly copy bytes result to output. */
8181 Py_ssize_t outsize = PyBytes_Size(*res);
8182 Py_ssize_t requiredsize;
8183 repsize = PyBytes_Size(repunicode);
8184 requiredsize = *respos + repsize;
8185 if (requiredsize > outsize)
8186 /* Make room for all additional bytes. */
8187 if (charmapencode_resize(res, respos, requiredsize)) {
8188 Py_DECREF(repunicode);
8189 return -1;
8190 }
8191 memcpy(PyBytes_AsString(*res) + *respos,
8192 PyBytes_AsString(repunicode), repsize);
8193 *respos += repsize;
8194 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008195 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00008196 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008197 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008198 /* generate replacement */
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008199 if (PyUnicode_READY(repunicode) < 0) {
8200 Py_DECREF(repunicode);
8201 return -1;
8202 }
Victor Stinner9e30aa52011-11-21 02:49:52 +01008203 repsize = PyUnicode_GET_LENGTH(repunicode);
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008204 data = PyUnicode_DATA(repunicode);
8205 kind = PyUnicode_KIND(repunicode);
8206 for (index = 0; index < repsize; index++) {
8207 Py_UCS4 repch = PyUnicode_READ(kind, data, index);
8208 x = charmapencode_output(repch, mapping, res, respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008209 if (x==enc_EXCEPTION) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008210 Py_DECREF(repunicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00008211 return -1;
8212 }
8213 else if (x==enc_FAILED) {
8214 Py_DECREF(repunicode);
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008215 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008216 return -1;
8217 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008218 }
8219 *inpos = newpos;
8220 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008221 }
8222 return 0;
8223}
8224
Alexander Belopolsky40018472011-02-26 01:02:56 +00008225PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008226_PyUnicode_EncodeCharmap(PyObject *unicode,
8227 PyObject *mapping,
8228 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008229{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008230 /* output object */
8231 PyObject *res = NULL;
8232 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008233 Py_ssize_t inpos = 0;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008234 Py_ssize_t size;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008235 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008236 Py_ssize_t respos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008237 PyObject *errorHandler = NULL;
8238 PyObject *exc = NULL;
8239 /* the following variable is used for caching string comparisons
8240 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8241 * 3=ignore, 4=xmlcharrefreplace */
8242 int known_errorHandler = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008243
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008244 if (PyUnicode_READY(unicode) < 0)
8245 return NULL;
8246 size = PyUnicode_GET_LENGTH(unicode);
8247
Guido van Rossumd57fd912000-03-10 22:53:23 +00008248 /* Default to Latin-1 */
8249 if (mapping == NULL)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008250 return unicode_encode_ucs1(unicode, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008251
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008252 /* allocate enough for a simple encoding without
8253 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00008254 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008255 if (res == NULL)
8256 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00008257 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008258 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008259
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008260 while (inpos<size) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008261 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, inpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008262 /* try to encode it */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008263 charmapencode_result x = charmapencode_output(ch, mapping, &res, &respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008264 if (x==enc_EXCEPTION) /* error */
8265 goto onError;
8266 if (x==enc_FAILED) { /* unencodable character */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008267 if (charmap_encoding_error(unicode, &inpos, mapping,
Benjamin Peterson29060642009-01-31 22:14:21 +00008268 &exc,
8269 &known_errorHandler, &errorHandler, errors,
8270 &res, &respos)) {
8271 goto onError;
8272 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008273 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008274 else
8275 /* done with this character => adjust input position */
8276 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008277 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008278
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008279 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00008280 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00008281 if (_PyBytes_Resize(&res, respos) < 0)
8282 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00008283
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008284 Py_XDECREF(exc);
8285 Py_XDECREF(errorHandler);
8286 return res;
8287
Benjamin Peterson29060642009-01-31 22:14:21 +00008288 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008289 Py_XDECREF(res);
8290 Py_XDECREF(exc);
8291 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008292 return NULL;
8293}
8294
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008295/* Deprecated */
8296PyObject *
8297PyUnicode_EncodeCharmap(const Py_UNICODE *p,
8298 Py_ssize_t size,
8299 PyObject *mapping,
8300 const char *errors)
8301{
8302 PyObject *result;
8303 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8304 if (unicode == NULL)
8305 return NULL;
8306 result = _PyUnicode_EncodeCharmap(unicode, mapping, errors);
8307 Py_DECREF(unicode);
Victor Stinnerfc026c92011-11-04 00:24:51 +01008308 return result;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008309}
8310
Alexander Belopolsky40018472011-02-26 01:02:56 +00008311PyObject *
8312PyUnicode_AsCharmapString(PyObject *unicode,
8313 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008314{
8315 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008316 PyErr_BadArgument();
8317 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008318 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008319 return _PyUnicode_EncodeCharmap(unicode, mapping, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008320}
8321
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008322/* create or adjust a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008323static void
8324make_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008325 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008326 Py_ssize_t startpos, Py_ssize_t endpos,
8327 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008328{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008329 if (*exceptionObject == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008330 *exceptionObject = _PyUnicodeTranslateError_Create(
8331 unicode, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008332 }
8333 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008334 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
8335 goto onError;
8336 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
8337 goto onError;
8338 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
8339 goto onError;
8340 return;
8341 onError:
8342 Py_DECREF(*exceptionObject);
8343 *exceptionObject = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008344 }
8345}
8346
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008347/* raises a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008348static void
8349raise_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008350 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008351 Py_ssize_t startpos, Py_ssize_t endpos,
8352 const char *reason)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008353{
8354 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008355 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008356 if (*exceptionObject != NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008357 PyCodec_StrictErrors(*exceptionObject);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008358}
8359
8360/* error handling callback helper:
8361 build arguments, call the callback and check the arguments,
8362 put the result into newpos and return the replacement string, which
8363 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008364static PyObject *
8365unicode_translate_call_errorhandler(const char *errors,
8366 PyObject **errorHandler,
8367 const char *reason,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008368 PyObject *unicode, PyObject **exceptionObject,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008369 Py_ssize_t startpos, Py_ssize_t endpos,
8370 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008371{
Benjamin Peterson142957c2008-07-04 19:55:29 +00008372 static char *argparse = "O!n;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008373
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008374 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008375 PyObject *restuple;
8376 PyObject *resunicode;
8377
8378 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008379 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008380 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008381 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008382 }
8383
8384 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008385 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008386 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008387 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008388
8389 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00008390 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008391 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008392 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008393 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00008394 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00008395 Py_DECREF(restuple);
8396 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008397 }
8398 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type,
Benjamin Peterson29060642009-01-31 22:14:21 +00008399 &resunicode, &i_newpos)) {
8400 Py_DECREF(restuple);
8401 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008402 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00008403 if (i_newpos<0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008404 *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008405 else
8406 *newpos = i_newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008407 if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008408 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
8409 Py_DECREF(restuple);
8410 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00008411 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008412 Py_INCREF(resunicode);
8413 Py_DECREF(restuple);
8414 return resunicode;
8415}
8416
8417/* Lookup the character ch in the mapping and put the result in result,
8418 which must be decrefed by the caller.
8419 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008420static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008421charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008422{
Christian Heimes217cfd12007-12-02 14:31:20 +00008423 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008424 PyObject *x;
8425
8426 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008427 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008428 x = PyObject_GetItem(mapping, w);
8429 Py_DECREF(w);
8430 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008431 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8432 /* No mapping found means: use 1:1 mapping. */
8433 PyErr_Clear();
8434 *result = NULL;
8435 return 0;
8436 } else
8437 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008438 }
8439 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008440 *result = x;
8441 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008442 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008443 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008444 long value = PyLong_AS_LONG(x);
8445 long max = PyUnicode_GetMax();
8446 if (value < 0 || value > max) {
8447 PyErr_Format(PyExc_TypeError,
Guido van Rossum5a2f7e602007-10-24 21:13:09 +00008448 "character mapping must be in range(0x%x)", max+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00008449 Py_DECREF(x);
8450 return -1;
8451 }
8452 *result = x;
8453 return 0;
8454 }
8455 else if (PyUnicode_Check(x)) {
8456 *result = x;
8457 return 0;
8458 }
8459 else {
8460 /* wrong return value */
8461 PyErr_SetString(PyExc_TypeError,
8462 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00008463 Py_DECREF(x);
8464 return -1;
8465 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008466}
8467/* ensure that *outobj is at least requiredsize characters long,
Benjamin Peterson29060642009-01-31 22:14:21 +00008468 if not reallocate and adjust various state variables.
8469 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008470static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008471charmaptranslate_makespace(Py_UCS4 **outobj, Py_ssize_t *psize,
Benjamin Peterson29060642009-01-31 22:14:21 +00008472 Py_ssize_t requiredsize)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008473{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008474 Py_ssize_t oldsize = *psize;
Walter Dörwald4894c302003-10-24 14:25:28 +00008475 if (requiredsize > oldsize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008476 /* exponentially overallocate to minimize reallocations */
8477 if (requiredsize < 2 * oldsize)
8478 requiredsize = 2 * oldsize;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008479 *outobj = PyMem_Realloc(*outobj, requiredsize * sizeof(Py_UCS4));
8480 if (*outobj == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008481 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008482 *psize = requiredsize;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008483 }
8484 return 0;
8485}
8486/* lookup the character, put the result in the output string and adjust
8487 various state variables. Return a new reference to the object that
8488 was put in the output buffer in *result, or Py_None, if the mapping was
8489 undefined (in which case no character was written).
8490 The called must decref result.
8491 Return 0 on success, -1 on error. */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008492static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008493charmaptranslate_output(PyObject *input, Py_ssize_t ipos,
8494 PyObject *mapping, Py_UCS4 **output,
8495 Py_ssize_t *osize, Py_ssize_t *opos,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008496 PyObject **res)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008497{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008498 Py_UCS4 curinp = PyUnicode_READ_CHAR(input, ipos);
8499 if (charmaptranslate_lookup(curinp, mapping, res))
Benjamin Peterson29060642009-01-31 22:14:21 +00008500 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008501 if (*res==NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008502 /* not found => default to 1:1 mapping */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008503 (*output)[(*opos)++] = curinp;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008504 }
8505 else if (*res==Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008506 ;
Christian Heimes217cfd12007-12-02 14:31:20 +00008507 else if (PyLong_Check(*res)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008508 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008509 (*output)[(*opos)++] = (Py_UCS4)PyLong_AS_LONG(*res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008510 }
8511 else if (PyUnicode_Check(*res)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008512 Py_ssize_t repsize;
8513 if (PyUnicode_READY(*res) == -1)
8514 return -1;
8515 repsize = PyUnicode_GET_LENGTH(*res);
Benjamin Peterson29060642009-01-31 22:14:21 +00008516 if (repsize==1) {
8517 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008518 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +00008519 }
8520 else if (repsize!=0) {
8521 /* more than one character */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008522 Py_ssize_t requiredsize = *opos +
8523 (PyUnicode_GET_LENGTH(input) - ipos) +
Benjamin Peterson29060642009-01-31 22:14:21 +00008524 repsize - 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008525 Py_ssize_t i;
8526 if (charmaptranslate_makespace(output, osize, requiredsize))
Benjamin Peterson29060642009-01-31 22:14:21 +00008527 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008528 for(i = 0; i < repsize; i++)
8529 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00008530 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008531 }
8532 else
Benjamin Peterson29060642009-01-31 22:14:21 +00008533 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008534 return 0;
8535}
8536
Alexander Belopolsky40018472011-02-26 01:02:56 +00008537PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008538_PyUnicode_TranslateCharmap(PyObject *input,
8539 PyObject *mapping,
8540 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008541{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008542 /* input object */
8543 char *idata;
8544 Py_ssize_t size, i;
8545 int kind;
8546 /* output buffer */
8547 Py_UCS4 *output = NULL;
8548 Py_ssize_t osize;
8549 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008550 /* current output position */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008551 Py_ssize_t opos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008552 char *reason = "character maps to <undefined>";
8553 PyObject *errorHandler = NULL;
8554 PyObject *exc = NULL;
8555 /* the following variable is used for caching string comparisons
8556 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8557 * 3=ignore, 4=xmlcharrefreplace */
8558 int known_errorHandler = -1;
8559
Guido van Rossumd57fd912000-03-10 22:53:23 +00008560 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008561 PyErr_BadArgument();
8562 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008563 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008564
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008565 if (PyUnicode_READY(input) == -1)
8566 return NULL;
8567 idata = (char*)PyUnicode_DATA(input);
8568 kind = PyUnicode_KIND(input);
8569 size = PyUnicode_GET_LENGTH(input);
8570 i = 0;
8571
8572 if (size == 0) {
8573 Py_INCREF(input);
8574 return input;
8575 }
8576
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008577 /* allocate enough for a simple 1:1 translation without
8578 replacements, if we need more, we'll resize */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008579 osize = size;
8580 output = PyMem_Malloc(osize * sizeof(Py_UCS4));
8581 opos = 0;
8582 if (output == NULL) {
8583 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00008584 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008585 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008586
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008587 while (i<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008588 /* try to encode it */
8589 PyObject *x = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008590 if (charmaptranslate_output(input, i, mapping,
8591 &output, &osize, &opos, &x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008592 Py_XDECREF(x);
8593 goto onError;
8594 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008595 Py_XDECREF(x);
Benjamin Peterson29060642009-01-31 22:14:21 +00008596 if (x!=Py_None) /* it worked => adjust input pointer */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008597 ++i;
Benjamin Peterson29060642009-01-31 22:14:21 +00008598 else { /* untranslatable character */
8599 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
8600 Py_ssize_t repsize;
8601 Py_ssize_t newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008602 Py_ssize_t uni2;
Benjamin Peterson29060642009-01-31 22:14:21 +00008603 /* startpos for collecting untranslatable chars */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008604 Py_ssize_t collstart = i;
8605 Py_ssize_t collend = i+1;
8606 Py_ssize_t coll;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008607
Benjamin Peterson29060642009-01-31 22:14:21 +00008608 /* find all untranslatable characters */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008609 while (collend < size) {
8610 if (charmaptranslate_lookup(PyUnicode_READ(kind,idata, collend), mapping, &x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008611 goto onError;
8612 Py_XDECREF(x);
8613 if (x!=Py_None)
8614 break;
8615 ++collend;
8616 }
8617 /* cache callback name lookup
8618 * (if not done yet, i.e. it's the first error) */
8619 if (known_errorHandler==-1) {
8620 if ((errors==NULL) || (!strcmp(errors, "strict")))
8621 known_errorHandler = 1;
8622 else if (!strcmp(errors, "replace"))
8623 known_errorHandler = 2;
8624 else if (!strcmp(errors, "ignore"))
8625 known_errorHandler = 3;
8626 else if (!strcmp(errors, "xmlcharrefreplace"))
8627 known_errorHandler = 4;
8628 else
8629 known_errorHandler = 0;
8630 }
8631 switch (known_errorHandler) {
8632 case 1: /* strict */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008633 raise_translate_exception(&exc, input, collstart,
8634 collend, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008635 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00008636 case 2: /* replace */
8637 /* No need to check for space, this is a 1:1 replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008638 for (coll = collstart; coll<collend; coll++)
8639 output[opos++] = '?';
Benjamin Peterson29060642009-01-31 22:14:21 +00008640 /* fall through */
8641 case 3: /* ignore */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008642 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008643 break;
8644 case 4: /* xmlcharrefreplace */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008645 /* generate replacement (temporarily (mis)uses i) */
8646 for (i = collstart; i < collend; ++i) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008647 char buffer[2+29+1+1];
8648 char *cp;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008649 sprintf(buffer, "&#%d;", PyUnicode_READ(kind, idata, i));
8650 if (charmaptranslate_makespace(&output, &osize,
8651 opos+strlen(buffer)+(size-collend)))
Benjamin Peterson29060642009-01-31 22:14:21 +00008652 goto onError;
8653 for (cp = buffer; *cp; ++cp)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008654 output[opos++] = *cp;
Benjamin Peterson29060642009-01-31 22:14:21 +00008655 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008656 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008657 break;
8658 default:
8659 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008660 reason, input, &exc,
8661 collstart, collend, &newpos);
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02008662 if (repunicode == NULL || _PyUnicode_READY_REPLACE(&repunicode))
Benjamin Peterson29060642009-01-31 22:14:21 +00008663 goto onError;
8664 /* generate replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008665 repsize = PyUnicode_GET_LENGTH(repunicode);
8666 if (charmaptranslate_makespace(&output, &osize,
8667 opos+repsize+(size-collend))) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008668 Py_DECREF(repunicode);
8669 goto onError;
8670 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008671 for (uni2 = 0; repsize-->0; ++uni2)
8672 output[opos++] = PyUnicode_READ_CHAR(repunicode, uni2);
8673 i = newpos;
Benjamin Peterson29060642009-01-31 22:14:21 +00008674 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008675 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008676 }
8677 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008678 res = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND, output, opos);
8679 if (!res)
8680 goto onError;
8681 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008682 Py_XDECREF(exc);
8683 Py_XDECREF(errorHandler);
8684 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008685
Benjamin Peterson29060642009-01-31 22:14:21 +00008686 onError:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008687 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008688 Py_XDECREF(exc);
8689 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008690 return NULL;
8691}
8692
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008693/* Deprecated. Use PyUnicode_Translate instead. */
8694PyObject *
8695PyUnicode_TranslateCharmap(const Py_UNICODE *p,
8696 Py_ssize_t size,
8697 PyObject *mapping,
8698 const char *errors)
8699{
8700 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8701 if (!unicode)
8702 return NULL;
8703 return _PyUnicode_TranslateCharmap(unicode, mapping, errors);
8704}
8705
Alexander Belopolsky40018472011-02-26 01:02:56 +00008706PyObject *
8707PyUnicode_Translate(PyObject *str,
8708 PyObject *mapping,
8709 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008710{
8711 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +00008712
Guido van Rossumd57fd912000-03-10 22:53:23 +00008713 str = PyUnicode_FromObject(str);
8714 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008715 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008716 result = _PyUnicode_TranslateCharmap(str, mapping, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008717 Py_DECREF(str);
8718 return result;
Tim Petersced69f82003-09-16 20:30:58 +00008719
Benjamin Peterson29060642009-01-31 22:14:21 +00008720 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00008721 Py_XDECREF(str);
8722 return NULL;
8723}
Tim Petersced69f82003-09-16 20:30:58 +00008724
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008725static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02008726fix_decimal_and_space_to_ascii(PyObject *self)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008727{
8728 /* No need to call PyUnicode_READY(self) because this function is only
8729 called as a callback from fixup() which does it already. */
8730 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
8731 const int kind = PyUnicode_KIND(self);
8732 void *data = PyUnicode_DATA(self);
8733 Py_UCS4 maxchar = 0, ch, fixed;
8734 Py_ssize_t i;
8735
8736 for (i = 0; i < len; ++i) {
8737 ch = PyUnicode_READ(kind, data, i);
8738 fixed = 0;
8739 if (ch > 127) {
8740 if (Py_UNICODE_ISSPACE(ch))
8741 fixed = ' ';
8742 else {
8743 const int decimal = Py_UNICODE_TODECIMAL(ch);
8744 if (decimal >= 0)
8745 fixed = '0' + decimal;
8746 }
8747 if (fixed != 0) {
8748 if (fixed > maxchar)
8749 maxchar = fixed;
8750 PyUnicode_WRITE(kind, data, i, fixed);
8751 }
8752 else if (ch > maxchar)
8753 maxchar = ch;
8754 }
8755 else if (ch > maxchar)
8756 maxchar = ch;
8757 }
8758
8759 return maxchar;
8760}
8761
8762PyObject *
8763_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
8764{
8765 if (!PyUnicode_Check(unicode)) {
8766 PyErr_BadInternalCall();
8767 return NULL;
8768 }
8769 if (PyUnicode_READY(unicode) == -1)
8770 return NULL;
8771 if (PyUnicode_MAX_CHAR_VALUE(unicode) <= 127) {
8772 /* If the string is already ASCII, just return the same string */
8773 Py_INCREF(unicode);
8774 return unicode;
8775 }
Victor Stinner9310abb2011-10-05 00:59:23 +02008776 return fixup(unicode, fix_decimal_and_space_to_ascii);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008777}
8778
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008779PyObject *
8780PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
8781 Py_ssize_t length)
8782{
8783 PyObject *result;
8784 Py_UNICODE *p; /* write pointer into result */
8785 Py_ssize_t i;
8786 /* Copy to a new string */
8787 result = (PyObject *)_PyUnicode_New(length);
8788 Py_UNICODE_COPY(PyUnicode_AS_UNICODE(result), s, length);
8789 if (result == NULL)
8790 return result;
8791 p = PyUnicode_AS_UNICODE(result);
8792 /* Iterate over code points */
8793 for (i = 0; i < length; i++) {
8794 Py_UNICODE ch =s[i];
8795 if (ch > 127) {
8796 int decimal = Py_UNICODE_TODECIMAL(ch);
8797 if (decimal >= 0)
8798 p[i] = '0' + decimal;
8799 }
8800 }
Victor Stinner17efeed2011-10-04 20:05:46 +02008801#ifndef DONT_MAKE_RESULT_READY
8802 if (_PyUnicode_READY_REPLACE(&result)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008803 Py_DECREF(result);
8804 return NULL;
8805 }
Victor Stinner17efeed2011-10-04 20:05:46 +02008806#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02008807 assert(_PyUnicode_CheckConsistency(result, 1));
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008808 return result;
8809}
Guido van Rossum9e896b32000-04-05 20:11:21 +00008810/* --- Decimal Encoder ---------------------------------------------------- */
8811
Alexander Belopolsky40018472011-02-26 01:02:56 +00008812int
8813PyUnicode_EncodeDecimal(Py_UNICODE *s,
8814 Py_ssize_t length,
8815 char *output,
8816 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00008817{
8818 Py_UNICODE *p, *end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008819 PyObject *errorHandler = NULL;
8820 PyObject *exc = NULL;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008821 PyObject *unicode;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008822 const char *encoding = "decimal";
8823 const char *reason = "invalid decimal Unicode string";
8824 /* the following variable is used for caching string comparisons
8825 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
8826 int known_errorHandler = -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008827
8828 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008829 PyErr_BadArgument();
8830 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008831 }
8832
8833 p = s;
8834 end = s + length;
8835 while (p < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008836 register Py_UNICODE ch = *p;
8837 int decimal;
8838 PyObject *repunicode;
8839 Py_ssize_t repsize;
8840 Py_ssize_t newpos;
8841 Py_UNICODE *uni2;
8842 Py_UNICODE *collstart;
8843 Py_UNICODE *collend;
Tim Petersced69f82003-09-16 20:30:58 +00008844
Benjamin Peterson29060642009-01-31 22:14:21 +00008845 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008846 *output++ = ' ';
Benjamin Peterson29060642009-01-31 22:14:21 +00008847 ++p;
8848 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008849 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008850 decimal = Py_UNICODE_TODECIMAL(ch);
8851 if (decimal >= 0) {
8852 *output++ = '0' + decimal;
8853 ++p;
8854 continue;
8855 }
8856 if (0 < ch && ch < 256) {
8857 *output++ = (char)ch;
8858 ++p;
8859 continue;
8860 }
8861 /* All other characters are considered unencodable */
8862 collstart = p;
8863 collend = p+1;
8864 while (collend < end) {
8865 if ((0 < *collend && *collend < 256) ||
8866 !Py_UNICODE_ISSPACE(*collend) ||
8867 Py_UNICODE_TODECIMAL(*collend))
8868 break;
8869 }
8870 /* cache callback name lookup
8871 * (if not done yet, i.e. it's the first error) */
8872 if (known_errorHandler==-1) {
8873 if ((errors==NULL) || (!strcmp(errors, "strict")))
8874 known_errorHandler = 1;
8875 else if (!strcmp(errors, "replace"))
8876 known_errorHandler = 2;
8877 else if (!strcmp(errors, "ignore"))
8878 known_errorHandler = 3;
8879 else if (!strcmp(errors, "xmlcharrefreplace"))
8880 known_errorHandler = 4;
8881 else
8882 known_errorHandler = 0;
8883 }
8884 switch (known_errorHandler) {
8885 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008886 unicode = PyUnicode_FromUnicode(s, length);
8887 if (unicode == NULL)
8888 goto onError;
8889 raise_encode_exception(&exc, encoding, unicode, collstart-s, collend-s, reason);
8890 Py_DECREF(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00008891 goto onError;
8892 case 2: /* replace */
8893 for (p = collstart; p < collend; ++p)
8894 *output++ = '?';
8895 /* fall through */
8896 case 3: /* ignore */
8897 p = collend;
8898 break;
8899 case 4: /* xmlcharrefreplace */
8900 /* generate replacement (temporarily (mis)uses p) */
8901 for (p = collstart; p < collend; ++p)
8902 output += sprintf(output, "&#%d;", (int)*p);
8903 p = collend;
8904 break;
8905 default:
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008906 unicode = PyUnicode_FromUnicode(s, length);
8907 if (unicode == NULL)
8908 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00008909 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008910 encoding, reason, unicode, &exc,
Benjamin Peterson29060642009-01-31 22:14:21 +00008911 collstart-s, collend-s, &newpos);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008912 Py_DECREF(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00008913 if (repunicode == NULL)
8914 goto onError;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008915 if (!PyUnicode_Check(repunicode)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00008916 /* Byte results not supported, since they have no decimal property. */
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008917 PyErr_SetString(PyExc_TypeError, "error handler should return unicode");
8918 Py_DECREF(repunicode);
8919 goto onError;
8920 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008921 /* generate replacement */
8922 repsize = PyUnicode_GET_SIZE(repunicode);
8923 for (uni2 = PyUnicode_AS_UNICODE(repunicode); repsize-->0; ++uni2) {
8924 Py_UNICODE ch = *uni2;
8925 if (Py_UNICODE_ISSPACE(ch))
8926 *output++ = ' ';
8927 else {
8928 decimal = Py_UNICODE_TODECIMAL(ch);
8929 if (decimal >= 0)
8930 *output++ = '0' + decimal;
8931 else if (0 < ch && ch < 256)
8932 *output++ = (char)ch;
8933 else {
8934 Py_DECREF(repunicode);
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008935 unicode = PyUnicode_FromUnicode(s, length);
8936 if (unicode == NULL)
8937 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00008938 raise_encode_exception(&exc, encoding,
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008939 unicode, collstart-s, collend-s, reason);
8940 Py_DECREF(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00008941 goto onError;
8942 }
8943 }
8944 }
8945 p = s + newpos;
8946 Py_DECREF(repunicode);
8947 }
Guido van Rossum9e896b32000-04-05 20:11:21 +00008948 }
8949 /* 0-terminate the output string */
8950 *output++ = '\0';
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008951 Py_XDECREF(exc);
8952 Py_XDECREF(errorHandler);
Guido van Rossum9e896b32000-04-05 20:11:21 +00008953 return 0;
8954
Benjamin Peterson29060642009-01-31 22:14:21 +00008955 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008956 Py_XDECREF(exc);
8957 Py_XDECREF(errorHandler);
Guido van Rossum9e896b32000-04-05 20:11:21 +00008958 return -1;
8959}
8960
Guido van Rossumd57fd912000-03-10 22:53:23 +00008961/* --- Helpers ------------------------------------------------------------ */
8962
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008963static Py_ssize_t
Victor Stinner794d5672011-10-10 03:21:36 +02008964any_find_slice(int direction, PyObject* s1, PyObject* s2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008965 Py_ssize_t start,
8966 Py_ssize_t end)
8967{
8968 int kind1, kind2, kind;
8969 void *buf1, *buf2;
8970 Py_ssize_t len1, len2, result;
8971
8972 kind1 = PyUnicode_KIND(s1);
8973 kind2 = PyUnicode_KIND(s2);
8974 kind = kind1 > kind2 ? kind1 : kind2;
8975 buf1 = PyUnicode_DATA(s1);
8976 buf2 = PyUnicode_DATA(s2);
8977 if (kind1 != kind)
8978 buf1 = _PyUnicode_AsKind(s1, kind);
8979 if (!buf1)
8980 return -2;
8981 if (kind2 != kind)
8982 buf2 = _PyUnicode_AsKind(s2, kind);
8983 if (!buf2) {
8984 if (kind1 != kind) PyMem_Free(buf1);
8985 return -2;
8986 }
8987 len1 = PyUnicode_GET_LENGTH(s1);
8988 len2 = PyUnicode_GET_LENGTH(s2);
8989
Victor Stinner794d5672011-10-10 03:21:36 +02008990 if (direction > 0) {
8991 switch(kind) {
8992 case PyUnicode_1BYTE_KIND:
8993 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
8994 result = asciilib_find_slice(buf1, len1, buf2, len2, start, end);
8995 else
8996 result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end);
8997 break;
8998 case PyUnicode_2BYTE_KIND:
8999 result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end);
9000 break;
9001 case PyUnicode_4BYTE_KIND:
9002 result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end);
9003 break;
9004 default:
9005 assert(0); result = -2;
9006 }
9007 }
9008 else {
9009 switch(kind) {
9010 case PyUnicode_1BYTE_KIND:
9011 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9012 result = asciilib_rfind_slice(buf1, len1, buf2, len2, start, end);
9013 else
9014 result = ucs1lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9015 break;
9016 case PyUnicode_2BYTE_KIND:
9017 result = ucs2lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9018 break;
9019 case PyUnicode_4BYTE_KIND:
9020 result = ucs4lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9021 break;
9022 default:
9023 assert(0); result = -2;
9024 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009025 }
9026
9027 if (kind1 != kind)
9028 PyMem_Free(buf1);
9029 if (kind2 != kind)
9030 PyMem_Free(buf2);
9031
9032 return result;
9033}
9034
9035Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +02009036_PyUnicode_InsertThousandsGrouping(PyObject *unicode, int kind, void *data,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009037 Py_ssize_t n_buffer,
9038 void *digits, Py_ssize_t n_digits,
9039 Py_ssize_t min_width,
9040 const char *grouping,
9041 const char *thousands_sep)
9042{
9043 switch(kind) {
9044 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009045 if (unicode != NULL && PyUnicode_IS_ASCII(unicode))
9046 return _PyUnicode_ascii_InsertThousandsGrouping(
9047 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
9048 min_width, grouping, thousands_sep);
9049 else
9050 return _PyUnicode_ucs1_InsertThousandsGrouping(
9051 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
9052 min_width, grouping, thousands_sep);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009053 case PyUnicode_2BYTE_KIND:
9054 return _PyUnicode_ucs2_InsertThousandsGrouping(
9055 (Py_UCS2*)data, n_buffer, (Py_UCS2*)digits, n_digits,
9056 min_width, grouping, thousands_sep);
9057 case PyUnicode_4BYTE_KIND:
9058 return _PyUnicode_ucs4_InsertThousandsGrouping(
9059 (Py_UCS4*)data, n_buffer, (Py_UCS4*)digits, n_digits,
9060 min_width, grouping, thousands_sep);
9061 }
9062 assert(0);
9063 return -1;
9064}
9065
9066
Thomas Wouters477c8d52006-05-27 19:21:47 +00009067/* helper macro to fixup start/end slice values */
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009068#define ADJUST_INDICES(start, end, len) \
9069 if (end > len) \
9070 end = len; \
9071 else if (end < 0) { \
9072 end += len; \
9073 if (end < 0) \
9074 end = 0; \
9075 } \
9076 if (start < 0) { \
9077 start += len; \
9078 if (start < 0) \
9079 start = 0; \
9080 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009081
Alexander Belopolsky40018472011-02-26 01:02:56 +00009082Py_ssize_t
9083PyUnicode_Count(PyObject *str,
9084 PyObject *substr,
9085 Py_ssize_t start,
9086 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009087{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009088 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009089 PyObject* str_obj;
9090 PyObject* sub_obj;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009091 int kind1, kind2, kind;
9092 void *buf1 = NULL, *buf2 = NULL;
9093 Py_ssize_t len1, len2;
Tim Petersced69f82003-09-16 20:30:58 +00009094
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009095 str_obj = PyUnicode_FromObject(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009096 if (!str_obj || PyUnicode_READY(str_obj) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00009097 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009098 sub_obj = PyUnicode_FromObject(substr);
Victor Stinnere9a29352011-10-01 02:14:59 +02009099 if (!sub_obj || PyUnicode_READY(sub_obj) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009100 Py_DECREF(str_obj);
9101 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009102 }
Tim Petersced69f82003-09-16 20:30:58 +00009103
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009104 kind1 = PyUnicode_KIND(str_obj);
9105 kind2 = PyUnicode_KIND(sub_obj);
9106 kind = kind1 > kind2 ? kind1 : kind2;
9107 buf1 = PyUnicode_DATA(str_obj);
9108 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009109 buf1 = _PyUnicode_AsKind(str_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009110 if (!buf1)
9111 goto onError;
9112 buf2 = PyUnicode_DATA(sub_obj);
9113 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009114 buf2 = _PyUnicode_AsKind(sub_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009115 if (!buf2)
9116 goto onError;
9117 len1 = PyUnicode_GET_LENGTH(str_obj);
9118 len2 = PyUnicode_GET_LENGTH(sub_obj);
9119
9120 ADJUST_INDICES(start, end, len1);
9121 switch(kind) {
9122 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009123 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sub_obj))
9124 result = asciilib_count(
9125 ((Py_UCS1*)buf1) + start, end - start,
9126 buf2, len2, PY_SSIZE_T_MAX
9127 );
9128 else
9129 result = ucs1lib_count(
9130 ((Py_UCS1*)buf1) + start, end - start,
9131 buf2, len2, PY_SSIZE_T_MAX
9132 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009133 break;
9134 case PyUnicode_2BYTE_KIND:
9135 result = ucs2lib_count(
9136 ((Py_UCS2*)buf1) + start, end - start,
9137 buf2, len2, PY_SSIZE_T_MAX
9138 );
9139 break;
9140 case PyUnicode_4BYTE_KIND:
9141 result = ucs4lib_count(
9142 ((Py_UCS4*)buf1) + start, end - start,
9143 buf2, len2, PY_SSIZE_T_MAX
9144 );
9145 break;
9146 default:
9147 assert(0); result = 0;
9148 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009149
9150 Py_DECREF(sub_obj);
9151 Py_DECREF(str_obj);
9152
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009153 if (kind1 != kind)
9154 PyMem_Free(buf1);
9155 if (kind2 != kind)
9156 PyMem_Free(buf2);
9157
Guido van Rossumd57fd912000-03-10 22:53:23 +00009158 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009159 onError:
9160 Py_DECREF(sub_obj);
9161 Py_DECREF(str_obj);
9162 if (kind1 != kind && buf1)
9163 PyMem_Free(buf1);
9164 if (kind2 != kind && buf2)
9165 PyMem_Free(buf2);
9166 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009167}
9168
Alexander Belopolsky40018472011-02-26 01:02:56 +00009169Py_ssize_t
9170PyUnicode_Find(PyObject *str,
9171 PyObject *sub,
9172 Py_ssize_t start,
9173 Py_ssize_t end,
9174 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009175{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009176 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009177
Guido van Rossumd57fd912000-03-10 22:53:23 +00009178 str = PyUnicode_FromObject(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009179 if (!str || PyUnicode_READY(str) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00009180 return -2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009181 sub = PyUnicode_FromObject(sub);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009182 if (!sub || PyUnicode_READY(sub) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009183 Py_DECREF(str);
9184 return -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009185 }
Tim Petersced69f82003-09-16 20:30:58 +00009186
Victor Stinner794d5672011-10-10 03:21:36 +02009187 result = any_find_slice(direction,
9188 str, sub, start, end
9189 );
Thomas Wouters477c8d52006-05-27 19:21:47 +00009190
Guido van Rossumd57fd912000-03-10 22:53:23 +00009191 Py_DECREF(str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009192 Py_DECREF(sub);
9193
Guido van Rossumd57fd912000-03-10 22:53:23 +00009194 return result;
9195}
9196
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009197Py_ssize_t
9198PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
9199 Py_ssize_t start, Py_ssize_t end,
9200 int direction)
9201{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009202 int kind;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009203 Py_ssize_t result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009204 if (PyUnicode_READY(str) == -1)
9205 return -2;
Victor Stinner267aa242011-10-02 01:08:37 +02009206 if (start < 0 || end < 0) {
9207 PyErr_SetString(PyExc_IndexError, "string index out of range");
9208 return -2;
9209 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009210 if (end > PyUnicode_GET_LENGTH(str))
9211 end = PyUnicode_GET_LENGTH(str);
9212 kind = PyUnicode_KIND(str);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009213 result = findchar(PyUnicode_1BYTE_DATA(str) + kind*start,
9214 kind, end-start, ch, direction);
9215 if (result == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009216 return -1;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009217 else
9218 return start + result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009219}
9220
Alexander Belopolsky40018472011-02-26 01:02:56 +00009221static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009222tailmatch(PyObject *self,
9223 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009224 Py_ssize_t start,
9225 Py_ssize_t end,
9226 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009227{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009228 int kind_self;
9229 int kind_sub;
9230 void *data_self;
9231 void *data_sub;
9232 Py_ssize_t offset;
9233 Py_ssize_t i;
9234 Py_ssize_t end_sub;
9235
9236 if (PyUnicode_READY(self) == -1 ||
9237 PyUnicode_READY(substring) == -1)
9238 return 0;
9239
9240 if (PyUnicode_GET_LENGTH(substring) == 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009241 return 1;
9242
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009243 ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
9244 end -= PyUnicode_GET_LENGTH(substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009245 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00009246 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009247
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009248 kind_self = PyUnicode_KIND(self);
9249 data_self = PyUnicode_DATA(self);
9250 kind_sub = PyUnicode_KIND(substring);
9251 data_sub = PyUnicode_DATA(substring);
9252 end_sub = PyUnicode_GET_LENGTH(substring) - 1;
9253
9254 if (direction > 0)
9255 offset = end;
9256 else
9257 offset = start;
9258
9259 if (PyUnicode_READ(kind_self, data_self, offset) ==
9260 PyUnicode_READ(kind_sub, data_sub, 0) &&
9261 PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
9262 PyUnicode_READ(kind_sub, data_sub, end_sub)) {
9263 /* If both are of the same kind, memcmp is sufficient */
9264 if (kind_self == kind_sub) {
9265 return ! memcmp((char *)data_self +
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009266 (offset * PyUnicode_KIND(substring)),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009267 data_sub,
9268 PyUnicode_GET_LENGTH(substring) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009269 PyUnicode_KIND(substring));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009270 }
9271 /* otherwise we have to compare each character by first accesing it */
9272 else {
9273 /* We do not need to compare 0 and len(substring)-1 because
9274 the if statement above ensured already that they are equal
9275 when we end up here. */
9276 // TODO: honor direction and do a forward or backwards search
9277 for (i = 1; i < end_sub; ++i) {
9278 if (PyUnicode_READ(kind_self, data_self, offset + i) !=
9279 PyUnicode_READ(kind_sub, data_sub, i))
9280 return 0;
9281 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009282 return 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009283 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009284 }
9285
9286 return 0;
9287}
9288
Alexander Belopolsky40018472011-02-26 01:02:56 +00009289Py_ssize_t
9290PyUnicode_Tailmatch(PyObject *str,
9291 PyObject *substr,
9292 Py_ssize_t start,
9293 Py_ssize_t end,
9294 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009295{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009296 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009297
Guido van Rossumd57fd912000-03-10 22:53:23 +00009298 str = PyUnicode_FromObject(str);
9299 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009300 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009301 substr = PyUnicode_FromObject(substr);
9302 if (substr == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009303 Py_DECREF(str);
9304 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009305 }
Tim Petersced69f82003-09-16 20:30:58 +00009306
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009307 result = tailmatch(str, substr,
Benjamin Peterson29060642009-01-31 22:14:21 +00009308 start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009309 Py_DECREF(str);
9310 Py_DECREF(substr);
9311 return result;
9312}
9313
Guido van Rossumd57fd912000-03-10 22:53:23 +00009314/* Apply fixfct filter to the Unicode object self and return a
9315 reference to the modified object */
9316
Alexander Belopolsky40018472011-02-26 01:02:56 +00009317static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009318fixup(PyObject *self,
9319 Py_UCS4 (*fixfct)(PyObject *s))
Guido van Rossumd57fd912000-03-10 22:53:23 +00009320{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009321 PyObject *u;
9322 Py_UCS4 maxchar_old, maxchar_new = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009323
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009324 if (PyUnicode_READY(self) == -1)
9325 return NULL;
9326 maxchar_old = PyUnicode_MAX_CHAR_VALUE(self);
9327 u = PyUnicode_New(PyUnicode_GET_LENGTH(self),
9328 maxchar_old);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009329 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009330 return NULL;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009331
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009332 Py_MEMCPY(PyUnicode_1BYTE_DATA(u), PyUnicode_1BYTE_DATA(self),
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009333 PyUnicode_GET_LENGTH(u) * PyUnicode_KIND(u));
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009334
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009335 /* fix functions return the new maximum character in a string,
9336 if the kind of the resulting unicode object does not change,
9337 everything is fine. Otherwise we need to change the string kind
9338 and re-run the fix function. */
Victor Stinner9310abb2011-10-05 00:59:23 +02009339 maxchar_new = fixfct(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009340 if (maxchar_new == 0)
9341 /* do nothing, keep maxchar_new at 0 which means no changes. */;
9342 else if (maxchar_new <= 127)
9343 maxchar_new = 127;
9344 else if (maxchar_new <= 255)
9345 maxchar_new = 255;
9346 else if (maxchar_new <= 65535)
9347 maxchar_new = 65535;
9348 else
9349 maxchar_new = 1114111; /* 0x10ffff */
9350
9351 if (!maxchar_new && PyUnicode_CheckExact(self)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009352 /* fixfct should return TRUE if it modified the buffer. If
9353 FALSE, return a reference to the original buffer instead
9354 (to save space, not time) */
9355 Py_INCREF(self);
9356 Py_DECREF(u);
Victor Stinner7931d9a2011-11-04 00:22:48 +01009357 return self;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009358 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009359 else if (maxchar_new == maxchar_old) {
9360 return u;
9361 }
9362 else {
9363 /* In case the maximum character changed, we need to
9364 convert the string to the new category. */
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009365 PyObject *v = PyUnicode_New(PyUnicode_GET_LENGTH(self), maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009366 if (v == NULL) {
9367 Py_DECREF(u);
9368 return NULL;
9369 }
9370 if (maxchar_new > maxchar_old) {
9371 /* If the maxchar increased so that the kind changed, not all
9372 characters are representable anymore and we need to fix the
9373 string again. This only happens in very few cases. */
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009374 copy_characters(v, 0, self, 0, PyUnicode_GET_LENGTH(self));
Victor Stinner9310abb2011-10-05 00:59:23 +02009375 maxchar_old = fixfct(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009376 assert(maxchar_old > 0 && maxchar_old <= maxchar_new);
9377 }
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009378 else {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009379 copy_characters(v, 0, u, 0, PyUnicode_GET_LENGTH(self));
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009380 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009381
9382 Py_DECREF(u);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009383 assert(_PyUnicode_CheckConsistency(v, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009384 return v;
9385 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009386}
9387
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009388static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009389fixupper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009390{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009391 /* No need to call PyUnicode_READY(self) because this function is only
9392 called as a callback from fixup() which does it already. */
9393 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9394 const int kind = PyUnicode_KIND(self);
9395 void *data = PyUnicode_DATA(self);
9396 int touched = 0;
9397 Py_UCS4 maxchar = 0;
9398 Py_ssize_t i;
Tim Petersced69f82003-09-16 20:30:58 +00009399
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009400 for (i = 0; i < len; ++i) {
9401 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9402 const Py_UCS4 up = Py_UNICODE_TOUPPER(ch);
9403 if (up != ch) {
9404 if (up > maxchar)
9405 maxchar = up;
9406 PyUnicode_WRITE(kind, data, i, up);
9407 touched = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00009408 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009409 else if (ch > maxchar)
9410 maxchar = ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009411 }
9412
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009413 if (touched)
9414 return maxchar;
9415 else
9416 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009417}
9418
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009419static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009420fixlower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009421{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009422 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
9423 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9424 const int kind = PyUnicode_KIND(self);
9425 void *data = PyUnicode_DATA(self);
9426 int touched = 0;
9427 Py_UCS4 maxchar = 0;
9428 Py_ssize_t i;
Tim Petersced69f82003-09-16 20:30:58 +00009429
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009430 for(i = 0; i < len; ++i) {
9431 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9432 const Py_UCS4 lo = Py_UNICODE_TOLOWER(ch);
9433 if (lo != ch) {
9434 if (lo > maxchar)
9435 maxchar = lo;
9436 PyUnicode_WRITE(kind, data, i, lo);
9437 touched = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00009438 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009439 else if (ch > maxchar)
9440 maxchar = ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009441 }
9442
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009443 if (touched)
9444 return maxchar;
9445 else
9446 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009447}
9448
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009449static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009450fixswapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009451{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009452 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
9453 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9454 const int kind = PyUnicode_KIND(self);
9455 void *data = PyUnicode_DATA(self);
9456 int touched = 0;
9457 Py_UCS4 maxchar = 0;
9458 Py_ssize_t i;
Tim Petersced69f82003-09-16 20:30:58 +00009459
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009460 for(i = 0; i < len; ++i) {
9461 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9462 Py_UCS4 nu = 0;
9463
9464 if (Py_UNICODE_ISUPPER(ch))
9465 nu = Py_UNICODE_TOLOWER(ch);
9466 else if (Py_UNICODE_ISLOWER(ch))
9467 nu = Py_UNICODE_TOUPPER(ch);
9468
9469 if (nu != 0) {
9470 if (nu > maxchar)
9471 maxchar = nu;
9472 PyUnicode_WRITE(kind, data, i, nu);
9473 touched = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009474 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009475 else if (ch > maxchar)
9476 maxchar = ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009477 }
9478
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009479 if (touched)
9480 return maxchar;
9481 else
9482 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009483}
9484
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009485static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009486fixcapitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009487{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009488 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
9489 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9490 const int kind = PyUnicode_KIND(self);
9491 void *data = PyUnicode_DATA(self);
9492 int touched = 0;
9493 Py_UCS4 maxchar = 0;
9494 Py_ssize_t i = 0;
9495 Py_UCS4 ch;
Tim Petersced69f82003-09-16 20:30:58 +00009496
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009497 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009498 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009499
9500 ch = PyUnicode_READ(kind, data, i);
9501 if (!Py_UNICODE_ISUPPER(ch)) {
9502 maxchar = Py_UNICODE_TOUPPER(ch);
9503 PyUnicode_WRITE(kind, data, i, maxchar);
9504 touched = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009505 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009506 ++i;
9507 for(; i < len; ++i) {
9508 ch = PyUnicode_READ(kind, data, i);
9509 if (!Py_UNICODE_ISLOWER(ch)) {
9510 const Py_UCS4 lo = Py_UNICODE_TOLOWER(ch);
9511 if (lo > maxchar)
9512 maxchar = lo;
9513 PyUnicode_WRITE(kind, data, i, lo);
9514 touched = 1;
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009515 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009516 else if (ch > maxchar)
9517 maxchar = ch;
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009518 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009519
9520 if (touched)
9521 return maxchar;
9522 else
9523 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009524}
9525
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009526static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009527fixtitle(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009528{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009529 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
9530 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9531 const int kind = PyUnicode_KIND(self);
9532 void *data = PyUnicode_DATA(self);
9533 Py_UCS4 maxchar = 0;
9534 Py_ssize_t i = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009535 int previous_is_cased;
9536
9537 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009538 if (len == 1) {
9539 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9540 const Py_UCS4 ti = Py_UNICODE_TOTITLE(ch);
9541 if (ti != ch) {
9542 PyUnicode_WRITE(kind, data, i, ti);
9543 return ti;
Benjamin Peterson29060642009-01-31 22:14:21 +00009544 }
9545 else
9546 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009547 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009548 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009549 for(; i < len; ++i) {
9550 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9551 Py_UCS4 nu;
Tim Petersced69f82003-09-16 20:30:58 +00009552
Benjamin Peterson29060642009-01-31 22:14:21 +00009553 if (previous_is_cased)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009554 nu = Py_UNICODE_TOLOWER(ch);
Benjamin Peterson29060642009-01-31 22:14:21 +00009555 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009556 nu = Py_UNICODE_TOTITLE(ch);
9557
9558 if (nu > maxchar)
9559 maxchar = nu;
9560 PyUnicode_WRITE(kind, data, i, nu);
Tim Petersced69f82003-09-16 20:30:58 +00009561
Benjamin Peterson29060642009-01-31 22:14:21 +00009562 if (Py_UNICODE_ISLOWER(ch) ||
9563 Py_UNICODE_ISUPPER(ch) ||
9564 Py_UNICODE_ISTITLE(ch))
9565 previous_is_cased = 1;
9566 else
9567 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009568 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009569 return maxchar;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009570}
9571
Tim Peters8ce9f162004-08-27 01:49:32 +00009572PyObject *
9573PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009574{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009575 PyObject *sep = NULL;
Victor Stinnerdd077322011-10-07 17:02:31 +02009576 Py_ssize_t seplen;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009577 PyObject *res = NULL; /* the result */
Tim Peters05eba1f2004-08-27 21:32:02 +00009578 PyObject *fseq; /* PySequence_Fast(seq) */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009579 Py_ssize_t seqlen; /* len(fseq) -- number of items in sequence */
9580 PyObject **items;
Tim Peters8ce9f162004-08-27 01:49:32 +00009581 PyObject *item;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009582 Py_ssize_t sz, i, res_offset;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009583 Py_UCS4 maxchar;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009584 Py_UCS4 item_maxchar;
Victor Stinnerdd077322011-10-07 17:02:31 +02009585 int use_memcpy;
9586 unsigned char *res_data = NULL, *sep_data = NULL;
9587 PyObject *last_obj;
9588 unsigned int kind = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009589
Tim Peters05eba1f2004-08-27 21:32:02 +00009590 fseq = PySequence_Fast(seq, "");
9591 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009592 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00009593 }
9594
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009595 /* NOTE: the following code can't call back into Python code,
9596 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00009597 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009598
Tim Peters05eba1f2004-08-27 21:32:02 +00009599 seqlen = PySequence_Fast_GET_SIZE(fseq);
9600 /* If empty sequence, return u"". */
9601 if (seqlen == 0) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009602 Py_DECREF(fseq);
9603 Py_INCREF(unicode_empty);
9604 res = unicode_empty;
9605 return res;
Tim Peters05eba1f2004-08-27 21:32:02 +00009606 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009607
Tim Peters05eba1f2004-08-27 21:32:02 +00009608 /* If singleton sequence with an exact Unicode, return that. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009609 last_obj = NULL;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009610 items = PySequence_Fast_ITEMS(fseq);
Victor Stinneracf47b82011-10-06 12:32:37 +02009611 if (seqlen == 1) {
9612 if (PyUnicode_CheckExact(items[0])) {
9613 res = items[0];
9614 Py_INCREF(res);
9615 Py_DECREF(fseq);
9616 return res;
9617 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009618 seplen = 0;
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009619 maxchar = 0;
Tim Peters8ce9f162004-08-27 01:49:32 +00009620 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009621 else {
Victor Stinneracf47b82011-10-06 12:32:37 +02009622 /* Set up sep and seplen */
9623 if (separator == NULL) {
9624 /* fall back to a blank space separator */
9625 sep = PyUnicode_FromOrdinal(' ');
9626 if (!sep)
9627 goto onError;
Victor Stinnerdd077322011-10-07 17:02:31 +02009628 seplen = 1;
Victor Stinneracf47b82011-10-06 12:32:37 +02009629 maxchar = 32;
Tim Peters05eba1f2004-08-27 21:32:02 +00009630 }
Victor Stinneracf47b82011-10-06 12:32:37 +02009631 else {
9632 if (!PyUnicode_Check(separator)) {
9633 PyErr_Format(PyExc_TypeError,
9634 "separator: expected str instance,"
9635 " %.80s found",
9636 Py_TYPE(separator)->tp_name);
9637 goto onError;
9638 }
9639 if (PyUnicode_READY(separator))
9640 goto onError;
9641 sep = separator;
9642 seplen = PyUnicode_GET_LENGTH(separator);
9643 maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
9644 /* inc refcount to keep this code path symmetric with the
9645 above case of a blank separator */
9646 Py_INCREF(sep);
9647 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009648 last_obj = sep;
Tim Peters05eba1f2004-08-27 21:32:02 +00009649 }
9650
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009651 /* There are at least two things to join, or else we have a subclass
9652 * of str in the sequence.
9653 * Do a pre-pass to figure out the total amount of space we'll
9654 * need (sz), and see whether all argument are strings.
9655 */
9656 sz = 0;
Victor Stinnerdd077322011-10-07 17:02:31 +02009657#ifdef Py_DEBUG
9658 use_memcpy = 0;
9659#else
9660 use_memcpy = 1;
9661#endif
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009662 for (i = 0; i < seqlen; i++) {
9663 const Py_ssize_t old_sz = sz;
9664 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009665 if (!PyUnicode_Check(item)) {
9666 PyErr_Format(PyExc_TypeError,
9667 "sequence item %zd: expected str instance,"
9668 " %.80s found",
9669 i, Py_TYPE(item)->tp_name);
9670 goto onError;
9671 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009672 if (PyUnicode_READY(item) == -1)
9673 goto onError;
9674 sz += PyUnicode_GET_LENGTH(item);
9675 item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009676 maxchar = Py_MAX(maxchar, item_maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009677 if (i != 0)
9678 sz += seplen;
9679 if (sz < old_sz || sz > PY_SSIZE_T_MAX) {
9680 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009681 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009682 goto onError;
9683 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009684 if (use_memcpy && last_obj != NULL) {
9685 if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
9686 use_memcpy = 0;
9687 }
9688 last_obj = item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009689 }
Tim Petersced69f82003-09-16 20:30:58 +00009690
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009691 res = PyUnicode_New(sz, maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009692 if (res == NULL)
9693 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +00009694
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009695 /* Catenate everything. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009696#ifdef Py_DEBUG
9697 use_memcpy = 0;
9698#else
9699 if (use_memcpy) {
9700 res_data = PyUnicode_1BYTE_DATA(res);
9701 kind = PyUnicode_KIND(res);
9702 if (seplen != 0)
9703 sep_data = PyUnicode_1BYTE_DATA(sep);
9704 }
9705#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009706 for (i = 0, res_offset = 0; i < seqlen; ++i) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009707 Py_ssize_t itemlen;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009708 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009709 /* Copy item, and maybe the separator. */
Victor Stinner9ce5a832011-10-03 23:36:02 +02009710 if (i && seplen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009711 if (use_memcpy) {
9712 Py_MEMCPY(res_data,
9713 sep_data,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009714 kind * seplen);
9715 res_data += kind * seplen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009716 }
9717 else {
9718 copy_characters(res, res_offset, sep, 0, seplen);
9719 res_offset += seplen;
9720 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009721 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009722 itemlen = PyUnicode_GET_LENGTH(item);
9723 if (itemlen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009724 if (use_memcpy) {
9725 Py_MEMCPY(res_data,
9726 PyUnicode_DATA(item),
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009727 kind * itemlen);
9728 res_data += kind * itemlen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009729 }
9730 else {
9731 copy_characters(res, res_offset, item, 0, itemlen);
9732 res_offset += itemlen;
9733 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009734 }
Tim Peters05eba1f2004-08-27 21:32:02 +00009735 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009736 if (use_memcpy)
9737 assert(res_data == PyUnicode_1BYTE_DATA(res)
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009738 + kind * PyUnicode_GET_LENGTH(res));
Victor Stinnerdd077322011-10-07 17:02:31 +02009739 else
9740 assert(res_offset == PyUnicode_GET_LENGTH(res));
Tim Peters8ce9f162004-08-27 01:49:32 +00009741
Tim Peters05eba1f2004-08-27 21:32:02 +00009742 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009743 Py_XDECREF(sep);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009744 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009745 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009746
Benjamin Peterson29060642009-01-31 22:14:21 +00009747 onError:
Tim Peters05eba1f2004-08-27 21:32:02 +00009748 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009749 Py_XDECREF(sep);
Tim Peters8ce9f162004-08-27 01:49:32 +00009750 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009751 return NULL;
9752}
9753
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009754#define FILL(kind, data, value, start, length) \
9755 do { \
9756 Py_ssize_t i_ = 0; \
9757 assert(kind != PyUnicode_WCHAR_KIND); \
9758 switch ((kind)) { \
9759 case PyUnicode_1BYTE_KIND: { \
9760 unsigned char * to_ = (unsigned char *)((data)) + (start); \
9761 memset(to_, (unsigned char)value, length); \
9762 break; \
9763 } \
9764 case PyUnicode_2BYTE_KIND: { \
9765 Py_UCS2 * to_ = (Py_UCS2 *)((data)) + (start); \
9766 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9767 break; \
9768 } \
9769 default: { \
9770 Py_UCS4 * to_ = (Py_UCS4 *)((data)) + (start); \
9771 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9772 break; \
9773 } \
9774 } \
9775 } while (0)
9776
Victor Stinner9310abb2011-10-05 00:59:23 +02009777static PyObject *
9778pad(PyObject *self,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009779 Py_ssize_t left,
9780 Py_ssize_t right,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009781 Py_UCS4 fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009782{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009783 PyObject *u;
9784 Py_UCS4 maxchar;
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009785 int kind;
9786 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009787
9788 if (left < 0)
9789 left = 0;
9790 if (right < 0)
9791 right = 0;
9792
Tim Peters7a29bd52001-09-12 03:03:31 +00009793 if (left == 0 && right == 0 && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00009794 Py_INCREF(self);
9795 return self;
9796 }
9797
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009798 if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
9799 right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +00009800 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
9801 return NULL;
9802 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009803 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
9804 if (fill > maxchar)
9805 maxchar = fill;
9806 u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009807 if (!u)
9808 return NULL;
9809
9810 kind = PyUnicode_KIND(u);
9811 data = PyUnicode_DATA(u);
9812 if (left)
9813 FILL(kind, data, fill, 0, left);
9814 if (right)
9815 FILL(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009816 copy_characters(u, left, self, 0, _PyUnicode_LENGTH(self));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009817 assert(_PyUnicode_CheckConsistency(u, 1));
9818 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009819}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009820#undef FILL
Guido van Rossumd57fd912000-03-10 22:53:23 +00009821
Alexander Belopolsky40018472011-02-26 01:02:56 +00009822PyObject *
9823PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009824{
Guido van Rossumd57fd912000-03-10 22:53:23 +00009825 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009826
9827 string = PyUnicode_FromObject(string);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009828 if (string == NULL || PyUnicode_READY(string) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00009829 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009830
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009831 switch(PyUnicode_KIND(string)) {
9832 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009833 if (PyUnicode_IS_ASCII(string))
9834 list = asciilib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009835 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009836 PyUnicode_GET_LENGTH(string), keepends);
9837 else
9838 list = ucs1lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009839 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009840 PyUnicode_GET_LENGTH(string), keepends);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009841 break;
9842 case PyUnicode_2BYTE_KIND:
9843 list = ucs2lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009844 string, PyUnicode_2BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009845 PyUnicode_GET_LENGTH(string), keepends);
9846 break;
9847 case PyUnicode_4BYTE_KIND:
9848 list = ucs4lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009849 string, PyUnicode_4BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009850 PyUnicode_GET_LENGTH(string), keepends);
9851 break;
9852 default:
9853 assert(0);
9854 list = 0;
9855 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009856 Py_DECREF(string);
9857 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009858}
9859
Alexander Belopolsky40018472011-02-26 01:02:56 +00009860static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009861split(PyObject *self,
9862 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009863 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009864{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009865 int kind1, kind2, kind;
9866 void *buf1, *buf2;
9867 Py_ssize_t len1, len2;
9868 PyObject* out;
9869
Guido van Rossumd57fd912000-03-10 22:53:23 +00009870 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00009871 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009872
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009873 if (PyUnicode_READY(self) == -1)
9874 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009875
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009876 if (substring == NULL)
9877 switch(PyUnicode_KIND(self)) {
9878 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009879 if (PyUnicode_IS_ASCII(self))
9880 return asciilib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009881 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009882 PyUnicode_GET_LENGTH(self), maxcount
9883 );
9884 else
9885 return ucs1lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009886 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009887 PyUnicode_GET_LENGTH(self), maxcount
9888 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009889 case PyUnicode_2BYTE_KIND:
9890 return ucs2lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009891 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009892 PyUnicode_GET_LENGTH(self), maxcount
9893 );
9894 case PyUnicode_4BYTE_KIND:
9895 return ucs4lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009896 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009897 PyUnicode_GET_LENGTH(self), maxcount
9898 );
9899 default:
9900 assert(0);
9901 return NULL;
9902 }
9903
9904 if (PyUnicode_READY(substring) == -1)
9905 return NULL;
9906
9907 kind1 = PyUnicode_KIND(self);
9908 kind2 = PyUnicode_KIND(substring);
9909 kind = kind1 > kind2 ? kind1 : kind2;
9910 buf1 = PyUnicode_DATA(self);
9911 buf2 = PyUnicode_DATA(substring);
9912 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009913 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009914 if (!buf1)
9915 return NULL;
9916 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009917 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009918 if (!buf2) {
9919 if (kind1 != kind) PyMem_Free(buf1);
9920 return NULL;
9921 }
9922 len1 = PyUnicode_GET_LENGTH(self);
9923 len2 = PyUnicode_GET_LENGTH(substring);
9924
9925 switch(kind) {
9926 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009927 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
9928 out = asciilib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009929 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +02009930 else
9931 out = ucs1lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009932 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009933 break;
9934 case PyUnicode_2BYTE_KIND:
9935 out = ucs2lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009936 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009937 break;
9938 case PyUnicode_4BYTE_KIND:
9939 out = ucs4lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009940 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009941 break;
9942 default:
9943 out = NULL;
9944 }
9945 if (kind1 != kind)
9946 PyMem_Free(buf1);
9947 if (kind2 != kind)
9948 PyMem_Free(buf2);
9949 return out;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009950}
9951
Alexander Belopolsky40018472011-02-26 01:02:56 +00009952static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009953rsplit(PyObject *self,
9954 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009955 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009956{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009957 int kind1, kind2, kind;
9958 void *buf1, *buf2;
9959 Py_ssize_t len1, len2;
9960 PyObject* out;
9961
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009962 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00009963 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009964
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009965 if (PyUnicode_READY(self) == -1)
9966 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009967
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009968 if (substring == NULL)
9969 switch(PyUnicode_KIND(self)) {
9970 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009971 if (PyUnicode_IS_ASCII(self))
9972 return asciilib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009973 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009974 PyUnicode_GET_LENGTH(self), maxcount
9975 );
9976 else
9977 return ucs1lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009978 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009979 PyUnicode_GET_LENGTH(self), maxcount
9980 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009981 case PyUnicode_2BYTE_KIND:
9982 return ucs2lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009983 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009984 PyUnicode_GET_LENGTH(self), maxcount
9985 );
9986 case PyUnicode_4BYTE_KIND:
9987 return ucs4lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009988 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009989 PyUnicode_GET_LENGTH(self), maxcount
9990 );
9991 default:
9992 assert(0);
9993 return NULL;
9994 }
9995
9996 if (PyUnicode_READY(substring) == -1)
9997 return NULL;
9998
9999 kind1 = PyUnicode_KIND(self);
10000 kind2 = PyUnicode_KIND(substring);
10001 kind = kind1 > kind2 ? kind1 : kind2;
10002 buf1 = PyUnicode_DATA(self);
10003 buf2 = PyUnicode_DATA(substring);
10004 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010005 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010006 if (!buf1)
10007 return NULL;
10008 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010009 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010010 if (!buf2) {
10011 if (kind1 != kind) PyMem_Free(buf1);
10012 return NULL;
10013 }
10014 len1 = PyUnicode_GET_LENGTH(self);
10015 len2 = PyUnicode_GET_LENGTH(substring);
10016
10017 switch(kind) {
10018 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010019 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10020 out = asciilib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010021 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010022 else
10023 out = ucs1lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010024 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010025 break;
10026 case PyUnicode_2BYTE_KIND:
10027 out = ucs2lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010028 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010029 break;
10030 case PyUnicode_4BYTE_KIND:
10031 out = ucs4lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010032 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010033 break;
10034 default:
10035 out = NULL;
10036 }
10037 if (kind1 != kind)
10038 PyMem_Free(buf1);
10039 if (kind2 != kind)
10040 PyMem_Free(buf2);
10041 return out;
10042}
10043
10044static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010045anylib_find(int kind, PyObject *str1, void *buf1, Py_ssize_t len1,
10046 PyObject *str2, void *buf2, Py_ssize_t len2, Py_ssize_t offset)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010047{
10048 switch(kind) {
10049 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010050 if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
10051 return asciilib_find(buf1, len1, buf2, len2, offset);
10052 else
10053 return ucs1lib_find(buf1, len1, buf2, len2, offset);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010054 case PyUnicode_2BYTE_KIND:
10055 return ucs2lib_find(buf1, len1, buf2, len2, offset);
10056 case PyUnicode_4BYTE_KIND:
10057 return ucs4lib_find(buf1, len1, buf2, len2, offset);
10058 }
10059 assert(0);
10060 return -1;
10061}
10062
10063static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010064anylib_count(int kind, PyObject *sstr, void* sbuf, Py_ssize_t slen,
10065 PyObject *str1, void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010066{
10067 switch(kind) {
10068 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010069 if (PyUnicode_IS_ASCII(sstr) && PyUnicode_IS_ASCII(str1))
10070 return asciilib_count(sbuf, slen, buf1, len1, maxcount);
10071 else
10072 return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010073 case PyUnicode_2BYTE_KIND:
10074 return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
10075 case PyUnicode_4BYTE_KIND:
10076 return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
10077 }
10078 assert(0);
10079 return 0;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010080}
10081
Alexander Belopolsky40018472011-02-26 01:02:56 +000010082static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010083replace(PyObject *self, PyObject *str1,
10084 PyObject *str2, Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010085{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010086 PyObject *u;
10087 char *sbuf = PyUnicode_DATA(self);
10088 char *buf1 = PyUnicode_DATA(str1);
10089 char *buf2 = PyUnicode_DATA(str2);
10090 int srelease = 0, release1 = 0, release2 = 0;
10091 int skind = PyUnicode_KIND(self);
10092 int kind1 = PyUnicode_KIND(str1);
10093 int kind2 = PyUnicode_KIND(str2);
10094 Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
10095 Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
10096 Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010097 int mayshrink;
10098 Py_UCS4 maxchar, maxchar_str2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010099
10100 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010101 maxcount = PY_SSIZE_T_MAX;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010102 else if (maxcount == 0 || slen == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010103 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010104
Victor Stinner59de0ee2011-10-07 10:01:28 +020010105 if (str1 == str2)
10106 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010107 if (skind < kind1)
10108 /* substring too wide to be present */
10109 goto nothing;
10110
Victor Stinner49a0a212011-10-12 23:46:10 +020010111 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
10112 maxchar_str2 = PyUnicode_MAX_CHAR_VALUE(str2);
10113 /* Replacing str1 with str2 may cause a maxchar reduction in the
10114 result string. */
10115 mayshrink = (maxchar_str2 < maxchar);
10116 maxchar = Py_MAX(maxchar, maxchar_str2);
10117
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010118 if (len1 == len2) {
Antoine Pitroucbfdee32010-01-13 08:58:08 +000010119 Py_ssize_t i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010120 /* same length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010121 if (len1 == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010122 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010123 if (len1 == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010124 /* replace characters */
Victor Stinner49a0a212011-10-12 23:46:10 +020010125 Py_UCS4 u1, u2;
10126 int rkind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010127 u1 = PyUnicode_READ_CHAR(str1, 0);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +020010128 if (findchar(sbuf, PyUnicode_KIND(self),
10129 slen, u1, 1) < 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010130 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010131 u2 = PyUnicode_READ_CHAR(str2, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010132 u = PyUnicode_New(slen, maxchar);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010133 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010134 goto error;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020010135 copy_characters(u, 0, self, 0, slen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010136 rkind = PyUnicode_KIND(u);
10137 for (i = 0; i < PyUnicode_GET_LENGTH(u); i++)
10138 if (PyUnicode_READ(rkind, PyUnicode_DATA(u), i) == u1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010139 if (--maxcount < 0)
10140 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010141 PyUnicode_WRITE(rkind, PyUnicode_DATA(u), i, u2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010142 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010143 }
10144 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010145 int rkind = skind;
10146 char *res;
Victor Stinner25a4b292011-10-06 12:31:55 +020010147
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010148 if (kind1 < rkind) {
10149 /* widen substring */
10150 buf1 = _PyUnicode_AsKind(str1, rkind);
10151 if (!buf1) goto error;
10152 release1 = 1;
10153 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010154 i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010155 if (i < 0)
10156 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010157 if (rkind > kind2) {
10158 /* widen replacement */
10159 buf2 = _PyUnicode_AsKind(str2, rkind);
10160 if (!buf2) goto error;
10161 release2 = 1;
10162 }
10163 else if (rkind < kind2) {
10164 /* widen self and buf1 */
10165 rkind = kind2;
10166 if (release1) PyMem_Free(buf1);
10167 sbuf = _PyUnicode_AsKind(self, rkind);
10168 if (!sbuf) goto error;
10169 srelease = 1;
10170 buf1 = _PyUnicode_AsKind(str1, rkind);
10171 if (!buf1) goto error;
10172 release1 = 1;
10173 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010174 u = PyUnicode_New(slen, maxchar);
10175 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010176 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010177 assert(PyUnicode_KIND(u) == rkind);
10178 res = PyUnicode_DATA(u);
Victor Stinner25a4b292011-10-06 12:31:55 +020010179
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010180 memcpy(res, sbuf, rkind * slen);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010181 /* change everything in-place, starting with this one */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010182 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010183 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010184 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010185 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010186
10187 while ( --maxcount > 0) {
Victor Stinnerc3cec782011-10-05 21:24:08 +020010188 i = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010189 sbuf+rkind*i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010190 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010191 if (i == -1)
10192 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010193 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010194 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010195 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010196 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010197 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010198 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010199 }
10200 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010201 Py_ssize_t n, i, j, ires;
10202 Py_ssize_t product, new_size;
10203 int rkind = skind;
10204 char *res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010205
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010206 if (kind1 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010207 /* widen substring */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010208 buf1 = _PyUnicode_AsKind(str1, rkind);
10209 if (!buf1) goto error;
10210 release1 = 1;
10211 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010212 n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010213 if (n == 0)
10214 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010215 if (kind2 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010216 /* widen replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010217 buf2 = _PyUnicode_AsKind(str2, rkind);
10218 if (!buf2) goto error;
10219 release2 = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010220 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010221 else if (kind2 > rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010222 /* widen self and buf1 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010223 rkind = kind2;
10224 sbuf = _PyUnicode_AsKind(self, rkind);
10225 if (!sbuf) goto error;
10226 srelease = 1;
10227 if (release1) PyMem_Free(buf1);
10228 buf1 = _PyUnicode_AsKind(str1, rkind);
10229 if (!buf1) goto error;
10230 release1 = 1;
10231 }
10232 /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
10233 PyUnicode_GET_LENGTH(str1))); */
10234 product = n * (len2-len1);
10235 if ((product / (len2-len1)) != n) {
10236 PyErr_SetString(PyExc_OverflowError,
10237 "replace string is too long");
10238 goto error;
10239 }
10240 new_size = slen + product;
Victor Stinner49a0a212011-10-12 23:46:10 +020010241 if (new_size == 0) {
10242 Py_INCREF(unicode_empty);
10243 u = unicode_empty;
10244 goto done;
10245 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010246 if (new_size < 0 || new_size > (PY_SSIZE_T_MAX >> (rkind-1))) {
10247 PyErr_SetString(PyExc_OverflowError,
10248 "replace string is too long");
10249 goto error;
10250 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010251 u = PyUnicode_New(new_size, maxchar);
10252 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010253 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010254 assert(PyUnicode_KIND(u) == rkind);
10255 res = PyUnicode_DATA(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010256 ires = i = 0;
10257 if (len1 > 0) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010258 while (n-- > 0) {
10259 /* look for next match */
Victor Stinnerc3cec782011-10-05 21:24:08 +020010260 j = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010261 sbuf + rkind * i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010262 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010263 if (j == -1)
10264 break;
10265 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010266 /* copy unchanged part [i:j] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010267 memcpy(res + rkind * ires,
10268 sbuf + rkind * i,
10269 rkind * (j-i));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010270 ires += j - i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010271 }
10272 /* copy substitution string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010273 if (len2 > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010274 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010275 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010276 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010277 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010278 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010279 i = j + len1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010280 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010281 if (i < slen)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010282 /* copy tail [i:] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010283 memcpy(res + rkind * ires,
10284 sbuf + rkind * i,
10285 rkind * (slen-i));
Victor Stinner49a0a212011-10-12 23:46:10 +020010286 }
10287 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010288 /* interleave */
10289 while (n > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010290 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010291 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010292 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010293 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010294 if (--n <= 0)
10295 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010296 memcpy(res + rkind * ires,
10297 sbuf + rkind * i,
10298 rkind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010299 ires++;
10300 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010301 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010302 memcpy(res + rkind * ires,
10303 sbuf + rkind * i,
10304 rkind * (slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +000010305 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010306 }
10307
10308 if (mayshrink) {
Victor Stinner25a4b292011-10-06 12:31:55 +020010309 unicode_adjust_maxchar(&u);
10310 if (u == NULL)
10311 goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010312 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010313
10314 done:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010315 if (srelease)
10316 PyMem_FREE(sbuf);
10317 if (release1)
10318 PyMem_FREE(buf1);
10319 if (release2)
10320 PyMem_FREE(buf2);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010321 assert(_PyUnicode_CheckConsistency(u, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010322 return u;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010323
Benjamin Peterson29060642009-01-31 22:14:21 +000010324 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +000010325 /* nothing to replace; return original string (when possible) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010326 if (srelease)
10327 PyMem_FREE(sbuf);
10328 if (release1)
10329 PyMem_FREE(buf1);
10330 if (release2)
10331 PyMem_FREE(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010332 if (PyUnicode_CheckExact(self)) {
10333 Py_INCREF(self);
Victor Stinner7931d9a2011-11-04 00:22:48 +010010334 return self;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010335 }
Victor Stinner034f6cf2011-09-30 02:26:44 +020010336 return PyUnicode_Copy(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010337 error:
10338 if (srelease && sbuf)
10339 PyMem_FREE(sbuf);
10340 if (release1 && buf1)
10341 PyMem_FREE(buf1);
10342 if (release2 && buf2)
10343 PyMem_FREE(buf2);
10344 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010345}
10346
10347/* --- Unicode Object Methods --------------------------------------------- */
10348
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010349PyDoc_STRVAR(title__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010350 "S.title() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010351\n\
10352Return a titlecased version of S, i.e. words start with title case\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010353characters, all remaining cased characters have lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010354
10355static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010356unicode_title(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010357{
Guido van Rossumd57fd912000-03-10 22:53:23 +000010358 return fixup(self, fixtitle);
10359}
10360
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010361PyDoc_STRVAR(capitalize__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010362 "S.capitalize() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010363\n\
10364Return a capitalized version of S, i.e. make the first character\n\
Senthil Kumarane51ee8a2010-07-05 12:00:56 +000010365have upper case and the rest lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010366
10367static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010368unicode_capitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010369{
Guido van Rossumd57fd912000-03-10 22:53:23 +000010370 return fixup(self, fixcapitalize);
10371}
10372
10373#if 0
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010374PyDoc_STRVAR(capwords__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010375 "S.capwords() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010376\n\
10377Apply .capitalize() to all words in S and return the result with\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010378normalized whitespace (all whitespace strings are replaced by ' ').");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010379
10380static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010381unicode_capwords(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010382{
10383 PyObject *list;
10384 PyObject *item;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010385 Py_ssize_t i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010386
Guido van Rossumd57fd912000-03-10 22:53:23 +000010387 /* Split into words */
10388 list = split(self, NULL, -1);
10389 if (!list)
10390 return NULL;
10391
10392 /* Capitalize each word */
10393 for (i = 0; i < PyList_GET_SIZE(list); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010394 item = fixup(PyList_GET_ITEM(list, i),
Benjamin Peterson29060642009-01-31 22:14:21 +000010395 fixcapitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010396 if (item == NULL)
10397 goto onError;
10398 Py_DECREF(PyList_GET_ITEM(list, i));
10399 PyList_SET_ITEM(list, i, item);
10400 }
10401
10402 /* Join the words to form a new string */
10403 item = PyUnicode_Join(NULL, list);
10404
Benjamin Peterson29060642009-01-31 22:14:21 +000010405 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000010406 Py_DECREF(list);
Victor Stinner7931d9a2011-11-04 00:22:48 +010010407 return item;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010408}
10409#endif
10410
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010411/* Argument converter. Coerces to a single unicode character */
10412
10413static int
10414convert_uc(PyObject *obj, void *addr)
10415{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010416 Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010417 PyObject *uniobj;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010418
Benjamin Peterson14339b62009-01-31 16:36:08 +000010419 uniobj = PyUnicode_FromObject(obj);
10420 if (uniobj == NULL) {
10421 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010422 "The fill character cannot be converted to Unicode");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010423 return 0;
10424 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010425 if (PyUnicode_GET_LENGTH(uniobj) != 1) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010426 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010427 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010428 Py_DECREF(uniobj);
10429 return 0;
10430 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010431 *fillcharloc = PyUnicode_READ_CHAR(uniobj, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010432 Py_DECREF(uniobj);
10433 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010434}
10435
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010436PyDoc_STRVAR(center__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010437 "S.center(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010438\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010439Return S centered in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010440done using the specified fill character (default is a space)");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010441
10442static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010443unicode_center(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010444{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010445 Py_ssize_t marg, left;
10446 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010447 Py_UCS4 fillchar = ' ';
10448
Victor Stinnere9a29352011-10-01 02:14:59 +020010449 if (!PyArg_ParseTuple(args, "n|O&:center", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010450 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010451
Victor Stinnere9a29352011-10-01 02:14:59 +020010452 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010453 return NULL;
10454
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010455 if (_PyUnicode_LENGTH(self) >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000010456 Py_INCREF(self);
Victor Stinner7931d9a2011-11-04 00:22:48 +010010457 return self;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010458 }
10459
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010460 marg = width - _PyUnicode_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010461 left = marg / 2 + (marg & width & 1);
10462
Victor Stinner9310abb2011-10-05 00:59:23 +020010463 return pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010464}
10465
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010466/* This function assumes that str1 and str2 are readied by the caller. */
10467
Marc-André Lemburge5034372000-08-08 08:04:29 +000010468static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010469unicode_compare(PyObject *str1, PyObject *str2)
Marc-André Lemburge5034372000-08-08 08:04:29 +000010470{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010471 int kind1, kind2;
10472 void *data1, *data2;
10473 Py_ssize_t len1, len2, i;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010474
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010475 kind1 = PyUnicode_KIND(str1);
10476 kind2 = PyUnicode_KIND(str2);
10477 data1 = PyUnicode_DATA(str1);
10478 data2 = PyUnicode_DATA(str2);
10479 len1 = PyUnicode_GET_LENGTH(str1);
10480 len2 = PyUnicode_GET_LENGTH(str2);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010481
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010482 for (i = 0; i < len1 && i < len2; ++i) {
10483 Py_UCS4 c1, c2;
10484 c1 = PyUnicode_READ(kind1, data1, i);
10485 c2 = PyUnicode_READ(kind2, data2, i);
Fredrik Lundh45714e92001-06-26 16:39:36 +000010486
10487 if (c1 != c2)
10488 return (c1 < c2) ? -1 : 1;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010489 }
10490
10491 return (len1 < len2) ? -1 : (len1 != len2);
10492}
10493
Alexander Belopolsky40018472011-02-26 01:02:56 +000010494int
10495PyUnicode_Compare(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010496{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010497 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10498 if (PyUnicode_READY(left) == -1 ||
10499 PyUnicode_READY(right) == -1)
10500 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010501 return unicode_compare(left, right);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010502 }
Guido van Rossum09dc34f2007-05-04 04:17:33 +000010503 PyErr_Format(PyExc_TypeError,
10504 "Can't compare %.100s and %.100s",
10505 left->ob_type->tp_name,
10506 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010507 return -1;
10508}
10509
Martin v. Löwis5b222132007-06-10 09:51:05 +000010510int
10511PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
10512{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010513 Py_ssize_t i;
10514 int kind;
10515 void *data;
10516 Py_UCS4 chr;
10517
Victor Stinner910337b2011-10-03 03:20:16 +020010518 assert(_PyUnicode_CHECK(uni));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010519 if (PyUnicode_READY(uni) == -1)
10520 return -1;
10521 kind = PyUnicode_KIND(uni);
10522 data = PyUnicode_DATA(uni);
Martin v. Löwis5b222132007-06-10 09:51:05 +000010523 /* Compare Unicode string and source character set string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010524 for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
10525 if (chr != str[i])
10526 return (chr < (unsigned char)(str[i])) ? -1 : 1;
Benjamin Peterson8667a9b2010-01-09 21:45:28 +000010527 /* This check keeps Python strings that end in '\0' from comparing equal
10528 to C strings identical up to that point. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010529 if (PyUnicode_GET_LENGTH(uni) != i || chr)
Benjamin Peterson29060642009-01-31 22:14:21 +000010530 return 1; /* uni is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010531 if (str[i])
Benjamin Peterson29060642009-01-31 22:14:21 +000010532 return -1; /* str is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010533 return 0;
10534}
10535
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010536
Benjamin Peterson29060642009-01-31 22:14:21 +000010537#define TEST_COND(cond) \
Benjamin Peterson14339b62009-01-31 16:36:08 +000010538 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010539
Alexander Belopolsky40018472011-02-26 01:02:56 +000010540PyObject *
10541PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010542{
10543 int result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010544
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010545 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10546 PyObject *v;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010547 if (PyUnicode_READY(left) == -1 ||
10548 PyUnicode_READY(right) == -1)
10549 return NULL;
10550 if (PyUnicode_GET_LENGTH(left) != PyUnicode_GET_LENGTH(right) ||
10551 PyUnicode_KIND(left) != PyUnicode_KIND(right)) {
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010552 if (op == Py_EQ) {
10553 Py_INCREF(Py_False);
10554 return Py_False;
10555 }
10556 if (op == Py_NE) {
10557 Py_INCREF(Py_True);
10558 return Py_True;
10559 }
10560 }
10561 if (left == right)
10562 result = 0;
10563 else
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010564 result = unicode_compare(left, right);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010565
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010566 /* Convert the return value to a Boolean */
10567 switch (op) {
10568 case Py_EQ:
10569 v = TEST_COND(result == 0);
10570 break;
10571 case Py_NE:
10572 v = TEST_COND(result != 0);
10573 break;
10574 case Py_LE:
10575 v = TEST_COND(result <= 0);
10576 break;
10577 case Py_GE:
10578 v = TEST_COND(result >= 0);
10579 break;
10580 case Py_LT:
10581 v = TEST_COND(result == -1);
10582 break;
10583 case Py_GT:
10584 v = TEST_COND(result == 1);
10585 break;
10586 default:
10587 PyErr_BadArgument();
10588 return NULL;
10589 }
10590 Py_INCREF(v);
10591 return v;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010592 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000010593
Brian Curtindfc80e32011-08-10 20:28:54 -050010594 Py_RETURN_NOTIMPLEMENTED;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010595}
10596
Alexander Belopolsky40018472011-02-26 01:02:56 +000010597int
10598PyUnicode_Contains(PyObject *container, PyObject *element)
Guido van Rossum403d68b2000-03-13 15:55:09 +000010599{
Thomas Wouters477c8d52006-05-27 19:21:47 +000010600 PyObject *str, *sub;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010601 int kind1, kind2, kind;
10602 void *buf1, *buf2;
10603 Py_ssize_t len1, len2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010604 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010605
10606 /* Coerce the two arguments */
Thomas Wouters477c8d52006-05-27 19:21:47 +000010607 sub = PyUnicode_FromObject(element);
10608 if (!sub) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010609 PyErr_Format(PyExc_TypeError,
10610 "'in <string>' requires string as left operand, not %s",
10611 element->ob_type->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010612 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010613 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010614 if (PyUnicode_READY(sub) == -1)
10615 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010616
Thomas Wouters477c8d52006-05-27 19:21:47 +000010617 str = PyUnicode_FromObject(container);
Victor Stinnere9a29352011-10-01 02:14:59 +020010618 if (!str || PyUnicode_READY(str) == -1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010619 Py_DECREF(sub);
10620 return -1;
10621 }
10622
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010623 kind1 = PyUnicode_KIND(str);
10624 kind2 = PyUnicode_KIND(sub);
10625 kind = kind1 > kind2 ? kind1 : kind2;
10626 buf1 = PyUnicode_DATA(str);
10627 buf2 = PyUnicode_DATA(sub);
10628 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010629 buf1 = _PyUnicode_AsKind(str, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010630 if (!buf1) {
10631 Py_DECREF(sub);
10632 return -1;
10633 }
10634 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010635 buf2 = _PyUnicode_AsKind(sub, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010636 if (!buf2) {
10637 Py_DECREF(sub);
10638 if (kind1 != kind) PyMem_Free(buf1);
10639 return -1;
10640 }
10641 len1 = PyUnicode_GET_LENGTH(str);
10642 len2 = PyUnicode_GET_LENGTH(sub);
10643
10644 switch(kind) {
10645 case PyUnicode_1BYTE_KIND:
10646 result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
10647 break;
10648 case PyUnicode_2BYTE_KIND:
10649 result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
10650 break;
10651 case PyUnicode_4BYTE_KIND:
10652 result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
10653 break;
10654 default:
10655 result = -1;
10656 assert(0);
10657 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000010658
10659 Py_DECREF(str);
10660 Py_DECREF(sub);
10661
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010662 if (kind1 != kind)
10663 PyMem_Free(buf1);
10664 if (kind2 != kind)
10665 PyMem_Free(buf2);
10666
Guido van Rossum403d68b2000-03-13 15:55:09 +000010667 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010668}
10669
Guido van Rossumd57fd912000-03-10 22:53:23 +000010670/* Concat to string or Unicode object giving a new Unicode object. */
10671
Alexander Belopolsky40018472011-02-26 01:02:56 +000010672PyObject *
10673PyUnicode_Concat(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010674{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010675 PyObject *u = NULL, *v = NULL, *w;
Victor Stinner127226b2011-10-13 01:12:34 +020010676 Py_UCS4 maxchar, maxchar2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010677
10678 /* Coerce the two arguments */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010679 u = PyUnicode_FromObject(left);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010680 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010681 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010682 v = PyUnicode_FromObject(right);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010683 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010684 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010685
10686 /* Shortcuts */
Victor Stinnera464fc12011-10-02 20:39:30 +020010687 if (v == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010688 Py_DECREF(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010689 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010690 }
Victor Stinnera464fc12011-10-02 20:39:30 +020010691 if (u == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010692 Py_DECREF(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010693 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010694 }
10695
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010696 maxchar = PyUnicode_MAX_CHAR_VALUE(u);
Victor Stinner127226b2011-10-13 01:12:34 +020010697 maxchar2 = PyUnicode_MAX_CHAR_VALUE(v);
10698 maxchar = Py_MAX(maxchar, maxchar2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010699
Guido van Rossumd57fd912000-03-10 22:53:23 +000010700 /* Concat the two Unicode strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010701 w = PyUnicode_New(
10702 PyUnicode_GET_LENGTH(u) + PyUnicode_GET_LENGTH(v),
10703 maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010704 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010705 goto onError;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020010706 copy_characters(w, 0, u, 0, PyUnicode_GET_LENGTH(u));
10707 copy_characters(w, PyUnicode_GET_LENGTH(u), v, 0, PyUnicode_GET_LENGTH(v));
Guido van Rossumd57fd912000-03-10 22:53:23 +000010708 Py_DECREF(u);
10709 Py_DECREF(v);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010710 assert(_PyUnicode_CheckConsistency(w, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010711 return w;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010712
Benjamin Peterson29060642009-01-31 22:14:21 +000010713 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000010714 Py_XDECREF(u);
10715 Py_XDECREF(v);
10716 return NULL;
10717}
10718
Victor Stinnerb0923652011-10-04 01:17:31 +020010719static void
10720unicode_append_inplace(PyObject **p_left, PyObject *right)
10721{
10722 Py_ssize_t left_len, right_len, new_len;
Victor Stinnerb0923652011-10-04 01:17:31 +020010723
10724 assert(PyUnicode_IS_READY(*p_left));
10725 assert(PyUnicode_IS_READY(right));
10726
10727 left_len = PyUnicode_GET_LENGTH(*p_left);
10728 right_len = PyUnicode_GET_LENGTH(right);
10729 if (left_len > PY_SSIZE_T_MAX - right_len) {
10730 PyErr_SetString(PyExc_OverflowError,
10731 "strings are too large to concat");
10732 goto error;
10733 }
10734 new_len = left_len + right_len;
10735
10736 /* Now we own the last reference to 'left', so we can resize it
10737 * in-place.
10738 */
10739 if (unicode_resize(p_left, new_len) != 0) {
10740 /* XXX if _PyUnicode_Resize() fails, 'left' has been
10741 * deallocated so it cannot be put back into
10742 * 'variable'. The MemoryError is raised when there
10743 * is no value in 'variable', which might (very
10744 * remotely) be a cause of incompatibilities.
10745 */
10746 goto error;
10747 }
10748 /* copy 'right' into the newly allocated area of 'left' */
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020010749 copy_characters(*p_left, left_len, right, 0, right_len);
10750 _PyUnicode_DIRTY(*p_left);
Victor Stinnerb0923652011-10-04 01:17:31 +020010751 return;
10752
10753error:
10754 Py_DECREF(*p_left);
10755 *p_left = NULL;
10756}
10757
Walter Dörwald1ab83302007-05-18 17:15:44 +000010758void
Victor Stinner23e56682011-10-03 03:54:37 +020010759PyUnicode_Append(PyObject **p_left, PyObject *right)
Walter Dörwald1ab83302007-05-18 17:15:44 +000010760{
Victor Stinner23e56682011-10-03 03:54:37 +020010761 PyObject *left, *res;
10762
10763 if (p_left == NULL) {
10764 if (!PyErr_Occurred())
10765 PyErr_BadInternalCall();
Benjamin Peterson14339b62009-01-31 16:36:08 +000010766 return;
10767 }
Victor Stinner23e56682011-10-03 03:54:37 +020010768 left = *p_left;
10769 if (right == NULL || !PyUnicode_Check(left)) {
10770 if (!PyErr_Occurred())
10771 PyErr_BadInternalCall();
10772 goto error;
10773 }
10774
Victor Stinnere1335c72011-10-04 20:53:03 +020010775 if (PyUnicode_READY(left))
10776 goto error;
10777 if (PyUnicode_READY(right))
10778 goto error;
10779
Victor Stinner23e56682011-10-03 03:54:37 +020010780 if (PyUnicode_CheckExact(left) && left != unicode_empty
10781 && PyUnicode_CheckExact(right) && right != unicode_empty
10782 && unicode_resizable(left)
10783 && (_PyUnicode_KIND(right) <= _PyUnicode_KIND(left)
10784 || _PyUnicode_WSTR(left) != NULL))
10785 {
Victor Stinnerb0923652011-10-04 01:17:31 +020010786 /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
10787 to change the structure size, but characters are stored just after
Georg Brandl7597add2011-10-05 16:36:47 +020010788 the structure, and so it requires to move all characters which is
Victor Stinnerb0923652011-10-04 01:17:31 +020010789 not so different than duplicating the string. */
10790 if (!(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
Victor Stinner23e56682011-10-03 03:54:37 +020010791 {
Victor Stinnerb0923652011-10-04 01:17:31 +020010792 unicode_append_inplace(p_left, right);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010793 if (p_left != NULL)
10794 assert(_PyUnicode_CheckConsistency(*p_left, 1));
Victor Stinner23e56682011-10-03 03:54:37 +020010795 return;
10796 }
10797 }
10798
10799 res = PyUnicode_Concat(left, right);
10800 if (res == NULL)
10801 goto error;
10802 Py_DECREF(left);
10803 *p_left = res;
10804 return;
10805
10806error:
10807 Py_DECREF(*p_left);
10808 *p_left = NULL;
Walter Dörwald1ab83302007-05-18 17:15:44 +000010809}
10810
10811void
10812PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
10813{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010814 PyUnicode_Append(pleft, right);
10815 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +000010816}
10817
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010818PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010819 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010820\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000010821Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010822string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010823interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010824
10825static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010826unicode_count(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010827{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010828 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010829 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010830 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010831 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010832 int kind1, kind2, kind;
10833 void *buf1, *buf2;
10834 Py_ssize_t len1, len2, iresult;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010835
Jesus Ceaac451502011-04-20 17:09:23 +020010836 if (!stringlib_parse_args_finds_unicode("count", args, &substring,
10837 &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000010838 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000010839
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010840 kind1 = PyUnicode_KIND(self);
10841 kind2 = PyUnicode_KIND(substring);
10842 kind = kind1 > kind2 ? kind1 : kind2;
10843 buf1 = PyUnicode_DATA(self);
10844 buf2 = PyUnicode_DATA(substring);
10845 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010846 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010847 if (!buf1) {
10848 Py_DECREF(substring);
10849 return NULL;
10850 }
10851 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010852 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010853 if (!buf2) {
10854 Py_DECREF(substring);
10855 if (kind1 != kind) PyMem_Free(buf1);
10856 return NULL;
10857 }
10858 len1 = PyUnicode_GET_LENGTH(self);
10859 len2 = PyUnicode_GET_LENGTH(substring);
10860
10861 ADJUST_INDICES(start, end, len1);
10862 switch(kind) {
10863 case PyUnicode_1BYTE_KIND:
10864 iresult = ucs1lib_count(
10865 ((Py_UCS1*)buf1) + start, end - start,
10866 buf2, len2, PY_SSIZE_T_MAX
10867 );
10868 break;
10869 case PyUnicode_2BYTE_KIND:
10870 iresult = ucs2lib_count(
10871 ((Py_UCS2*)buf1) + start, end - start,
10872 buf2, len2, PY_SSIZE_T_MAX
10873 );
10874 break;
10875 case PyUnicode_4BYTE_KIND:
10876 iresult = ucs4lib_count(
10877 ((Py_UCS4*)buf1) + start, end - start,
10878 buf2, len2, PY_SSIZE_T_MAX
10879 );
10880 break;
10881 default:
10882 assert(0); iresult = 0;
10883 }
10884
10885 result = PyLong_FromSsize_t(iresult);
10886
10887 if (kind1 != kind)
10888 PyMem_Free(buf1);
10889 if (kind2 != kind)
10890 PyMem_Free(buf2);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010891
10892 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010893
Guido van Rossumd57fd912000-03-10 22:53:23 +000010894 return result;
10895}
10896
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010897PyDoc_STRVAR(encode__doc__,
Victor Stinnerc911bbf2010-11-07 19:04:46 +000010898 "S.encode(encoding='utf-8', errors='strict') -> bytes\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010899\n\
Victor Stinnere14e2122010-11-07 18:41:46 +000010900Encode S using the codec registered for encoding. Default encoding\n\
10901is 'utf-8'. errors may be given to set a different error\n\
Fred Drakee4315f52000-05-09 19:53:39 +000010902handling scheme. Default is 'strict' meaning that encoding errors raise\n\
Walter Dörwald3aeb6322002-09-02 13:14:32 +000010903a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
10904'xmlcharrefreplace' as well as any other name registered with\n\
10905codecs.register_error that can handle UnicodeEncodeErrors.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010906
10907static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010908unicode_encode(PyObject *self, PyObject *args, PyObject *kwargs)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010909{
Benjamin Peterson308d6372009-09-18 21:42:35 +000010910 static char *kwlist[] = {"encoding", "errors", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000010911 char *encoding = NULL;
10912 char *errors = NULL;
Guido van Rossum35d94282007-08-27 18:20:11 +000010913
Benjamin Peterson308d6372009-09-18 21:42:35 +000010914 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:encode",
10915 kwlist, &encoding, &errors))
Guido van Rossumd57fd912000-03-10 22:53:23 +000010916 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010917 return PyUnicode_AsEncodedString(self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +000010918}
10919
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010920PyDoc_STRVAR(expandtabs__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010921 "S.expandtabs([tabsize]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010922\n\
10923Return a copy of S where all tab characters are expanded using spaces.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010924If tabsize is not given, a tab size of 8 characters is assumed.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010925
10926static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010927unicode_expandtabs(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010928{
Antoine Pitroue71d5742011-10-04 15:55:09 +020010929 Py_ssize_t i, j, line_pos, src_len, incr;
10930 Py_UCS4 ch;
10931 PyObject *u;
10932 void *src_data, *dest_data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010933 int tabsize = 8;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010934 int kind;
Antoine Pitroue19aa382011-10-04 16:04:01 +020010935 int found;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010936
10937 if (!PyArg_ParseTuple(args, "|i:expandtabs", &tabsize))
Benjamin Peterson29060642009-01-31 22:14:21 +000010938 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010939
Antoine Pitrou22425222011-10-04 19:10:51 +020010940 if (PyUnicode_READY(self) == -1)
10941 return NULL;
10942
Thomas Wouters7e474022000-07-16 12:04:32 +000010943 /* First pass: determine size of output string */
Antoine Pitroue71d5742011-10-04 15:55:09 +020010944 src_len = PyUnicode_GET_LENGTH(self);
10945 i = j = line_pos = 0;
10946 kind = PyUnicode_KIND(self);
10947 src_data = PyUnicode_DATA(self);
Antoine Pitroue19aa382011-10-04 16:04:01 +020010948 found = 0;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010949 for (; i < src_len; i++) {
10950 ch = PyUnicode_READ(kind, src_data, i);
10951 if (ch == '\t') {
Antoine Pitroue19aa382011-10-04 16:04:01 +020010952 found = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000010953 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020010954 incr = tabsize - (line_pos % tabsize); /* cannot overflow */
Benjamin Peterson29060642009-01-31 22:14:21 +000010955 if (j > PY_SSIZE_T_MAX - incr)
Antoine Pitroue71d5742011-10-04 15:55:09 +020010956 goto overflow;
10957 line_pos += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000010958 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010959 }
Benjamin Peterson29060642009-01-31 22:14:21 +000010960 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010961 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000010962 if (j > PY_SSIZE_T_MAX - 1)
Antoine Pitroue71d5742011-10-04 15:55:09 +020010963 goto overflow;
10964 line_pos++;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010965 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010966 if (ch == '\n' || ch == '\r')
10967 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010968 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020010969 }
Antoine Pitroue19aa382011-10-04 16:04:01 +020010970 if (!found && PyUnicode_CheckExact(self)) {
Victor Stinner7931d9a2011-11-04 00:22:48 +010010971 Py_INCREF(self);
10972 return self;
Antoine Pitroue19aa382011-10-04 16:04:01 +020010973 }
Guido van Rossumcd16bf62007-06-13 18:07:49 +000010974
Guido van Rossumd57fd912000-03-10 22:53:23 +000010975 /* Second pass: create output string and fill it */
Antoine Pitroue71d5742011-10-04 15:55:09 +020010976 u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +000010977 if (!u)
10978 return NULL;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010979 dest_data = PyUnicode_DATA(u);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010980
Antoine Pitroue71d5742011-10-04 15:55:09 +020010981 i = j = line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010982
Antoine Pitroue71d5742011-10-04 15:55:09 +020010983 for (; i < src_len; i++) {
10984 ch = PyUnicode_READ(kind, src_data, i);
10985 if (ch == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +000010986 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020010987 incr = tabsize - (line_pos % tabsize);
10988 line_pos += incr;
10989 while (incr--) {
10990 PyUnicode_WRITE(kind, dest_data, j, ' ');
10991 j++;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010992 }
Benjamin Peterson29060642009-01-31 22:14:21 +000010993 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000010994 }
Benjamin Peterson29060642009-01-31 22:14:21 +000010995 else {
Antoine Pitroue71d5742011-10-04 15:55:09 +020010996 line_pos++;
10997 PyUnicode_WRITE(kind, dest_data, j, ch);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010998 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010999 if (ch == '\n' || ch == '\r')
11000 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011001 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011002 }
11003 assert (j == PyUnicode_GET_LENGTH(u));
Victor Stinner17efeed2011-10-04 20:05:46 +020011004#ifndef DONT_MAKE_RESULT_READY
11005 if (_PyUnicode_READY_REPLACE(&u)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011006 Py_DECREF(u);
11007 return NULL;
11008 }
Victor Stinner17efeed2011-10-04 20:05:46 +020011009#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020011010 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +010011011 return u;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011012
Antoine Pitroue71d5742011-10-04 15:55:09 +020011013 overflow:
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011014 PyErr_SetString(PyExc_OverflowError, "new string is too long");
11015 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011016}
11017
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011018PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011019 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011020\n\
11021Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080011022such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011023arguments start and end are interpreted as in slice notation.\n\
11024\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011025Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011026
11027static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011028unicode_find(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011029{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011030 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011031 Py_ssize_t start;
11032 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011033 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011034
Jesus Ceaac451502011-04-20 17:09:23 +020011035 if (!stringlib_parse_args_finds_unicode("find", args, &substring,
11036 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011037 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011038
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011039 if (PyUnicode_READY(self) == -1)
11040 return NULL;
11041 if (PyUnicode_READY(substring) == -1)
11042 return NULL;
11043
Victor Stinner7931d9a2011-11-04 00:22:48 +010011044 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011045
11046 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011047
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011048 if (result == -2)
11049 return NULL;
11050
Christian Heimes217cfd12007-12-02 14:31:20 +000011051 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011052}
11053
11054static PyObject *
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011055unicode_getitem(PyObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011056{
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011057 Py_UCS4 ch = PyUnicode_ReadChar(self, index);
11058 if (ch == (Py_UCS4)-1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011059 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011060 return PyUnicode_FromOrdinal(ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011061}
11062
Guido van Rossumc2504932007-09-18 19:42:40 +000011063/* Believe it or not, this produces the same value for ASCII strings
Mark Dickinson57e683e2011-09-24 18:18:40 +010011064 as bytes_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +000011065static Py_hash_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011066unicode_hash(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011067{
Guido van Rossumc2504932007-09-18 19:42:40 +000011068 Py_ssize_t len;
Mark Dickinson57e683e2011-09-24 18:18:40 +010011069 Py_uhash_t x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011070
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011071 if (_PyUnicode_HASH(self) != -1)
11072 return _PyUnicode_HASH(self);
11073 if (PyUnicode_READY(self) == -1)
11074 return -1;
11075 len = PyUnicode_GET_LENGTH(self);
11076
11077 /* The hash function as a macro, gets expanded three times below. */
11078#define HASH(P) \
11079 x = (Py_uhash_t)*P << 7; \
11080 while (--len >= 0) \
11081 x = (1000003*x) ^ (Py_uhash_t)*P++;
11082
11083 switch (PyUnicode_KIND(self)) {
11084 case PyUnicode_1BYTE_KIND: {
11085 const unsigned char *c = PyUnicode_1BYTE_DATA(self);
11086 HASH(c);
11087 break;
11088 }
11089 case PyUnicode_2BYTE_KIND: {
11090 const Py_UCS2 *s = PyUnicode_2BYTE_DATA(self);
11091 HASH(s);
11092 break;
11093 }
11094 default: {
11095 Py_UCS4 *l;
11096 assert(PyUnicode_KIND(self) == PyUnicode_4BYTE_KIND &&
11097 "Impossible switch case in unicode_hash");
11098 l = PyUnicode_4BYTE_DATA(self);
11099 HASH(l);
11100 break;
11101 }
11102 }
11103 x ^= (Py_uhash_t)PyUnicode_GET_LENGTH(self);
11104
Guido van Rossumc2504932007-09-18 19:42:40 +000011105 if (x == -1)
11106 x = -2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011107 _PyUnicode_HASH(self) = x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011108 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011109}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011110#undef HASH
Guido van Rossumd57fd912000-03-10 22:53:23 +000011111
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011112PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011113 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011114\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011115Like S.find() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011116
11117static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011118unicode_index(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011119{
Martin v. Löwis18e16552006-02-15 17:27:45 +000011120 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011121 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011122 Py_ssize_t start;
11123 Py_ssize_t end;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011124
Jesus Ceaac451502011-04-20 17:09:23 +020011125 if (!stringlib_parse_args_finds_unicode("index", args, &substring,
11126 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011127 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011128
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011129 if (PyUnicode_READY(self) == -1)
11130 return NULL;
11131 if (PyUnicode_READY(substring) == -1)
11132 return NULL;
11133
Victor Stinner7931d9a2011-11-04 00:22:48 +010011134 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011135
11136 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011137
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011138 if (result == -2)
11139 return NULL;
11140
Guido van Rossumd57fd912000-03-10 22:53:23 +000011141 if (result < 0) {
11142 PyErr_SetString(PyExc_ValueError, "substring not found");
11143 return NULL;
11144 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011145
Christian Heimes217cfd12007-12-02 14:31:20 +000011146 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011147}
11148
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011149PyDoc_STRVAR(islower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011150 "S.islower() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011151\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011152Return True if all cased characters in S are lowercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011153at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011154
11155static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011156unicode_islower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011157{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011158 Py_ssize_t i, length;
11159 int kind;
11160 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011161 int cased;
11162
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011163 if (PyUnicode_READY(self) == -1)
11164 return NULL;
11165 length = PyUnicode_GET_LENGTH(self);
11166 kind = PyUnicode_KIND(self);
11167 data = PyUnicode_DATA(self);
11168
Guido van Rossumd57fd912000-03-10 22:53:23 +000011169 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011170 if (length == 1)
11171 return PyBool_FromLong(
11172 Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011173
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011174 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011175 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011176 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011177
Guido van Rossumd57fd912000-03-10 22:53:23 +000011178 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011179 for (i = 0; i < length; i++) {
11180 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011181
Benjamin Peterson29060642009-01-31 22:14:21 +000011182 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
11183 return PyBool_FromLong(0);
11184 else if (!cased && Py_UNICODE_ISLOWER(ch))
11185 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011186 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011187 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011188}
11189
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011190PyDoc_STRVAR(isupper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011191 "S.isupper() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011192\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011193Return True if all cased characters in S are uppercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011194at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011195
11196static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011197unicode_isupper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011198{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011199 Py_ssize_t i, length;
11200 int kind;
11201 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011202 int cased;
11203
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011204 if (PyUnicode_READY(self) == -1)
11205 return NULL;
11206 length = PyUnicode_GET_LENGTH(self);
11207 kind = PyUnicode_KIND(self);
11208 data = PyUnicode_DATA(self);
11209
Guido van Rossumd57fd912000-03-10 22:53:23 +000011210 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011211 if (length == 1)
11212 return PyBool_FromLong(
11213 Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011214
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011215 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011216 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011217 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011218
Guido van Rossumd57fd912000-03-10 22:53:23 +000011219 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011220 for (i = 0; i < length; i++) {
11221 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011222
Benjamin Peterson29060642009-01-31 22:14:21 +000011223 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
11224 return PyBool_FromLong(0);
11225 else if (!cased && Py_UNICODE_ISUPPER(ch))
11226 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011227 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011228 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011229}
11230
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011231PyDoc_STRVAR(istitle__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011232 "S.istitle() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011233\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011234Return True if S is a titlecased string and there is at least one\n\
11235character in S, i.e. upper- and titlecase characters may only\n\
11236follow uncased characters and lowercase characters only cased ones.\n\
11237Return False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011238
11239static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011240unicode_istitle(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011241{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011242 Py_ssize_t i, length;
11243 int kind;
11244 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011245 int cased, previous_is_cased;
11246
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011247 if (PyUnicode_READY(self) == -1)
11248 return NULL;
11249 length = PyUnicode_GET_LENGTH(self);
11250 kind = PyUnicode_KIND(self);
11251 data = PyUnicode_DATA(self);
11252
Guido van Rossumd57fd912000-03-10 22:53:23 +000011253 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011254 if (length == 1) {
11255 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11256 return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
11257 (Py_UNICODE_ISUPPER(ch) != 0));
11258 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011259
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011260 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011261 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011262 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011263
Guido van Rossumd57fd912000-03-10 22:53:23 +000011264 cased = 0;
11265 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011266 for (i = 0; i < length; i++) {
11267 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011268
Benjamin Peterson29060642009-01-31 22:14:21 +000011269 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
11270 if (previous_is_cased)
11271 return PyBool_FromLong(0);
11272 previous_is_cased = 1;
11273 cased = 1;
11274 }
11275 else if (Py_UNICODE_ISLOWER(ch)) {
11276 if (!previous_is_cased)
11277 return PyBool_FromLong(0);
11278 previous_is_cased = 1;
11279 cased = 1;
11280 }
11281 else
11282 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011283 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011284 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011285}
11286
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011287PyDoc_STRVAR(isspace__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011288 "S.isspace() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011289\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011290Return True if all characters in S are whitespace\n\
11291and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011292
11293static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011294unicode_isspace(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011295{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011296 Py_ssize_t i, length;
11297 int kind;
11298 void *data;
11299
11300 if (PyUnicode_READY(self) == -1)
11301 return NULL;
11302 length = PyUnicode_GET_LENGTH(self);
11303 kind = PyUnicode_KIND(self);
11304 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011305
Guido van Rossumd57fd912000-03-10 22:53:23 +000011306 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011307 if (length == 1)
11308 return PyBool_FromLong(
11309 Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011310
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011311 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011312 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011313 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011314
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011315 for (i = 0; i < length; i++) {
11316 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011317 if (!Py_UNICODE_ISSPACE(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011318 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011319 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011320 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011321}
11322
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011323PyDoc_STRVAR(isalpha__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011324 "S.isalpha() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011325\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011326Return True if all characters in S are alphabetic\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011327and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011328
11329static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011330unicode_isalpha(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011331{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011332 Py_ssize_t i, length;
11333 int kind;
11334 void *data;
11335
11336 if (PyUnicode_READY(self) == -1)
11337 return NULL;
11338 length = PyUnicode_GET_LENGTH(self);
11339 kind = PyUnicode_KIND(self);
11340 data = PyUnicode_DATA(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011341
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011342 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011343 if (length == 1)
11344 return PyBool_FromLong(
11345 Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011346
11347 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011348 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011349 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011350
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011351 for (i = 0; i < length; i++) {
11352 if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011353 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011354 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011355 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011356}
11357
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011358PyDoc_STRVAR(isalnum__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011359 "S.isalnum() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011360\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011361Return True if all characters in S are alphanumeric\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011362and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011363
11364static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011365unicode_isalnum(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011366{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011367 int kind;
11368 void *data;
11369 Py_ssize_t len, i;
11370
11371 if (PyUnicode_READY(self) == -1)
11372 return NULL;
11373
11374 kind = PyUnicode_KIND(self);
11375 data = PyUnicode_DATA(self);
11376 len = PyUnicode_GET_LENGTH(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011377
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011378 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011379 if (len == 1) {
11380 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11381 return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
11382 }
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011383
11384 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011385 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011386 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011387
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011388 for (i = 0; i < len; i++) {
11389 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011390 if (!Py_UNICODE_ISALNUM(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011391 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011392 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011393 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011394}
11395
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011396PyDoc_STRVAR(isdecimal__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011397 "S.isdecimal() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011398\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011399Return True if there are only decimal characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011400False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011401
11402static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011403unicode_isdecimal(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011404{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011405 Py_ssize_t i, length;
11406 int kind;
11407 void *data;
11408
11409 if (PyUnicode_READY(self) == -1)
11410 return NULL;
11411 length = PyUnicode_GET_LENGTH(self);
11412 kind = PyUnicode_KIND(self);
11413 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011414
Guido van Rossumd57fd912000-03-10 22:53:23 +000011415 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011416 if (length == 1)
11417 return PyBool_FromLong(
11418 Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011419
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011420 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011421 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011422 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011423
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011424 for (i = 0; i < length; i++) {
11425 if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011426 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011427 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011428 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011429}
11430
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011431PyDoc_STRVAR(isdigit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011432 "S.isdigit() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011433\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011434Return True if all characters in S are digits\n\
11435and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011436
11437static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011438unicode_isdigit(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011439{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011440 Py_ssize_t i, length;
11441 int kind;
11442 void *data;
11443
11444 if (PyUnicode_READY(self) == -1)
11445 return NULL;
11446 length = PyUnicode_GET_LENGTH(self);
11447 kind = PyUnicode_KIND(self);
11448 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011449
Guido van Rossumd57fd912000-03-10 22:53:23 +000011450 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011451 if (length == 1) {
11452 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11453 return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
11454 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011455
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011456 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011457 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011458 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011459
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011460 for (i = 0; i < length; i++) {
11461 if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011462 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011463 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011464 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011465}
11466
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011467PyDoc_STRVAR(isnumeric__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011468 "S.isnumeric() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011469\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011470Return True if there are only numeric characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011471False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011472
11473static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011474unicode_isnumeric(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011475{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011476 Py_ssize_t i, length;
11477 int kind;
11478 void *data;
11479
11480 if (PyUnicode_READY(self) == -1)
11481 return NULL;
11482 length = PyUnicode_GET_LENGTH(self);
11483 kind = PyUnicode_KIND(self);
11484 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011485
Guido van Rossumd57fd912000-03-10 22:53:23 +000011486 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011487 if (length == 1)
11488 return PyBool_FromLong(
11489 Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011490
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011491 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011492 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011493 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011494
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011495 for (i = 0; i < length; i++) {
11496 if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011497 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011498 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011499 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011500}
11501
Martin v. Löwis47383402007-08-15 07:32:56 +000011502int
11503PyUnicode_IsIdentifier(PyObject *self)
11504{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011505 int kind;
11506 void *data;
11507 Py_ssize_t i;
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011508 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +000011509
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011510 if (PyUnicode_READY(self) == -1) {
11511 Py_FatalError("identifier not ready");
Benjamin Peterson29060642009-01-31 22:14:21 +000011512 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011513 }
11514
11515 /* Special case for empty strings */
11516 if (PyUnicode_GET_LENGTH(self) == 0)
11517 return 0;
11518 kind = PyUnicode_KIND(self);
11519 data = PyUnicode_DATA(self);
Martin v. Löwis47383402007-08-15 07:32:56 +000011520
11521 /* PEP 3131 says that the first character must be in
11522 XID_Start and subsequent characters in XID_Continue,
11523 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +000011524 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +000011525 letters, digits, underscore). However, given the current
11526 definition of XID_Start and XID_Continue, it is sufficient
11527 to check just for these, except that _ must be allowed
11528 as starting an identifier. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011529 first = PyUnicode_READ(kind, data, 0);
Benjamin Petersonf413b802011-08-12 22:17:18 -050011530 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +000011531 return 0;
11532
Benjamin Peterson9c6e6a02011-09-28 08:09:05 -040011533 for (i = 1; i < PyUnicode_GET_LENGTH(self); i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011534 if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011535 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +000011536 return 1;
11537}
11538
11539PyDoc_STRVAR(isidentifier__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011540 "S.isidentifier() -> bool\n\
Martin v. Löwis47383402007-08-15 07:32:56 +000011541\n\
11542Return True if S is a valid identifier according\n\
11543to the language definition.");
11544
11545static PyObject*
11546unicode_isidentifier(PyObject *self)
11547{
11548 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
11549}
11550
Georg Brandl559e5d72008-06-11 18:37:52 +000011551PyDoc_STRVAR(isprintable__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011552 "S.isprintable() -> bool\n\
Georg Brandl559e5d72008-06-11 18:37:52 +000011553\n\
11554Return True if all characters in S are considered\n\
11555printable in repr() or S is empty, False otherwise.");
11556
11557static PyObject*
11558unicode_isprintable(PyObject *self)
11559{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011560 Py_ssize_t i, length;
11561 int kind;
11562 void *data;
11563
11564 if (PyUnicode_READY(self) == -1)
11565 return NULL;
11566 length = PyUnicode_GET_LENGTH(self);
11567 kind = PyUnicode_KIND(self);
11568 data = PyUnicode_DATA(self);
Georg Brandl559e5d72008-06-11 18:37:52 +000011569
11570 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011571 if (length == 1)
11572 return PyBool_FromLong(
11573 Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
Georg Brandl559e5d72008-06-11 18:37:52 +000011574
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011575 for (i = 0; i < length; i++) {
11576 if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
Georg Brandl559e5d72008-06-11 18:37:52 +000011577 Py_RETURN_FALSE;
11578 }
11579 }
11580 Py_RETURN_TRUE;
11581}
11582
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011583PyDoc_STRVAR(join__doc__,
Georg Brandl495f7b52009-10-27 15:28:25 +000011584 "S.join(iterable) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011585\n\
11586Return a string which is the concatenation of the strings in the\n\
Georg Brandl495f7b52009-10-27 15:28:25 +000011587iterable. The separator between elements is S.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011588
11589static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011590unicode_join(PyObject *self, PyObject *data)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011591{
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011592 return PyUnicode_Join(self, data);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011593}
11594
Martin v. Löwis18e16552006-02-15 17:27:45 +000011595static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011596unicode_length(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011597{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011598 if (PyUnicode_READY(self) == -1)
11599 return -1;
11600 return PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011601}
11602
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011603PyDoc_STRVAR(ljust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011604 "S.ljust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011605\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000011606Return S left-justified in a Unicode string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011607done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011608
11609static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020011610unicode_ljust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011611{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011612 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011613 Py_UCS4 fillchar = ' ';
11614
11615 if (PyUnicode_READY(self) == -1)
11616 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011617
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011618 if (!PyArg_ParseTuple(args, "n|O&:ljust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011619 return NULL;
11620
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011621 if (_PyUnicode_LENGTH(self) >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000011622 Py_INCREF(self);
Victor Stinner7931d9a2011-11-04 00:22:48 +010011623 return self;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011624 }
11625
Victor Stinner7931d9a2011-11-04 00:22:48 +010011626 return pad(self, 0, width - _PyUnicode_LENGTH(self), fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011627}
11628
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011629PyDoc_STRVAR(lower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011630 "S.lower() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011631\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011632Return a copy of the string S converted to lowercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011633
11634static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020011635unicode_lower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011636{
Guido van Rossumd57fd912000-03-10 22:53:23 +000011637 return fixup(self, fixlower);
11638}
11639
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011640#define LEFTSTRIP 0
11641#define RIGHTSTRIP 1
11642#define BOTHSTRIP 2
11643
11644/* Arrays indexed by above */
11645static const char *stripformat[] = {"|O:lstrip", "|O:rstrip", "|O:strip"};
11646
11647#define STRIPNAME(i) (stripformat[i]+3)
11648
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011649/* externally visible for str.strip(unicode) */
11650PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011651_PyUnicode_XStrip(PyObject *self, int striptype, PyObject *sepobj)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011652{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011653 void *data;
11654 int kind;
11655 Py_ssize_t i, j, len;
11656 BLOOM_MASK sepmask;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011657
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011658 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
11659 return NULL;
11660
11661 kind = PyUnicode_KIND(self);
11662 data = PyUnicode_DATA(self);
11663 len = PyUnicode_GET_LENGTH(self);
11664 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
11665 PyUnicode_DATA(sepobj),
11666 PyUnicode_GET_LENGTH(sepobj));
Thomas Wouters477c8d52006-05-27 19:21:47 +000011667
Benjamin Peterson14339b62009-01-31 16:36:08 +000011668 i = 0;
11669 if (striptype != RIGHTSTRIP) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011670 while (i < len &&
11671 BLOOM_MEMBER(sepmask, PyUnicode_READ(kind, data, i), sepobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011672 i++;
11673 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011674 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011675
Benjamin Peterson14339b62009-01-31 16:36:08 +000011676 j = len;
11677 if (striptype != LEFTSTRIP) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011678 do {
11679 j--;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011680 } while (j >= i &&
11681 BLOOM_MEMBER(sepmask, PyUnicode_READ(kind, data, j), sepobj));
Benjamin Peterson29060642009-01-31 22:14:21 +000011682 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011683 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011684
Victor Stinner7931d9a2011-11-04 00:22:48 +010011685 return PyUnicode_Substring(self, i, j);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011686}
11687
11688PyObject*
11689PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
11690{
11691 unsigned char *data;
11692 int kind;
Victor Stinner12bab6d2011-10-01 01:53:49 +020011693 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011694
Victor Stinnerde636f32011-10-01 03:55:54 +020011695 if (PyUnicode_READY(self) == -1)
11696 return NULL;
11697
11698 end = Py_MIN(end, PyUnicode_GET_LENGTH(self));
11699
Victor Stinner12bab6d2011-10-01 01:53:49 +020011700 if (start == 0 && end == PyUnicode_GET_LENGTH(self))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011701 {
Victor Stinner12bab6d2011-10-01 01:53:49 +020011702 if (PyUnicode_CheckExact(self)) {
11703 Py_INCREF(self);
11704 return self;
11705 }
11706 else
11707 return PyUnicode_Copy(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011708 }
11709
Victor Stinner12bab6d2011-10-01 01:53:49 +020011710 length = end - start;
11711 if (length == 1)
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011712 return unicode_getitem(self, start);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011713
Victor Stinnerde636f32011-10-01 03:55:54 +020011714 if (start < 0 || end < 0) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020011715 PyErr_SetString(PyExc_IndexError, "string index out of range");
11716 return NULL;
11717 }
11718
Victor Stinnerb9275c12011-10-05 14:01:42 +020011719 if (PyUnicode_IS_ASCII(self)) {
11720 kind = PyUnicode_KIND(self);
11721 data = PyUnicode_1BYTE_DATA(self);
11722 return unicode_fromascii(data + start, length);
11723 }
11724 else {
11725 kind = PyUnicode_KIND(self);
11726 data = PyUnicode_1BYTE_DATA(self);
11727 return PyUnicode_FromKindAndData(kind,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020011728 data + kind * start,
Victor Stinnerb9275c12011-10-05 14:01:42 +020011729 length);
11730 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011731}
Guido van Rossumd57fd912000-03-10 22:53:23 +000011732
11733static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011734do_strip(PyObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011735{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011736 int kind;
11737 void *data;
11738 Py_ssize_t len, i, j;
11739
11740 if (PyUnicode_READY(self) == -1)
11741 return NULL;
11742
11743 kind = PyUnicode_KIND(self);
11744 data = PyUnicode_DATA(self);
11745 len = PyUnicode_GET_LENGTH(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011746
Benjamin Peterson14339b62009-01-31 16:36:08 +000011747 i = 0;
11748 if (striptype != RIGHTSTRIP) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011749 while (i < len && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, i))) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000011750 i++;
11751 }
11752 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011753
Benjamin Peterson14339b62009-01-31 16:36:08 +000011754 j = len;
11755 if (striptype != LEFTSTRIP) {
11756 do {
11757 j--;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011758 } while (j >= i && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, j)));
Benjamin Peterson14339b62009-01-31 16:36:08 +000011759 j++;
11760 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011761
Victor Stinner7931d9a2011-11-04 00:22:48 +010011762 return PyUnicode_Substring(self, i, j);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011763}
11764
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011765
11766static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011767do_argstrip(PyObject *self, int striptype, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011768{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011769 PyObject *sep = NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011770
Benjamin Peterson14339b62009-01-31 16:36:08 +000011771 if (!PyArg_ParseTuple(args, (char *)stripformat[striptype], &sep))
11772 return NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011773
Benjamin Peterson14339b62009-01-31 16:36:08 +000011774 if (sep != NULL && sep != Py_None) {
11775 if (PyUnicode_Check(sep))
11776 return _PyUnicode_XStrip(self, striptype, sep);
11777 else {
11778 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000011779 "%s arg must be None or str",
11780 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +000011781 return NULL;
11782 }
11783 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011784
Benjamin Peterson14339b62009-01-31 16:36:08 +000011785 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011786}
11787
11788
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011789PyDoc_STRVAR(strip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011790 "S.strip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011791\n\
11792Return a copy of the string S with leading and trailing\n\
11793whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011794If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011795
11796static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011797unicode_strip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011798{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011799 if (PyTuple_GET_SIZE(args) == 0)
11800 return do_strip(self, BOTHSTRIP); /* Common case */
11801 else
11802 return do_argstrip(self, BOTHSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011803}
11804
11805
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011806PyDoc_STRVAR(lstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011807 "S.lstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011808\n\
11809Return a copy of the string S with leading whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011810If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011811
11812static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011813unicode_lstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011814{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011815 if (PyTuple_GET_SIZE(args) == 0)
11816 return do_strip(self, LEFTSTRIP); /* Common case */
11817 else
11818 return do_argstrip(self, LEFTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011819}
11820
11821
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011822PyDoc_STRVAR(rstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011823 "S.rstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011824\n\
11825Return a copy of the string S with trailing whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011826If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011827
11828static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011829unicode_rstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011830{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011831 if (PyTuple_GET_SIZE(args) == 0)
11832 return do_strip(self, RIGHTSTRIP); /* Common case */
11833 else
11834 return do_argstrip(self, RIGHTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011835}
11836
11837
Guido van Rossumd57fd912000-03-10 22:53:23 +000011838static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011839unicode_repeat(PyObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011840{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011841 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011842 Py_ssize_t nchars, n;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011843
Georg Brandl222de0f2009-04-12 12:01:50 +000011844 if (len < 1) {
11845 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +020011846 return unicode_empty;
Georg Brandl222de0f2009-04-12 12:01:50 +000011847 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011848
Tim Peters7a29bd52001-09-12 03:03:31 +000011849 if (len == 1 && PyUnicode_CheckExact(str)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000011850 /* no repeat, return original string */
11851 Py_INCREF(str);
Victor Stinner7931d9a2011-11-04 00:22:48 +010011852 return str;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011853 }
Tim Peters8f422462000-09-09 06:13:41 +000011854
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011855 if (PyUnicode_READY(str) == -1)
11856 return NULL;
11857
Victor Stinnerc759f3e2011-10-01 03:09:58 +020011858 if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
Victor Stinner67ca64c2011-10-01 02:47:29 +020011859 PyErr_SetString(PyExc_OverflowError,
11860 "repeated string is too long");
11861 return NULL;
11862 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011863 nchars = len * PyUnicode_GET_LENGTH(str);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011864
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011865 u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011866 if (!u)
11867 return NULL;
Victor Stinner67ca64c2011-10-01 02:47:29 +020011868 assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011869
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011870 if (PyUnicode_GET_LENGTH(str) == 1) {
11871 const int kind = PyUnicode_KIND(str);
11872 const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
11873 void *to = PyUnicode_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011874 if (kind == PyUnicode_1BYTE_KIND)
11875 memset(to, (unsigned char)fill_char, len);
11876 else {
11877 for (n = 0; n < len; ++n)
11878 PyUnicode_WRITE(kind, to, n, fill_char);
11879 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011880 }
11881 else {
11882 /* number of characters copied this far */
11883 Py_ssize_t done = PyUnicode_GET_LENGTH(str);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020011884 const Py_ssize_t char_size = PyUnicode_KIND(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011885 char *to = (char *) PyUnicode_DATA(u);
11886 Py_MEMCPY(to, PyUnicode_DATA(str),
11887 PyUnicode_GET_LENGTH(str) * char_size);
Benjamin Peterson29060642009-01-31 22:14:21 +000011888 while (done < nchars) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011889 n = (done <= nchars-done) ? done : nchars-done;
11890 Py_MEMCPY(to + (done * char_size), to, n * char_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011891 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +000011892 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011893 }
11894
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020011895 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011896 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011897}
11898
Alexander Belopolsky40018472011-02-26 01:02:56 +000011899PyObject *
11900PyUnicode_Replace(PyObject *obj,
11901 PyObject *subobj,
11902 PyObject *replobj,
11903 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011904{
11905 PyObject *self;
11906 PyObject *str1;
11907 PyObject *str2;
11908 PyObject *result;
11909
11910 self = PyUnicode_FromObject(obj);
Victor Stinnere9a29352011-10-01 02:14:59 +020011911 if (self == NULL || PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000011912 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011913 str1 = PyUnicode_FromObject(subobj);
Victor Stinnere9a29352011-10-01 02:14:59 +020011914 if (str1 == NULL || PyUnicode_READY(str1) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011915 Py_DECREF(self);
11916 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011917 }
11918 str2 = PyUnicode_FromObject(replobj);
Victor Stinnere9a29352011-10-01 02:14:59 +020011919 if (str2 == NULL || PyUnicode_READY(str2)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011920 Py_DECREF(self);
11921 Py_DECREF(str1);
11922 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011923 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011924 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011925 Py_DECREF(self);
11926 Py_DECREF(str1);
11927 Py_DECREF(str2);
11928 return result;
11929}
11930
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011931PyDoc_STRVAR(replace__doc__,
Ezio Melottic1897e72010-06-26 18:50:39 +000011932 "S.replace(old, new[, count]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011933\n\
11934Return a copy of S with all occurrences of substring\n\
Georg Brandlf08a9dd2008-06-10 16:57:31 +000011935old replaced by new. If the optional argument count is\n\
11936given, only the first count occurrences are replaced.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011937
11938static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011939unicode_replace(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011940{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011941 PyObject *str1;
11942 PyObject *str2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011943 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011944 PyObject *result;
11945
Martin v. Löwis18e16552006-02-15 17:27:45 +000011946 if (!PyArg_ParseTuple(args, "OO|n:replace", &str1, &str2, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011947 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011948 if (!PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000011949 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011950 str1 = PyUnicode_FromObject(str1);
11951 if (str1 == NULL || PyUnicode_READY(str1) == -1)
11952 return NULL;
11953 str2 = PyUnicode_FromObject(str2);
Victor Stinnere9a29352011-10-01 02:14:59 +020011954 if (str2 == NULL || PyUnicode_READY(str2) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011955 Py_DECREF(str1);
11956 return NULL;
Walter Dörwaldf6b56ae2003-02-09 23:42:56 +000011957 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011958
11959 result = replace(self, str1, str2, maxcount);
11960
11961 Py_DECREF(str1);
11962 Py_DECREF(str2);
11963 return result;
11964}
11965
Alexander Belopolsky40018472011-02-26 01:02:56 +000011966static PyObject *
11967unicode_repr(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011968{
Walter Dörwald79e913e2007-05-12 11:08:06 +000011969 PyObject *repr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011970 Py_ssize_t isize;
11971 Py_ssize_t osize, squote, dquote, i, o;
11972 Py_UCS4 max, quote;
11973 int ikind, okind;
11974 void *idata, *odata;
Walter Dörwald79e913e2007-05-12 11:08:06 +000011975
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011976 if (PyUnicode_READY(unicode) == -1)
Walter Dörwald79e913e2007-05-12 11:08:06 +000011977 return NULL;
11978
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011979 isize = PyUnicode_GET_LENGTH(unicode);
11980 idata = PyUnicode_DATA(unicode);
Walter Dörwald79e913e2007-05-12 11:08:06 +000011981
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011982 /* Compute length of output, quote characters, and
11983 maximum character */
11984 osize = 2; /* quotes */
11985 max = 127;
11986 squote = dquote = 0;
11987 ikind = PyUnicode_KIND(unicode);
11988 for (i = 0; i < isize; i++) {
11989 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
11990 switch (ch) {
11991 case '\'': squote++; osize++; break;
11992 case '"': dquote++; osize++; break;
11993 case '\\': case '\t': case '\r': case '\n':
11994 osize += 2; break;
11995 default:
11996 /* Fast-path ASCII */
11997 if (ch < ' ' || ch == 0x7f)
11998 osize += 4; /* \xHH */
11999 else if (ch < 0x7f)
12000 osize++;
12001 else if (Py_UNICODE_ISPRINTABLE(ch)) {
12002 osize++;
12003 max = ch > max ? ch : max;
12004 }
12005 else if (ch < 0x100)
12006 osize += 4; /* \xHH */
12007 else if (ch < 0x10000)
12008 osize += 6; /* \uHHHH */
12009 else
12010 osize += 10; /* \uHHHHHHHH */
12011 }
12012 }
12013
12014 quote = '\'';
12015 if (squote) {
12016 if (dquote)
12017 /* Both squote and dquote present. Use squote,
12018 and escape them */
12019 osize += squote;
12020 else
12021 quote = '"';
12022 }
12023
12024 repr = PyUnicode_New(osize, max);
12025 if (repr == NULL)
12026 return NULL;
12027 okind = PyUnicode_KIND(repr);
12028 odata = PyUnicode_DATA(repr);
12029
12030 PyUnicode_WRITE(okind, odata, 0, quote);
12031 PyUnicode_WRITE(okind, odata, osize-1, quote);
12032
12033 for (i = 0, o = 1; i < isize; i++) {
12034 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012035
12036 /* Escape quotes and backslashes */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012037 if ((ch == quote) || (ch == '\\')) {
12038 PyUnicode_WRITE(okind, odata, o++, '\\');
12039 PyUnicode_WRITE(okind, odata, o++, ch);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012040 continue;
12041 }
12042
Benjamin Peterson29060642009-01-31 22:14:21 +000012043 /* Map special whitespace to '\t', \n', '\r' */
Georg Brandl559e5d72008-06-11 18:37:52 +000012044 if (ch == '\t') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012045 PyUnicode_WRITE(okind, odata, o++, '\\');
12046 PyUnicode_WRITE(okind, odata, o++, 't');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012047 }
12048 else if (ch == '\n') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012049 PyUnicode_WRITE(okind, odata, o++, '\\');
12050 PyUnicode_WRITE(okind, odata, o++, 'n');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012051 }
12052 else if (ch == '\r') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012053 PyUnicode_WRITE(okind, odata, o++, '\\');
12054 PyUnicode_WRITE(okind, odata, o++, 'r');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012055 }
12056
12057 /* Map non-printable US ASCII to '\xhh' */
Georg Brandl559e5d72008-06-11 18:37:52 +000012058 else if (ch < ' ' || ch == 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012059 PyUnicode_WRITE(okind, odata, o++, '\\');
12060 PyUnicode_WRITE(okind, odata, o++, 'x');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012061 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12062 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012063 }
12064
Georg Brandl559e5d72008-06-11 18:37:52 +000012065 /* Copy ASCII characters as-is */
12066 else if (ch < 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012067 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000012068 }
12069
Benjamin Peterson29060642009-01-31 22:14:21 +000012070 /* Non-ASCII characters */
Georg Brandl559e5d72008-06-11 18:37:52 +000012071 else {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012072 /* Map Unicode whitespace and control characters
Georg Brandl559e5d72008-06-11 18:37:52 +000012073 (categories Z* and C* except ASCII space)
12074 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012075 if (!Py_UNICODE_ISPRINTABLE(ch)) {
Georg Brandl559e5d72008-06-11 18:37:52 +000012076 /* Map 8-bit characters to '\xhh' */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012077 if (ch <= 0xff) {
12078 PyUnicode_WRITE(okind, odata, o++, '\\');
12079 PyUnicode_WRITE(okind, odata, o++, 'x');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012080 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12081 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012082 }
12083 /* Map 21-bit characters to '\U00xxxxxx' */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012084 else if (ch >= 0x10000) {
12085 PyUnicode_WRITE(okind, odata, o++, '\\');
12086 PyUnicode_WRITE(okind, odata, o++, 'U');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012087 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 28) & 0xF]);
12088 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 24) & 0xF]);
12089 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 20) & 0xF]);
12090 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 16) & 0xF]);
12091 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12092 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12093 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12094 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012095 }
12096 /* Map 16-bit characters to '\uxxxx' */
12097 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012098 PyUnicode_WRITE(okind, odata, o++, '\\');
12099 PyUnicode_WRITE(okind, odata, o++, 'u');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012100 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12101 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12102 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12103 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012104 }
12105 }
12106 /* Copy characters as-is */
12107 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012108 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000012109 }
12110 }
Walter Dörwald79e913e2007-05-12 11:08:06 +000012111 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012112 /* Closing quote already added at the beginning */
Victor Stinner05d11892011-10-06 01:13:58 +020012113 assert(_PyUnicode_CheckConsistency(repr, 1));
Walter Dörwald79e913e2007-05-12 11:08:06 +000012114 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012115}
12116
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012117PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012118 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012119\n\
12120Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080012121such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012122arguments start and end are interpreted as in slice notation.\n\
12123\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012124Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012125
12126static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012127unicode_rfind(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012128{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012129 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012130 Py_ssize_t start;
12131 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012132 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012133
Jesus Ceaac451502011-04-20 17:09:23 +020012134 if (!stringlib_parse_args_finds_unicode("rfind", args, &substring,
12135 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012136 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012137
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012138 if (PyUnicode_READY(self) == -1)
12139 return NULL;
12140 if (PyUnicode_READY(substring) == -1)
12141 return NULL;
12142
Victor Stinner7931d9a2011-11-04 00:22:48 +010012143 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012144
12145 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012146
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012147 if (result == -2)
12148 return NULL;
12149
Christian Heimes217cfd12007-12-02 14:31:20 +000012150 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012151}
12152
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012153PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012154 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012155\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012156Like S.rfind() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012157
12158static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012159unicode_rindex(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012160{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012161 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012162 Py_ssize_t start;
12163 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012164 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012165
Jesus Ceaac451502011-04-20 17:09:23 +020012166 if (!stringlib_parse_args_finds_unicode("rindex", args, &substring,
12167 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012168 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012169
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012170 if (PyUnicode_READY(self) == -1)
12171 return NULL;
12172 if (PyUnicode_READY(substring) == -1)
12173 return NULL;
12174
Victor Stinner7931d9a2011-11-04 00:22:48 +010012175 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012176
12177 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012178
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012179 if (result == -2)
12180 return NULL;
12181
Guido van Rossumd57fd912000-03-10 22:53:23 +000012182 if (result < 0) {
12183 PyErr_SetString(PyExc_ValueError, "substring not found");
12184 return NULL;
12185 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012186
Christian Heimes217cfd12007-12-02 14:31:20 +000012187 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012188}
12189
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012190PyDoc_STRVAR(rjust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012191 "S.rjust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012192\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012193Return S right-justified in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012194done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012195
12196static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012197unicode_rjust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012198{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012199 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012200 Py_UCS4 fillchar = ' ';
12201
Victor Stinnere9a29352011-10-01 02:14:59 +020012202 if (!PyArg_ParseTuple(args, "n|O&:rjust", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012203 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012204
Victor Stinnere9a29352011-10-01 02:14:59 +020012205 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012206 return NULL;
12207
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012208 if (_PyUnicode_LENGTH(self) >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000012209 Py_INCREF(self);
Victor Stinner7931d9a2011-11-04 00:22:48 +010012210 return self;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012211 }
12212
Victor Stinner7931d9a2011-11-04 00:22:48 +010012213 return pad(self, width - _PyUnicode_LENGTH(self), 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012214}
12215
Alexander Belopolsky40018472011-02-26 01:02:56 +000012216PyObject *
12217PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012218{
12219 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +000012220
Guido van Rossumd57fd912000-03-10 22:53:23 +000012221 s = PyUnicode_FromObject(s);
12222 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012223 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012224 if (sep != NULL) {
12225 sep = PyUnicode_FromObject(sep);
12226 if (sep == NULL) {
12227 Py_DECREF(s);
12228 return NULL;
12229 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012230 }
12231
Victor Stinner9310abb2011-10-05 00:59:23 +020012232 result = split(s, sep, maxsplit);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012233
12234 Py_DECREF(s);
12235 Py_XDECREF(sep);
12236 return result;
12237}
12238
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012239PyDoc_STRVAR(split__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012240 "S.split([sep[, maxsplit]]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012241\n\
12242Return a list of the words in S, using sep as the\n\
12243delimiter string. If maxsplit is given, at most maxsplit\n\
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000012244splits are done. If sep is not specified or is None, any\n\
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +000012245whitespace string is a separator and empty strings are\n\
12246removed from the result.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012247
12248static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012249unicode_split(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012250{
12251 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012252 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012253
Martin v. Löwis18e16552006-02-15 17:27:45 +000012254 if (!PyArg_ParseTuple(args, "|On:split", &substring, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012255 return NULL;
12256
12257 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012258 return split(self, NULL, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012259 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012260 return split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012261 else
Victor Stinner7931d9a2011-11-04 00:22:48 +010012262 return PyUnicode_Split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012263}
12264
Thomas Wouters477c8d52006-05-27 19:21:47 +000012265PyObject *
12266PyUnicode_Partition(PyObject *str_in, PyObject *sep_in)
12267{
12268 PyObject* str_obj;
12269 PyObject* sep_obj;
12270 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012271 int kind1, kind2, kind;
12272 void *buf1 = NULL, *buf2 = NULL;
12273 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012274
12275 str_obj = PyUnicode_FromObject(str_in);
Victor Stinnere9a29352011-10-01 02:14:59 +020012276 if (!str_obj || PyUnicode_READY(str_obj) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000012277 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012278 sep_obj = PyUnicode_FromObject(sep_in);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012279 if (!sep_obj || PyUnicode_READY(sep_obj) == -1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000012280 Py_DECREF(str_obj);
12281 return NULL;
12282 }
12283
Victor Stinner14f8f022011-10-05 20:58:25 +020012284 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012285 kind2 = PyUnicode_KIND(sep_obj);
Victor Stinner14f8f022011-10-05 20:58:25 +020012286 kind = Py_MAX(kind1, kind2);
12287 buf1 = PyUnicode_DATA(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012288 if (kind1 != kind)
Victor Stinner14f8f022011-10-05 20:58:25 +020012289 buf1 = _PyUnicode_AsKind(str_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012290 if (!buf1)
12291 goto onError;
12292 buf2 = PyUnicode_DATA(sep_obj);
12293 if (kind2 != kind)
12294 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12295 if (!buf2)
12296 goto onError;
12297 len1 = PyUnicode_GET_LENGTH(str_obj);
12298 len2 = PyUnicode_GET_LENGTH(sep_obj);
12299
Victor Stinner14f8f022011-10-05 20:58:25 +020012300 switch(PyUnicode_KIND(str_obj)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012301 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012302 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12303 out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12304 else
12305 out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012306 break;
12307 case PyUnicode_2BYTE_KIND:
12308 out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12309 break;
12310 case PyUnicode_4BYTE_KIND:
12311 out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12312 break;
12313 default:
12314 assert(0);
12315 out = 0;
12316 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012317
12318 Py_DECREF(sep_obj);
12319 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012320 if (kind1 != kind)
12321 PyMem_Free(buf1);
12322 if (kind2 != kind)
12323 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012324
12325 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012326 onError:
12327 Py_DECREF(sep_obj);
12328 Py_DECREF(str_obj);
12329 if (kind1 != kind && buf1)
12330 PyMem_Free(buf1);
12331 if (kind2 != kind && buf2)
12332 PyMem_Free(buf2);
12333 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012334}
12335
12336
12337PyObject *
12338PyUnicode_RPartition(PyObject *str_in, PyObject *sep_in)
12339{
12340 PyObject* str_obj;
12341 PyObject* sep_obj;
12342 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012343 int kind1, kind2, kind;
12344 void *buf1 = NULL, *buf2 = NULL;
12345 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012346
12347 str_obj = PyUnicode_FromObject(str_in);
12348 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012349 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012350 sep_obj = PyUnicode_FromObject(sep_in);
12351 if (!sep_obj) {
12352 Py_DECREF(str_obj);
12353 return NULL;
12354 }
12355
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012356 kind1 = PyUnicode_KIND(str_in);
12357 kind2 = PyUnicode_KIND(sep_obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +020012358 kind = Py_MAX(kind1, kind2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012359 buf1 = PyUnicode_DATA(str_in);
12360 if (kind1 != kind)
12361 buf1 = _PyUnicode_AsKind(str_in, kind);
12362 if (!buf1)
12363 goto onError;
12364 buf2 = PyUnicode_DATA(sep_obj);
12365 if (kind2 != kind)
12366 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12367 if (!buf2)
12368 goto onError;
12369 len1 = PyUnicode_GET_LENGTH(str_obj);
12370 len2 = PyUnicode_GET_LENGTH(sep_obj);
12371
12372 switch(PyUnicode_KIND(str_in)) {
12373 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012374 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12375 out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12376 else
12377 out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012378 break;
12379 case PyUnicode_2BYTE_KIND:
12380 out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12381 break;
12382 case PyUnicode_4BYTE_KIND:
12383 out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12384 break;
12385 default:
12386 assert(0);
12387 out = 0;
12388 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012389
12390 Py_DECREF(sep_obj);
12391 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012392 if (kind1 != kind)
12393 PyMem_Free(buf1);
12394 if (kind2 != kind)
12395 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012396
12397 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012398 onError:
12399 Py_DECREF(sep_obj);
12400 Py_DECREF(str_obj);
12401 if (kind1 != kind && buf1)
12402 PyMem_Free(buf1);
12403 if (kind2 != kind && buf2)
12404 PyMem_Free(buf2);
12405 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012406}
12407
12408PyDoc_STRVAR(partition__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012409 "S.partition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012410\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012411Search for the separator sep in S, and return the part before it,\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012412the separator itself, and the part after it. If the separator is not\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012413found, return S and two empty strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012414
12415static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012416unicode_partition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012417{
Victor Stinner9310abb2011-10-05 00:59:23 +020012418 return PyUnicode_Partition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012419}
12420
12421PyDoc_STRVAR(rpartition__doc__,
Ezio Melotti5b2b2422010-01-25 11:58:28 +000012422 "S.rpartition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012423\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012424Search for the separator sep in S, starting at the end of S, and return\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012425the part before it, the separator itself, and the part after it. If the\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012426separator is not found, return two empty strings and S.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012427
12428static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012429unicode_rpartition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012430{
Victor Stinner9310abb2011-10-05 00:59:23 +020012431 return PyUnicode_RPartition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012432}
12433
Alexander Belopolsky40018472011-02-26 01:02:56 +000012434PyObject *
12435PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012436{
12437 PyObject *result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012438
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012439 s = PyUnicode_FromObject(s);
12440 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012441 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012442 if (sep != NULL) {
12443 sep = PyUnicode_FromObject(sep);
12444 if (sep == NULL) {
12445 Py_DECREF(s);
12446 return NULL;
12447 }
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012448 }
12449
Victor Stinner9310abb2011-10-05 00:59:23 +020012450 result = rsplit(s, sep, maxsplit);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012451
12452 Py_DECREF(s);
12453 Py_XDECREF(sep);
12454 return result;
12455}
12456
12457PyDoc_STRVAR(rsplit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012458 "S.rsplit([sep[, maxsplit]]) -> list of strings\n\
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012459\n\
12460Return a list of the words in S, using sep as the\n\
12461delimiter string, starting at the end of the string and\n\
12462working to the front. If maxsplit is given, at most maxsplit\n\
12463splits are done. If sep is not specified, any whitespace string\n\
12464is a separator.");
12465
12466static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012467unicode_rsplit(PyObject *self, PyObject *args)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012468{
12469 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012470 Py_ssize_t maxcount = -1;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012471
Martin v. Löwis18e16552006-02-15 17:27:45 +000012472 if (!PyArg_ParseTuple(args, "|On:rsplit", &substring, &maxcount))
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012473 return NULL;
12474
12475 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012476 return rsplit(self, NULL, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012477 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012478 return rsplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012479 else
Victor Stinner9310abb2011-10-05 00:59:23 +020012480 return PyUnicode_RSplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012481}
12482
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012483PyDoc_STRVAR(splitlines__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012484 "S.splitlines([keepends]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012485\n\
12486Return a list of the lines in S, breaking at line boundaries.\n\
Guido van Rossum86662912000-04-11 15:38:46 +000012487Line breaks are not included in the resulting list unless keepends\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012488is given and true.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012489
12490static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012491unicode_splitlines(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012492{
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012493 static char *kwlist[] = {"keepends", 0};
Guido van Rossum86662912000-04-11 15:38:46 +000012494 int keepends = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012495
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012496 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:splitlines",
12497 kwlist, &keepends))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012498 return NULL;
12499
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012500 return PyUnicode_Splitlines(self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012501}
12502
12503static
Guido van Rossumf15a29f2007-05-04 00:41:39 +000012504PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012505{
Walter Dörwald346737f2007-05-31 10:44:43 +000012506 if (PyUnicode_CheckExact(self)) {
12507 Py_INCREF(self);
12508 return self;
12509 } else
12510 /* Subtype -- return genuine unicode string with the same value. */
Victor Stinner034f6cf2011-09-30 02:26:44 +020012511 return PyUnicode_Copy(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012512}
12513
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012514PyDoc_STRVAR(swapcase__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012515 "S.swapcase() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012516\n\
12517Return a copy of S with uppercase characters converted to lowercase\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012518and vice versa.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012519
12520static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012521unicode_swapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012522{
Guido van Rossumd57fd912000-03-10 22:53:23 +000012523 return fixup(self, fixswapcase);
12524}
12525
Georg Brandlceee0772007-11-27 23:48:05 +000012526PyDoc_STRVAR(maketrans__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012527 "str.maketrans(x[, y[, z]]) -> dict (static method)\n\
Georg Brandlceee0772007-11-27 23:48:05 +000012528\n\
12529Return a translation table usable for str.translate().\n\
12530If there is only one argument, it must be a dictionary mapping Unicode\n\
12531ordinals (integers) or characters to Unicode ordinals, strings or None.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012532Character keys will be then converted to ordinals.\n\
Georg Brandlceee0772007-11-27 23:48:05 +000012533If there are two arguments, they must be strings of equal length, and\n\
12534in the resulting dictionary, each character in x will be mapped to the\n\
12535character at the same position in y. If there is a third argument, it\n\
12536must be a string, whose characters will be mapped to None in the result.");
12537
12538static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012539unicode_maketrans(PyObject *null, PyObject *args)
Georg Brandlceee0772007-11-27 23:48:05 +000012540{
12541 PyObject *x, *y = NULL, *z = NULL;
12542 PyObject *new = NULL, *key, *value;
12543 Py_ssize_t i = 0;
12544 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012545
Georg Brandlceee0772007-11-27 23:48:05 +000012546 if (!PyArg_ParseTuple(args, "O|UU:maketrans", &x, &y, &z))
12547 return NULL;
12548 new = PyDict_New();
12549 if (!new)
12550 return NULL;
12551 if (y != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012552 int x_kind, y_kind, z_kind;
12553 void *x_data, *y_data, *z_data;
12554
Georg Brandlceee0772007-11-27 23:48:05 +000012555 /* x must be a string too, of equal length */
Georg Brandlceee0772007-11-27 23:48:05 +000012556 if (!PyUnicode_Check(x)) {
12557 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
12558 "be a string if there is a second argument");
12559 goto err;
12560 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012561 if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012562 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
12563 "arguments must have equal length");
12564 goto err;
12565 }
12566 /* create entries for translating chars in x to those in y */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012567 x_kind = PyUnicode_KIND(x);
12568 y_kind = PyUnicode_KIND(y);
12569 x_data = PyUnicode_DATA(x);
12570 y_data = PyUnicode_DATA(y);
12571 for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
12572 key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
12573 value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000012574 if (!key || !value)
12575 goto err;
12576 res = PyDict_SetItem(new, key, value);
12577 Py_DECREF(key);
12578 Py_DECREF(value);
12579 if (res < 0)
12580 goto err;
12581 }
12582 /* create entries for deleting chars in z */
12583 if (z != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012584 z_kind = PyUnicode_KIND(z);
12585 z_data = PyUnicode_DATA(z);
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012586 for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012587 key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000012588 if (!key)
12589 goto err;
12590 res = PyDict_SetItem(new, key, Py_None);
12591 Py_DECREF(key);
12592 if (res < 0)
12593 goto err;
12594 }
12595 }
12596 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012597 int kind;
12598 void *data;
12599
Georg Brandlceee0772007-11-27 23:48:05 +000012600 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +000012601 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012602 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
12603 "to maketrans it must be a dict");
12604 goto err;
12605 }
12606 /* copy entries into the new dict, converting string keys to int keys */
12607 while (PyDict_Next(x, &i, &key, &value)) {
12608 if (PyUnicode_Check(key)) {
12609 /* convert string keys to integer keys */
12610 PyObject *newkey;
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012611 if (PyUnicode_GET_LENGTH(key) != 1) {
Georg Brandlceee0772007-11-27 23:48:05 +000012612 PyErr_SetString(PyExc_ValueError, "string keys in translate "
12613 "table must be of length 1");
12614 goto err;
12615 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012616 kind = PyUnicode_KIND(key);
12617 data = PyUnicode_DATA(key);
12618 newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
Georg Brandlceee0772007-11-27 23:48:05 +000012619 if (!newkey)
12620 goto err;
12621 res = PyDict_SetItem(new, newkey, value);
12622 Py_DECREF(newkey);
12623 if (res < 0)
12624 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +000012625 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012626 /* just keep integer keys */
12627 if (PyDict_SetItem(new, key, value) < 0)
12628 goto err;
12629 } else {
12630 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
12631 "be strings or integers");
12632 goto err;
12633 }
12634 }
12635 }
12636 return new;
12637 err:
12638 Py_DECREF(new);
12639 return NULL;
12640}
12641
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012642PyDoc_STRVAR(translate__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012643 "S.translate(table) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012644\n\
12645Return a copy of the string S, where all characters have been mapped\n\
12646through the given translation table, which must be a mapping of\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012647Unicode ordinals to Unicode ordinals, strings, or None.\n\
Walter Dörwald5c1ee172002-09-04 20:31:32 +000012648Unmapped characters are left untouched. Characters mapped to None\n\
12649are deleted.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012650
12651static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012652unicode_translate(PyObject *self, PyObject *table)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012653{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012654 return _PyUnicode_TranslateCharmap(self, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012655}
12656
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012657PyDoc_STRVAR(upper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012658 "S.upper() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012659\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012660Return a copy of S converted to uppercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012661
12662static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012663unicode_upper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012664{
Guido van Rossumd57fd912000-03-10 22:53:23 +000012665 return fixup(self, fixupper);
12666}
12667
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012668PyDoc_STRVAR(zfill__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012669 "S.zfill(width) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012670\n\
Benjamin Peterson9aa42992008-09-10 21:57:34 +000012671Pad a numeric string S with zeros on the left, to fill a field\n\
12672of the specified width. The string S is never truncated.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012673
12674static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012675unicode_zfill(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012676{
Martin v. Löwis18e16552006-02-15 17:27:45 +000012677 Py_ssize_t fill;
Victor Stinner9310abb2011-10-05 00:59:23 +020012678 PyObject *u;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012679 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012680 int kind;
12681 void *data;
12682 Py_UCS4 chr;
12683
12684 if (PyUnicode_READY(self) == -1)
12685 return NULL;
12686
Martin v. Löwis18e16552006-02-15 17:27:45 +000012687 if (!PyArg_ParseTuple(args, "n:zfill", &width))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012688 return NULL;
12689
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012690 if (PyUnicode_GET_LENGTH(self) >= width) {
Walter Dörwald0fe940c2002-04-15 18:42:15 +000012691 if (PyUnicode_CheckExact(self)) {
12692 Py_INCREF(self);
Victor Stinner7931d9a2011-11-04 00:22:48 +010012693 return self;
Walter Dörwald0fe940c2002-04-15 18:42:15 +000012694 }
12695 else
Victor Stinner7931d9a2011-11-04 00:22:48 +010012696 return PyUnicode_Copy(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012697 }
12698
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012699 fill = width - _PyUnicode_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012700
12701 u = pad(self, fill, 0, '0');
12702
Walter Dörwald068325e2002-04-15 13:36:47 +000012703 if (u == NULL)
12704 return NULL;
12705
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012706 kind = PyUnicode_KIND(u);
12707 data = PyUnicode_DATA(u);
12708 chr = PyUnicode_READ(kind, data, fill);
12709
12710 if (chr == '+' || chr == '-') {
Guido van Rossumd57fd912000-03-10 22:53:23 +000012711 /* move sign to beginning of string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012712 PyUnicode_WRITE(kind, data, 0, chr);
12713 PyUnicode_WRITE(kind, data, fill, '0');
Guido van Rossumd57fd912000-03-10 22:53:23 +000012714 }
12715
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012716 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +010012717 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012718}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012719
12720#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012721static PyObject *
12722unicode__decimal2ascii(PyObject *self)
12723{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012724 return PyUnicode_TransformDecimalAndSpaceToASCII(self);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012725}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012726#endif
12727
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012728PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012729 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012730\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000012731Return True if S starts with the specified prefix, False otherwise.\n\
12732With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012733With optional end, stop comparing S at that position.\n\
12734prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012735
12736static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012737unicode_startswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000012738 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012739{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012740 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012741 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012742 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012743 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012744 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012745
Jesus Ceaac451502011-04-20 17:09:23 +020012746 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000012747 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012748 if (PyTuple_Check(subobj)) {
12749 Py_ssize_t i;
12750 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012751 substring = PyUnicode_FromObject(PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012752 if (substring == NULL)
12753 return NULL;
12754 result = tailmatch(self, substring, start, end, -1);
12755 Py_DECREF(substring);
12756 if (result) {
12757 Py_RETURN_TRUE;
12758 }
12759 }
12760 /* nothing matched */
12761 Py_RETURN_FALSE;
12762 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012763 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030012764 if (substring == NULL) {
12765 if (PyErr_ExceptionMatches(PyExc_TypeError))
12766 PyErr_Format(PyExc_TypeError, "startswith first arg must be str or "
12767 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000012768 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030012769 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012770 result = tailmatch(self, substring, start, end, -1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012771 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012772 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012773}
12774
12775
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012776PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012777 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012778\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000012779Return True if S ends with the specified suffix, False otherwise.\n\
12780With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012781With optional end, stop comparing S at that position.\n\
12782suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012783
12784static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012785unicode_endswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000012786 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012787{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012788 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012789 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012790 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012791 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012792 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012793
Jesus Ceaac451502011-04-20 17:09:23 +020012794 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000012795 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012796 if (PyTuple_Check(subobj)) {
12797 Py_ssize_t i;
12798 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012799 substring = PyUnicode_FromObject(
Benjamin Peterson29060642009-01-31 22:14:21 +000012800 PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012801 if (substring == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000012802 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012803 result = tailmatch(self, substring, start, end, +1);
12804 Py_DECREF(substring);
12805 if (result) {
12806 Py_RETURN_TRUE;
12807 }
12808 }
12809 Py_RETURN_FALSE;
12810 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012811 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030012812 if (substring == NULL) {
12813 if (PyErr_ExceptionMatches(PyExc_TypeError))
12814 PyErr_Format(PyExc_TypeError, "endswith first arg must be str or "
12815 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000012816 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030012817 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012818 result = tailmatch(self, substring, start, end, +1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012819 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012820 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012821}
12822
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012823#include "stringlib/unicode_format.h"
Eric Smith8c663262007-08-25 02:26:07 +000012824
12825PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012826 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000012827\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012828Return a formatted version of S, using substitutions from args and kwargs.\n\
12829The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +000012830
Eric Smith27bbca62010-11-04 17:06:58 +000012831PyDoc_STRVAR(format_map__doc__,
12832 "S.format_map(mapping) -> str\n\
12833\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012834Return a formatted version of S, using substitutions from mapping.\n\
12835The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +000012836
Eric Smith4a7d76d2008-05-30 18:10:19 +000012837static PyObject *
12838unicode__format__(PyObject* self, PyObject* args)
12839{
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012840 PyObject *format_spec, *out;
Eric Smith4a7d76d2008-05-30 18:10:19 +000012841
12842 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
12843 return NULL;
12844
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012845 out = _PyUnicode_FormatAdvanced(self, format_spec, 0,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012846 PyUnicode_GET_LENGTH(format_spec));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012847 return out;
Eric Smith4a7d76d2008-05-30 18:10:19 +000012848}
12849
Eric Smith8c663262007-08-25 02:26:07 +000012850PyDoc_STRVAR(p_format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012851 "S.__format__(format_spec) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000012852\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012853Return a formatted version of S as described by format_spec.");
Eric Smith8c663262007-08-25 02:26:07 +000012854
12855static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012856unicode__sizeof__(PyObject *v)
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012857{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012858 Py_ssize_t size;
12859
12860 /* If it's a compact object, account for base structure +
12861 character data. */
12862 if (PyUnicode_IS_COMPACT_ASCII(v))
12863 size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(v) + 1;
12864 else if (PyUnicode_IS_COMPACT(v))
12865 size = sizeof(PyCompactUnicodeObject) +
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012866 (PyUnicode_GET_LENGTH(v) + 1) * PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012867 else {
12868 /* If it is a two-block object, account for base object, and
12869 for character block if present. */
12870 size = sizeof(PyUnicodeObject);
Victor Stinnerc3c74152011-10-02 20:39:55 +020012871 if (_PyUnicode_DATA_ANY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012872 size += (PyUnicode_GET_LENGTH(v) + 1) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012873 PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012874 }
12875 /* If the wstr pointer is present, account for it unless it is shared
Victor Stinnera3be6132011-10-03 02:16:37 +020012876 with the data pointer. Check if the data is not shared. */
Victor Stinner03490912011-10-03 23:45:12 +020012877 if (_PyUnicode_HAS_WSTR_MEMORY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012878 size += (PyUnicode_WSTR_LENGTH(v) + 1) * sizeof(wchar_t);
Victor Stinner829c0ad2011-10-03 01:08:02 +020012879 if (_PyUnicode_HAS_UTF8_MEMORY(v))
Victor Stinnere90fe6a2011-10-01 16:48:13 +020012880 size += PyUnicode_UTF8_LENGTH(v) + 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012881
12882 return PyLong_FromSsize_t(size);
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012883}
12884
12885PyDoc_STRVAR(sizeof__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012886 "S.__sizeof__() -> size of S in memory, in bytes");
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012887
12888static PyObject *
Victor Stinner034f6cf2011-09-30 02:26:44 +020012889unicode_getnewargs(PyObject *v)
Guido van Rossum5d9113d2003-01-29 17:58:45 +000012890{
Victor Stinner034f6cf2011-09-30 02:26:44 +020012891 PyObject *copy = PyUnicode_Copy(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012892 if (!copy)
12893 return NULL;
12894 return Py_BuildValue("(N)", copy);
Guido van Rossum5d9113d2003-01-29 17:58:45 +000012895}
12896
Guido van Rossumd57fd912000-03-10 22:53:23 +000012897static PyMethodDef unicode_methods[] = {
12898
12899 /* Order is according to common usage: often used methods should
12900 appear first, since lookup is done sequentially. */
12901
Benjamin Peterson28a4dce2010-12-12 01:33:04 +000012902 {"encode", (PyCFunction) unicode_encode, METH_VARARGS | METH_KEYWORDS, encode__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012903 {"replace", (PyCFunction) unicode_replace, METH_VARARGS, replace__doc__},
12904 {"split", (PyCFunction) unicode_split, METH_VARARGS, split__doc__},
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012905 {"rsplit", (PyCFunction) unicode_rsplit, METH_VARARGS, rsplit__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012906 {"join", (PyCFunction) unicode_join, METH_O, join__doc__},
12907 {"capitalize", (PyCFunction) unicode_capitalize, METH_NOARGS, capitalize__doc__},
12908 {"title", (PyCFunction) unicode_title, METH_NOARGS, title__doc__},
12909 {"center", (PyCFunction) unicode_center, METH_VARARGS, center__doc__},
12910 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
12911 {"expandtabs", (PyCFunction) unicode_expandtabs, METH_VARARGS, expandtabs__doc__},
12912 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000012913 {"partition", (PyCFunction) unicode_partition, METH_O, partition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012914 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
12915 {"ljust", (PyCFunction) unicode_ljust, METH_VARARGS, ljust__doc__},
12916 {"lower", (PyCFunction) unicode_lower, METH_NOARGS, lower__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012917 {"lstrip", (PyCFunction) unicode_lstrip, METH_VARARGS, lstrip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012918 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
12919 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
12920 {"rjust", (PyCFunction) unicode_rjust, METH_VARARGS, rjust__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012921 {"rstrip", (PyCFunction) unicode_rstrip, METH_VARARGS, rstrip__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000012922 {"rpartition", (PyCFunction) unicode_rpartition, METH_O, rpartition__doc__},
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012923 {"splitlines", (PyCFunction) unicode_splitlines, METH_VARARGS | METH_KEYWORDS, splitlines__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012924 {"strip", (PyCFunction) unicode_strip, METH_VARARGS, strip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012925 {"swapcase", (PyCFunction) unicode_swapcase, METH_NOARGS, swapcase__doc__},
12926 {"translate", (PyCFunction) unicode_translate, METH_O, translate__doc__},
12927 {"upper", (PyCFunction) unicode_upper, METH_NOARGS, upper__doc__},
12928 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
12929 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
12930 {"islower", (PyCFunction) unicode_islower, METH_NOARGS, islower__doc__},
12931 {"isupper", (PyCFunction) unicode_isupper, METH_NOARGS, isupper__doc__},
12932 {"istitle", (PyCFunction) unicode_istitle, METH_NOARGS, istitle__doc__},
12933 {"isspace", (PyCFunction) unicode_isspace, METH_NOARGS, isspace__doc__},
12934 {"isdecimal", (PyCFunction) unicode_isdecimal, METH_NOARGS, isdecimal__doc__},
12935 {"isdigit", (PyCFunction) unicode_isdigit, METH_NOARGS, isdigit__doc__},
12936 {"isnumeric", (PyCFunction) unicode_isnumeric, METH_NOARGS, isnumeric__doc__},
12937 {"isalpha", (PyCFunction) unicode_isalpha, METH_NOARGS, isalpha__doc__},
12938 {"isalnum", (PyCFunction) unicode_isalnum, METH_NOARGS, isalnum__doc__},
Martin v. Löwis47383402007-08-15 07:32:56 +000012939 {"isidentifier", (PyCFunction) unicode_isidentifier, METH_NOARGS, isidentifier__doc__},
Georg Brandl559e5d72008-06-11 18:37:52 +000012940 {"isprintable", (PyCFunction) unicode_isprintable, METH_NOARGS, isprintable__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012941 {"zfill", (PyCFunction) unicode_zfill, METH_VARARGS, zfill__doc__},
Eric Smith9cd1e092007-08-31 18:39:38 +000012942 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +000012943 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
Eric Smith4a7d76d2008-05-30 18:10:19 +000012944 {"__format__", (PyCFunction) unicode__format__, METH_VARARGS, p_format__doc__},
Georg Brandlceee0772007-11-27 23:48:05 +000012945 {"maketrans", (PyCFunction) unicode_maketrans,
12946 METH_VARARGS | METH_STATIC, maketrans__doc__},
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012947 {"__sizeof__", (PyCFunction) unicode__sizeof__, METH_NOARGS, sizeof__doc__},
Walter Dörwald068325e2002-04-15 13:36:47 +000012948#if 0
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012949 {"capwords", (PyCFunction) unicode_capwords, METH_NOARGS, capwords__doc__},
Guido van Rossumd57fd912000-03-10 22:53:23 +000012950#endif
12951
12952#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012953 /* These methods are just used for debugging the implementation. */
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012954 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000012955#endif
12956
Benjamin Peterson14339b62009-01-31 16:36:08 +000012957 {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000012958 {NULL, NULL}
12959};
12960
Neil Schemenauerce30bc92002-11-18 16:10:18 +000012961static PyObject *
12962unicode_mod(PyObject *v, PyObject *w)
12963{
Brian Curtindfc80e32011-08-10 20:28:54 -050012964 if (!PyUnicode_Check(v))
12965 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson29060642009-01-31 22:14:21 +000012966 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +000012967}
12968
12969static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012970 0, /*nb_add*/
12971 0, /*nb_subtract*/
12972 0, /*nb_multiply*/
12973 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +000012974};
12975
Guido van Rossumd57fd912000-03-10 22:53:23 +000012976static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012977 (lenfunc) unicode_length, /* sq_length */
12978 PyUnicode_Concat, /* sq_concat */
12979 (ssizeargfunc) unicode_repeat, /* sq_repeat */
12980 (ssizeargfunc) unicode_getitem, /* sq_item */
12981 0, /* sq_slice */
12982 0, /* sq_ass_item */
12983 0, /* sq_ass_slice */
12984 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +000012985};
12986
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012987static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012988unicode_subscript(PyObject* self, PyObject* item)
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012989{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012990 if (PyUnicode_READY(self) == -1)
12991 return NULL;
12992
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000012993 if (PyIndex_Check(item)) {
12994 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012995 if (i == -1 && PyErr_Occurred())
12996 return NULL;
12997 if (i < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012998 i += PyUnicode_GET_LENGTH(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012999 return unicode_getitem(self, i);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013000 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000013001 Py_ssize_t start, stop, step, slicelength, cur, i;
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013002 PyObject *result;
13003 void *src_data, *dest_data;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013004 int src_kind, dest_kind;
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013005 Py_UCS4 ch, max_char, kind_limit;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013006
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013007 if (PySlice_GetIndicesEx(item, PyUnicode_GET_LENGTH(self),
Benjamin Peterson29060642009-01-31 22:14:21 +000013008 &start, &stop, &step, &slicelength) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013009 return NULL;
13010 }
13011
13012 if (slicelength <= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013013 return PyUnicode_New(0, 0);
13014 } else if (start == 0 && step == 1 &&
13015 slicelength == PyUnicode_GET_LENGTH(self) &&
Thomas Woutersed03b412007-08-28 21:37:11 +000013016 PyUnicode_CheckExact(self)) {
13017 Py_INCREF(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013018 return self;
Thomas Woutersed03b412007-08-28 21:37:11 +000013019 } else if (step == 1) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013020 return PyUnicode_Substring(self,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013021 start, start + slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013022 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013023 /* General case */
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013024 src_kind = PyUnicode_KIND(self);
13025 src_data = PyUnicode_DATA(self);
Victor Stinner55c99112011-10-13 01:17:06 +020013026 if (!PyUnicode_IS_ASCII(self)) {
13027 kind_limit = kind_maxchar_limit(src_kind);
13028 max_char = 0;
13029 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
13030 ch = PyUnicode_READ(src_kind, src_data, cur);
13031 if (ch > max_char) {
13032 max_char = ch;
13033 if (max_char >= kind_limit)
13034 break;
13035 }
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013036 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013037 }
Victor Stinner55c99112011-10-13 01:17:06 +020013038 else
13039 max_char = 127;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013040 result = PyUnicode_New(slicelength, max_char);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013041 if (result == NULL)
13042 return NULL;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013043 dest_kind = PyUnicode_KIND(result);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013044 dest_data = PyUnicode_DATA(result);
13045
13046 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013047 Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
13048 PyUnicode_WRITE(dest_kind, dest_data, i, ch);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013049 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013050 assert(_PyUnicode_CheckConsistency(result, 1));
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013051 return result;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013052 } else {
13053 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
13054 return NULL;
13055 }
13056}
13057
13058static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013059 (lenfunc)unicode_length, /* mp_length */
13060 (binaryfunc)unicode_subscript, /* mp_subscript */
13061 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013062};
13063
Guido van Rossumd57fd912000-03-10 22:53:23 +000013064
Guido van Rossumd57fd912000-03-10 22:53:23 +000013065/* Helpers for PyUnicode_Format() */
13066
13067static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +000013068getnextarg(PyObject *args, Py_ssize_t arglen, Py_ssize_t *p_argidx)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013069{
Martin v. Löwis18e16552006-02-15 17:27:45 +000013070 Py_ssize_t argidx = *p_argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013071 if (argidx < arglen) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013072 (*p_argidx)++;
13073 if (arglen < 0)
13074 return args;
13075 else
13076 return PyTuple_GetItem(args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013077 }
13078 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013079 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013080 return NULL;
13081}
13082
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013083/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013084
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013085static PyObject *
13086formatfloat(PyObject *v, int flags, int prec, int type)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013087{
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013088 char *p;
13089 PyObject *result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013090 double x;
Tim Petersced69f82003-09-16 20:30:58 +000013091
Guido van Rossumd57fd912000-03-10 22:53:23 +000013092 x = PyFloat_AsDouble(v);
13093 if (x == -1.0 && PyErr_Occurred())
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013094 return NULL;
13095
Guido van Rossumd57fd912000-03-10 22:53:23 +000013096 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000013097 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +000013098
Eric Smith0923d1d2009-04-16 20:16:10 +000013099 p = PyOS_double_to_string(x, type, prec,
13100 (flags & F_ALT) ? Py_DTSF_ALT : 0, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013101 if (p == NULL)
13102 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013103 result = PyUnicode_DecodeASCII(p, strlen(p), NULL);
Eric Smith0923d1d2009-04-16 20:16:10 +000013104 PyMem_Free(p);
13105 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013106}
13107
Tim Peters38fd5b62000-09-21 05:43:11 +000013108static PyObject*
13109formatlong(PyObject *val, int flags, int prec, int type)
13110{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013111 char *buf;
13112 int len;
13113 PyObject *str; /* temporary string object. */
13114 PyObject *result;
Tim Peters38fd5b62000-09-21 05:43:11 +000013115
Benjamin Peterson14339b62009-01-31 16:36:08 +000013116 str = _PyBytes_FormatLong(val, flags, prec, type, &buf, &len);
13117 if (!str)
13118 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013119 result = PyUnicode_DecodeASCII(buf, len, NULL);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013120 Py_DECREF(str);
13121 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +000013122}
13123
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013124static Py_UCS4
13125formatchar(PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013126{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000013127 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000013128 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013129 if (PyUnicode_GET_LENGTH(v) == 1) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013130 return PyUnicode_READ_CHAR(v, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +000013131 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013132 goto onError;
13133 }
13134 else {
13135 /* Integer input truncated to a character */
13136 long x;
13137 x = PyLong_AsLong(v);
13138 if (x == -1 && PyErr_Occurred())
13139 goto onError;
13140
13141 if (x < 0 || x > 0x10ffff) {
13142 PyErr_SetString(PyExc_OverflowError,
13143 "%c arg not in range(0x110000)");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013144 return (Py_UCS4) -1;
Benjamin Peterson29060642009-01-31 22:14:21 +000013145 }
13146
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013147 return (Py_UCS4) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013148 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000013149
Benjamin Peterson29060642009-01-31 22:14:21 +000013150 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000013151 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013152 "%c requires int or char");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013153 return (Py_UCS4) -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013154}
13155
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013156static int
13157repeat_accumulate(_PyAccu *acc, PyObject *obj, Py_ssize_t count)
13158{
13159 int r;
13160 assert(count > 0);
13161 assert(PyUnicode_Check(obj));
13162 if (count > 5) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013163 PyObject *repeated = unicode_repeat(obj, count);
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013164 if (repeated == NULL)
13165 return -1;
13166 r = _PyAccu_Accumulate(acc, repeated);
13167 Py_DECREF(repeated);
13168 return r;
13169 }
13170 else {
13171 do {
13172 if (_PyAccu_Accumulate(acc, obj))
13173 return -1;
13174 } while (--count);
13175 return 0;
13176 }
13177}
13178
Alexander Belopolsky40018472011-02-26 01:02:56 +000013179PyObject *
13180PyUnicode_Format(PyObject *format, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013181{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013182 void *fmt;
13183 int fmtkind;
13184 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013185 int kind;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013186 int r;
13187 Py_ssize_t fmtcnt, fmtpos, arglen, argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013188 int args_owned = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013189 PyObject *dict = NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013190 PyObject *temp = NULL;
13191 PyObject *second = NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013192 PyObject *uformat;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013193 _PyAccu acc;
13194 static PyObject *plus, *minus, *blank, *zero, *percent;
13195
13196 if (!plus && !(plus = get_latin1_char('+')))
13197 return NULL;
13198 if (!minus && !(minus = get_latin1_char('-')))
13199 return NULL;
13200 if (!blank && !(blank = get_latin1_char(' ')))
13201 return NULL;
13202 if (!zero && !(zero = get_latin1_char('0')))
13203 return NULL;
13204 if (!percent && !(percent = get_latin1_char('%')))
13205 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000013206
Guido van Rossumd57fd912000-03-10 22:53:23 +000013207 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013208 PyErr_BadInternalCall();
13209 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013210 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013211 uformat = PyUnicode_FromObject(format);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013212 if (uformat == NULL || PyUnicode_READY(uformat) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000013213 return NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013214 if (_PyAccu_Init(&acc))
13215 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013216 fmt = PyUnicode_DATA(uformat);
13217 fmtkind = PyUnicode_KIND(uformat);
13218 fmtcnt = PyUnicode_GET_LENGTH(uformat);
13219 fmtpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013220
Guido van Rossumd57fd912000-03-10 22:53:23 +000013221 if (PyTuple_Check(args)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013222 arglen = PyTuple_Size(args);
13223 argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013224 }
13225 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013226 arglen = -1;
13227 argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013228 }
Christian Heimes90aa7642007-12-19 02:45:37 +000013229 if (Py_TYPE(args)->tp_as_mapping && !PyTuple_Check(args) &&
Christian Heimesf3863112007-11-22 07:46:41 +000013230 !PyUnicode_Check(args))
Benjamin Peterson29060642009-01-31 22:14:21 +000013231 dict = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013232
13233 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013234 if (PyUnicode_READ(fmtkind, fmt, fmtpos) != '%') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013235 PyObject *nonfmt;
13236 Py_ssize_t nonfmtpos;
13237 nonfmtpos = fmtpos++;
13238 while (fmtcnt >= 0 &&
13239 PyUnicode_READ(fmtkind, fmt, fmtpos) != '%') {
13240 fmtpos++;
13241 fmtcnt--;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013242 }
Victor Stinner7931d9a2011-11-04 00:22:48 +010013243 nonfmt = PyUnicode_Substring(uformat, nonfmtpos, fmtpos);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013244 if (nonfmt == NULL)
13245 goto onError;
13246 r = _PyAccu_Accumulate(&acc, nonfmt);
13247 Py_DECREF(nonfmt);
13248 if (r)
13249 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013250 }
13251 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013252 /* Got a format specifier */
13253 int flags = 0;
13254 Py_ssize_t width = -1;
13255 int prec = -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013256 Py_UCS4 c = '\0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013257 Py_UCS4 fill, sign;
Benjamin Peterson29060642009-01-31 22:14:21 +000013258 int isnumok;
13259 PyObject *v = NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013260 void *pbuf = NULL;
13261 Py_ssize_t pindex, len;
13262 PyObject *signobj = NULL, *fillobj = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013263
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013264 fmtpos++;
13265 if (PyUnicode_READ(fmtkind, fmt, fmtpos) == '(') {
13266 Py_ssize_t keystart;
Benjamin Peterson29060642009-01-31 22:14:21 +000013267 Py_ssize_t keylen;
13268 PyObject *key;
13269 int pcount = 1;
Christian Heimesa612dc02008-02-24 13:08:18 +000013270
Benjamin Peterson29060642009-01-31 22:14:21 +000013271 if (dict == NULL) {
13272 PyErr_SetString(PyExc_TypeError,
13273 "format requires a mapping");
13274 goto onError;
13275 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013276 ++fmtpos;
Benjamin Peterson29060642009-01-31 22:14:21 +000013277 --fmtcnt;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013278 keystart = fmtpos;
Benjamin Peterson29060642009-01-31 22:14:21 +000013279 /* Skip over balanced parentheses */
13280 while (pcount > 0 && --fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013281 if (PyUnicode_READ(fmtkind, fmt, fmtpos) == ')')
Benjamin Peterson29060642009-01-31 22:14:21 +000013282 --pcount;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013283 else if (PyUnicode_READ(fmtkind, fmt, fmtpos) == '(')
Benjamin Peterson29060642009-01-31 22:14:21 +000013284 ++pcount;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013285 fmtpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +000013286 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013287 keylen = fmtpos - keystart - 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000013288 if (fmtcnt < 0 || pcount > 0) {
13289 PyErr_SetString(PyExc_ValueError,
13290 "incomplete format key");
13291 goto onError;
13292 }
Victor Stinner7931d9a2011-11-04 00:22:48 +010013293 key = PyUnicode_Substring(uformat,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013294 keystart, keystart + keylen);
Benjamin Peterson29060642009-01-31 22:14:21 +000013295 if (key == NULL)
13296 goto onError;
13297 if (args_owned) {
13298 Py_DECREF(args);
13299 args_owned = 0;
13300 }
13301 args = PyObject_GetItem(dict, key);
13302 Py_DECREF(key);
13303 if (args == NULL) {
13304 goto onError;
13305 }
13306 args_owned = 1;
13307 arglen = -1;
13308 argidx = -2;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013309 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013310 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013311 switch (c = PyUnicode_READ(fmtkind, fmt, fmtpos++)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013312 case '-': flags |= F_LJUST; continue;
13313 case '+': flags |= F_SIGN; continue;
13314 case ' ': flags |= F_BLANK; continue;
13315 case '#': flags |= F_ALT; continue;
13316 case '0': flags |= F_ZERO; continue;
13317 }
13318 break;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013319 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013320 if (c == '*') {
13321 v = getnextarg(args, arglen, &argidx);
13322 if (v == NULL)
13323 goto onError;
13324 if (!PyLong_Check(v)) {
13325 PyErr_SetString(PyExc_TypeError,
13326 "* wants int");
13327 goto onError;
13328 }
13329 width = PyLong_AsLong(v);
13330 if (width == -1 && PyErr_Occurred())
13331 goto onError;
13332 if (width < 0) {
13333 flags |= F_LJUST;
13334 width = -width;
13335 }
13336 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013337 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013338 }
13339 else if (c >= '0' && c <= '9') {
13340 width = c - '0';
13341 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013342 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013343 if (c < '0' || c > '9')
13344 break;
13345 if ((width*10) / 10 != width) {
13346 PyErr_SetString(PyExc_ValueError,
13347 "width too big");
Benjamin Peterson14339b62009-01-31 16:36:08 +000013348 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +000013349 }
13350 width = width*10 + (c - '0');
13351 }
13352 }
13353 if (c == '.') {
13354 prec = 0;
13355 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013356 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013357 if (c == '*') {
13358 v = getnextarg(args, arglen, &argidx);
13359 if (v == NULL)
13360 goto onError;
13361 if (!PyLong_Check(v)) {
13362 PyErr_SetString(PyExc_TypeError,
13363 "* wants int");
13364 goto onError;
13365 }
13366 prec = PyLong_AsLong(v);
13367 if (prec == -1 && PyErr_Occurred())
13368 goto onError;
13369 if (prec < 0)
13370 prec = 0;
13371 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013372 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013373 }
13374 else if (c >= '0' && c <= '9') {
13375 prec = c - '0';
13376 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013377 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013378 if (c < '0' || c > '9')
13379 break;
13380 if ((prec*10) / 10 != prec) {
13381 PyErr_SetString(PyExc_ValueError,
13382 "prec too big");
13383 goto onError;
13384 }
13385 prec = prec*10 + (c - '0');
13386 }
13387 }
13388 } /* prec */
13389 if (fmtcnt >= 0) {
13390 if (c == 'h' || c == 'l' || c == 'L') {
13391 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013392 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013393 }
13394 }
13395 if (fmtcnt < 0) {
13396 PyErr_SetString(PyExc_ValueError,
13397 "incomplete format");
13398 goto onError;
13399 }
13400 if (c != '%') {
13401 v = getnextarg(args, arglen, &argidx);
13402 if (v == NULL)
13403 goto onError;
13404 }
13405 sign = 0;
13406 fill = ' ';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013407 fillobj = blank;
Benjamin Peterson29060642009-01-31 22:14:21 +000013408 switch (c) {
13409
13410 case '%':
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013411 _PyAccu_Accumulate(&acc, percent);
13412 continue;
Benjamin Peterson29060642009-01-31 22:14:21 +000013413
13414 case 's':
13415 case 'r':
13416 case 'a':
Victor Stinner808fc0a2010-03-22 12:50:40 +000013417 if (PyUnicode_CheckExact(v) && c == 's') {
Benjamin Peterson29060642009-01-31 22:14:21 +000013418 temp = v;
13419 Py_INCREF(temp);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013420 }
13421 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013422 if (c == 's')
13423 temp = PyObject_Str(v);
13424 else if (c == 'r')
13425 temp = PyObject_Repr(v);
13426 else
13427 temp = PyObject_ASCII(v);
13428 if (temp == NULL)
13429 goto onError;
13430 if (PyUnicode_Check(temp))
13431 /* nothing to do */;
13432 else {
13433 Py_DECREF(temp);
13434 PyErr_SetString(PyExc_TypeError,
13435 "%s argument has non-string str()");
13436 goto onError;
13437 }
13438 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013439 if (PyUnicode_READY(temp) == -1) {
13440 Py_CLEAR(temp);
13441 goto onError;
13442 }
13443 pbuf = PyUnicode_DATA(temp);
13444 kind = PyUnicode_KIND(temp);
13445 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013446 if (prec >= 0 && len > prec)
13447 len = prec;
13448 break;
13449
13450 case 'i':
13451 case 'd':
13452 case 'u':
13453 case 'o':
13454 case 'x':
13455 case 'X':
Benjamin Peterson29060642009-01-31 22:14:21 +000013456 isnumok = 0;
13457 if (PyNumber_Check(v)) {
13458 PyObject *iobj=NULL;
13459
13460 if (PyLong_Check(v)) {
13461 iobj = v;
13462 Py_INCREF(iobj);
13463 }
13464 else {
13465 iobj = PyNumber_Long(v);
13466 }
13467 if (iobj!=NULL) {
13468 if (PyLong_Check(iobj)) {
13469 isnumok = 1;
Senthil Kumaran9ebe08d2011-07-03 21:03:16 -070013470 temp = formatlong(iobj, flags, prec, (c == 'i'? 'd': c));
Benjamin Peterson29060642009-01-31 22:14:21 +000013471 Py_DECREF(iobj);
13472 if (!temp)
13473 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013474 if (PyUnicode_READY(temp) == -1) {
13475 Py_CLEAR(temp);
13476 goto onError;
13477 }
13478 pbuf = PyUnicode_DATA(temp);
13479 kind = PyUnicode_KIND(temp);
13480 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013481 sign = 1;
13482 }
13483 else {
13484 Py_DECREF(iobj);
13485 }
13486 }
13487 }
13488 if (!isnumok) {
13489 PyErr_Format(PyExc_TypeError,
13490 "%%%c format: a number is required, "
13491 "not %.200s", (char)c, Py_TYPE(v)->tp_name);
13492 goto onError;
13493 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013494 if (flags & F_ZERO) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013495 fill = '0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013496 fillobj = zero;
13497 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013498 break;
13499
13500 case 'e':
13501 case 'E':
13502 case 'f':
13503 case 'F':
13504 case 'g':
13505 case 'G':
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013506 temp = formatfloat(v, flags, prec, c);
13507 if (!temp)
Benjamin Peterson29060642009-01-31 22:14:21 +000013508 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013509 if (PyUnicode_READY(temp) == -1) {
13510 Py_CLEAR(temp);
13511 goto onError;
13512 }
13513 pbuf = PyUnicode_DATA(temp);
13514 kind = PyUnicode_KIND(temp);
13515 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013516 sign = 1;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013517 if (flags & F_ZERO) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013518 fill = '0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013519 fillobj = zero;
13520 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013521 break;
13522
13523 case 'c':
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013524 {
13525 Py_UCS4 ch = formatchar(v);
13526 if (ch == (Py_UCS4) -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000013527 goto onError;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013528 temp = _PyUnicode_FromUCS4(&ch, 1);
13529 if (temp == NULL)
13530 goto onError;
13531 pbuf = PyUnicode_DATA(temp);
13532 kind = PyUnicode_KIND(temp);
13533 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013534 break;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013535 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013536
13537 default:
13538 PyErr_Format(PyExc_ValueError,
13539 "unsupported format character '%c' (0x%x) "
13540 "at index %zd",
13541 (31<=c && c<=126) ? (char)c : '?',
13542 (int)c,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013543 fmtpos - 1);
Benjamin Peterson29060642009-01-31 22:14:21 +000013544 goto onError;
13545 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013546 /* pbuf is initialized here. */
13547 pindex = 0;
Benjamin Peterson29060642009-01-31 22:14:21 +000013548 if (sign) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013549 if (PyUnicode_READ(kind, pbuf, pindex) == '-') {
13550 signobj = minus;
Benjamin Peterson29060642009-01-31 22:14:21 +000013551 len--;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013552 pindex++;
13553 }
13554 else if (PyUnicode_READ(kind, pbuf, pindex) == '+') {
13555 signobj = plus;
13556 len--;
13557 pindex++;
Benjamin Peterson29060642009-01-31 22:14:21 +000013558 }
13559 else if (flags & F_SIGN)
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013560 signobj = plus;
Benjamin Peterson29060642009-01-31 22:14:21 +000013561 else if (flags & F_BLANK)
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013562 signobj = blank;
Benjamin Peterson29060642009-01-31 22:14:21 +000013563 else
13564 sign = 0;
13565 }
13566 if (width < len)
13567 width = len;
Benjamin Peterson29060642009-01-31 22:14:21 +000013568 if (sign) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013569 if (fill != ' ') {
13570 assert(signobj != NULL);
13571 if (_PyAccu_Accumulate(&acc, signobj))
13572 goto onError;
13573 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013574 if (width > len)
13575 width--;
13576 }
13577 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013578 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013579 assert(PyUnicode_READ(kind, pbuf, pindex + 1) == c);
Benjamin Peterson29060642009-01-31 22:14:21 +000013580 if (fill != ' ') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013581 second = get_latin1_char(
13582 PyUnicode_READ(kind, pbuf, pindex + 1));
13583 pindex += 2;
13584 if (second == NULL ||
13585 _PyAccu_Accumulate(&acc, zero) ||
13586 _PyAccu_Accumulate(&acc, second))
13587 goto onError;
13588 Py_CLEAR(second);
Benjamin Peterson29060642009-01-31 22:14:21 +000013589 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013590 width -= 2;
13591 if (width < 0)
13592 width = 0;
13593 len -= 2;
13594 }
13595 if (width > len && !(flags & F_LJUST)) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013596 assert(fillobj != NULL);
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013597 if (repeat_accumulate(&acc, fillobj, width - len))
13598 goto onError;
13599 width = len;
Benjamin Peterson29060642009-01-31 22:14:21 +000013600 }
13601 if (fill == ' ') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013602 if (sign) {
13603 assert(signobj != NULL);
13604 if (_PyAccu_Accumulate(&acc, signobj))
13605 goto onError;
13606 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013607 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013608 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
13609 assert(PyUnicode_READ(kind, pbuf, pindex+1) == c);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013610 second = get_latin1_char(
13611 PyUnicode_READ(kind, pbuf, pindex + 1));
13612 pindex += 2;
13613 if (second == NULL ||
13614 _PyAccu_Accumulate(&acc, zero) ||
13615 _PyAccu_Accumulate(&acc, second))
13616 goto onError;
13617 Py_CLEAR(second);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013618 }
13619 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013620 /* Copy all characters, preserving len */
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013621 if (temp != NULL) {
13622 assert(pbuf == PyUnicode_DATA(temp));
13623 v = PyUnicode_Substring(temp, pindex, pindex + len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013624 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013625 else {
13626 const char *p = (const char *) pbuf;
13627 assert(pbuf != NULL);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013628 p += kind * pindex;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013629 v = PyUnicode_FromKindAndData(kind, p, len);
13630 }
13631 if (v == NULL)
13632 goto onError;
13633 r = _PyAccu_Accumulate(&acc, v);
13634 Py_DECREF(v);
13635 if (r)
13636 goto onError;
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013637 if (width > len && repeat_accumulate(&acc, blank, width - len))
13638 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +000013639 if (dict && (argidx < arglen) && c != '%') {
13640 PyErr_SetString(PyExc_TypeError,
13641 "not all arguments converted during string formatting");
Benjamin Peterson29060642009-01-31 22:14:21 +000013642 goto onError;
13643 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013644 Py_CLEAR(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013645 } /* '%' */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013646 } /* until end */
13647 if (argidx < arglen && !dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013648 PyErr_SetString(PyExc_TypeError,
13649 "not all arguments converted during string formatting");
13650 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013651 }
13652
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013653 result = _PyAccu_Finish(&acc);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013654 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013655 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013656 }
13657 Py_DECREF(uformat);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013658 Py_XDECREF(temp);
13659 Py_XDECREF(second);
Victor Stinner7931d9a2011-11-04 00:22:48 +010013660 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013661
Benjamin Peterson29060642009-01-31 22:14:21 +000013662 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000013663 Py_DECREF(uformat);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013664 Py_XDECREF(temp);
13665 Py_XDECREF(second);
13666 _PyAccu_Destroy(&acc);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013667 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013668 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013669 }
13670 return NULL;
13671}
13672
Jeremy Hylton938ace62002-07-17 16:30:39 +000013673static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +000013674unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
13675
Tim Peters6d6c1a32001-08-02 04:15:00 +000013676static PyObject *
13677unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
13678{
Benjamin Peterson29060642009-01-31 22:14:21 +000013679 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013680 static char *kwlist[] = {"object", "encoding", "errors", 0};
13681 char *encoding = NULL;
13682 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000013683
Benjamin Peterson14339b62009-01-31 16:36:08 +000013684 if (type != &PyUnicode_Type)
13685 return unicode_subtype_new(type, args, kwds);
13686 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +000013687 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +000013688 return NULL;
13689 if (x == NULL)
Victor Stinner7931d9a2011-11-04 00:22:48 +010013690 return PyUnicode_New(0, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013691 if (encoding == NULL && errors == NULL)
13692 return PyObject_Str(x);
13693 else
Benjamin Peterson29060642009-01-31 22:14:21 +000013694 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +000013695}
13696
Guido van Rossume023fe02001-08-30 03:12:59 +000013697static PyObject *
13698unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
13699{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013700 PyObject *unicode, *self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013701 Py_ssize_t length, char_size;
13702 int share_wstr, share_utf8;
13703 unsigned int kind;
13704 void *data;
Guido van Rossume023fe02001-08-30 03:12:59 +000013705
Benjamin Peterson14339b62009-01-31 16:36:08 +000013706 assert(PyType_IsSubtype(type, &PyUnicode_Type));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013707
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013708 unicode = unicode_new(&PyUnicode_Type, args, kwds);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013709 if (unicode == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000013710 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020013711 assert(_PyUnicode_CHECK(unicode));
Victor Stinnere06e1452011-10-04 20:52:31 +020013712 if (PyUnicode_READY(unicode))
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013713 return NULL;
13714
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013715 self = type->tp_alloc(type, 0);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013716 if (self == NULL) {
13717 Py_DECREF(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013718 return NULL;
13719 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013720 kind = PyUnicode_KIND(unicode);
13721 length = PyUnicode_GET_LENGTH(unicode);
13722
13723 _PyUnicode_LENGTH(self) = length;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020013724#ifdef Py_DEBUG
13725 _PyUnicode_HASH(self) = -1;
13726#else
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013727 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020013728#endif
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013729 _PyUnicode_STATE(self).interned = 0;
13730 _PyUnicode_STATE(self).kind = kind;
13731 _PyUnicode_STATE(self).compact = 0;
Victor Stinner3cf46372011-10-03 14:42:15 +020013732 _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013733 _PyUnicode_STATE(self).ready = 1;
13734 _PyUnicode_WSTR(self) = NULL;
13735 _PyUnicode_UTF8_LENGTH(self) = 0;
13736 _PyUnicode_UTF8(self) = NULL;
13737 _PyUnicode_WSTR_LENGTH(self) = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +020013738 _PyUnicode_DATA_ANY(self) = NULL;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013739
13740 share_utf8 = 0;
13741 share_wstr = 0;
13742 if (kind == PyUnicode_1BYTE_KIND) {
13743 char_size = 1;
13744 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
13745 share_utf8 = 1;
13746 }
13747 else if (kind == PyUnicode_2BYTE_KIND) {
13748 char_size = 2;
13749 if (sizeof(wchar_t) == 2)
13750 share_wstr = 1;
13751 }
13752 else {
13753 assert(kind == PyUnicode_4BYTE_KIND);
13754 char_size = 4;
13755 if (sizeof(wchar_t) == 4)
13756 share_wstr = 1;
13757 }
13758
13759 /* Ensure we won't overflow the length. */
13760 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
13761 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013762 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013763 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013764 data = PyObject_MALLOC((length + 1) * char_size);
13765 if (data == NULL) {
13766 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013767 goto onError;
13768 }
13769
Victor Stinnerc3c74152011-10-02 20:39:55 +020013770 _PyUnicode_DATA_ANY(self) = data;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013771 if (share_utf8) {
13772 _PyUnicode_UTF8_LENGTH(self) = length;
13773 _PyUnicode_UTF8(self) = data;
13774 }
13775 if (share_wstr) {
13776 _PyUnicode_WSTR_LENGTH(self) = length;
13777 _PyUnicode_WSTR(self) = (wchar_t *)data;
13778 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013779
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013780 Py_MEMCPY(data, PyUnicode_DATA(unicode),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013781 kind * (length + 1));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013782 assert(_PyUnicode_CheckConsistency(self, 1));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020013783#ifdef Py_DEBUG
13784 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
13785#endif
Victor Stinnerdd18d3a2011-10-22 11:08:10 +020013786 Py_DECREF(unicode);
Victor Stinner7931d9a2011-11-04 00:22:48 +010013787 return self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013788
13789onError:
13790 Py_DECREF(unicode);
13791 Py_DECREF(self);
13792 return NULL;
Guido van Rossume023fe02001-08-30 03:12:59 +000013793}
13794
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013795PyDoc_STRVAR(unicode_doc,
Benjamin Peterson29060642009-01-31 22:14:21 +000013796 "str(string[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +000013797\n\
Collin Winterd474ce82007-08-07 19:42:11 +000013798Create a new string object from the given encoded string.\n\
Skip Montanaro35b37a52002-07-26 16:22:46 +000013799encoding defaults to the current default string encoding.\n\
13800errors can be 'strict', 'replace' or 'ignore' and defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +000013801
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013802static PyObject *unicode_iter(PyObject *seq);
13803
Guido van Rossumd57fd912000-03-10 22:53:23 +000013804PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000013805 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Benjamin Peterson14339b62009-01-31 16:36:08 +000013806 "str", /* tp_name */
13807 sizeof(PyUnicodeObject), /* tp_size */
13808 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013809 /* Slots */
Benjamin Peterson14339b62009-01-31 16:36:08 +000013810 (destructor)unicode_dealloc, /* tp_dealloc */
13811 0, /* tp_print */
13812 0, /* tp_getattr */
13813 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000013814 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000013815 unicode_repr, /* tp_repr */
13816 &unicode_as_number, /* tp_as_number */
13817 &unicode_as_sequence, /* tp_as_sequence */
13818 &unicode_as_mapping, /* tp_as_mapping */
13819 (hashfunc) unicode_hash, /* tp_hash*/
13820 0, /* tp_call*/
13821 (reprfunc) unicode_str, /* tp_str */
13822 PyObject_GenericGetAttr, /* tp_getattro */
13823 0, /* tp_setattro */
13824 0, /* tp_as_buffer */
13825 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Benjamin Peterson29060642009-01-31 22:14:21 +000013826 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
Benjamin Peterson14339b62009-01-31 16:36:08 +000013827 unicode_doc, /* tp_doc */
13828 0, /* tp_traverse */
13829 0, /* tp_clear */
13830 PyUnicode_RichCompare, /* tp_richcompare */
13831 0, /* tp_weaklistoffset */
13832 unicode_iter, /* tp_iter */
13833 0, /* tp_iternext */
13834 unicode_methods, /* tp_methods */
13835 0, /* tp_members */
13836 0, /* tp_getset */
13837 &PyBaseObject_Type, /* tp_base */
13838 0, /* tp_dict */
13839 0, /* tp_descr_get */
13840 0, /* tp_descr_set */
13841 0, /* tp_dictoffset */
13842 0, /* tp_init */
13843 0, /* tp_alloc */
13844 unicode_new, /* tp_new */
13845 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013846};
13847
13848/* Initialize the Unicode implementation */
13849
Victor Stinner3a50e702011-10-18 21:21:00 +020013850int _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013851{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013852 int i;
13853
Thomas Wouters477c8d52006-05-27 19:21:47 +000013854 /* XXX - move this array to unicodectype.c ? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013855 Py_UCS2 linebreak[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +000013856 0x000A, /* LINE FEED */
13857 0x000D, /* CARRIAGE RETURN */
13858 0x001C, /* FILE SEPARATOR */
13859 0x001D, /* GROUP SEPARATOR */
13860 0x001E, /* RECORD SEPARATOR */
13861 0x0085, /* NEXT LINE */
13862 0x2028, /* LINE SEPARATOR */
13863 0x2029, /* PARAGRAPH SEPARATOR */
13864 };
13865
Fred Drakee4315f52000-05-09 19:53:39 +000013866 /* Init the implementation */
Victor Stinnera464fc12011-10-02 20:39:30 +020013867 unicode_empty = PyUnicode_New(0, 0);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013868 assert(_PyUnicode_CheckConsistency(unicode_empty, 1));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013869 if (!unicode_empty)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013870 Py_FatalError("Can't create empty string");
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013871
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013872 for (i = 0; i < 256; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +000013873 unicode_latin1[i] = NULL;
Guido van Rossumcacfc072002-05-24 19:01:59 +000013874 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000013875 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +000013876
13877 /* initialize the linebreak bloom filter */
13878 bloom_linebreak = make_bloom_mask(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013879 PyUnicode_2BYTE_KIND, linebreak,
Victor Stinner63941882011-09-29 00:42:28 +020013880 Py_ARRAY_LENGTH(linebreak));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013881
13882 PyType_Ready(&EncodingMapType);
Victor Stinner3a50e702011-10-18 21:21:00 +020013883
13884#ifdef HAVE_MBCS
13885 winver.dwOSVersionInfoSize = sizeof(winver);
13886 if (!GetVersionEx((OSVERSIONINFO*)&winver)) {
13887 PyErr_SetFromWindowsErr(0);
13888 return -1;
13889 }
13890#endif
13891 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013892}
13893
13894/* Finalize the Unicode implementation */
13895
Christian Heimesa156e092008-02-16 07:38:31 +000013896int
13897PyUnicode_ClearFreeList(void)
13898{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013899 return 0;
Christian Heimesa156e092008-02-16 07:38:31 +000013900}
13901
Guido van Rossumd57fd912000-03-10 22:53:23 +000013902void
Thomas Wouters78890102000-07-22 19:25:51 +000013903_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013904{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013905 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013906
Guido van Rossum4ae8ef82000-10-03 18:09:04 +000013907 Py_XDECREF(unicode_empty);
13908 unicode_empty = NULL;
Barry Warsaw5b4c2282000-10-03 20:45:26 +000013909
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013910 for (i = 0; i < 256; i++) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013911 if (unicode_latin1[i]) {
13912 Py_DECREF(unicode_latin1[i]);
13913 unicode_latin1[i] = NULL;
13914 }
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013915 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020013916 _PyUnicode_ClearStaticStrings();
Christian Heimesa156e092008-02-16 07:38:31 +000013917 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +000013918}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000013919
Walter Dörwald16807132007-05-25 13:52:07 +000013920void
13921PyUnicode_InternInPlace(PyObject **p)
13922{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013923 register PyObject *s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013924 PyObject *t;
Victor Stinner4fae54c2011-10-03 02:01:52 +020013925#ifdef Py_DEBUG
13926 assert(s != NULL);
13927 assert(_PyUnicode_CHECK(s));
13928#else
Benjamin Peterson14339b62009-01-31 16:36:08 +000013929 if (s == NULL || !PyUnicode_Check(s))
Victor Stinner4fae54c2011-10-03 02:01:52 +020013930 return;
13931#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000013932 /* If it's a subclass, we don't really know what putting
13933 it in the interned dict might do. */
13934 if (!PyUnicode_CheckExact(s))
13935 return;
13936 if (PyUnicode_CHECK_INTERNED(s))
13937 return;
Victor Stinner1b4f9ce2011-10-03 13:28:14 +020013938 if (_PyUnicode_READY_REPLACE(p)) {
Victor Stinner6b56a7f2011-10-04 20:04:52 +020013939 assert(0 && "_PyUnicode_READY_REPLACE fail in PyUnicode_InternInPlace");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013940 return;
13941 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013942 s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013943 if (interned == NULL) {
13944 interned = PyDict_New();
13945 if (interned == NULL) {
13946 PyErr_Clear(); /* Don't leave an exception */
13947 return;
13948 }
13949 }
13950 /* It might be that the GetItem call fails even
13951 though the key is present in the dictionary,
13952 namely when this happens during a stack overflow. */
13953 Py_ALLOW_RECURSION
Victor Stinner7931d9a2011-11-04 00:22:48 +010013954 t = PyDict_GetItem(interned, s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013955 Py_END_ALLOW_RECURSION
Martin v. Löwis5b222132007-06-10 09:51:05 +000013956
Benjamin Peterson29060642009-01-31 22:14:21 +000013957 if (t) {
13958 Py_INCREF(t);
13959 Py_DECREF(*p);
13960 *p = t;
13961 return;
13962 }
Walter Dörwald16807132007-05-25 13:52:07 +000013963
Benjamin Peterson14339b62009-01-31 16:36:08 +000013964 PyThreadState_GET()->recursion_critical = 1;
Victor Stinner7931d9a2011-11-04 00:22:48 +010013965 if (PyDict_SetItem(interned, s, s) < 0) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013966 PyErr_Clear();
13967 PyThreadState_GET()->recursion_critical = 0;
13968 return;
13969 }
13970 PyThreadState_GET()->recursion_critical = 0;
13971 /* The two references in interned are not counted by refcnt.
13972 The deallocator will take care of this */
13973 Py_REFCNT(s) -= 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013974 _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000013975}
13976
13977void
13978PyUnicode_InternImmortal(PyObject **p)
13979{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013980 PyUnicode_InternInPlace(p);
13981 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
Victor Stinneraf9e4b82011-10-23 20:07:00 +020013982 _PyUnicode_STATE(*p).interned = SSTATE_INTERNED_IMMORTAL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013983 Py_INCREF(*p);
13984 }
Walter Dörwald16807132007-05-25 13:52:07 +000013985}
13986
13987PyObject *
13988PyUnicode_InternFromString(const char *cp)
13989{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013990 PyObject *s = PyUnicode_FromString(cp);
13991 if (s == NULL)
13992 return NULL;
13993 PyUnicode_InternInPlace(&s);
13994 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000013995}
13996
Alexander Belopolsky40018472011-02-26 01:02:56 +000013997void
13998_Py_ReleaseInternedUnicodeStrings(void)
Walter Dörwald16807132007-05-25 13:52:07 +000013999{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014000 PyObject *keys;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014001 PyObject *s;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014002 Py_ssize_t i, n;
14003 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000014004
Benjamin Peterson14339b62009-01-31 16:36:08 +000014005 if (interned == NULL || !PyDict_Check(interned))
14006 return;
14007 keys = PyDict_Keys(interned);
14008 if (keys == NULL || !PyList_Check(keys)) {
14009 PyErr_Clear();
14010 return;
14011 }
Walter Dörwald16807132007-05-25 13:52:07 +000014012
Benjamin Peterson14339b62009-01-31 16:36:08 +000014013 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
14014 detector, interned unicode strings are not forcibly deallocated;
14015 rather, we give them their stolen references back, and then clear
14016 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000014017
Benjamin Peterson14339b62009-01-31 16:36:08 +000014018 n = PyList_GET_SIZE(keys);
14019 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000014020 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014021 for (i = 0; i < n; i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014022 s = PyList_GET_ITEM(keys, i);
Victor Stinner6b56a7f2011-10-04 20:04:52 +020014023 if (PyUnicode_READY(s) == -1) {
14024 assert(0 && "could not ready string");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014025 fprintf(stderr, "could not ready string\n");
Victor Stinner6b56a7f2011-10-04 20:04:52 +020014026 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014027 switch (PyUnicode_CHECK_INTERNED(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014028 case SSTATE_NOT_INTERNED:
14029 /* XXX Shouldn't happen */
14030 break;
14031 case SSTATE_INTERNED_IMMORTAL:
14032 Py_REFCNT(s) += 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014033 immortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014034 break;
14035 case SSTATE_INTERNED_MORTAL:
14036 Py_REFCNT(s) += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014037 mortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014038 break;
14039 default:
14040 Py_FatalError("Inconsistent interned string state.");
14041 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014042 _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014043 }
14044 fprintf(stderr, "total size of all interned strings: "
14045 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
14046 "mortal/immortal\n", mortal_size, immortal_size);
14047 Py_DECREF(keys);
14048 PyDict_Clear(interned);
14049 Py_DECREF(interned);
14050 interned = NULL;
Walter Dörwald16807132007-05-25 13:52:07 +000014051}
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014052
14053
14054/********************* Unicode Iterator **************************/
14055
14056typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014057 PyObject_HEAD
14058 Py_ssize_t it_index;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014059 PyObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014060} unicodeiterobject;
14061
14062static void
14063unicodeiter_dealloc(unicodeiterobject *it)
14064{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014065 _PyObject_GC_UNTRACK(it);
14066 Py_XDECREF(it->it_seq);
14067 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014068}
14069
14070static int
14071unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
14072{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014073 Py_VISIT(it->it_seq);
14074 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014075}
14076
14077static PyObject *
14078unicodeiter_next(unicodeiterobject *it)
14079{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014080 PyObject *seq, *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014081
Benjamin Peterson14339b62009-01-31 16:36:08 +000014082 assert(it != NULL);
14083 seq = it->it_seq;
14084 if (seq == NULL)
14085 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020014086 assert(_PyUnicode_CHECK(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014087
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014088 if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
14089 int kind = PyUnicode_KIND(seq);
14090 void *data = PyUnicode_DATA(seq);
14091 Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
14092 item = PyUnicode_FromOrdinal(chr);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014093 if (item != NULL)
14094 ++it->it_index;
14095 return item;
14096 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014097
Benjamin Peterson14339b62009-01-31 16:36:08 +000014098 Py_DECREF(seq);
14099 it->it_seq = NULL;
14100 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014101}
14102
14103static PyObject *
14104unicodeiter_len(unicodeiterobject *it)
14105{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014106 Py_ssize_t len = 0;
14107 if (it->it_seq)
Victor Stinnerc4f281e2011-10-11 22:11:42 +020014108 len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014109 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014110}
14111
14112PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
14113
14114static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014115 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000014116 length_hint_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000014117 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014118};
14119
14120PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014121 PyVarObject_HEAD_INIT(&PyType_Type, 0)
14122 "str_iterator", /* tp_name */
14123 sizeof(unicodeiterobject), /* tp_basicsize */
14124 0, /* tp_itemsize */
14125 /* methods */
14126 (destructor)unicodeiter_dealloc, /* tp_dealloc */
14127 0, /* tp_print */
14128 0, /* tp_getattr */
14129 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000014130 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014131 0, /* tp_repr */
14132 0, /* tp_as_number */
14133 0, /* tp_as_sequence */
14134 0, /* tp_as_mapping */
14135 0, /* tp_hash */
14136 0, /* tp_call */
14137 0, /* tp_str */
14138 PyObject_GenericGetAttr, /* tp_getattro */
14139 0, /* tp_setattro */
14140 0, /* tp_as_buffer */
14141 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
14142 0, /* tp_doc */
14143 (traverseproc)unicodeiter_traverse, /* tp_traverse */
14144 0, /* tp_clear */
14145 0, /* tp_richcompare */
14146 0, /* tp_weaklistoffset */
14147 PyObject_SelfIter, /* tp_iter */
14148 (iternextfunc)unicodeiter_next, /* tp_iternext */
14149 unicodeiter_methods, /* tp_methods */
14150 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014151};
14152
14153static PyObject *
14154unicode_iter(PyObject *seq)
14155{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014156 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014157
Benjamin Peterson14339b62009-01-31 16:36:08 +000014158 if (!PyUnicode_Check(seq)) {
14159 PyErr_BadInternalCall();
14160 return NULL;
14161 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014162 if (PyUnicode_READY(seq) == -1)
14163 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014164 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
14165 if (it == NULL)
14166 return NULL;
14167 it->it_index = 0;
14168 Py_INCREF(seq);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014169 it->it_seq = seq;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014170 _PyObject_GC_TRACK(it);
14171 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014172}
14173
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010014174
14175size_t
14176Py_UNICODE_strlen(const Py_UNICODE *u)
14177{
14178 int res = 0;
14179 while(*u++)
14180 res++;
14181 return res;
14182}
14183
14184Py_UNICODE*
14185Py_UNICODE_strcpy(Py_UNICODE *s1, const Py_UNICODE *s2)
14186{
14187 Py_UNICODE *u = s1;
14188 while ((*u++ = *s2++));
14189 return s1;
14190}
14191
14192Py_UNICODE*
14193Py_UNICODE_strncpy(Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
14194{
14195 Py_UNICODE *u = s1;
14196 while ((*u++ = *s2++))
14197 if (n-- == 0)
14198 break;
14199 return s1;
14200}
14201
14202Py_UNICODE*
14203Py_UNICODE_strcat(Py_UNICODE *s1, const Py_UNICODE *s2)
14204{
14205 Py_UNICODE *u1 = s1;
14206 u1 += Py_UNICODE_strlen(u1);
14207 Py_UNICODE_strcpy(u1, s2);
14208 return s1;
14209}
14210
14211int
14212Py_UNICODE_strcmp(const Py_UNICODE *s1, const Py_UNICODE *s2)
14213{
14214 while (*s1 && *s2 && *s1 == *s2)
14215 s1++, s2++;
14216 if (*s1 && *s2)
14217 return (*s1 < *s2) ? -1 : +1;
14218 if (*s1)
14219 return 1;
14220 if (*s2)
14221 return -1;
14222 return 0;
14223}
14224
14225int
14226Py_UNICODE_strncmp(const Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
14227{
14228 register Py_UNICODE u1, u2;
14229 for (; n != 0; n--) {
14230 u1 = *s1;
14231 u2 = *s2;
14232 if (u1 != u2)
14233 return (u1 < u2) ? -1 : +1;
14234 if (u1 == '\0')
14235 return 0;
14236 s1++;
14237 s2++;
14238 }
14239 return 0;
14240}
14241
14242Py_UNICODE*
14243Py_UNICODE_strchr(const Py_UNICODE *s, Py_UNICODE c)
14244{
14245 const Py_UNICODE *p;
14246 for (p = s; *p; p++)
14247 if (*p == c)
14248 return (Py_UNICODE*)p;
14249 return NULL;
14250}
14251
14252Py_UNICODE*
14253Py_UNICODE_strrchr(const Py_UNICODE *s, Py_UNICODE c)
14254{
14255 const Py_UNICODE *p;
14256 p = s + Py_UNICODE_strlen(s);
14257 while (p != s) {
14258 p--;
14259 if (*p == c)
14260 return (Py_UNICODE*)p;
14261 }
14262 return NULL;
14263}
Victor Stinner331ea922010-08-10 16:37:20 +000014264
Victor Stinner71133ff2010-09-01 23:43:53 +000014265Py_UNICODE*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014266PyUnicode_AsUnicodeCopy(PyObject *unicode)
Victor Stinner71133ff2010-09-01 23:43:53 +000014267{
Victor Stinner577db2c2011-10-11 22:12:48 +020014268 Py_UNICODE *u, *copy;
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014269 Py_ssize_t len, size;
Victor Stinner71133ff2010-09-01 23:43:53 +000014270
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014271 if (!PyUnicode_Check(unicode)) {
14272 PyErr_BadArgument();
14273 return NULL;
14274 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014275 u = PyUnicode_AsUnicodeAndSize(unicode, &len);
Victor Stinner577db2c2011-10-11 22:12:48 +020014276 if (u == NULL)
14277 return NULL;
Victor Stinner71133ff2010-09-01 23:43:53 +000014278 /* Ensure we won't overflow the size. */
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014279 if (len > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
Victor Stinner71133ff2010-09-01 23:43:53 +000014280 PyErr_NoMemory();
14281 return NULL;
14282 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014283 size = len + 1; /* copy the null character */
Victor Stinner71133ff2010-09-01 23:43:53 +000014284 size *= sizeof(Py_UNICODE);
14285 copy = PyMem_Malloc(size);
14286 if (copy == NULL) {
14287 PyErr_NoMemory();
14288 return NULL;
14289 }
Victor Stinner577db2c2011-10-11 22:12:48 +020014290 memcpy(copy, u, size);
Victor Stinner71133ff2010-09-01 23:43:53 +000014291 return copy;
14292}
Martin v. Löwis5b222132007-06-10 09:51:05 +000014293
Georg Brandl66c221e2010-10-14 07:04:07 +000014294/* A _string module, to export formatter_parser and formatter_field_name_split
14295 to the string.Formatter class implemented in Python. */
14296
14297static PyMethodDef _string_methods[] = {
14298 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
14299 METH_O, PyDoc_STR("split the argument as a field name")},
14300 {"formatter_parser", (PyCFunction) formatter_parser,
14301 METH_O, PyDoc_STR("parse the argument as a format string")},
14302 {NULL, NULL}
14303};
14304
14305static struct PyModuleDef _string_module = {
14306 PyModuleDef_HEAD_INIT,
14307 "_string",
14308 PyDoc_STR("string helper module"),
14309 0,
14310 _string_methods,
14311 NULL,
14312 NULL,
14313 NULL,
14314 NULL
14315};
14316
14317PyMODINIT_FUNC
14318PyInit__string(void)
14319{
14320 return PyModule_Create(&_string_module);
14321}
14322
14323
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000014324#ifdef __cplusplus
14325}
14326#endif